1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TypeLocBuilder.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/CommentDiagnostic.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/NonTrivialTypeVisitor.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 36 #include "clang/Sema/CXXFieldCollector.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaInternal.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/ADT/SmallString.h" 47 #include "llvm/ADT/Triple.h" 48 #include <algorithm> 49 #include <cstring> 50 #include <functional> 51 #include <unordered_map> 52 53 using namespace clang; 54 using namespace sema; 55 56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 57 if (OwnedType) { 58 Decl *Group[2] = { OwnedType, Ptr }; 59 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 60 } 61 62 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 63 } 64 65 namespace { 66 67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 68 public: 69 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 70 bool AllowTemplates = false, 71 bool AllowNonTemplates = true) 72 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 73 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 74 WantExpressionKeywords = false; 75 WantCXXNamedCasts = false; 76 WantRemainingKeywords = false; 77 } 78 79 bool ValidateCandidate(const TypoCorrection &candidate) override { 80 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 81 if (!AllowInvalidDecl && ND->isInvalidDecl()) 82 return false; 83 84 if (getAsTypeTemplateDecl(ND)) 85 return AllowTemplates; 86 87 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 88 if (!IsType) 89 return false; 90 91 if (AllowNonTemplates) 92 return true; 93 94 // An injected-class-name of a class template (specialization) is valid 95 // as a template or as a non-template. 96 if (AllowTemplates) { 97 auto *RD = dyn_cast<CXXRecordDecl>(ND); 98 if (!RD || !RD->isInjectedClassName()) 99 return false; 100 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 101 return RD->getDescribedClassTemplate() || 102 isa<ClassTemplateSpecializationDecl>(RD); 103 } 104 105 return false; 106 } 107 108 return !WantClassName && candidate.isKeyword(); 109 } 110 111 std::unique_ptr<CorrectionCandidateCallback> clone() override { 112 return std::make_unique<TypeNameValidatorCCC>(*this); 113 } 114 115 private: 116 bool AllowInvalidDecl; 117 bool WantClassName; 118 bool AllowTemplates; 119 bool AllowNonTemplates; 120 }; 121 122 } // end anonymous namespace 123 124 /// Determine whether the token kind starts a simple-type-specifier. 125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 126 switch (Kind) { 127 // FIXME: Take into account the current language when deciding whether a 128 // token kind is a valid type specifier 129 case tok::kw_short: 130 case tok::kw_long: 131 case tok::kw___int64: 132 case tok::kw___int128: 133 case tok::kw_signed: 134 case tok::kw_unsigned: 135 case tok::kw_void: 136 case tok::kw_char: 137 case tok::kw_int: 138 case tok::kw_half: 139 case tok::kw_float: 140 case tok::kw_double: 141 case tok::kw___bf16: 142 case tok::kw__Float16: 143 case tok::kw___float128: 144 case tok::kw___ibm128: 145 case tok::kw_wchar_t: 146 case tok::kw_bool: 147 case tok::kw___underlying_type: 148 case tok::kw___auto_type: 149 return true; 150 151 case tok::annot_typename: 152 case tok::kw_char16_t: 153 case tok::kw_char32_t: 154 case tok::kw_typeof: 155 case tok::annot_decltype: 156 case tok::kw_decltype: 157 return getLangOpts().CPlusPlus; 158 159 case tok::kw_char8_t: 160 return getLangOpts().Char8; 161 162 default: 163 break; 164 } 165 166 return false; 167 } 168 169 namespace { 170 enum class UnqualifiedTypeNameLookupResult { 171 NotFound, 172 FoundNonType, 173 FoundType 174 }; 175 } // end anonymous namespace 176 177 /// Tries to perform unqualified lookup of the type decls in bases for 178 /// dependent class. 179 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 180 /// type decl, \a FoundType if only type decls are found. 181 static UnqualifiedTypeNameLookupResult 182 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 183 SourceLocation NameLoc, 184 const CXXRecordDecl *RD) { 185 if (!RD->hasDefinition()) 186 return UnqualifiedTypeNameLookupResult::NotFound; 187 // Look for type decls in base classes. 188 UnqualifiedTypeNameLookupResult FoundTypeDecl = 189 UnqualifiedTypeNameLookupResult::NotFound; 190 for (const auto &Base : RD->bases()) { 191 const CXXRecordDecl *BaseRD = nullptr; 192 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 193 BaseRD = BaseTT->getAsCXXRecordDecl(); 194 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 195 // Look for type decls in dependent base classes that have known primary 196 // templates. 197 if (!TST || !TST->isDependentType()) 198 continue; 199 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 200 if (!TD) 201 continue; 202 if (auto *BasePrimaryTemplate = 203 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 204 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 205 BaseRD = BasePrimaryTemplate; 206 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 207 if (const ClassTemplatePartialSpecializationDecl *PS = 208 CTD->findPartialSpecialization(Base.getType())) 209 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 210 BaseRD = PS; 211 } 212 } 213 } 214 if (BaseRD) { 215 for (NamedDecl *ND : BaseRD->lookup(&II)) { 216 if (!isa<TypeDecl>(ND)) 217 return UnqualifiedTypeNameLookupResult::FoundNonType; 218 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 219 } 220 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 221 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 222 case UnqualifiedTypeNameLookupResult::FoundNonType: 223 return UnqualifiedTypeNameLookupResult::FoundNonType; 224 case UnqualifiedTypeNameLookupResult::FoundType: 225 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 226 break; 227 case UnqualifiedTypeNameLookupResult::NotFound: 228 break; 229 } 230 } 231 } 232 } 233 234 return FoundTypeDecl; 235 } 236 237 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 238 const IdentifierInfo &II, 239 SourceLocation NameLoc) { 240 // Lookup in the parent class template context, if any. 241 const CXXRecordDecl *RD = nullptr; 242 UnqualifiedTypeNameLookupResult FoundTypeDecl = 243 UnqualifiedTypeNameLookupResult::NotFound; 244 for (DeclContext *DC = S.CurContext; 245 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 246 DC = DC->getParent()) { 247 // Look for type decls in dependent base classes that have known primary 248 // templates. 249 RD = dyn_cast<CXXRecordDecl>(DC); 250 if (RD && RD->getDescribedClassTemplate()) 251 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 252 } 253 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 254 return nullptr; 255 256 // We found some types in dependent base classes. Recover as if the user 257 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 258 // lookup during template instantiation. 259 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II; 260 261 ASTContext &Context = S.Context; 262 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 263 cast<Type>(Context.getRecordType(RD))); 264 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 265 266 CXXScopeSpec SS; 267 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 268 269 TypeLocBuilder Builder; 270 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 271 DepTL.setNameLoc(NameLoc); 272 DepTL.setElaboratedKeywordLoc(SourceLocation()); 273 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 274 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 275 } 276 277 /// If the identifier refers to a type name within this scope, 278 /// return the declaration of that type. 279 /// 280 /// This routine performs ordinary name lookup of the identifier II 281 /// within the given scope, with optional C++ scope specifier SS, to 282 /// determine whether the name refers to a type. If so, returns an 283 /// opaque pointer (actually a QualType) corresponding to that 284 /// type. Otherwise, returns NULL. 285 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 286 Scope *S, CXXScopeSpec *SS, 287 bool isClassName, bool HasTrailingDot, 288 ParsedType ObjectTypePtr, 289 bool IsCtorOrDtorName, 290 bool WantNontrivialTypeSourceInfo, 291 bool IsClassTemplateDeductionContext, 292 IdentifierInfo **CorrectedII) { 293 // FIXME: Consider allowing this outside C++1z mode as an extension. 294 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 295 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 296 !isClassName && !HasTrailingDot; 297 298 // Determine where we will perform name lookup. 299 DeclContext *LookupCtx = nullptr; 300 if (ObjectTypePtr) { 301 QualType ObjectType = ObjectTypePtr.get(); 302 if (ObjectType->isRecordType()) 303 LookupCtx = computeDeclContext(ObjectType); 304 } else if (SS && SS->isNotEmpty()) { 305 LookupCtx = computeDeclContext(*SS, false); 306 307 if (!LookupCtx) { 308 if (isDependentScopeSpecifier(*SS)) { 309 // C++ [temp.res]p3: 310 // A qualified-id that refers to a type and in which the 311 // nested-name-specifier depends on a template-parameter (14.6.2) 312 // shall be prefixed by the keyword typename to indicate that the 313 // qualified-id denotes a type, forming an 314 // elaborated-type-specifier (7.1.5.3). 315 // 316 // We therefore do not perform any name lookup if the result would 317 // refer to a member of an unknown specialization. 318 if (!isClassName && !IsCtorOrDtorName) 319 return nullptr; 320 321 // We know from the grammar that this name refers to a type, 322 // so build a dependent node to describe the type. 323 if (WantNontrivialTypeSourceInfo) 324 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 325 326 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 327 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 328 II, NameLoc); 329 return ParsedType::make(T); 330 } 331 332 return nullptr; 333 } 334 335 if (!LookupCtx->isDependentContext() && 336 RequireCompleteDeclContext(*SS, LookupCtx)) 337 return nullptr; 338 } 339 340 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 341 // lookup for class-names. 342 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 343 LookupOrdinaryName; 344 LookupResult Result(*this, &II, NameLoc, Kind); 345 if (LookupCtx) { 346 // Perform "qualified" name lookup into the declaration context we 347 // computed, which is either the type of the base of a member access 348 // expression or the declaration context associated with a prior 349 // nested-name-specifier. 350 LookupQualifiedName(Result, LookupCtx); 351 352 if (ObjectTypePtr && Result.empty()) { 353 // C++ [basic.lookup.classref]p3: 354 // If the unqualified-id is ~type-name, the type-name is looked up 355 // in the context of the entire postfix-expression. If the type T of 356 // the object expression is of a class type C, the type-name is also 357 // looked up in the scope of class C. At least one of the lookups shall 358 // find a name that refers to (possibly cv-qualified) T. 359 LookupName(Result, S); 360 } 361 } else { 362 // Perform unqualified name lookup. 363 LookupName(Result, S); 364 365 // For unqualified lookup in a class template in MSVC mode, look into 366 // dependent base classes where the primary class template is known. 367 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 368 if (ParsedType TypeInBase = 369 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 370 return TypeInBase; 371 } 372 } 373 374 NamedDecl *IIDecl = nullptr; 375 switch (Result.getResultKind()) { 376 case LookupResult::NotFound: 377 case LookupResult::NotFoundInCurrentInstantiation: 378 if (CorrectedII) { 379 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 380 AllowDeducedTemplate); 381 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 382 S, SS, CCC, CTK_ErrorRecovery); 383 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 384 TemplateTy Template; 385 bool MemberOfUnknownSpecialization; 386 UnqualifiedId TemplateName; 387 TemplateName.setIdentifier(NewII, NameLoc); 388 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 389 CXXScopeSpec NewSS, *NewSSPtr = SS; 390 if (SS && NNS) { 391 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 392 NewSSPtr = &NewSS; 393 } 394 if (Correction && (NNS || NewII != &II) && 395 // Ignore a correction to a template type as the to-be-corrected 396 // identifier is not a template (typo correction for template names 397 // is handled elsewhere). 398 !(getLangOpts().CPlusPlus && NewSSPtr && 399 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 400 Template, MemberOfUnknownSpecialization))) { 401 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 402 isClassName, HasTrailingDot, ObjectTypePtr, 403 IsCtorOrDtorName, 404 WantNontrivialTypeSourceInfo, 405 IsClassTemplateDeductionContext); 406 if (Ty) { 407 diagnoseTypo(Correction, 408 PDiag(diag::err_unknown_type_or_class_name_suggest) 409 << Result.getLookupName() << isClassName); 410 if (SS && NNS) 411 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 412 *CorrectedII = NewII; 413 return Ty; 414 } 415 } 416 } 417 // If typo correction failed or was not performed, fall through 418 LLVM_FALLTHROUGH; 419 case LookupResult::FoundOverloaded: 420 case LookupResult::FoundUnresolvedValue: 421 Result.suppressDiagnostics(); 422 return nullptr; 423 424 case LookupResult::Ambiguous: 425 // Recover from type-hiding ambiguities by hiding the type. We'll 426 // do the lookup again when looking for an object, and we can 427 // diagnose the error then. If we don't do this, then the error 428 // about hiding the type will be immediately followed by an error 429 // that only makes sense if the identifier was treated like a type. 430 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 431 Result.suppressDiagnostics(); 432 return nullptr; 433 } 434 435 // Look to see if we have a type anywhere in the list of results. 436 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 437 Res != ResEnd; ++Res) { 438 NamedDecl *RealRes = (*Res)->getUnderlyingDecl(); 439 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>( 440 RealRes) || 441 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) { 442 if (!IIDecl || 443 // Make the selection of the recovery decl deterministic. 444 RealRes->getLocation() < IIDecl->getLocation()) 445 IIDecl = RealRes; 446 } 447 } 448 449 if (!IIDecl) { 450 // None of the entities we found is a type, so there is no way 451 // to even assume that the result is a type. In this case, don't 452 // complain about the ambiguity. The parser will either try to 453 // perform this lookup again (e.g., as an object name), which 454 // will produce the ambiguity, or will complain that it expected 455 // a type name. 456 Result.suppressDiagnostics(); 457 return nullptr; 458 } 459 460 // We found a type within the ambiguous lookup; diagnose the 461 // ambiguity and then return that type. This might be the right 462 // answer, or it might not be, but it suppresses any attempt to 463 // perform the name lookup again. 464 break; 465 466 case LookupResult::Found: 467 IIDecl = Result.getFoundDecl(); 468 break; 469 } 470 471 assert(IIDecl && "Didn't find decl"); 472 473 QualType T; 474 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 475 // C++ [class.qual]p2: A lookup that would find the injected-class-name 476 // instead names the constructors of the class, except when naming a class. 477 // This is ill-formed when we're not actually forming a ctor or dtor name. 478 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 479 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 480 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 481 FoundRD->isInjectedClassName() && 482 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 483 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 484 << &II << /*Type*/1; 485 486 DiagnoseUseOfDecl(IIDecl, NameLoc); 487 488 T = Context.getTypeDeclType(TD); 489 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 490 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 491 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 492 if (!HasTrailingDot) 493 T = Context.getObjCInterfaceType(IDecl); 494 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) { 495 (void)DiagnoseUseOfDecl(UD, NameLoc); 496 // Recover with 'int' 497 T = Context.IntTy; 498 } else if (AllowDeducedTemplate) { 499 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 500 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 501 QualType(), false); 502 } 503 504 if (T.isNull()) { 505 // If it's not plausibly a type, suppress diagnostics. 506 Result.suppressDiagnostics(); 507 return nullptr; 508 } 509 510 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 511 // constructor or destructor name (in such a case, the scope specifier 512 // will be attached to the enclosing Expr or Decl node). 513 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 514 !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) { 515 if (WantNontrivialTypeSourceInfo) { 516 // Construct a type with type-source information. 517 TypeLocBuilder Builder; 518 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 519 520 T = getElaboratedType(ETK_None, *SS, T); 521 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 522 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 523 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 524 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 525 } else { 526 T = getElaboratedType(ETK_None, *SS, T); 527 } 528 } 529 530 return ParsedType::make(T); 531 } 532 533 // Builds a fake NNS for the given decl context. 534 static NestedNameSpecifier * 535 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 536 for (;; DC = DC->getLookupParent()) { 537 DC = DC->getPrimaryContext(); 538 auto *ND = dyn_cast<NamespaceDecl>(DC); 539 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 540 return NestedNameSpecifier::Create(Context, nullptr, ND); 541 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 542 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 543 RD->getTypeForDecl()); 544 else if (isa<TranslationUnitDecl>(DC)) 545 return NestedNameSpecifier::GlobalSpecifier(Context); 546 } 547 llvm_unreachable("something isn't in TU scope?"); 548 } 549 550 /// Find the parent class with dependent bases of the innermost enclosing method 551 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 552 /// up allowing unqualified dependent type names at class-level, which MSVC 553 /// correctly rejects. 554 static const CXXRecordDecl * 555 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 556 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 557 DC = DC->getPrimaryContext(); 558 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 559 if (MD->getParent()->hasAnyDependentBases()) 560 return MD->getParent(); 561 } 562 return nullptr; 563 } 564 565 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 566 SourceLocation NameLoc, 567 bool IsTemplateTypeArg) { 568 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 569 570 NestedNameSpecifier *NNS = nullptr; 571 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 572 // If we weren't able to parse a default template argument, delay lookup 573 // until instantiation time by making a non-dependent DependentTypeName. We 574 // pretend we saw a NestedNameSpecifier referring to the current scope, and 575 // lookup is retried. 576 // FIXME: This hurts our diagnostic quality, since we get errors like "no 577 // type named 'Foo' in 'current_namespace'" when the user didn't write any 578 // name specifiers. 579 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 580 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 581 } else if (const CXXRecordDecl *RD = 582 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 583 // Build a DependentNameType that will perform lookup into RD at 584 // instantiation time. 585 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 586 RD->getTypeForDecl()); 587 588 // Diagnose that this identifier was undeclared, and retry the lookup during 589 // template instantiation. 590 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 591 << RD; 592 } else { 593 // This is not a situation that we should recover from. 594 return ParsedType(); 595 } 596 597 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 598 599 // Build type location information. We synthesized the qualifier, so we have 600 // to build a fake NestedNameSpecifierLoc. 601 NestedNameSpecifierLocBuilder NNSLocBuilder; 602 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 603 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 604 605 TypeLocBuilder Builder; 606 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 607 DepTL.setNameLoc(NameLoc); 608 DepTL.setElaboratedKeywordLoc(SourceLocation()); 609 DepTL.setQualifierLoc(QualifierLoc); 610 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 611 } 612 613 /// isTagName() - This method is called *for error recovery purposes only* 614 /// to determine if the specified name is a valid tag name ("struct foo"). If 615 /// so, this returns the TST for the tag corresponding to it (TST_enum, 616 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 617 /// cases in C where the user forgot to specify the tag. 618 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 619 // Do a tag name lookup in this scope. 620 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 621 LookupName(R, S, false); 622 R.suppressDiagnostics(); 623 if (R.getResultKind() == LookupResult::Found) 624 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 625 switch (TD->getTagKind()) { 626 case TTK_Struct: return DeclSpec::TST_struct; 627 case TTK_Interface: return DeclSpec::TST_interface; 628 case TTK_Union: return DeclSpec::TST_union; 629 case TTK_Class: return DeclSpec::TST_class; 630 case TTK_Enum: return DeclSpec::TST_enum; 631 } 632 } 633 634 return DeclSpec::TST_unspecified; 635 } 636 637 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 638 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 639 /// then downgrade the missing typename error to a warning. 640 /// This is needed for MSVC compatibility; Example: 641 /// @code 642 /// template<class T> class A { 643 /// public: 644 /// typedef int TYPE; 645 /// }; 646 /// template<class T> class B : public A<T> { 647 /// public: 648 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 649 /// }; 650 /// @endcode 651 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 652 if (CurContext->isRecord()) { 653 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 654 return true; 655 656 const Type *Ty = SS->getScopeRep()->getAsType(); 657 658 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 659 for (const auto &Base : RD->bases()) 660 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 661 return true; 662 return S->isFunctionPrototypeScope(); 663 } 664 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 665 } 666 667 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 668 SourceLocation IILoc, 669 Scope *S, 670 CXXScopeSpec *SS, 671 ParsedType &SuggestedType, 672 bool IsTemplateName) { 673 // Don't report typename errors for editor placeholders. 674 if (II->isEditorPlaceholder()) 675 return; 676 // We don't have anything to suggest (yet). 677 SuggestedType = nullptr; 678 679 // There may have been a typo in the name of the type. Look up typo 680 // results, in case we have something that we can suggest. 681 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 682 /*AllowTemplates=*/IsTemplateName, 683 /*AllowNonTemplates=*/!IsTemplateName); 684 if (TypoCorrection Corrected = 685 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 686 CCC, CTK_ErrorRecovery)) { 687 // FIXME: Support error recovery for the template-name case. 688 bool CanRecover = !IsTemplateName; 689 if (Corrected.isKeyword()) { 690 // We corrected to a keyword. 691 diagnoseTypo(Corrected, 692 PDiag(IsTemplateName ? diag::err_no_template_suggest 693 : diag::err_unknown_typename_suggest) 694 << II); 695 II = Corrected.getCorrectionAsIdentifierInfo(); 696 } else { 697 // We found a similarly-named type or interface; suggest that. 698 if (!SS || !SS->isSet()) { 699 diagnoseTypo(Corrected, 700 PDiag(IsTemplateName ? diag::err_no_template_suggest 701 : diag::err_unknown_typename_suggest) 702 << II, CanRecover); 703 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 704 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 705 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 706 II->getName().equals(CorrectedStr); 707 diagnoseTypo(Corrected, 708 PDiag(IsTemplateName 709 ? diag::err_no_member_template_suggest 710 : diag::err_unknown_nested_typename_suggest) 711 << II << DC << DroppedSpecifier << SS->getRange(), 712 CanRecover); 713 } else { 714 llvm_unreachable("could not have corrected a typo here"); 715 } 716 717 if (!CanRecover) 718 return; 719 720 CXXScopeSpec tmpSS; 721 if (Corrected.getCorrectionSpecifier()) 722 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 723 SourceRange(IILoc)); 724 // FIXME: Support class template argument deduction here. 725 SuggestedType = 726 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 727 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 728 /*IsCtorOrDtorName=*/false, 729 /*WantNontrivialTypeSourceInfo=*/true); 730 } 731 return; 732 } 733 734 if (getLangOpts().CPlusPlus && !IsTemplateName) { 735 // See if II is a class template that the user forgot to pass arguments to. 736 UnqualifiedId Name; 737 Name.setIdentifier(II, IILoc); 738 CXXScopeSpec EmptySS; 739 TemplateTy TemplateResult; 740 bool MemberOfUnknownSpecialization; 741 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 742 Name, nullptr, true, TemplateResult, 743 MemberOfUnknownSpecialization) == TNK_Type_template) { 744 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 745 return; 746 } 747 } 748 749 // FIXME: Should we move the logic that tries to recover from a missing tag 750 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 751 752 if (!SS || (!SS->isSet() && !SS->isInvalid())) 753 Diag(IILoc, IsTemplateName ? diag::err_no_template 754 : diag::err_unknown_typename) 755 << II; 756 else if (DeclContext *DC = computeDeclContext(*SS, false)) 757 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 758 : diag::err_typename_nested_not_found) 759 << II << DC << SS->getRange(); 760 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { 761 SuggestedType = 762 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); 763 } else if (isDependentScopeSpecifier(*SS)) { 764 unsigned DiagID = diag::err_typename_missing; 765 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 766 DiagID = diag::ext_typename_missing; 767 768 Diag(SS->getRange().getBegin(), DiagID) 769 << SS->getScopeRep() << II->getName() 770 << SourceRange(SS->getRange().getBegin(), IILoc) 771 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 772 SuggestedType = ActOnTypenameType(S, SourceLocation(), 773 *SS, *II, IILoc).get(); 774 } else { 775 assert(SS && SS->isInvalid() && 776 "Invalid scope specifier has already been diagnosed"); 777 } 778 } 779 780 /// Determine whether the given result set contains either a type name 781 /// or 782 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 783 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 784 NextToken.is(tok::less); 785 786 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 787 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 788 return true; 789 790 if (CheckTemplate && isa<TemplateDecl>(*I)) 791 return true; 792 } 793 794 return false; 795 } 796 797 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 798 Scope *S, CXXScopeSpec &SS, 799 IdentifierInfo *&Name, 800 SourceLocation NameLoc) { 801 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 802 SemaRef.LookupParsedName(R, S, &SS); 803 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 804 StringRef FixItTagName; 805 switch (Tag->getTagKind()) { 806 case TTK_Class: 807 FixItTagName = "class "; 808 break; 809 810 case TTK_Enum: 811 FixItTagName = "enum "; 812 break; 813 814 case TTK_Struct: 815 FixItTagName = "struct "; 816 break; 817 818 case TTK_Interface: 819 FixItTagName = "__interface "; 820 break; 821 822 case TTK_Union: 823 FixItTagName = "union "; 824 break; 825 } 826 827 StringRef TagName = FixItTagName.drop_back(); 828 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 829 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 830 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 831 832 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 833 I != IEnd; ++I) 834 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 835 << Name << TagName; 836 837 // Replace lookup results with just the tag decl. 838 Result.clear(Sema::LookupTagName); 839 SemaRef.LookupParsedName(Result, S, &SS); 840 return true; 841 } 842 843 return false; 844 } 845 846 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 847 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 848 QualType T, SourceLocation NameLoc) { 849 ASTContext &Context = S.Context; 850 851 TypeLocBuilder Builder; 852 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 853 854 T = S.getElaboratedType(ETK_None, SS, T); 855 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 856 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 857 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 858 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 859 } 860 861 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 862 IdentifierInfo *&Name, 863 SourceLocation NameLoc, 864 const Token &NextToken, 865 CorrectionCandidateCallback *CCC) { 866 DeclarationNameInfo NameInfo(Name, NameLoc); 867 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 868 869 assert(NextToken.isNot(tok::coloncolon) && 870 "parse nested name specifiers before calling ClassifyName"); 871 if (getLangOpts().CPlusPlus && SS.isSet() && 872 isCurrentClassName(*Name, S, &SS)) { 873 // Per [class.qual]p2, this names the constructors of SS, not the 874 // injected-class-name. We don't have a classification for that. 875 // There's not much point caching this result, since the parser 876 // will reject it later. 877 return NameClassification::Unknown(); 878 } 879 880 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 881 LookupParsedName(Result, S, &SS, !CurMethod); 882 883 if (SS.isInvalid()) 884 return NameClassification::Error(); 885 886 // For unqualified lookup in a class template in MSVC mode, look into 887 // dependent base classes where the primary class template is known. 888 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 889 if (ParsedType TypeInBase = 890 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 891 return TypeInBase; 892 } 893 894 // Perform lookup for Objective-C instance variables (including automatically 895 // synthesized instance variables), if we're in an Objective-C method. 896 // FIXME: This lookup really, really needs to be folded in to the normal 897 // unqualified lookup mechanism. 898 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 899 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 900 if (Ivar.isInvalid()) 901 return NameClassification::Error(); 902 if (Ivar.isUsable()) 903 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 904 905 // We defer builtin creation until after ivar lookup inside ObjC methods. 906 if (Result.empty()) 907 LookupBuiltin(Result); 908 } 909 910 bool SecondTry = false; 911 bool IsFilteredTemplateName = false; 912 913 Corrected: 914 switch (Result.getResultKind()) { 915 case LookupResult::NotFound: 916 // If an unqualified-id is followed by a '(', then we have a function 917 // call. 918 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 919 // In C++, this is an ADL-only call. 920 // FIXME: Reference? 921 if (getLangOpts().CPlusPlus) 922 return NameClassification::UndeclaredNonType(); 923 924 // C90 6.3.2.2: 925 // If the expression that precedes the parenthesized argument list in a 926 // function call consists solely of an identifier, and if no 927 // declaration is visible for this identifier, the identifier is 928 // implicitly declared exactly as if, in the innermost block containing 929 // the function call, the declaration 930 // 931 // extern int identifier (); 932 // 933 // appeared. 934 // 935 // We also allow this in C99 as an extension. 936 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 937 return NameClassification::NonType(D); 938 } 939 940 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 941 // In C++20 onwards, this could be an ADL-only call to a function 942 // template, and we're required to assume that this is a template name. 943 // 944 // FIXME: Find a way to still do typo correction in this case. 945 TemplateName Template = 946 Context.getAssumedTemplateName(NameInfo.getName()); 947 return NameClassification::UndeclaredTemplate(Template); 948 } 949 950 // In C, we first see whether there is a tag type by the same name, in 951 // which case it's likely that the user just forgot to write "enum", 952 // "struct", or "union". 953 if (!getLangOpts().CPlusPlus && !SecondTry && 954 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 955 break; 956 } 957 958 // Perform typo correction to determine if there is another name that is 959 // close to this name. 960 if (!SecondTry && CCC) { 961 SecondTry = true; 962 if (TypoCorrection Corrected = 963 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 964 &SS, *CCC, CTK_ErrorRecovery)) { 965 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 966 unsigned QualifiedDiag = diag::err_no_member_suggest; 967 968 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 969 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 970 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 971 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 972 UnqualifiedDiag = diag::err_no_template_suggest; 973 QualifiedDiag = diag::err_no_member_template_suggest; 974 } else if (UnderlyingFirstDecl && 975 (isa<TypeDecl>(UnderlyingFirstDecl) || 976 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 977 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 978 UnqualifiedDiag = diag::err_unknown_typename_suggest; 979 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 980 } 981 982 if (SS.isEmpty()) { 983 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 984 } else {// FIXME: is this even reachable? Test it. 985 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 986 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 987 Name->getName().equals(CorrectedStr); 988 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 989 << Name << computeDeclContext(SS, false) 990 << DroppedSpecifier << SS.getRange()); 991 } 992 993 // Update the name, so that the caller has the new name. 994 Name = Corrected.getCorrectionAsIdentifierInfo(); 995 996 // Typo correction corrected to a keyword. 997 if (Corrected.isKeyword()) 998 return Name; 999 1000 // Also update the LookupResult... 1001 // FIXME: This should probably go away at some point 1002 Result.clear(); 1003 Result.setLookupName(Corrected.getCorrection()); 1004 if (FirstDecl) 1005 Result.addDecl(FirstDecl); 1006 1007 // If we found an Objective-C instance variable, let 1008 // LookupInObjCMethod build the appropriate expression to 1009 // reference the ivar. 1010 // FIXME: This is a gross hack. 1011 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1012 DeclResult R = 1013 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1014 if (R.isInvalid()) 1015 return NameClassification::Error(); 1016 if (R.isUsable()) 1017 return NameClassification::NonType(Ivar); 1018 } 1019 1020 goto Corrected; 1021 } 1022 } 1023 1024 // We failed to correct; just fall through and let the parser deal with it. 1025 Result.suppressDiagnostics(); 1026 return NameClassification::Unknown(); 1027 1028 case LookupResult::NotFoundInCurrentInstantiation: { 1029 // We performed name lookup into the current instantiation, and there were 1030 // dependent bases, so we treat this result the same way as any other 1031 // dependent nested-name-specifier. 1032 1033 // C++ [temp.res]p2: 1034 // A name used in a template declaration or definition and that is 1035 // dependent on a template-parameter is assumed not to name a type 1036 // unless the applicable name lookup finds a type name or the name is 1037 // qualified by the keyword typename. 1038 // 1039 // FIXME: If the next token is '<', we might want to ask the parser to 1040 // perform some heroics to see if we actually have a 1041 // template-argument-list, which would indicate a missing 'template' 1042 // keyword here. 1043 return NameClassification::DependentNonType(); 1044 } 1045 1046 case LookupResult::Found: 1047 case LookupResult::FoundOverloaded: 1048 case LookupResult::FoundUnresolvedValue: 1049 break; 1050 1051 case LookupResult::Ambiguous: 1052 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1053 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1054 /*AllowDependent=*/false)) { 1055 // C++ [temp.local]p3: 1056 // A lookup that finds an injected-class-name (10.2) can result in an 1057 // ambiguity in certain cases (for example, if it is found in more than 1058 // one base class). If all of the injected-class-names that are found 1059 // refer to specializations of the same class template, and if the name 1060 // is followed by a template-argument-list, the reference refers to the 1061 // class template itself and not a specialization thereof, and is not 1062 // ambiguous. 1063 // 1064 // This filtering can make an ambiguous result into an unambiguous one, 1065 // so try again after filtering out template names. 1066 FilterAcceptableTemplateNames(Result); 1067 if (!Result.isAmbiguous()) { 1068 IsFilteredTemplateName = true; 1069 break; 1070 } 1071 } 1072 1073 // Diagnose the ambiguity and return an error. 1074 return NameClassification::Error(); 1075 } 1076 1077 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1078 (IsFilteredTemplateName || 1079 hasAnyAcceptableTemplateNames( 1080 Result, /*AllowFunctionTemplates=*/true, 1081 /*AllowDependent=*/false, 1082 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1083 getLangOpts().CPlusPlus20))) { 1084 // C++ [temp.names]p3: 1085 // After name lookup (3.4) finds that a name is a template-name or that 1086 // an operator-function-id or a literal- operator-id refers to a set of 1087 // overloaded functions any member of which is a function template if 1088 // this is followed by a <, the < is always taken as the delimiter of a 1089 // template-argument-list and never as the less-than operator. 1090 // C++2a [temp.names]p2: 1091 // A name is also considered to refer to a template if it is an 1092 // unqualified-id followed by a < and name lookup finds either one 1093 // or more functions or finds nothing. 1094 if (!IsFilteredTemplateName) 1095 FilterAcceptableTemplateNames(Result); 1096 1097 bool IsFunctionTemplate; 1098 bool IsVarTemplate; 1099 TemplateName Template; 1100 if (Result.end() - Result.begin() > 1) { 1101 IsFunctionTemplate = true; 1102 Template = Context.getOverloadedTemplateName(Result.begin(), 1103 Result.end()); 1104 } else if (!Result.empty()) { 1105 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1106 *Result.begin(), /*AllowFunctionTemplates=*/true, 1107 /*AllowDependent=*/false)); 1108 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1109 IsVarTemplate = isa<VarTemplateDecl>(TD); 1110 1111 if (SS.isNotEmpty()) 1112 Template = 1113 Context.getQualifiedTemplateName(SS.getScopeRep(), 1114 /*TemplateKeyword=*/false, TD); 1115 else 1116 Template = TemplateName(TD); 1117 } else { 1118 // All results were non-template functions. This is a function template 1119 // name. 1120 IsFunctionTemplate = true; 1121 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1122 } 1123 1124 if (IsFunctionTemplate) { 1125 // Function templates always go through overload resolution, at which 1126 // point we'll perform the various checks (e.g., accessibility) we need 1127 // to based on which function we selected. 1128 Result.suppressDiagnostics(); 1129 1130 return NameClassification::FunctionTemplate(Template); 1131 } 1132 1133 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1134 : NameClassification::TypeTemplate(Template); 1135 } 1136 1137 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1138 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1139 DiagnoseUseOfDecl(Type, NameLoc); 1140 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1141 QualType T = Context.getTypeDeclType(Type); 1142 if (SS.isNotEmpty()) 1143 return buildNestedType(*this, SS, T, NameLoc); 1144 return ParsedType::make(T); 1145 } 1146 1147 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1148 if (!Class) { 1149 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1150 if (ObjCCompatibleAliasDecl *Alias = 1151 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1152 Class = Alias->getClassInterface(); 1153 } 1154 1155 if (Class) { 1156 DiagnoseUseOfDecl(Class, NameLoc); 1157 1158 if (NextToken.is(tok::period)) { 1159 // Interface. <something> is parsed as a property reference expression. 1160 // Just return "unknown" as a fall-through for now. 1161 Result.suppressDiagnostics(); 1162 return NameClassification::Unknown(); 1163 } 1164 1165 QualType T = Context.getObjCInterfaceType(Class); 1166 return ParsedType::make(T); 1167 } 1168 1169 if (isa<ConceptDecl>(FirstDecl)) 1170 return NameClassification::Concept( 1171 TemplateName(cast<TemplateDecl>(FirstDecl))); 1172 1173 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) { 1174 (void)DiagnoseUseOfDecl(EmptyD, NameLoc); 1175 return NameClassification::Error(); 1176 } 1177 1178 // We can have a type template here if we're classifying a template argument. 1179 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1180 !isa<VarTemplateDecl>(FirstDecl)) 1181 return NameClassification::TypeTemplate( 1182 TemplateName(cast<TemplateDecl>(FirstDecl))); 1183 1184 // Check for a tag type hidden by a non-type decl in a few cases where it 1185 // seems likely a type is wanted instead of the non-type that was found. 1186 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1187 if ((NextToken.is(tok::identifier) || 1188 (NextIsOp && 1189 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1190 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1191 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1192 DiagnoseUseOfDecl(Type, NameLoc); 1193 QualType T = Context.getTypeDeclType(Type); 1194 if (SS.isNotEmpty()) 1195 return buildNestedType(*this, SS, T, NameLoc); 1196 return ParsedType::make(T); 1197 } 1198 1199 // If we already know which single declaration is referenced, just annotate 1200 // that declaration directly. Defer resolving even non-overloaded class 1201 // member accesses, as we need to defer certain access checks until we know 1202 // the context. 1203 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1204 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember()) 1205 return NameClassification::NonType(Result.getRepresentativeDecl()); 1206 1207 // Otherwise, this is an overload set that we will need to resolve later. 1208 Result.suppressDiagnostics(); 1209 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( 1210 Context, Result.getNamingClass(), SS.getWithLocInContext(Context), 1211 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), 1212 Result.begin(), Result.end())); 1213 } 1214 1215 ExprResult 1216 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1217 SourceLocation NameLoc) { 1218 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1219 CXXScopeSpec SS; 1220 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1221 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1222 } 1223 1224 ExprResult 1225 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1226 IdentifierInfo *Name, 1227 SourceLocation NameLoc, 1228 bool IsAddressOfOperand) { 1229 DeclarationNameInfo NameInfo(Name, NameLoc); 1230 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1231 NameInfo, IsAddressOfOperand, 1232 /*TemplateArgs=*/nullptr); 1233 } 1234 1235 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1236 NamedDecl *Found, 1237 SourceLocation NameLoc, 1238 const Token &NextToken) { 1239 if (getCurMethodDecl() && SS.isEmpty()) 1240 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1241 return BuildIvarRefExpr(S, NameLoc, Ivar); 1242 1243 // Reconstruct the lookup result. 1244 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1245 Result.addDecl(Found); 1246 Result.resolveKind(); 1247 1248 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1249 return BuildDeclarationNameExpr(SS, Result, ADL); 1250 } 1251 1252 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { 1253 // For an implicit class member access, transform the result into a member 1254 // access expression if necessary. 1255 auto *ULE = cast<UnresolvedLookupExpr>(E); 1256 if ((*ULE->decls_begin())->isCXXClassMember()) { 1257 CXXScopeSpec SS; 1258 SS.Adopt(ULE->getQualifierLoc()); 1259 1260 // Reconstruct the lookup result. 1261 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), 1262 LookupOrdinaryName); 1263 Result.setNamingClass(ULE->getNamingClass()); 1264 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) 1265 Result.addDecl(*I, I.getAccess()); 1266 Result.resolveKind(); 1267 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1268 nullptr, S); 1269 } 1270 1271 // Otherwise, this is already in the form we needed, and no further checks 1272 // are necessary. 1273 return ULE; 1274 } 1275 1276 Sema::TemplateNameKindForDiagnostics 1277 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1278 auto *TD = Name.getAsTemplateDecl(); 1279 if (!TD) 1280 return TemplateNameKindForDiagnostics::DependentTemplate; 1281 if (isa<ClassTemplateDecl>(TD)) 1282 return TemplateNameKindForDiagnostics::ClassTemplate; 1283 if (isa<FunctionTemplateDecl>(TD)) 1284 return TemplateNameKindForDiagnostics::FunctionTemplate; 1285 if (isa<VarTemplateDecl>(TD)) 1286 return TemplateNameKindForDiagnostics::VarTemplate; 1287 if (isa<TypeAliasTemplateDecl>(TD)) 1288 return TemplateNameKindForDiagnostics::AliasTemplate; 1289 if (isa<TemplateTemplateParmDecl>(TD)) 1290 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1291 if (isa<ConceptDecl>(TD)) 1292 return TemplateNameKindForDiagnostics::Concept; 1293 return TemplateNameKindForDiagnostics::DependentTemplate; 1294 } 1295 1296 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1297 assert(DC->getLexicalParent() == CurContext && 1298 "The next DeclContext should be lexically contained in the current one."); 1299 CurContext = DC; 1300 S->setEntity(DC); 1301 } 1302 1303 void Sema::PopDeclContext() { 1304 assert(CurContext && "DeclContext imbalance!"); 1305 1306 CurContext = CurContext->getLexicalParent(); 1307 assert(CurContext && "Popped translation unit!"); 1308 } 1309 1310 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1311 Decl *D) { 1312 // Unlike PushDeclContext, the context to which we return is not necessarily 1313 // the containing DC of TD, because the new context will be some pre-existing 1314 // TagDecl definition instead of a fresh one. 1315 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1316 CurContext = cast<TagDecl>(D)->getDefinition(); 1317 assert(CurContext && "skipping definition of undefined tag"); 1318 // Start lookups from the parent of the current context; we don't want to look 1319 // into the pre-existing complete definition. 1320 S->setEntity(CurContext->getLookupParent()); 1321 return Result; 1322 } 1323 1324 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1325 CurContext = static_cast<decltype(CurContext)>(Context); 1326 } 1327 1328 /// EnterDeclaratorContext - Used when we must lookup names in the context 1329 /// of a declarator's nested name specifier. 1330 /// 1331 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1332 // C++0x [basic.lookup.unqual]p13: 1333 // A name used in the definition of a static data member of class 1334 // X (after the qualified-id of the static member) is looked up as 1335 // if the name was used in a member function of X. 1336 // C++0x [basic.lookup.unqual]p14: 1337 // If a variable member of a namespace is defined outside of the 1338 // scope of its namespace then any name used in the definition of 1339 // the variable member (after the declarator-id) is looked up as 1340 // if the definition of the variable member occurred in its 1341 // namespace. 1342 // Both of these imply that we should push a scope whose context 1343 // is the semantic context of the declaration. We can't use 1344 // PushDeclContext here because that context is not necessarily 1345 // lexically contained in the current context. Fortunately, 1346 // the containing scope should have the appropriate information. 1347 1348 assert(!S->getEntity() && "scope already has entity"); 1349 1350 #ifndef NDEBUG 1351 Scope *Ancestor = S->getParent(); 1352 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1353 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1354 #endif 1355 1356 CurContext = DC; 1357 S->setEntity(DC); 1358 1359 if (S->getParent()->isTemplateParamScope()) { 1360 // Also set the corresponding entities for all immediately-enclosing 1361 // template parameter scopes. 1362 EnterTemplatedContext(S->getParent(), DC); 1363 } 1364 } 1365 1366 void Sema::ExitDeclaratorContext(Scope *S) { 1367 assert(S->getEntity() == CurContext && "Context imbalance!"); 1368 1369 // Switch back to the lexical context. The safety of this is 1370 // enforced by an assert in EnterDeclaratorContext. 1371 Scope *Ancestor = S->getParent(); 1372 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1373 CurContext = Ancestor->getEntity(); 1374 1375 // We don't need to do anything with the scope, which is going to 1376 // disappear. 1377 } 1378 1379 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1380 assert(S->isTemplateParamScope() && 1381 "expected to be initializing a template parameter scope"); 1382 1383 // C++20 [temp.local]p7: 1384 // In the definition of a member of a class template that appears outside 1385 // of the class template definition, the name of a member of the class 1386 // template hides the name of a template-parameter of any enclosing class 1387 // templates (but not a template-parameter of the member if the member is a 1388 // class or function template). 1389 // C++20 [temp.local]p9: 1390 // In the definition of a class template or in the definition of a member 1391 // of such a template that appears outside of the template definition, for 1392 // each non-dependent base class (13.8.2.1), if the name of the base class 1393 // or the name of a member of the base class is the same as the name of a 1394 // template-parameter, the base class name or member name hides the 1395 // template-parameter name (6.4.10). 1396 // 1397 // This means that a template parameter scope should be searched immediately 1398 // after searching the DeclContext for which it is a template parameter 1399 // scope. For example, for 1400 // template<typename T> template<typename U> template<typename V> 1401 // void N::A<T>::B<U>::f(...) 1402 // we search V then B<U> (and base classes) then U then A<T> (and base 1403 // classes) then T then N then ::. 1404 unsigned ScopeDepth = getTemplateDepth(S); 1405 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1406 DeclContext *SearchDCAfterScope = DC; 1407 for (; DC; DC = DC->getLookupParent()) { 1408 if (const TemplateParameterList *TPL = 1409 cast<Decl>(DC)->getDescribedTemplateParams()) { 1410 unsigned DCDepth = TPL->getDepth() + 1; 1411 if (DCDepth > ScopeDepth) 1412 continue; 1413 if (ScopeDepth == DCDepth) 1414 SearchDCAfterScope = DC = DC->getLookupParent(); 1415 break; 1416 } 1417 } 1418 S->setLookupEntity(SearchDCAfterScope); 1419 } 1420 } 1421 1422 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1423 // We assume that the caller has already called 1424 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1425 FunctionDecl *FD = D->getAsFunction(); 1426 if (!FD) 1427 return; 1428 1429 // Same implementation as PushDeclContext, but enters the context 1430 // from the lexical parent, rather than the top-level class. 1431 assert(CurContext == FD->getLexicalParent() && 1432 "The next DeclContext should be lexically contained in the current one."); 1433 CurContext = FD; 1434 S->setEntity(CurContext); 1435 1436 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1437 ParmVarDecl *Param = FD->getParamDecl(P); 1438 // If the parameter has an identifier, then add it to the scope 1439 if (Param->getIdentifier()) { 1440 S->AddDecl(Param); 1441 IdResolver.AddDecl(Param); 1442 } 1443 } 1444 } 1445 1446 void Sema::ActOnExitFunctionContext() { 1447 // Same implementation as PopDeclContext, but returns to the lexical parent, 1448 // rather than the top-level class. 1449 assert(CurContext && "DeclContext imbalance!"); 1450 CurContext = CurContext->getLexicalParent(); 1451 assert(CurContext && "Popped translation unit!"); 1452 } 1453 1454 /// Determine whether we allow overloading of the function 1455 /// PrevDecl with another declaration. 1456 /// 1457 /// This routine determines whether overloading is possible, not 1458 /// whether some new function is actually an overload. It will return 1459 /// true in C++ (where we can always provide overloads) or, as an 1460 /// extension, in C when the previous function is already an 1461 /// overloaded function declaration or has the "overloadable" 1462 /// attribute. 1463 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1464 ASTContext &Context, 1465 const FunctionDecl *New) { 1466 if (Context.getLangOpts().CPlusPlus) 1467 return true; 1468 1469 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1470 return true; 1471 1472 return Previous.getResultKind() == LookupResult::Found && 1473 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1474 New->hasAttr<OverloadableAttr>()); 1475 } 1476 1477 /// Add this decl to the scope shadowed decl chains. 1478 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1479 // Move up the scope chain until we find the nearest enclosing 1480 // non-transparent context. The declaration will be introduced into this 1481 // scope. 1482 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1483 S = S->getParent(); 1484 1485 // Add scoped declarations into their context, so that they can be 1486 // found later. Declarations without a context won't be inserted 1487 // into any context. 1488 if (AddToContext) 1489 CurContext->addDecl(D); 1490 1491 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1492 // are function-local declarations. 1493 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) 1494 return; 1495 1496 // Template instantiations should also not be pushed into scope. 1497 if (isa<FunctionDecl>(D) && 1498 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1499 return; 1500 1501 // If this replaces anything in the current scope, 1502 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1503 IEnd = IdResolver.end(); 1504 for (; I != IEnd; ++I) { 1505 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1506 S->RemoveDecl(*I); 1507 IdResolver.RemoveDecl(*I); 1508 1509 // Should only need to replace one decl. 1510 break; 1511 } 1512 } 1513 1514 S->AddDecl(D); 1515 1516 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1517 // Implicitly-generated labels may end up getting generated in an order that 1518 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1519 // the label at the appropriate place in the identifier chain. 1520 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1521 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1522 if (IDC == CurContext) { 1523 if (!S->isDeclScope(*I)) 1524 continue; 1525 } else if (IDC->Encloses(CurContext)) 1526 break; 1527 } 1528 1529 IdResolver.InsertDeclAfter(I, D); 1530 } else { 1531 IdResolver.AddDecl(D); 1532 } 1533 warnOnReservedIdentifier(D); 1534 } 1535 1536 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1537 bool AllowInlineNamespace) { 1538 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1539 } 1540 1541 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1542 DeclContext *TargetDC = DC->getPrimaryContext(); 1543 do { 1544 if (DeclContext *ScopeDC = S->getEntity()) 1545 if (ScopeDC->getPrimaryContext() == TargetDC) 1546 return S; 1547 } while ((S = S->getParent())); 1548 1549 return nullptr; 1550 } 1551 1552 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1553 DeclContext*, 1554 ASTContext&); 1555 1556 /// Filters out lookup results that don't fall within the given scope 1557 /// as determined by isDeclInScope. 1558 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1559 bool ConsiderLinkage, 1560 bool AllowInlineNamespace) { 1561 LookupResult::Filter F = R.makeFilter(); 1562 while (F.hasNext()) { 1563 NamedDecl *D = F.next(); 1564 1565 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1566 continue; 1567 1568 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1569 continue; 1570 1571 F.erase(); 1572 } 1573 1574 F.done(); 1575 } 1576 1577 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1578 /// have compatible owning modules. 1579 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1580 // FIXME: The Modules TS is not clear about how friend declarations are 1581 // to be treated. It's not meaningful to have different owning modules for 1582 // linkage in redeclarations of the same entity, so for now allow the 1583 // redeclaration and change the owning modules to match. 1584 if (New->getFriendObjectKind() && 1585 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1586 New->setLocalOwningModule(Old->getOwningModule()); 1587 makeMergedDefinitionVisible(New); 1588 return false; 1589 } 1590 1591 Module *NewM = New->getOwningModule(); 1592 Module *OldM = Old->getOwningModule(); 1593 1594 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1595 NewM = NewM->Parent; 1596 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1597 OldM = OldM->Parent; 1598 1599 if (NewM == OldM) 1600 return false; 1601 1602 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1603 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1604 if (NewIsModuleInterface || OldIsModuleInterface) { 1605 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1606 // if a declaration of D [...] appears in the purview of a module, all 1607 // other such declarations shall appear in the purview of the same module 1608 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1609 << New 1610 << NewIsModuleInterface 1611 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1612 << OldIsModuleInterface 1613 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1614 Diag(Old->getLocation(), diag::note_previous_declaration); 1615 New->setInvalidDecl(); 1616 return true; 1617 } 1618 1619 return false; 1620 } 1621 1622 static bool isUsingDecl(NamedDecl *D) { 1623 return isa<UsingShadowDecl>(D) || 1624 isa<UnresolvedUsingTypenameDecl>(D) || 1625 isa<UnresolvedUsingValueDecl>(D); 1626 } 1627 1628 /// Removes using shadow declarations from the lookup results. 1629 static void RemoveUsingDecls(LookupResult &R) { 1630 LookupResult::Filter F = R.makeFilter(); 1631 while (F.hasNext()) 1632 if (isUsingDecl(F.next())) 1633 F.erase(); 1634 1635 F.done(); 1636 } 1637 1638 /// Check for this common pattern: 1639 /// @code 1640 /// class S { 1641 /// S(const S&); // DO NOT IMPLEMENT 1642 /// void operator=(const S&); // DO NOT IMPLEMENT 1643 /// }; 1644 /// @endcode 1645 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1646 // FIXME: Should check for private access too but access is set after we get 1647 // the decl here. 1648 if (D->doesThisDeclarationHaveABody()) 1649 return false; 1650 1651 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1652 return CD->isCopyConstructor(); 1653 return D->isCopyAssignmentOperator(); 1654 } 1655 1656 // We need this to handle 1657 // 1658 // typedef struct { 1659 // void *foo() { return 0; } 1660 // } A; 1661 // 1662 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1663 // for example. If 'A', foo will have external linkage. If we have '*A', 1664 // foo will have no linkage. Since we can't know until we get to the end 1665 // of the typedef, this function finds out if D might have non-external linkage. 1666 // Callers should verify at the end of the TU if it D has external linkage or 1667 // not. 1668 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1669 const DeclContext *DC = D->getDeclContext(); 1670 while (!DC->isTranslationUnit()) { 1671 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1672 if (!RD->hasNameForLinkage()) 1673 return true; 1674 } 1675 DC = DC->getParent(); 1676 } 1677 1678 return !D->isExternallyVisible(); 1679 } 1680 1681 // FIXME: This needs to be refactored; some other isInMainFile users want 1682 // these semantics. 1683 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1684 if (S.TUKind != TU_Complete) 1685 return false; 1686 return S.SourceMgr.isInMainFile(Loc); 1687 } 1688 1689 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1690 assert(D); 1691 1692 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1693 return false; 1694 1695 // Ignore all entities declared within templates, and out-of-line definitions 1696 // of members of class templates. 1697 if (D->getDeclContext()->isDependentContext() || 1698 D->getLexicalDeclContext()->isDependentContext()) 1699 return false; 1700 1701 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1702 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1703 return false; 1704 // A non-out-of-line declaration of a member specialization was implicitly 1705 // instantiated; it's the out-of-line declaration that we're interested in. 1706 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1707 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1708 return false; 1709 1710 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1711 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1712 return false; 1713 } else { 1714 // 'static inline' functions are defined in headers; don't warn. 1715 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1716 return false; 1717 } 1718 1719 if (FD->doesThisDeclarationHaveABody() && 1720 Context.DeclMustBeEmitted(FD)) 1721 return false; 1722 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1723 // Constants and utility variables are defined in headers with internal 1724 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1725 // like "inline".) 1726 if (!isMainFileLoc(*this, VD->getLocation())) 1727 return false; 1728 1729 if (Context.DeclMustBeEmitted(VD)) 1730 return false; 1731 1732 if (VD->isStaticDataMember() && 1733 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1734 return false; 1735 if (VD->isStaticDataMember() && 1736 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1737 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1738 return false; 1739 1740 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1741 return false; 1742 } else { 1743 return false; 1744 } 1745 1746 // Only warn for unused decls internal to the translation unit. 1747 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1748 // for inline functions defined in the main source file, for instance. 1749 return mightHaveNonExternalLinkage(D); 1750 } 1751 1752 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1753 if (!D) 1754 return; 1755 1756 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1757 const FunctionDecl *First = FD->getFirstDecl(); 1758 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1759 return; // First should already be in the vector. 1760 } 1761 1762 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1763 const VarDecl *First = VD->getFirstDecl(); 1764 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1765 return; // First should already be in the vector. 1766 } 1767 1768 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1769 UnusedFileScopedDecls.push_back(D); 1770 } 1771 1772 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1773 if (D->isInvalidDecl()) 1774 return false; 1775 1776 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1777 // For a decomposition declaration, warn if none of the bindings are 1778 // referenced, instead of if the variable itself is referenced (which 1779 // it is, by the bindings' expressions). 1780 for (auto *BD : DD->bindings()) 1781 if (BD->isReferenced()) 1782 return false; 1783 } else if (!D->getDeclName()) { 1784 return false; 1785 } else if (D->isReferenced() || D->isUsed()) { 1786 return false; 1787 } 1788 1789 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) 1790 return false; 1791 1792 if (isa<LabelDecl>(D)) 1793 return true; 1794 1795 // Except for labels, we only care about unused decls that are local to 1796 // functions. 1797 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1798 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1799 // For dependent types, the diagnostic is deferred. 1800 WithinFunction = 1801 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1802 if (!WithinFunction) 1803 return false; 1804 1805 if (isa<TypedefNameDecl>(D)) 1806 return true; 1807 1808 // White-list anything that isn't a local variable. 1809 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1810 return false; 1811 1812 // Types of valid local variables should be complete, so this should succeed. 1813 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1814 1815 // White-list anything with an __attribute__((unused)) type. 1816 const auto *Ty = VD->getType().getTypePtr(); 1817 1818 // Only look at the outermost level of typedef. 1819 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1820 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1821 return false; 1822 } 1823 1824 // If we failed to complete the type for some reason, or if the type is 1825 // dependent, don't diagnose the variable. 1826 if (Ty->isIncompleteType() || Ty->isDependentType()) 1827 return false; 1828 1829 // Look at the element type to ensure that the warning behaviour is 1830 // consistent for both scalars and arrays. 1831 Ty = Ty->getBaseElementTypeUnsafe(); 1832 1833 if (const TagType *TT = Ty->getAs<TagType>()) { 1834 const TagDecl *Tag = TT->getDecl(); 1835 if (Tag->hasAttr<UnusedAttr>()) 1836 return false; 1837 1838 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1839 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1840 return false; 1841 1842 if (const Expr *Init = VD->getInit()) { 1843 if (const ExprWithCleanups *Cleanups = 1844 dyn_cast<ExprWithCleanups>(Init)) 1845 Init = Cleanups->getSubExpr(); 1846 const CXXConstructExpr *Construct = 1847 dyn_cast<CXXConstructExpr>(Init); 1848 if (Construct && !Construct->isElidable()) { 1849 CXXConstructorDecl *CD = Construct->getConstructor(); 1850 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1851 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1852 return false; 1853 } 1854 1855 // Suppress the warning if we don't know how this is constructed, and 1856 // it could possibly be non-trivial constructor. 1857 if (Init->isTypeDependent()) 1858 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1859 if (!Ctor->isTrivial()) 1860 return false; 1861 } 1862 } 1863 } 1864 1865 // TODO: __attribute__((unused)) templates? 1866 } 1867 1868 return true; 1869 } 1870 1871 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1872 FixItHint &Hint) { 1873 if (isa<LabelDecl>(D)) { 1874 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1875 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1876 true); 1877 if (AfterColon.isInvalid()) 1878 return; 1879 Hint = FixItHint::CreateRemoval( 1880 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1881 } 1882 } 1883 1884 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1885 if (D->getTypeForDecl()->isDependentType()) 1886 return; 1887 1888 for (auto *TmpD : D->decls()) { 1889 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1890 DiagnoseUnusedDecl(T); 1891 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1892 DiagnoseUnusedNestedTypedefs(R); 1893 } 1894 } 1895 1896 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1897 /// unless they are marked attr(unused). 1898 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1899 if (!ShouldDiagnoseUnusedDecl(D)) 1900 return; 1901 1902 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1903 // typedefs can be referenced later on, so the diagnostics are emitted 1904 // at end-of-translation-unit. 1905 UnusedLocalTypedefNameCandidates.insert(TD); 1906 return; 1907 } 1908 1909 FixItHint Hint; 1910 GenerateFixForUnusedDecl(D, Context, Hint); 1911 1912 unsigned DiagID; 1913 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1914 DiagID = diag::warn_unused_exception_param; 1915 else if (isa<LabelDecl>(D)) 1916 DiagID = diag::warn_unused_label; 1917 else 1918 DiagID = diag::warn_unused_variable; 1919 1920 Diag(D->getLocation(), DiagID) << D << Hint; 1921 } 1922 1923 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) { 1924 // If it's not referenced, it can't be set. If it has the Cleanup attribute, 1925 // it's not really unused. 1926 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() || 1927 VD->hasAttr<CleanupAttr>()) 1928 return; 1929 1930 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe(); 1931 1932 if (Ty->isReferenceType() || Ty->isDependentType()) 1933 return; 1934 1935 if (const TagType *TT = Ty->getAs<TagType>()) { 1936 const TagDecl *Tag = TT->getDecl(); 1937 if (Tag->hasAttr<UnusedAttr>()) 1938 return; 1939 // In C++, don't warn for record types that don't have WarnUnusedAttr, to 1940 // mimic gcc's behavior. 1941 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1942 if (!RD->hasAttr<WarnUnusedAttr>()) 1943 return; 1944 } 1945 } 1946 1947 auto iter = RefsMinusAssignments.find(VD); 1948 if (iter == RefsMinusAssignments.end()) 1949 return; 1950 1951 assert(iter->getSecond() >= 0 && 1952 "Found a negative number of references to a VarDecl"); 1953 if (iter->getSecond() != 0) 1954 return; 1955 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter 1956 : diag::warn_unused_but_set_variable; 1957 Diag(VD->getLocation(), DiagID) << VD; 1958 } 1959 1960 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1961 // Verify that we have no forward references left. If so, there was a goto 1962 // or address of a label taken, but no definition of it. Label fwd 1963 // definitions are indicated with a null substmt which is also not a resolved 1964 // MS inline assembly label name. 1965 bool Diagnose = false; 1966 if (L->isMSAsmLabel()) 1967 Diagnose = !L->isResolvedMSAsmLabel(); 1968 else 1969 Diagnose = L->getStmt() == nullptr; 1970 if (Diagnose) 1971 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; 1972 } 1973 1974 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1975 S->mergeNRVOIntoParent(); 1976 1977 if (S->decl_empty()) return; 1978 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1979 "Scope shouldn't contain decls!"); 1980 1981 for (auto *TmpD : S->decls()) { 1982 assert(TmpD && "This decl didn't get pushed??"); 1983 1984 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1985 NamedDecl *D = cast<NamedDecl>(TmpD); 1986 1987 // Diagnose unused variables in this scope. 1988 if (!S->hasUnrecoverableErrorOccurred()) { 1989 DiagnoseUnusedDecl(D); 1990 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1991 DiagnoseUnusedNestedTypedefs(RD); 1992 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1993 DiagnoseUnusedButSetDecl(VD); 1994 RefsMinusAssignments.erase(VD); 1995 } 1996 } 1997 1998 if (!D->getDeclName()) continue; 1999 2000 // If this was a forward reference to a label, verify it was defined. 2001 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 2002 CheckPoppedLabel(LD, *this); 2003 2004 // Remove this name from our lexical scope, and warn on it if we haven't 2005 // already. 2006 IdResolver.RemoveDecl(D); 2007 auto ShadowI = ShadowingDecls.find(D); 2008 if (ShadowI != ShadowingDecls.end()) { 2009 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 2010 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 2011 << D << FD << FD->getParent(); 2012 Diag(FD->getLocation(), diag::note_previous_declaration); 2013 } 2014 ShadowingDecls.erase(ShadowI); 2015 } 2016 } 2017 } 2018 2019 /// Look for an Objective-C class in the translation unit. 2020 /// 2021 /// \param Id The name of the Objective-C class we're looking for. If 2022 /// typo-correction fixes this name, the Id will be updated 2023 /// to the fixed name. 2024 /// 2025 /// \param IdLoc The location of the name in the translation unit. 2026 /// 2027 /// \param DoTypoCorrection If true, this routine will attempt typo correction 2028 /// if there is no class with the given name. 2029 /// 2030 /// \returns The declaration of the named Objective-C class, or NULL if the 2031 /// class could not be found. 2032 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 2033 SourceLocation IdLoc, 2034 bool DoTypoCorrection) { 2035 // The third "scope" argument is 0 since we aren't enabling lazy built-in 2036 // creation from this context. 2037 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 2038 2039 if (!IDecl && DoTypoCorrection) { 2040 // Perform typo correction at the given location, but only if we 2041 // find an Objective-C class name. 2042 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 2043 if (TypoCorrection C = 2044 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 2045 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 2046 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 2047 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 2048 Id = IDecl->getIdentifier(); 2049 } 2050 } 2051 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 2052 // This routine must always return a class definition, if any. 2053 if (Def && Def->getDefinition()) 2054 Def = Def->getDefinition(); 2055 return Def; 2056 } 2057 2058 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2059 /// from S, where a non-field would be declared. This routine copes 2060 /// with the difference between C and C++ scoping rules in structs and 2061 /// unions. For example, the following code is well-formed in C but 2062 /// ill-formed in C++: 2063 /// @code 2064 /// struct S6 { 2065 /// enum { BAR } e; 2066 /// }; 2067 /// 2068 /// void test_S6() { 2069 /// struct S6 a; 2070 /// a.e = BAR; 2071 /// } 2072 /// @endcode 2073 /// For the declaration of BAR, this routine will return a different 2074 /// scope. The scope S will be the scope of the unnamed enumeration 2075 /// within S6. In C++, this routine will return the scope associated 2076 /// with S6, because the enumeration's scope is a transparent 2077 /// context but structures can contain non-field names. In C, this 2078 /// routine will return the translation unit scope, since the 2079 /// enumeration's scope is a transparent context and structures cannot 2080 /// contain non-field names. 2081 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2082 while (((S->getFlags() & Scope::DeclScope) == 0) || 2083 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2084 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2085 S = S->getParent(); 2086 return S; 2087 } 2088 2089 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2090 ASTContext::GetBuiltinTypeError Error) { 2091 switch (Error) { 2092 case ASTContext::GE_None: 2093 return ""; 2094 case ASTContext::GE_Missing_type: 2095 return BuiltinInfo.getHeaderName(ID); 2096 case ASTContext::GE_Missing_stdio: 2097 return "stdio.h"; 2098 case ASTContext::GE_Missing_setjmp: 2099 return "setjmp.h"; 2100 case ASTContext::GE_Missing_ucontext: 2101 return "ucontext.h"; 2102 } 2103 llvm_unreachable("unhandled error kind"); 2104 } 2105 2106 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2107 unsigned ID, SourceLocation Loc) { 2108 DeclContext *Parent = Context.getTranslationUnitDecl(); 2109 2110 if (getLangOpts().CPlusPlus) { 2111 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2112 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); 2113 CLinkageDecl->setImplicit(); 2114 Parent->addDecl(CLinkageDecl); 2115 Parent = CLinkageDecl; 2116 } 2117 2118 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2119 /*TInfo=*/nullptr, SC_Extern, 2120 getCurFPFeatures().isFPConstrained(), 2121 false, Type->isFunctionProtoType()); 2122 New->setImplicit(); 2123 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2124 2125 // Create Decl objects for each parameter, adding them to the 2126 // FunctionDecl. 2127 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2128 SmallVector<ParmVarDecl *, 16> Params; 2129 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2130 ParmVarDecl *parm = ParmVarDecl::Create( 2131 Context, New, SourceLocation(), SourceLocation(), nullptr, 2132 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2133 parm->setScopeInfo(0, i); 2134 Params.push_back(parm); 2135 } 2136 New->setParams(Params); 2137 } 2138 2139 AddKnownFunctionAttributes(New); 2140 return New; 2141 } 2142 2143 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2144 /// file scope. lazily create a decl for it. ForRedeclaration is true 2145 /// if we're creating this built-in in anticipation of redeclaring the 2146 /// built-in. 2147 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2148 Scope *S, bool ForRedeclaration, 2149 SourceLocation Loc) { 2150 LookupNecessaryTypesForBuiltin(S, ID); 2151 2152 ASTContext::GetBuiltinTypeError Error; 2153 QualType R = Context.GetBuiltinType(ID, Error); 2154 if (Error) { 2155 if (!ForRedeclaration) 2156 return nullptr; 2157 2158 // If we have a builtin without an associated type we should not emit a 2159 // warning when we were not able to find a type for it. 2160 if (Error == ASTContext::GE_Missing_type || 2161 Context.BuiltinInfo.allowTypeMismatch(ID)) 2162 return nullptr; 2163 2164 // If we could not find a type for setjmp it is because the jmp_buf type was 2165 // not defined prior to the setjmp declaration. 2166 if (Error == ASTContext::GE_Missing_setjmp) { 2167 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2168 << Context.BuiltinInfo.getName(ID); 2169 return nullptr; 2170 } 2171 2172 // Generally, we emit a warning that the declaration requires the 2173 // appropriate header. 2174 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2175 << getHeaderName(Context.BuiltinInfo, ID, Error) 2176 << Context.BuiltinInfo.getName(ID); 2177 return nullptr; 2178 } 2179 2180 if (!ForRedeclaration && 2181 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2182 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2183 Diag(Loc, diag::ext_implicit_lib_function_decl) 2184 << Context.BuiltinInfo.getName(ID) << R; 2185 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2186 Diag(Loc, diag::note_include_header_or_declare) 2187 << Header << Context.BuiltinInfo.getName(ID); 2188 } 2189 2190 if (R.isNull()) 2191 return nullptr; 2192 2193 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2194 RegisterLocallyScopedExternCDecl(New, S); 2195 2196 // TUScope is the translation-unit scope to insert this function into. 2197 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2198 // relate Scopes to DeclContexts, and probably eliminate CurContext 2199 // entirely, but we're not there yet. 2200 DeclContext *SavedContext = CurContext; 2201 CurContext = New->getDeclContext(); 2202 PushOnScopeChains(New, TUScope); 2203 CurContext = SavedContext; 2204 return New; 2205 } 2206 2207 /// Typedef declarations don't have linkage, but they still denote the same 2208 /// entity if their types are the same. 2209 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2210 /// isSameEntity. 2211 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2212 TypedefNameDecl *Decl, 2213 LookupResult &Previous) { 2214 // This is only interesting when modules are enabled. 2215 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2216 return; 2217 2218 // Empty sets are uninteresting. 2219 if (Previous.empty()) 2220 return; 2221 2222 LookupResult::Filter Filter = Previous.makeFilter(); 2223 while (Filter.hasNext()) { 2224 NamedDecl *Old = Filter.next(); 2225 2226 // Non-hidden declarations are never ignored. 2227 if (S.isVisible(Old)) 2228 continue; 2229 2230 // Declarations of the same entity are not ignored, even if they have 2231 // different linkages. 2232 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2233 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2234 Decl->getUnderlyingType())) 2235 continue; 2236 2237 // If both declarations give a tag declaration a typedef name for linkage 2238 // purposes, then they declare the same entity. 2239 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2240 Decl->getAnonDeclWithTypedefName()) 2241 continue; 2242 } 2243 2244 Filter.erase(); 2245 } 2246 2247 Filter.done(); 2248 } 2249 2250 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2251 QualType OldType; 2252 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2253 OldType = OldTypedef->getUnderlyingType(); 2254 else 2255 OldType = Context.getTypeDeclType(Old); 2256 QualType NewType = New->getUnderlyingType(); 2257 2258 if (NewType->isVariablyModifiedType()) { 2259 // Must not redefine a typedef with a variably-modified type. 2260 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2261 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2262 << Kind << NewType; 2263 if (Old->getLocation().isValid()) 2264 notePreviousDefinition(Old, New->getLocation()); 2265 New->setInvalidDecl(); 2266 return true; 2267 } 2268 2269 if (OldType != NewType && 2270 !OldType->isDependentType() && 2271 !NewType->isDependentType() && 2272 !Context.hasSameType(OldType, NewType)) { 2273 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2274 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2275 << Kind << NewType << OldType; 2276 if (Old->getLocation().isValid()) 2277 notePreviousDefinition(Old, New->getLocation()); 2278 New->setInvalidDecl(); 2279 return true; 2280 } 2281 return false; 2282 } 2283 2284 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2285 /// same name and scope as a previous declaration 'Old'. Figure out 2286 /// how to resolve this situation, merging decls or emitting 2287 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2288 /// 2289 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2290 LookupResult &OldDecls) { 2291 // If the new decl is known invalid already, don't bother doing any 2292 // merging checks. 2293 if (New->isInvalidDecl()) return; 2294 2295 // Allow multiple definitions for ObjC built-in typedefs. 2296 // FIXME: Verify the underlying types are equivalent! 2297 if (getLangOpts().ObjC) { 2298 const IdentifierInfo *TypeID = New->getIdentifier(); 2299 switch (TypeID->getLength()) { 2300 default: break; 2301 case 2: 2302 { 2303 if (!TypeID->isStr("id")) 2304 break; 2305 QualType T = New->getUnderlyingType(); 2306 if (!T->isPointerType()) 2307 break; 2308 if (!T->isVoidPointerType()) { 2309 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2310 if (!PT->isStructureType()) 2311 break; 2312 } 2313 Context.setObjCIdRedefinitionType(T); 2314 // Install the built-in type for 'id', ignoring the current definition. 2315 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2316 return; 2317 } 2318 case 5: 2319 if (!TypeID->isStr("Class")) 2320 break; 2321 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2322 // Install the built-in type for 'Class', ignoring the current definition. 2323 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2324 return; 2325 case 3: 2326 if (!TypeID->isStr("SEL")) 2327 break; 2328 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2329 // Install the built-in type for 'SEL', ignoring the current definition. 2330 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2331 return; 2332 } 2333 // Fall through - the typedef name was not a builtin type. 2334 } 2335 2336 // Verify the old decl was also a type. 2337 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2338 if (!Old) { 2339 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2340 << New->getDeclName(); 2341 2342 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2343 if (OldD->getLocation().isValid()) 2344 notePreviousDefinition(OldD, New->getLocation()); 2345 2346 return New->setInvalidDecl(); 2347 } 2348 2349 // If the old declaration is invalid, just give up here. 2350 if (Old->isInvalidDecl()) 2351 return New->setInvalidDecl(); 2352 2353 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2354 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2355 auto *NewTag = New->getAnonDeclWithTypedefName(); 2356 NamedDecl *Hidden = nullptr; 2357 if (OldTag && NewTag && 2358 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2359 !hasVisibleDefinition(OldTag, &Hidden)) { 2360 // There is a definition of this tag, but it is not visible. Use it 2361 // instead of our tag. 2362 New->setTypeForDecl(OldTD->getTypeForDecl()); 2363 if (OldTD->isModed()) 2364 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2365 OldTD->getUnderlyingType()); 2366 else 2367 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2368 2369 // Make the old tag definition visible. 2370 makeMergedDefinitionVisible(Hidden); 2371 2372 // If this was an unscoped enumeration, yank all of its enumerators 2373 // out of the scope. 2374 if (isa<EnumDecl>(NewTag)) { 2375 Scope *EnumScope = getNonFieldDeclScope(S); 2376 for (auto *D : NewTag->decls()) { 2377 auto *ED = cast<EnumConstantDecl>(D); 2378 assert(EnumScope->isDeclScope(ED)); 2379 EnumScope->RemoveDecl(ED); 2380 IdResolver.RemoveDecl(ED); 2381 ED->getLexicalDeclContext()->removeDecl(ED); 2382 } 2383 } 2384 } 2385 } 2386 2387 // If the typedef types are not identical, reject them in all languages and 2388 // with any extensions enabled. 2389 if (isIncompatibleTypedef(Old, New)) 2390 return; 2391 2392 // The types match. Link up the redeclaration chain and merge attributes if 2393 // the old declaration was a typedef. 2394 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2395 New->setPreviousDecl(Typedef); 2396 mergeDeclAttributes(New, Old); 2397 } 2398 2399 if (getLangOpts().MicrosoftExt) 2400 return; 2401 2402 if (getLangOpts().CPlusPlus) { 2403 // C++ [dcl.typedef]p2: 2404 // In a given non-class scope, a typedef specifier can be used to 2405 // redefine the name of any type declared in that scope to refer 2406 // to the type to which it already refers. 2407 if (!isa<CXXRecordDecl>(CurContext)) 2408 return; 2409 2410 // C++0x [dcl.typedef]p4: 2411 // In a given class scope, a typedef specifier can be used to redefine 2412 // any class-name declared in that scope that is not also a typedef-name 2413 // to refer to the type to which it already refers. 2414 // 2415 // This wording came in via DR424, which was a correction to the 2416 // wording in DR56, which accidentally banned code like: 2417 // 2418 // struct S { 2419 // typedef struct A { } A; 2420 // }; 2421 // 2422 // in the C++03 standard. We implement the C++0x semantics, which 2423 // allow the above but disallow 2424 // 2425 // struct S { 2426 // typedef int I; 2427 // typedef int I; 2428 // }; 2429 // 2430 // since that was the intent of DR56. 2431 if (!isa<TypedefNameDecl>(Old)) 2432 return; 2433 2434 Diag(New->getLocation(), diag::err_redefinition) 2435 << New->getDeclName(); 2436 notePreviousDefinition(Old, New->getLocation()); 2437 return New->setInvalidDecl(); 2438 } 2439 2440 // Modules always permit redefinition of typedefs, as does C11. 2441 if (getLangOpts().Modules || getLangOpts().C11) 2442 return; 2443 2444 // If we have a redefinition of a typedef in C, emit a warning. This warning 2445 // is normally mapped to an error, but can be controlled with 2446 // -Wtypedef-redefinition. If either the original or the redefinition is 2447 // in a system header, don't emit this for compatibility with GCC. 2448 if (getDiagnostics().getSuppressSystemWarnings() && 2449 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2450 (Old->isImplicit() || 2451 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2452 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2453 return; 2454 2455 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2456 << New->getDeclName(); 2457 notePreviousDefinition(Old, New->getLocation()); 2458 } 2459 2460 /// DeclhasAttr - returns true if decl Declaration already has the target 2461 /// attribute. 2462 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2463 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2464 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2465 for (const auto *i : D->attrs()) 2466 if (i->getKind() == A->getKind()) { 2467 if (Ann) { 2468 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2469 return true; 2470 continue; 2471 } 2472 // FIXME: Don't hardcode this check 2473 if (OA && isa<OwnershipAttr>(i)) 2474 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2475 return true; 2476 } 2477 2478 return false; 2479 } 2480 2481 static bool isAttributeTargetADefinition(Decl *D) { 2482 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2483 return VD->isThisDeclarationADefinition(); 2484 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2485 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2486 return true; 2487 } 2488 2489 /// Merge alignment attributes from \p Old to \p New, taking into account the 2490 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2491 /// 2492 /// \return \c true if any attributes were added to \p New. 2493 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2494 // Look for alignas attributes on Old, and pick out whichever attribute 2495 // specifies the strictest alignment requirement. 2496 AlignedAttr *OldAlignasAttr = nullptr; 2497 AlignedAttr *OldStrictestAlignAttr = nullptr; 2498 unsigned OldAlign = 0; 2499 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2500 // FIXME: We have no way of representing inherited dependent alignments 2501 // in a case like: 2502 // template<int A, int B> struct alignas(A) X; 2503 // template<int A, int B> struct alignas(B) X {}; 2504 // For now, we just ignore any alignas attributes which are not on the 2505 // definition in such a case. 2506 if (I->isAlignmentDependent()) 2507 return false; 2508 2509 if (I->isAlignas()) 2510 OldAlignasAttr = I; 2511 2512 unsigned Align = I->getAlignment(S.Context); 2513 if (Align > OldAlign) { 2514 OldAlign = Align; 2515 OldStrictestAlignAttr = I; 2516 } 2517 } 2518 2519 // Look for alignas attributes on New. 2520 AlignedAttr *NewAlignasAttr = nullptr; 2521 unsigned NewAlign = 0; 2522 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2523 if (I->isAlignmentDependent()) 2524 return false; 2525 2526 if (I->isAlignas()) 2527 NewAlignasAttr = I; 2528 2529 unsigned Align = I->getAlignment(S.Context); 2530 if (Align > NewAlign) 2531 NewAlign = Align; 2532 } 2533 2534 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2535 // Both declarations have 'alignas' attributes. We require them to match. 2536 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2537 // fall short. (If two declarations both have alignas, they must both match 2538 // every definition, and so must match each other if there is a definition.) 2539 2540 // If either declaration only contains 'alignas(0)' specifiers, then it 2541 // specifies the natural alignment for the type. 2542 if (OldAlign == 0 || NewAlign == 0) { 2543 QualType Ty; 2544 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2545 Ty = VD->getType(); 2546 else 2547 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2548 2549 if (OldAlign == 0) 2550 OldAlign = S.Context.getTypeAlign(Ty); 2551 if (NewAlign == 0) 2552 NewAlign = S.Context.getTypeAlign(Ty); 2553 } 2554 2555 if (OldAlign != NewAlign) { 2556 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2557 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2558 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2559 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2560 } 2561 } 2562 2563 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2564 // C++11 [dcl.align]p6: 2565 // if any declaration of an entity has an alignment-specifier, 2566 // every defining declaration of that entity shall specify an 2567 // equivalent alignment. 2568 // C11 6.7.5/7: 2569 // If the definition of an object does not have an alignment 2570 // specifier, any other declaration of that object shall also 2571 // have no alignment specifier. 2572 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2573 << OldAlignasAttr; 2574 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2575 << OldAlignasAttr; 2576 } 2577 2578 bool AnyAdded = false; 2579 2580 // Ensure we have an attribute representing the strictest alignment. 2581 if (OldAlign > NewAlign) { 2582 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2583 Clone->setInherited(true); 2584 New->addAttr(Clone); 2585 AnyAdded = true; 2586 } 2587 2588 // Ensure we have an alignas attribute if the old declaration had one. 2589 if (OldAlignasAttr && !NewAlignasAttr && 2590 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2591 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2592 Clone->setInherited(true); 2593 New->addAttr(Clone); 2594 AnyAdded = true; 2595 } 2596 2597 return AnyAdded; 2598 } 2599 2600 #define WANT_DECL_MERGE_LOGIC 2601 #include "clang/Sema/AttrParsedAttrImpl.inc" 2602 #undef WANT_DECL_MERGE_LOGIC 2603 2604 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2605 const InheritableAttr *Attr, 2606 Sema::AvailabilityMergeKind AMK) { 2607 // Diagnose any mutual exclusions between the attribute that we want to add 2608 // and attributes that already exist on the declaration. 2609 if (!DiagnoseMutualExclusions(S, D, Attr)) 2610 return false; 2611 2612 // This function copies an attribute Attr from a previous declaration to the 2613 // new declaration D if the new declaration doesn't itself have that attribute 2614 // yet or if that attribute allows duplicates. 2615 // If you're adding a new attribute that requires logic different from 2616 // "use explicit attribute on decl if present, else use attribute from 2617 // previous decl", for example if the attribute needs to be consistent 2618 // between redeclarations, you need to call a custom merge function here. 2619 InheritableAttr *NewAttr = nullptr; 2620 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2621 NewAttr = S.mergeAvailabilityAttr( 2622 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2623 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2624 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2625 AA->getPriority()); 2626 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2627 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2628 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2629 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2630 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2631 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2632 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2633 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2634 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr)) 2635 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic()); 2636 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2637 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2638 FA->getFirstArg()); 2639 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2640 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2641 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2642 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2643 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2644 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2645 IA->getInheritanceModel()); 2646 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2647 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2648 &S.Context.Idents.get(AA->getSpelling())); 2649 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2650 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2651 isa<CUDAGlobalAttr>(Attr))) { 2652 // CUDA target attributes are part of function signature for 2653 // overloading purposes and must not be merged. 2654 return false; 2655 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2656 NewAttr = S.mergeMinSizeAttr(D, *MA); 2657 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2658 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2659 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2660 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2661 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2662 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2663 else if (isa<AlignedAttr>(Attr)) 2664 // AlignedAttrs are handled separately, because we need to handle all 2665 // such attributes on a declaration at the same time. 2666 NewAttr = nullptr; 2667 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2668 (AMK == Sema::AMK_Override || 2669 AMK == Sema::AMK_ProtocolImplementation || 2670 AMK == Sema::AMK_OptionalProtocolImplementation)) 2671 NewAttr = nullptr; 2672 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2673 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2674 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2675 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2676 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2677 NewAttr = S.mergeImportNameAttr(D, *INA); 2678 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 2679 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 2680 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 2681 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 2682 else if (const auto *BTFA = dyn_cast<BTFTagAttr>(Attr)) 2683 NewAttr = S.mergeBTFTagAttr(D, *BTFA); 2684 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2685 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2686 2687 if (NewAttr) { 2688 NewAttr->setInherited(true); 2689 D->addAttr(NewAttr); 2690 if (isa<MSInheritanceAttr>(NewAttr)) 2691 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2692 return true; 2693 } 2694 2695 return false; 2696 } 2697 2698 static const NamedDecl *getDefinition(const Decl *D) { 2699 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2700 return TD->getDefinition(); 2701 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2702 const VarDecl *Def = VD->getDefinition(); 2703 if (Def) 2704 return Def; 2705 return VD->getActingDefinition(); 2706 } 2707 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2708 const FunctionDecl *Def = nullptr; 2709 if (FD->isDefined(Def, true)) 2710 return Def; 2711 } 2712 return nullptr; 2713 } 2714 2715 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2716 for (const auto *Attribute : D->attrs()) 2717 if (Attribute->getKind() == Kind) 2718 return true; 2719 return false; 2720 } 2721 2722 /// checkNewAttributesAfterDef - If we already have a definition, check that 2723 /// there are no new attributes in this declaration. 2724 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2725 if (!New->hasAttrs()) 2726 return; 2727 2728 const NamedDecl *Def = getDefinition(Old); 2729 if (!Def || Def == New) 2730 return; 2731 2732 AttrVec &NewAttributes = New->getAttrs(); 2733 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2734 const Attr *NewAttribute = NewAttributes[I]; 2735 2736 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2737 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2738 Sema::SkipBodyInfo SkipBody; 2739 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2740 2741 // If we're skipping this definition, drop the "alias" attribute. 2742 if (SkipBody.ShouldSkip) { 2743 NewAttributes.erase(NewAttributes.begin() + I); 2744 --E; 2745 continue; 2746 } 2747 } else { 2748 VarDecl *VD = cast<VarDecl>(New); 2749 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2750 VarDecl::TentativeDefinition 2751 ? diag::err_alias_after_tentative 2752 : diag::err_redefinition; 2753 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2754 if (Diag == diag::err_redefinition) 2755 S.notePreviousDefinition(Def, VD->getLocation()); 2756 else 2757 S.Diag(Def->getLocation(), diag::note_previous_definition); 2758 VD->setInvalidDecl(); 2759 } 2760 ++I; 2761 continue; 2762 } 2763 2764 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2765 // Tentative definitions are only interesting for the alias check above. 2766 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2767 ++I; 2768 continue; 2769 } 2770 } 2771 2772 if (hasAttribute(Def, NewAttribute->getKind())) { 2773 ++I; 2774 continue; // regular attr merging will take care of validating this. 2775 } 2776 2777 if (isa<C11NoReturnAttr>(NewAttribute)) { 2778 // C's _Noreturn is allowed to be added to a function after it is defined. 2779 ++I; 2780 continue; 2781 } else if (isa<UuidAttr>(NewAttribute)) { 2782 // msvc will allow a subsequent definition to add an uuid to a class 2783 ++I; 2784 continue; 2785 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2786 if (AA->isAlignas()) { 2787 // C++11 [dcl.align]p6: 2788 // if any declaration of an entity has an alignment-specifier, 2789 // every defining declaration of that entity shall specify an 2790 // equivalent alignment. 2791 // C11 6.7.5/7: 2792 // If the definition of an object does not have an alignment 2793 // specifier, any other declaration of that object shall also 2794 // have no alignment specifier. 2795 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2796 << AA; 2797 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2798 << AA; 2799 NewAttributes.erase(NewAttributes.begin() + I); 2800 --E; 2801 continue; 2802 } 2803 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2804 // If there is a C definition followed by a redeclaration with this 2805 // attribute then there are two different definitions. In C++, prefer the 2806 // standard diagnostics. 2807 if (!S.getLangOpts().CPlusPlus) { 2808 S.Diag(NewAttribute->getLocation(), 2809 diag::err_loader_uninitialized_redeclaration); 2810 S.Diag(Def->getLocation(), diag::note_previous_definition); 2811 NewAttributes.erase(NewAttributes.begin() + I); 2812 --E; 2813 continue; 2814 } 2815 } else if (isa<SelectAnyAttr>(NewAttribute) && 2816 cast<VarDecl>(New)->isInline() && 2817 !cast<VarDecl>(New)->isInlineSpecified()) { 2818 // Don't warn about applying selectany to implicitly inline variables. 2819 // Older compilers and language modes would require the use of selectany 2820 // to make such variables inline, and it would have no effect if we 2821 // honored it. 2822 ++I; 2823 continue; 2824 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2825 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2826 // declarations after defintions. 2827 ++I; 2828 continue; 2829 } 2830 2831 S.Diag(NewAttribute->getLocation(), 2832 diag::warn_attribute_precede_definition); 2833 S.Diag(Def->getLocation(), diag::note_previous_definition); 2834 NewAttributes.erase(NewAttributes.begin() + I); 2835 --E; 2836 } 2837 } 2838 2839 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2840 const ConstInitAttr *CIAttr, 2841 bool AttrBeforeInit) { 2842 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2843 2844 // Figure out a good way to write this specifier on the old declaration. 2845 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2846 // enough of the attribute list spelling information to extract that without 2847 // heroics. 2848 std::string SuitableSpelling; 2849 if (S.getLangOpts().CPlusPlus20) 2850 SuitableSpelling = std::string( 2851 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2852 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2853 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2854 InsertLoc, {tok::l_square, tok::l_square, 2855 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2856 S.PP.getIdentifierInfo("require_constant_initialization"), 2857 tok::r_square, tok::r_square})); 2858 if (SuitableSpelling.empty()) 2859 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2860 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2861 S.PP.getIdentifierInfo("require_constant_initialization"), 2862 tok::r_paren, tok::r_paren})); 2863 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2864 SuitableSpelling = "constinit"; 2865 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2866 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2867 if (SuitableSpelling.empty()) 2868 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2869 SuitableSpelling += " "; 2870 2871 if (AttrBeforeInit) { 2872 // extern constinit int a; 2873 // int a = 0; // error (missing 'constinit'), accepted as extension 2874 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2875 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2876 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2877 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2878 } else { 2879 // int a = 0; 2880 // constinit extern int a; // error (missing 'constinit') 2881 S.Diag(CIAttr->getLocation(), 2882 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2883 : diag::warn_require_const_init_added_too_late) 2884 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2885 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2886 << CIAttr->isConstinit() 2887 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2888 } 2889 } 2890 2891 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2892 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2893 AvailabilityMergeKind AMK) { 2894 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2895 UsedAttr *NewAttr = OldAttr->clone(Context); 2896 NewAttr->setInherited(true); 2897 New->addAttr(NewAttr); 2898 } 2899 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { 2900 RetainAttr *NewAttr = OldAttr->clone(Context); 2901 NewAttr->setInherited(true); 2902 New->addAttr(NewAttr); 2903 } 2904 2905 if (!Old->hasAttrs() && !New->hasAttrs()) 2906 return; 2907 2908 // [dcl.constinit]p1: 2909 // If the [constinit] specifier is applied to any declaration of a 2910 // variable, it shall be applied to the initializing declaration. 2911 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2912 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2913 if (bool(OldConstInit) != bool(NewConstInit)) { 2914 const auto *OldVD = cast<VarDecl>(Old); 2915 auto *NewVD = cast<VarDecl>(New); 2916 2917 // Find the initializing declaration. Note that we might not have linked 2918 // the new declaration into the redeclaration chain yet. 2919 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2920 if (!InitDecl && 2921 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2922 InitDecl = NewVD; 2923 2924 if (InitDecl == NewVD) { 2925 // This is the initializing declaration. If it would inherit 'constinit', 2926 // that's ill-formed. (Note that we do not apply this to the attribute 2927 // form). 2928 if (OldConstInit && OldConstInit->isConstinit()) 2929 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2930 /*AttrBeforeInit=*/true); 2931 } else if (NewConstInit) { 2932 // This is the first time we've been told that this declaration should 2933 // have a constant initializer. If we already saw the initializing 2934 // declaration, this is too late. 2935 if (InitDecl && InitDecl != NewVD) { 2936 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2937 /*AttrBeforeInit=*/false); 2938 NewVD->dropAttr<ConstInitAttr>(); 2939 } 2940 } 2941 } 2942 2943 // Attributes declared post-definition are currently ignored. 2944 checkNewAttributesAfterDef(*this, New, Old); 2945 2946 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2947 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2948 if (!OldA->isEquivalent(NewA)) { 2949 // This redeclaration changes __asm__ label. 2950 Diag(New->getLocation(), diag::err_different_asm_label); 2951 Diag(OldA->getLocation(), diag::note_previous_declaration); 2952 } 2953 } else if (Old->isUsed()) { 2954 // This redeclaration adds an __asm__ label to a declaration that has 2955 // already been ODR-used. 2956 Diag(New->getLocation(), diag::err_late_asm_label_name) 2957 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2958 } 2959 } 2960 2961 // Re-declaration cannot add abi_tag's. 2962 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2963 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2964 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2965 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2966 NewTag) == OldAbiTagAttr->tags_end()) { 2967 Diag(NewAbiTagAttr->getLocation(), 2968 diag::err_new_abi_tag_on_redeclaration) 2969 << NewTag; 2970 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2971 } 2972 } 2973 } else { 2974 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2975 Diag(Old->getLocation(), diag::note_previous_declaration); 2976 } 2977 } 2978 2979 // This redeclaration adds a section attribute. 2980 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2981 if (auto *VD = dyn_cast<VarDecl>(New)) { 2982 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2983 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2984 Diag(Old->getLocation(), diag::note_previous_declaration); 2985 } 2986 } 2987 } 2988 2989 // Redeclaration adds code-seg attribute. 2990 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2991 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2992 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2993 Diag(New->getLocation(), diag::warn_mismatched_section) 2994 << 0 /*codeseg*/; 2995 Diag(Old->getLocation(), diag::note_previous_declaration); 2996 } 2997 2998 if (!Old->hasAttrs()) 2999 return; 3000 3001 bool foundAny = New->hasAttrs(); 3002 3003 // Ensure that any moving of objects within the allocated map is done before 3004 // we process them. 3005 if (!foundAny) New->setAttrs(AttrVec()); 3006 3007 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 3008 // Ignore deprecated/unavailable/availability attributes if requested. 3009 AvailabilityMergeKind LocalAMK = AMK_None; 3010 if (isa<DeprecatedAttr>(I) || 3011 isa<UnavailableAttr>(I) || 3012 isa<AvailabilityAttr>(I)) { 3013 switch (AMK) { 3014 case AMK_None: 3015 continue; 3016 3017 case AMK_Redeclaration: 3018 case AMK_Override: 3019 case AMK_ProtocolImplementation: 3020 case AMK_OptionalProtocolImplementation: 3021 LocalAMK = AMK; 3022 break; 3023 } 3024 } 3025 3026 // Already handled. 3027 if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) 3028 continue; 3029 3030 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 3031 foundAny = true; 3032 } 3033 3034 if (mergeAlignedAttrs(*this, New, Old)) 3035 foundAny = true; 3036 3037 if (!foundAny) New->dropAttrs(); 3038 } 3039 3040 /// mergeParamDeclAttributes - Copy attributes from the old parameter 3041 /// to the new one. 3042 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 3043 const ParmVarDecl *oldDecl, 3044 Sema &S) { 3045 // C++11 [dcl.attr.depend]p2: 3046 // The first declaration of a function shall specify the 3047 // carries_dependency attribute for its declarator-id if any declaration 3048 // of the function specifies the carries_dependency attribute. 3049 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 3050 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 3051 S.Diag(CDA->getLocation(), 3052 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 3053 // Find the first declaration of the parameter. 3054 // FIXME: Should we build redeclaration chains for function parameters? 3055 const FunctionDecl *FirstFD = 3056 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 3057 const ParmVarDecl *FirstVD = 3058 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 3059 S.Diag(FirstVD->getLocation(), 3060 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 3061 } 3062 3063 if (!oldDecl->hasAttrs()) 3064 return; 3065 3066 bool foundAny = newDecl->hasAttrs(); 3067 3068 // Ensure that any moving of objects within the allocated map is 3069 // done before we process them. 3070 if (!foundAny) newDecl->setAttrs(AttrVec()); 3071 3072 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3073 if (!DeclHasAttr(newDecl, I)) { 3074 InheritableAttr *newAttr = 3075 cast<InheritableParamAttr>(I->clone(S.Context)); 3076 newAttr->setInherited(true); 3077 newDecl->addAttr(newAttr); 3078 foundAny = true; 3079 } 3080 } 3081 3082 if (!foundAny) newDecl->dropAttrs(); 3083 } 3084 3085 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3086 const ParmVarDecl *OldParam, 3087 Sema &S) { 3088 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3089 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3090 if (*Oldnullability != *Newnullability) { 3091 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3092 << DiagNullabilityKind( 3093 *Newnullability, 3094 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3095 != 0)) 3096 << DiagNullabilityKind( 3097 *Oldnullability, 3098 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3099 != 0)); 3100 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3101 } 3102 } else { 3103 QualType NewT = NewParam->getType(); 3104 NewT = S.Context.getAttributedType( 3105 AttributedType::getNullabilityAttrKind(*Oldnullability), 3106 NewT, NewT); 3107 NewParam->setType(NewT); 3108 } 3109 } 3110 } 3111 3112 namespace { 3113 3114 /// Used in MergeFunctionDecl to keep track of function parameters in 3115 /// C. 3116 struct GNUCompatibleParamWarning { 3117 ParmVarDecl *OldParm; 3118 ParmVarDecl *NewParm; 3119 QualType PromotedType; 3120 }; 3121 3122 } // end anonymous namespace 3123 3124 // Determine whether the previous declaration was a definition, implicit 3125 // declaration, or a declaration. 3126 template <typename T> 3127 static std::pair<diag::kind, SourceLocation> 3128 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3129 diag::kind PrevDiag; 3130 SourceLocation OldLocation = Old->getLocation(); 3131 if (Old->isThisDeclarationADefinition()) 3132 PrevDiag = diag::note_previous_definition; 3133 else if (Old->isImplicit()) { 3134 PrevDiag = diag::note_previous_implicit_declaration; 3135 if (OldLocation.isInvalid()) 3136 OldLocation = New->getLocation(); 3137 } else 3138 PrevDiag = diag::note_previous_declaration; 3139 return std::make_pair(PrevDiag, OldLocation); 3140 } 3141 3142 /// canRedefineFunction - checks if a function can be redefined. Currently, 3143 /// only extern inline functions can be redefined, and even then only in 3144 /// GNU89 mode. 3145 static bool canRedefineFunction(const FunctionDecl *FD, 3146 const LangOptions& LangOpts) { 3147 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3148 !LangOpts.CPlusPlus && 3149 FD->isInlineSpecified() && 3150 FD->getStorageClass() == SC_Extern); 3151 } 3152 3153 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3154 const AttributedType *AT = T->getAs<AttributedType>(); 3155 while (AT && !AT->isCallingConv()) 3156 AT = AT->getModifiedType()->getAs<AttributedType>(); 3157 return AT; 3158 } 3159 3160 template <typename T> 3161 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3162 const DeclContext *DC = Old->getDeclContext(); 3163 if (DC->isRecord()) 3164 return false; 3165 3166 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3167 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3168 return true; 3169 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3170 return true; 3171 return false; 3172 } 3173 3174 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3175 static bool isExternC(VarTemplateDecl *) { return false; } 3176 static bool isExternC(FunctionTemplateDecl *) { return false; } 3177 3178 /// Check whether a redeclaration of an entity introduced by a 3179 /// using-declaration is valid, given that we know it's not an overload 3180 /// (nor a hidden tag declaration). 3181 template<typename ExpectedDecl> 3182 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3183 ExpectedDecl *New) { 3184 // C++11 [basic.scope.declarative]p4: 3185 // Given a set of declarations in a single declarative region, each of 3186 // which specifies the same unqualified name, 3187 // -- they shall all refer to the same entity, or all refer to functions 3188 // and function templates; or 3189 // -- exactly one declaration shall declare a class name or enumeration 3190 // name that is not a typedef name and the other declarations shall all 3191 // refer to the same variable or enumerator, or all refer to functions 3192 // and function templates; in this case the class name or enumeration 3193 // name is hidden (3.3.10). 3194 3195 // C++11 [namespace.udecl]p14: 3196 // If a function declaration in namespace scope or block scope has the 3197 // same name and the same parameter-type-list as a function introduced 3198 // by a using-declaration, and the declarations do not declare the same 3199 // function, the program is ill-formed. 3200 3201 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3202 if (Old && 3203 !Old->getDeclContext()->getRedeclContext()->Equals( 3204 New->getDeclContext()->getRedeclContext()) && 3205 !(isExternC(Old) && isExternC(New))) 3206 Old = nullptr; 3207 3208 if (!Old) { 3209 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3210 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3211 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0; 3212 return true; 3213 } 3214 return false; 3215 } 3216 3217 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3218 const FunctionDecl *B) { 3219 assert(A->getNumParams() == B->getNumParams()); 3220 3221 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3222 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3223 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3224 if (AttrA == AttrB) 3225 return true; 3226 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3227 AttrA->isDynamic() == AttrB->isDynamic(); 3228 }; 3229 3230 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3231 } 3232 3233 /// If necessary, adjust the semantic declaration context for a qualified 3234 /// declaration to name the correct inline namespace within the qualifier. 3235 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3236 DeclaratorDecl *OldD) { 3237 // The only case where we need to update the DeclContext is when 3238 // redeclaration lookup for a qualified name finds a declaration 3239 // in an inline namespace within the context named by the qualifier: 3240 // 3241 // inline namespace N { int f(); } 3242 // int ::f(); // Sema DC needs adjusting from :: to N::. 3243 // 3244 // For unqualified declarations, the semantic context *can* change 3245 // along the redeclaration chain (for local extern declarations, 3246 // extern "C" declarations, and friend declarations in particular). 3247 if (!NewD->getQualifier()) 3248 return; 3249 3250 // NewD is probably already in the right context. 3251 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3252 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3253 if (NamedDC->Equals(SemaDC)) 3254 return; 3255 3256 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3257 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3258 "unexpected context for redeclaration"); 3259 3260 auto *LexDC = NewD->getLexicalDeclContext(); 3261 auto FixSemaDC = [=](NamedDecl *D) { 3262 if (!D) 3263 return; 3264 D->setDeclContext(SemaDC); 3265 D->setLexicalDeclContext(LexDC); 3266 }; 3267 3268 FixSemaDC(NewD); 3269 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3270 FixSemaDC(FD->getDescribedFunctionTemplate()); 3271 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3272 FixSemaDC(VD->getDescribedVarTemplate()); 3273 } 3274 3275 /// MergeFunctionDecl - We just parsed a function 'New' from 3276 /// declarator D which has the same name and scope as a previous 3277 /// declaration 'Old'. Figure out how to resolve this situation, 3278 /// merging decls or emitting diagnostics as appropriate. 3279 /// 3280 /// In C++, New and Old must be declarations that are not 3281 /// overloaded. Use IsOverload to determine whether New and Old are 3282 /// overloaded, and to select the Old declaration that New should be 3283 /// merged with. 3284 /// 3285 /// Returns true if there was an error, false otherwise. 3286 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3287 Scope *S, bool MergeTypeWithOld) { 3288 // Verify the old decl was also a function. 3289 FunctionDecl *Old = OldD->getAsFunction(); 3290 if (!Old) { 3291 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3292 if (New->getFriendObjectKind()) { 3293 Diag(New->getLocation(), diag::err_using_decl_friend); 3294 Diag(Shadow->getTargetDecl()->getLocation(), 3295 diag::note_using_decl_target); 3296 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 3297 << 0; 3298 return true; 3299 } 3300 3301 // Check whether the two declarations might declare the same function or 3302 // function template. 3303 if (FunctionTemplateDecl *NewTemplate = 3304 New->getDescribedFunctionTemplate()) { 3305 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow, 3306 NewTemplate)) 3307 return true; 3308 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl()) 3309 ->getAsFunction(); 3310 } else { 3311 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3312 return true; 3313 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3314 } 3315 } else { 3316 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3317 << New->getDeclName(); 3318 notePreviousDefinition(OldD, New->getLocation()); 3319 return true; 3320 } 3321 } 3322 3323 // If the old declaration was found in an inline namespace and the new 3324 // declaration was qualified, update the DeclContext to match. 3325 adjustDeclContextForDeclaratorDecl(New, Old); 3326 3327 // If the old declaration is invalid, just give up here. 3328 if (Old->isInvalidDecl()) 3329 return true; 3330 3331 // Disallow redeclaration of some builtins. 3332 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3333 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3334 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3335 << Old << Old->getType(); 3336 return true; 3337 } 3338 3339 diag::kind PrevDiag; 3340 SourceLocation OldLocation; 3341 std::tie(PrevDiag, OldLocation) = 3342 getNoteDiagForInvalidRedeclaration(Old, New); 3343 3344 // Don't complain about this if we're in GNU89 mode and the old function 3345 // is an extern inline function. 3346 // Don't complain about specializations. They are not supposed to have 3347 // storage classes. 3348 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3349 New->getStorageClass() == SC_Static && 3350 Old->hasExternalFormalLinkage() && 3351 !New->getTemplateSpecializationInfo() && 3352 !canRedefineFunction(Old, getLangOpts())) { 3353 if (getLangOpts().MicrosoftExt) { 3354 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3355 Diag(OldLocation, PrevDiag); 3356 } else { 3357 Diag(New->getLocation(), diag::err_static_non_static) << New; 3358 Diag(OldLocation, PrevDiag); 3359 return true; 3360 } 3361 } 3362 3363 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 3364 if (!Old->hasAttr<InternalLinkageAttr>()) { 3365 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 3366 << ILA; 3367 Diag(Old->getLocation(), diag::note_previous_declaration); 3368 New->dropAttr<InternalLinkageAttr>(); 3369 } 3370 3371 if (auto *EA = New->getAttr<ErrorAttr>()) { 3372 if (!Old->hasAttr<ErrorAttr>()) { 3373 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA; 3374 Diag(Old->getLocation(), diag::note_previous_declaration); 3375 New->dropAttr<ErrorAttr>(); 3376 } 3377 } 3378 3379 if (CheckRedeclarationModuleOwnership(New, Old)) 3380 return true; 3381 3382 if (!getLangOpts().CPlusPlus) { 3383 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3384 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3385 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3386 << New << OldOvl; 3387 3388 // Try our best to find a decl that actually has the overloadable 3389 // attribute for the note. In most cases (e.g. programs with only one 3390 // broken declaration/definition), this won't matter. 3391 // 3392 // FIXME: We could do this if we juggled some extra state in 3393 // OverloadableAttr, rather than just removing it. 3394 const Decl *DiagOld = Old; 3395 if (OldOvl) { 3396 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3397 const auto *A = D->getAttr<OverloadableAttr>(); 3398 return A && !A->isImplicit(); 3399 }); 3400 // If we've implicitly added *all* of the overloadable attrs to this 3401 // chain, emitting a "previous redecl" note is pointless. 3402 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3403 } 3404 3405 if (DiagOld) 3406 Diag(DiagOld->getLocation(), 3407 diag::note_attribute_overloadable_prev_overload) 3408 << OldOvl; 3409 3410 if (OldOvl) 3411 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3412 else 3413 New->dropAttr<OverloadableAttr>(); 3414 } 3415 } 3416 3417 // If a function is first declared with a calling convention, but is later 3418 // declared or defined without one, all following decls assume the calling 3419 // convention of the first. 3420 // 3421 // It's OK if a function is first declared without a calling convention, 3422 // but is later declared or defined with the default calling convention. 3423 // 3424 // To test if either decl has an explicit calling convention, we look for 3425 // AttributedType sugar nodes on the type as written. If they are missing or 3426 // were canonicalized away, we assume the calling convention was implicit. 3427 // 3428 // Note also that we DO NOT return at this point, because we still have 3429 // other tests to run. 3430 QualType OldQType = Context.getCanonicalType(Old->getType()); 3431 QualType NewQType = Context.getCanonicalType(New->getType()); 3432 const FunctionType *OldType = cast<FunctionType>(OldQType); 3433 const FunctionType *NewType = cast<FunctionType>(NewQType); 3434 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3435 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3436 bool RequiresAdjustment = false; 3437 3438 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3439 FunctionDecl *First = Old->getFirstDecl(); 3440 const FunctionType *FT = 3441 First->getType().getCanonicalType()->castAs<FunctionType>(); 3442 FunctionType::ExtInfo FI = FT->getExtInfo(); 3443 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3444 if (!NewCCExplicit) { 3445 // Inherit the CC from the previous declaration if it was specified 3446 // there but not here. 3447 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3448 RequiresAdjustment = true; 3449 } else if (Old->getBuiltinID()) { 3450 // Builtin attribute isn't propagated to the new one yet at this point, 3451 // so we check if the old one is a builtin. 3452 3453 // Calling Conventions on a Builtin aren't really useful and setting a 3454 // default calling convention and cdecl'ing some builtin redeclarations is 3455 // common, so warn and ignore the calling convention on the redeclaration. 3456 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3457 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3458 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3459 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3460 RequiresAdjustment = true; 3461 } else { 3462 // Calling conventions aren't compatible, so complain. 3463 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3464 Diag(New->getLocation(), diag::err_cconv_change) 3465 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3466 << !FirstCCExplicit 3467 << (!FirstCCExplicit ? "" : 3468 FunctionType::getNameForCallConv(FI.getCC())); 3469 3470 // Put the note on the first decl, since it is the one that matters. 3471 Diag(First->getLocation(), diag::note_previous_declaration); 3472 return true; 3473 } 3474 } 3475 3476 // FIXME: diagnose the other way around? 3477 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3478 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3479 RequiresAdjustment = true; 3480 } 3481 3482 // Merge regparm attribute. 3483 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3484 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3485 if (NewTypeInfo.getHasRegParm()) { 3486 Diag(New->getLocation(), diag::err_regparm_mismatch) 3487 << NewType->getRegParmType() 3488 << OldType->getRegParmType(); 3489 Diag(OldLocation, diag::note_previous_declaration); 3490 return true; 3491 } 3492 3493 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3494 RequiresAdjustment = true; 3495 } 3496 3497 // Merge ns_returns_retained attribute. 3498 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3499 if (NewTypeInfo.getProducesResult()) { 3500 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3501 << "'ns_returns_retained'"; 3502 Diag(OldLocation, diag::note_previous_declaration); 3503 return true; 3504 } 3505 3506 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3507 RequiresAdjustment = true; 3508 } 3509 3510 if (OldTypeInfo.getNoCallerSavedRegs() != 3511 NewTypeInfo.getNoCallerSavedRegs()) { 3512 if (NewTypeInfo.getNoCallerSavedRegs()) { 3513 AnyX86NoCallerSavedRegistersAttr *Attr = 3514 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3515 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3516 Diag(OldLocation, diag::note_previous_declaration); 3517 return true; 3518 } 3519 3520 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3521 RequiresAdjustment = true; 3522 } 3523 3524 if (RequiresAdjustment) { 3525 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3526 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3527 New->setType(QualType(AdjustedType, 0)); 3528 NewQType = Context.getCanonicalType(New->getType()); 3529 } 3530 3531 // If this redeclaration makes the function inline, we may need to add it to 3532 // UndefinedButUsed. 3533 if (!Old->isInlined() && New->isInlined() && 3534 !New->hasAttr<GNUInlineAttr>() && 3535 !getLangOpts().GNUInline && 3536 Old->isUsed(false) && 3537 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3538 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3539 SourceLocation())); 3540 3541 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3542 // about it. 3543 if (New->hasAttr<GNUInlineAttr>() && 3544 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3545 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3546 } 3547 3548 // If pass_object_size params don't match up perfectly, this isn't a valid 3549 // redeclaration. 3550 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3551 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3552 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3553 << New->getDeclName(); 3554 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3555 return true; 3556 } 3557 3558 if (getLangOpts().CPlusPlus) { 3559 // C++1z [over.load]p2 3560 // Certain function declarations cannot be overloaded: 3561 // -- Function declarations that differ only in the return type, 3562 // the exception specification, or both cannot be overloaded. 3563 3564 // Check the exception specifications match. This may recompute the type of 3565 // both Old and New if it resolved exception specifications, so grab the 3566 // types again after this. Because this updates the type, we do this before 3567 // any of the other checks below, which may update the "de facto" NewQType 3568 // but do not necessarily update the type of New. 3569 if (CheckEquivalentExceptionSpec(Old, New)) 3570 return true; 3571 OldQType = Context.getCanonicalType(Old->getType()); 3572 NewQType = Context.getCanonicalType(New->getType()); 3573 3574 // Go back to the type source info to compare the declared return types, 3575 // per C++1y [dcl.type.auto]p13: 3576 // Redeclarations or specializations of a function or function template 3577 // with a declared return type that uses a placeholder type shall also 3578 // use that placeholder, not a deduced type. 3579 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3580 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3581 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3582 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3583 OldDeclaredReturnType)) { 3584 QualType ResQT; 3585 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3586 OldDeclaredReturnType->isObjCObjectPointerType()) 3587 // FIXME: This does the wrong thing for a deduced return type. 3588 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3589 if (ResQT.isNull()) { 3590 if (New->isCXXClassMember() && New->isOutOfLine()) 3591 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3592 << New << New->getReturnTypeSourceRange(); 3593 else 3594 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3595 << New->getReturnTypeSourceRange(); 3596 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3597 << Old->getReturnTypeSourceRange(); 3598 return true; 3599 } 3600 else 3601 NewQType = ResQT; 3602 } 3603 3604 QualType OldReturnType = OldType->getReturnType(); 3605 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3606 if (OldReturnType != NewReturnType) { 3607 // If this function has a deduced return type and has already been 3608 // defined, copy the deduced value from the old declaration. 3609 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3610 if (OldAT && OldAT->isDeduced()) { 3611 New->setType( 3612 SubstAutoType(New->getType(), 3613 OldAT->isDependentType() ? Context.DependentTy 3614 : OldAT->getDeducedType())); 3615 NewQType = Context.getCanonicalType( 3616 SubstAutoType(NewQType, 3617 OldAT->isDependentType() ? Context.DependentTy 3618 : OldAT->getDeducedType())); 3619 } 3620 } 3621 3622 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3623 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3624 if (OldMethod && NewMethod) { 3625 // Preserve triviality. 3626 NewMethod->setTrivial(OldMethod->isTrivial()); 3627 3628 // MSVC allows explicit template specialization at class scope: 3629 // 2 CXXMethodDecls referring to the same function will be injected. 3630 // We don't want a redeclaration error. 3631 bool IsClassScopeExplicitSpecialization = 3632 OldMethod->isFunctionTemplateSpecialization() && 3633 NewMethod->isFunctionTemplateSpecialization(); 3634 bool isFriend = NewMethod->getFriendObjectKind(); 3635 3636 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3637 !IsClassScopeExplicitSpecialization) { 3638 // -- Member function declarations with the same name and the 3639 // same parameter types cannot be overloaded if any of them 3640 // is a static member function declaration. 3641 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3642 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3643 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3644 return true; 3645 } 3646 3647 // C++ [class.mem]p1: 3648 // [...] A member shall not be declared twice in the 3649 // member-specification, except that a nested class or member 3650 // class template can be declared and then later defined. 3651 if (!inTemplateInstantiation()) { 3652 unsigned NewDiag; 3653 if (isa<CXXConstructorDecl>(OldMethod)) 3654 NewDiag = diag::err_constructor_redeclared; 3655 else if (isa<CXXDestructorDecl>(NewMethod)) 3656 NewDiag = diag::err_destructor_redeclared; 3657 else if (isa<CXXConversionDecl>(NewMethod)) 3658 NewDiag = diag::err_conv_function_redeclared; 3659 else 3660 NewDiag = diag::err_member_redeclared; 3661 3662 Diag(New->getLocation(), NewDiag); 3663 } else { 3664 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3665 << New << New->getType(); 3666 } 3667 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3668 return true; 3669 3670 // Complain if this is an explicit declaration of a special 3671 // member that was initially declared implicitly. 3672 // 3673 // As an exception, it's okay to befriend such methods in order 3674 // to permit the implicit constructor/destructor/operator calls. 3675 } else if (OldMethod->isImplicit()) { 3676 if (isFriend) { 3677 NewMethod->setImplicit(); 3678 } else { 3679 Diag(NewMethod->getLocation(), 3680 diag::err_definition_of_implicitly_declared_member) 3681 << New << getSpecialMember(OldMethod); 3682 return true; 3683 } 3684 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3685 Diag(NewMethod->getLocation(), 3686 diag::err_definition_of_explicitly_defaulted_member) 3687 << getSpecialMember(OldMethod); 3688 return true; 3689 } 3690 } 3691 3692 // C++11 [dcl.attr.noreturn]p1: 3693 // The first declaration of a function shall specify the noreturn 3694 // attribute if any declaration of that function specifies the noreturn 3695 // attribute. 3696 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>()) 3697 if (!Old->hasAttr<CXX11NoReturnAttr>()) { 3698 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl) 3699 << NRA; 3700 Diag(Old->getLocation(), diag::note_previous_declaration); 3701 } 3702 3703 // C++11 [dcl.attr.depend]p2: 3704 // The first declaration of a function shall specify the 3705 // carries_dependency attribute for its declarator-id if any declaration 3706 // of the function specifies the carries_dependency attribute. 3707 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3708 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3709 Diag(CDA->getLocation(), 3710 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3711 Diag(Old->getFirstDecl()->getLocation(), 3712 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3713 } 3714 3715 // (C++98 8.3.5p3): 3716 // All declarations for a function shall agree exactly in both the 3717 // return type and the parameter-type-list. 3718 // We also want to respect all the extended bits except noreturn. 3719 3720 // noreturn should now match unless the old type info didn't have it. 3721 QualType OldQTypeForComparison = OldQType; 3722 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3723 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3724 const FunctionType *OldTypeForComparison 3725 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3726 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3727 assert(OldQTypeForComparison.isCanonical()); 3728 } 3729 3730 if (haveIncompatibleLanguageLinkages(Old, New)) { 3731 // As a special case, retain the language linkage from previous 3732 // declarations of a friend function as an extension. 3733 // 3734 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3735 // and is useful because there's otherwise no way to specify language 3736 // linkage within class scope. 3737 // 3738 // Check cautiously as the friend object kind isn't yet complete. 3739 if (New->getFriendObjectKind() != Decl::FOK_None) { 3740 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3741 Diag(OldLocation, PrevDiag); 3742 } else { 3743 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3744 Diag(OldLocation, PrevDiag); 3745 return true; 3746 } 3747 } 3748 3749 // If the function types are compatible, merge the declarations. Ignore the 3750 // exception specifier because it was already checked above in 3751 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3752 // about incompatible types under -fms-compatibility. 3753 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3754 NewQType)) 3755 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3756 3757 // If the types are imprecise (due to dependent constructs in friends or 3758 // local extern declarations), it's OK if they differ. We'll check again 3759 // during instantiation. 3760 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3761 return false; 3762 3763 // Fall through for conflicting redeclarations and redefinitions. 3764 } 3765 3766 // C: Function types need to be compatible, not identical. This handles 3767 // duplicate function decls like "void f(int); void f(enum X);" properly. 3768 if (!getLangOpts().CPlusPlus && 3769 Context.typesAreCompatible(OldQType, NewQType)) { 3770 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3771 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3772 const FunctionProtoType *OldProto = nullptr; 3773 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3774 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3775 // The old declaration provided a function prototype, but the 3776 // new declaration does not. Merge in the prototype. 3777 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3778 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3779 NewQType = 3780 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3781 OldProto->getExtProtoInfo()); 3782 New->setType(NewQType); 3783 New->setHasInheritedPrototype(); 3784 3785 // Synthesize parameters with the same types. 3786 SmallVector<ParmVarDecl*, 16> Params; 3787 for (const auto &ParamType : OldProto->param_types()) { 3788 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3789 SourceLocation(), nullptr, 3790 ParamType, /*TInfo=*/nullptr, 3791 SC_None, nullptr); 3792 Param->setScopeInfo(0, Params.size()); 3793 Param->setImplicit(); 3794 Params.push_back(Param); 3795 } 3796 3797 New->setParams(Params); 3798 } 3799 3800 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3801 } 3802 3803 // Check if the function types are compatible when pointer size address 3804 // spaces are ignored. 3805 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3806 return false; 3807 3808 // GNU C permits a K&R definition to follow a prototype declaration 3809 // if the declared types of the parameters in the K&R definition 3810 // match the types in the prototype declaration, even when the 3811 // promoted types of the parameters from the K&R definition differ 3812 // from the types in the prototype. GCC then keeps the types from 3813 // the prototype. 3814 // 3815 // If a variadic prototype is followed by a non-variadic K&R definition, 3816 // the K&R definition becomes variadic. This is sort of an edge case, but 3817 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3818 // C99 6.9.1p8. 3819 if (!getLangOpts().CPlusPlus && 3820 Old->hasPrototype() && !New->hasPrototype() && 3821 New->getType()->getAs<FunctionProtoType>() && 3822 Old->getNumParams() == New->getNumParams()) { 3823 SmallVector<QualType, 16> ArgTypes; 3824 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3825 const FunctionProtoType *OldProto 3826 = Old->getType()->getAs<FunctionProtoType>(); 3827 const FunctionProtoType *NewProto 3828 = New->getType()->getAs<FunctionProtoType>(); 3829 3830 // Determine whether this is the GNU C extension. 3831 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3832 NewProto->getReturnType()); 3833 bool LooseCompatible = !MergedReturn.isNull(); 3834 for (unsigned Idx = 0, End = Old->getNumParams(); 3835 LooseCompatible && Idx != End; ++Idx) { 3836 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3837 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3838 if (Context.typesAreCompatible(OldParm->getType(), 3839 NewProto->getParamType(Idx))) { 3840 ArgTypes.push_back(NewParm->getType()); 3841 } else if (Context.typesAreCompatible(OldParm->getType(), 3842 NewParm->getType(), 3843 /*CompareUnqualified=*/true)) { 3844 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3845 NewProto->getParamType(Idx) }; 3846 Warnings.push_back(Warn); 3847 ArgTypes.push_back(NewParm->getType()); 3848 } else 3849 LooseCompatible = false; 3850 } 3851 3852 if (LooseCompatible) { 3853 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3854 Diag(Warnings[Warn].NewParm->getLocation(), 3855 diag::ext_param_promoted_not_compatible_with_prototype) 3856 << Warnings[Warn].PromotedType 3857 << Warnings[Warn].OldParm->getType(); 3858 if (Warnings[Warn].OldParm->getLocation().isValid()) 3859 Diag(Warnings[Warn].OldParm->getLocation(), 3860 diag::note_previous_declaration); 3861 } 3862 3863 if (MergeTypeWithOld) 3864 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3865 OldProto->getExtProtoInfo())); 3866 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3867 } 3868 3869 // Fall through to diagnose conflicting types. 3870 } 3871 3872 // A function that has already been declared has been redeclared or 3873 // defined with a different type; show an appropriate diagnostic. 3874 3875 // If the previous declaration was an implicitly-generated builtin 3876 // declaration, then at the very least we should use a specialized note. 3877 unsigned BuiltinID; 3878 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3879 // If it's actually a library-defined builtin function like 'malloc' 3880 // or 'printf', just warn about the incompatible redeclaration. 3881 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3882 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3883 Diag(OldLocation, diag::note_previous_builtin_declaration) 3884 << Old << Old->getType(); 3885 return false; 3886 } 3887 3888 PrevDiag = diag::note_previous_builtin_declaration; 3889 } 3890 3891 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3892 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3893 return true; 3894 } 3895 3896 /// Completes the merge of two function declarations that are 3897 /// known to be compatible. 3898 /// 3899 /// This routine handles the merging of attributes and other 3900 /// properties of function declarations from the old declaration to 3901 /// the new declaration, once we know that New is in fact a 3902 /// redeclaration of Old. 3903 /// 3904 /// \returns false 3905 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3906 Scope *S, bool MergeTypeWithOld) { 3907 // Merge the attributes 3908 mergeDeclAttributes(New, Old); 3909 3910 // Merge "pure" flag. 3911 if (Old->isPure()) 3912 New->setPure(); 3913 3914 // Merge "used" flag. 3915 if (Old->getMostRecentDecl()->isUsed(false)) 3916 New->setIsUsed(); 3917 3918 // Merge attributes from the parameters. These can mismatch with K&R 3919 // declarations. 3920 if (New->getNumParams() == Old->getNumParams()) 3921 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3922 ParmVarDecl *NewParam = New->getParamDecl(i); 3923 ParmVarDecl *OldParam = Old->getParamDecl(i); 3924 mergeParamDeclAttributes(NewParam, OldParam, *this); 3925 mergeParamDeclTypes(NewParam, OldParam, *this); 3926 } 3927 3928 if (getLangOpts().CPlusPlus) 3929 return MergeCXXFunctionDecl(New, Old, S); 3930 3931 // Merge the function types so the we get the composite types for the return 3932 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3933 // was visible. 3934 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3935 if (!Merged.isNull() && MergeTypeWithOld) 3936 New->setType(Merged); 3937 3938 return false; 3939 } 3940 3941 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3942 ObjCMethodDecl *oldMethod) { 3943 // Merge the attributes, including deprecated/unavailable 3944 AvailabilityMergeKind MergeKind = 3945 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3946 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation 3947 : AMK_ProtocolImplementation) 3948 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3949 : AMK_Override; 3950 3951 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3952 3953 // Merge attributes from the parameters. 3954 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3955 oe = oldMethod->param_end(); 3956 for (ObjCMethodDecl::param_iterator 3957 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3958 ni != ne && oi != oe; ++ni, ++oi) 3959 mergeParamDeclAttributes(*ni, *oi, *this); 3960 3961 CheckObjCMethodOverride(newMethod, oldMethod); 3962 } 3963 3964 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3965 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3966 3967 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3968 ? diag::err_redefinition_different_type 3969 : diag::err_redeclaration_different_type) 3970 << New->getDeclName() << New->getType() << Old->getType(); 3971 3972 diag::kind PrevDiag; 3973 SourceLocation OldLocation; 3974 std::tie(PrevDiag, OldLocation) 3975 = getNoteDiagForInvalidRedeclaration(Old, New); 3976 S.Diag(OldLocation, PrevDiag); 3977 New->setInvalidDecl(); 3978 } 3979 3980 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3981 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3982 /// emitting diagnostics as appropriate. 3983 /// 3984 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3985 /// to here in AddInitializerToDecl. We can't check them before the initializer 3986 /// is attached. 3987 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3988 bool MergeTypeWithOld) { 3989 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3990 return; 3991 3992 QualType MergedT; 3993 if (getLangOpts().CPlusPlus) { 3994 if (New->getType()->isUndeducedType()) { 3995 // We don't know what the new type is until the initializer is attached. 3996 return; 3997 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3998 // These could still be something that needs exception specs checked. 3999 return MergeVarDeclExceptionSpecs(New, Old); 4000 } 4001 // C++ [basic.link]p10: 4002 // [...] the types specified by all declarations referring to a given 4003 // object or function shall be identical, except that declarations for an 4004 // array object can specify array types that differ by the presence or 4005 // absence of a major array bound (8.3.4). 4006 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 4007 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 4008 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 4009 4010 // We are merging a variable declaration New into Old. If it has an array 4011 // bound, and that bound differs from Old's bound, we should diagnose the 4012 // mismatch. 4013 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 4014 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 4015 PrevVD = PrevVD->getPreviousDecl()) { 4016 QualType PrevVDTy = PrevVD->getType(); 4017 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 4018 continue; 4019 4020 if (!Context.hasSameType(New->getType(), PrevVDTy)) 4021 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 4022 } 4023 } 4024 4025 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 4026 if (Context.hasSameType(OldArray->getElementType(), 4027 NewArray->getElementType())) 4028 MergedT = New->getType(); 4029 } 4030 // FIXME: Check visibility. New is hidden but has a complete type. If New 4031 // has no array bound, it should not inherit one from Old, if Old is not 4032 // visible. 4033 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 4034 if (Context.hasSameType(OldArray->getElementType(), 4035 NewArray->getElementType())) 4036 MergedT = Old->getType(); 4037 } 4038 } 4039 else if (New->getType()->isObjCObjectPointerType() && 4040 Old->getType()->isObjCObjectPointerType()) { 4041 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 4042 Old->getType()); 4043 } 4044 } else { 4045 // C 6.2.7p2: 4046 // All declarations that refer to the same object or function shall have 4047 // compatible type. 4048 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 4049 } 4050 if (MergedT.isNull()) { 4051 // It's OK if we couldn't merge types if either type is dependent, for a 4052 // block-scope variable. In other cases (static data members of class 4053 // templates, variable templates, ...), we require the types to be 4054 // equivalent. 4055 // FIXME: The C++ standard doesn't say anything about this. 4056 if ((New->getType()->isDependentType() || 4057 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 4058 // If the old type was dependent, we can't merge with it, so the new type 4059 // becomes dependent for now. We'll reproduce the original type when we 4060 // instantiate the TypeSourceInfo for the variable. 4061 if (!New->getType()->isDependentType() && MergeTypeWithOld) 4062 New->setType(Context.DependentTy); 4063 return; 4064 } 4065 return diagnoseVarDeclTypeMismatch(*this, New, Old); 4066 } 4067 4068 // Don't actually update the type on the new declaration if the old 4069 // declaration was an extern declaration in a different scope. 4070 if (MergeTypeWithOld) 4071 New->setType(MergedT); 4072 } 4073 4074 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 4075 LookupResult &Previous) { 4076 // C11 6.2.7p4: 4077 // For an identifier with internal or external linkage declared 4078 // in a scope in which a prior declaration of that identifier is 4079 // visible, if the prior declaration specifies internal or 4080 // external linkage, the type of the identifier at the later 4081 // declaration becomes the composite type. 4082 // 4083 // If the variable isn't visible, we do not merge with its type. 4084 if (Previous.isShadowed()) 4085 return false; 4086 4087 if (S.getLangOpts().CPlusPlus) { 4088 // C++11 [dcl.array]p3: 4089 // If there is a preceding declaration of the entity in the same 4090 // scope in which the bound was specified, an omitted array bound 4091 // is taken to be the same as in that earlier declaration. 4092 return NewVD->isPreviousDeclInSameBlockScope() || 4093 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4094 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4095 } else { 4096 // If the old declaration was function-local, don't merge with its 4097 // type unless we're in the same function. 4098 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4099 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4100 } 4101 } 4102 4103 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4104 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4105 /// situation, merging decls or emitting diagnostics as appropriate. 4106 /// 4107 /// Tentative definition rules (C99 6.9.2p2) are checked by 4108 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4109 /// definitions here, since the initializer hasn't been attached. 4110 /// 4111 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4112 // If the new decl is already invalid, don't do any other checking. 4113 if (New->isInvalidDecl()) 4114 return; 4115 4116 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4117 return; 4118 4119 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4120 4121 // Verify the old decl was also a variable or variable template. 4122 VarDecl *Old = nullptr; 4123 VarTemplateDecl *OldTemplate = nullptr; 4124 if (Previous.isSingleResult()) { 4125 if (NewTemplate) { 4126 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4127 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4128 4129 if (auto *Shadow = 4130 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4131 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4132 return New->setInvalidDecl(); 4133 } else { 4134 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4135 4136 if (auto *Shadow = 4137 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4138 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4139 return New->setInvalidDecl(); 4140 } 4141 } 4142 if (!Old) { 4143 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4144 << New->getDeclName(); 4145 notePreviousDefinition(Previous.getRepresentativeDecl(), 4146 New->getLocation()); 4147 return New->setInvalidDecl(); 4148 } 4149 4150 // If the old declaration was found in an inline namespace and the new 4151 // declaration was qualified, update the DeclContext to match. 4152 adjustDeclContextForDeclaratorDecl(New, Old); 4153 4154 // Ensure the template parameters are compatible. 4155 if (NewTemplate && 4156 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4157 OldTemplate->getTemplateParameters(), 4158 /*Complain=*/true, TPL_TemplateMatch)) 4159 return New->setInvalidDecl(); 4160 4161 // C++ [class.mem]p1: 4162 // A member shall not be declared twice in the member-specification [...] 4163 // 4164 // Here, we need only consider static data members. 4165 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4166 Diag(New->getLocation(), diag::err_duplicate_member) 4167 << New->getIdentifier(); 4168 Diag(Old->getLocation(), diag::note_previous_declaration); 4169 New->setInvalidDecl(); 4170 } 4171 4172 mergeDeclAttributes(New, Old); 4173 // Warn if an already-declared variable is made a weak_import in a subsequent 4174 // declaration 4175 if (New->hasAttr<WeakImportAttr>() && 4176 Old->getStorageClass() == SC_None && 4177 !Old->hasAttr<WeakImportAttr>()) { 4178 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4179 Diag(Old->getLocation(), diag::note_previous_declaration); 4180 // Remove weak_import attribute on new declaration. 4181 New->dropAttr<WeakImportAttr>(); 4182 } 4183 4184 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 4185 if (!Old->hasAttr<InternalLinkageAttr>()) { 4186 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 4187 << ILA; 4188 Diag(Old->getLocation(), diag::note_previous_declaration); 4189 New->dropAttr<InternalLinkageAttr>(); 4190 } 4191 4192 // Merge the types. 4193 VarDecl *MostRecent = Old->getMostRecentDecl(); 4194 if (MostRecent != Old) { 4195 MergeVarDeclTypes(New, MostRecent, 4196 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4197 if (New->isInvalidDecl()) 4198 return; 4199 } 4200 4201 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4202 if (New->isInvalidDecl()) 4203 return; 4204 4205 diag::kind PrevDiag; 4206 SourceLocation OldLocation; 4207 std::tie(PrevDiag, OldLocation) = 4208 getNoteDiagForInvalidRedeclaration(Old, New); 4209 4210 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4211 if (New->getStorageClass() == SC_Static && 4212 !New->isStaticDataMember() && 4213 Old->hasExternalFormalLinkage()) { 4214 if (getLangOpts().MicrosoftExt) { 4215 Diag(New->getLocation(), diag::ext_static_non_static) 4216 << New->getDeclName(); 4217 Diag(OldLocation, PrevDiag); 4218 } else { 4219 Diag(New->getLocation(), diag::err_static_non_static) 4220 << New->getDeclName(); 4221 Diag(OldLocation, PrevDiag); 4222 return New->setInvalidDecl(); 4223 } 4224 } 4225 // C99 6.2.2p4: 4226 // For an identifier declared with the storage-class specifier 4227 // extern in a scope in which a prior declaration of that 4228 // identifier is visible,23) if the prior declaration specifies 4229 // internal or external linkage, the linkage of the identifier at 4230 // the later declaration is the same as the linkage specified at 4231 // the prior declaration. If no prior declaration is visible, or 4232 // if the prior declaration specifies no linkage, then the 4233 // identifier has external linkage. 4234 if (New->hasExternalStorage() && Old->hasLinkage()) 4235 /* Okay */; 4236 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4237 !New->isStaticDataMember() && 4238 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4239 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4240 Diag(OldLocation, PrevDiag); 4241 return New->setInvalidDecl(); 4242 } 4243 4244 // Check if extern is followed by non-extern and vice-versa. 4245 if (New->hasExternalStorage() && 4246 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4247 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4248 Diag(OldLocation, PrevDiag); 4249 return New->setInvalidDecl(); 4250 } 4251 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4252 !New->hasExternalStorage()) { 4253 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4254 Diag(OldLocation, PrevDiag); 4255 return New->setInvalidDecl(); 4256 } 4257 4258 if (CheckRedeclarationModuleOwnership(New, Old)) 4259 return; 4260 4261 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4262 4263 // FIXME: The test for external storage here seems wrong? We still 4264 // need to check for mismatches. 4265 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4266 // Don't complain about out-of-line definitions of static members. 4267 !(Old->getLexicalDeclContext()->isRecord() && 4268 !New->getLexicalDeclContext()->isRecord())) { 4269 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4270 Diag(OldLocation, PrevDiag); 4271 return New->setInvalidDecl(); 4272 } 4273 4274 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4275 if (VarDecl *Def = Old->getDefinition()) { 4276 // C++1z [dcl.fcn.spec]p4: 4277 // If the definition of a variable appears in a translation unit before 4278 // its first declaration as inline, the program is ill-formed. 4279 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4280 Diag(Def->getLocation(), diag::note_previous_definition); 4281 } 4282 } 4283 4284 // If this redeclaration makes the variable inline, we may need to add it to 4285 // UndefinedButUsed. 4286 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4287 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4288 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4289 SourceLocation())); 4290 4291 if (New->getTLSKind() != Old->getTLSKind()) { 4292 if (!Old->getTLSKind()) { 4293 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4294 Diag(OldLocation, PrevDiag); 4295 } else if (!New->getTLSKind()) { 4296 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4297 Diag(OldLocation, PrevDiag); 4298 } else { 4299 // Do not allow redeclaration to change the variable between requiring 4300 // static and dynamic initialization. 4301 // FIXME: GCC allows this, but uses the TLS keyword on the first 4302 // declaration to determine the kind. Do we need to be compatible here? 4303 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4304 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4305 Diag(OldLocation, PrevDiag); 4306 } 4307 } 4308 4309 // C++ doesn't have tentative definitions, so go right ahead and check here. 4310 if (getLangOpts().CPlusPlus && 4311 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4312 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4313 Old->getCanonicalDecl()->isConstexpr()) { 4314 // This definition won't be a definition any more once it's been merged. 4315 Diag(New->getLocation(), 4316 diag::warn_deprecated_redundant_constexpr_static_def); 4317 } else if (VarDecl *Def = Old->getDefinition()) { 4318 if (checkVarDeclRedefinition(Def, New)) 4319 return; 4320 } 4321 } 4322 4323 if (haveIncompatibleLanguageLinkages(Old, New)) { 4324 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4325 Diag(OldLocation, PrevDiag); 4326 New->setInvalidDecl(); 4327 return; 4328 } 4329 4330 // Merge "used" flag. 4331 if (Old->getMostRecentDecl()->isUsed(false)) 4332 New->setIsUsed(); 4333 4334 // Keep a chain of previous declarations. 4335 New->setPreviousDecl(Old); 4336 if (NewTemplate) 4337 NewTemplate->setPreviousDecl(OldTemplate); 4338 4339 // Inherit access appropriately. 4340 New->setAccess(Old->getAccess()); 4341 if (NewTemplate) 4342 NewTemplate->setAccess(New->getAccess()); 4343 4344 if (Old->isInline()) 4345 New->setImplicitlyInline(); 4346 } 4347 4348 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4349 SourceManager &SrcMgr = getSourceManager(); 4350 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4351 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4352 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4353 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4354 auto &HSI = PP.getHeaderSearchInfo(); 4355 StringRef HdrFilename = 4356 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4357 4358 auto noteFromModuleOrInclude = [&](Module *Mod, 4359 SourceLocation IncLoc) -> bool { 4360 // Redefinition errors with modules are common with non modular mapped 4361 // headers, example: a non-modular header H in module A that also gets 4362 // included directly in a TU. Pointing twice to the same header/definition 4363 // is confusing, try to get better diagnostics when modules is on. 4364 if (IncLoc.isValid()) { 4365 if (Mod) { 4366 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4367 << HdrFilename.str() << Mod->getFullModuleName(); 4368 if (!Mod->DefinitionLoc.isInvalid()) 4369 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4370 << Mod->getFullModuleName(); 4371 } else { 4372 Diag(IncLoc, diag::note_redefinition_include_same_file) 4373 << HdrFilename.str(); 4374 } 4375 return true; 4376 } 4377 4378 return false; 4379 }; 4380 4381 // Is it the same file and same offset? Provide more information on why 4382 // this leads to a redefinition error. 4383 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4384 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4385 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4386 bool EmittedDiag = 4387 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4388 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4389 4390 // If the header has no guards, emit a note suggesting one. 4391 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4392 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4393 4394 if (EmittedDiag) 4395 return; 4396 } 4397 4398 // Redefinition coming from different files or couldn't do better above. 4399 if (Old->getLocation().isValid()) 4400 Diag(Old->getLocation(), diag::note_previous_definition); 4401 } 4402 4403 /// We've just determined that \p Old and \p New both appear to be definitions 4404 /// of the same variable. Either diagnose or fix the problem. 4405 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4406 if (!hasVisibleDefinition(Old) && 4407 (New->getFormalLinkage() == InternalLinkage || 4408 New->isInline() || 4409 New->getDescribedVarTemplate() || 4410 New->getNumTemplateParameterLists() || 4411 New->getDeclContext()->isDependentContext())) { 4412 // The previous definition is hidden, and multiple definitions are 4413 // permitted (in separate TUs). Demote this to a declaration. 4414 New->demoteThisDefinitionToDeclaration(); 4415 4416 // Make the canonical definition visible. 4417 if (auto *OldTD = Old->getDescribedVarTemplate()) 4418 makeMergedDefinitionVisible(OldTD); 4419 makeMergedDefinitionVisible(Old); 4420 return false; 4421 } else { 4422 Diag(New->getLocation(), diag::err_redefinition) << New; 4423 notePreviousDefinition(Old, New->getLocation()); 4424 New->setInvalidDecl(); 4425 return true; 4426 } 4427 } 4428 4429 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4430 /// no declarator (e.g. "struct foo;") is parsed. 4431 Decl * 4432 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4433 RecordDecl *&AnonRecord) { 4434 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4435 AnonRecord); 4436 } 4437 4438 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4439 // disambiguate entities defined in different scopes. 4440 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4441 // compatibility. 4442 // We will pick our mangling number depending on which version of MSVC is being 4443 // targeted. 4444 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4445 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4446 ? S->getMSCurManglingNumber() 4447 : S->getMSLastManglingNumber(); 4448 } 4449 4450 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4451 if (!Context.getLangOpts().CPlusPlus) 4452 return; 4453 4454 if (isa<CXXRecordDecl>(Tag->getParent())) { 4455 // If this tag is the direct child of a class, number it if 4456 // it is anonymous. 4457 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4458 return; 4459 MangleNumberingContext &MCtx = 4460 Context.getManglingNumberContext(Tag->getParent()); 4461 Context.setManglingNumber( 4462 Tag, MCtx.getManglingNumber( 4463 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4464 return; 4465 } 4466 4467 // If this tag isn't a direct child of a class, number it if it is local. 4468 MangleNumberingContext *MCtx; 4469 Decl *ManglingContextDecl; 4470 std::tie(MCtx, ManglingContextDecl) = 4471 getCurrentMangleNumberContext(Tag->getDeclContext()); 4472 if (MCtx) { 4473 Context.setManglingNumber( 4474 Tag, MCtx->getManglingNumber( 4475 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4476 } 4477 } 4478 4479 namespace { 4480 struct NonCLikeKind { 4481 enum { 4482 None, 4483 BaseClass, 4484 DefaultMemberInit, 4485 Lambda, 4486 Friend, 4487 OtherMember, 4488 Invalid, 4489 } Kind = None; 4490 SourceRange Range; 4491 4492 explicit operator bool() { return Kind != None; } 4493 }; 4494 } 4495 4496 /// Determine whether a class is C-like, according to the rules of C++ 4497 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4498 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4499 if (RD->isInvalidDecl()) 4500 return {NonCLikeKind::Invalid, {}}; 4501 4502 // C++ [dcl.typedef]p9: [P1766R1] 4503 // An unnamed class with a typedef name for linkage purposes shall not 4504 // 4505 // -- have any base classes 4506 if (RD->getNumBases()) 4507 return {NonCLikeKind::BaseClass, 4508 SourceRange(RD->bases_begin()->getBeginLoc(), 4509 RD->bases_end()[-1].getEndLoc())}; 4510 bool Invalid = false; 4511 for (Decl *D : RD->decls()) { 4512 // Don't complain about things we already diagnosed. 4513 if (D->isInvalidDecl()) { 4514 Invalid = true; 4515 continue; 4516 } 4517 4518 // -- have any [...] default member initializers 4519 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4520 if (FD->hasInClassInitializer()) { 4521 auto *Init = FD->getInClassInitializer(); 4522 return {NonCLikeKind::DefaultMemberInit, 4523 Init ? Init->getSourceRange() : D->getSourceRange()}; 4524 } 4525 continue; 4526 } 4527 4528 // FIXME: We don't allow friend declarations. This violates the wording of 4529 // P1766, but not the intent. 4530 if (isa<FriendDecl>(D)) 4531 return {NonCLikeKind::Friend, D->getSourceRange()}; 4532 4533 // -- declare any members other than non-static data members, member 4534 // enumerations, or member classes, 4535 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4536 isa<EnumDecl>(D)) 4537 continue; 4538 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4539 if (!MemberRD) { 4540 if (D->isImplicit()) 4541 continue; 4542 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4543 } 4544 4545 // -- contain a lambda-expression, 4546 if (MemberRD->isLambda()) 4547 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4548 4549 // and all member classes shall also satisfy these requirements 4550 // (recursively). 4551 if (MemberRD->isThisDeclarationADefinition()) { 4552 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4553 return Kind; 4554 } 4555 } 4556 4557 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4558 } 4559 4560 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4561 TypedefNameDecl *NewTD) { 4562 if (TagFromDeclSpec->isInvalidDecl()) 4563 return; 4564 4565 // Do nothing if the tag already has a name for linkage purposes. 4566 if (TagFromDeclSpec->hasNameForLinkage()) 4567 return; 4568 4569 // A well-formed anonymous tag must always be a TUK_Definition. 4570 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4571 4572 // The type must match the tag exactly; no qualifiers allowed. 4573 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4574 Context.getTagDeclType(TagFromDeclSpec))) { 4575 if (getLangOpts().CPlusPlus) 4576 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4577 return; 4578 } 4579 4580 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4581 // An unnamed class with a typedef name for linkage purposes shall [be 4582 // C-like]. 4583 // 4584 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4585 // shouldn't happen, but there are constructs that the language rule doesn't 4586 // disallow for which we can't reasonably avoid computing linkage early. 4587 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4588 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4589 : NonCLikeKind(); 4590 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4591 if (NonCLike || ChangesLinkage) { 4592 if (NonCLike.Kind == NonCLikeKind::Invalid) 4593 return; 4594 4595 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4596 if (ChangesLinkage) { 4597 // If the linkage changes, we can't accept this as an extension. 4598 if (NonCLike.Kind == NonCLikeKind::None) 4599 DiagID = diag::err_typedef_changes_linkage; 4600 else 4601 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4602 } 4603 4604 SourceLocation FixitLoc = 4605 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4606 llvm::SmallString<40> TextToInsert; 4607 TextToInsert += ' '; 4608 TextToInsert += NewTD->getIdentifier()->getName(); 4609 4610 Diag(FixitLoc, DiagID) 4611 << isa<TypeAliasDecl>(NewTD) 4612 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4613 if (NonCLike.Kind != NonCLikeKind::None) { 4614 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4615 << NonCLike.Kind - 1 << NonCLike.Range; 4616 } 4617 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4618 << NewTD << isa<TypeAliasDecl>(NewTD); 4619 4620 if (ChangesLinkage) 4621 return; 4622 } 4623 4624 // Otherwise, set this as the anon-decl typedef for the tag. 4625 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4626 } 4627 4628 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4629 switch (T) { 4630 case DeclSpec::TST_class: 4631 return 0; 4632 case DeclSpec::TST_struct: 4633 return 1; 4634 case DeclSpec::TST_interface: 4635 return 2; 4636 case DeclSpec::TST_union: 4637 return 3; 4638 case DeclSpec::TST_enum: 4639 return 4; 4640 default: 4641 llvm_unreachable("unexpected type specifier"); 4642 } 4643 } 4644 4645 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4646 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4647 /// parameters to cope with template friend declarations. 4648 Decl * 4649 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4650 MultiTemplateParamsArg TemplateParams, 4651 bool IsExplicitInstantiation, 4652 RecordDecl *&AnonRecord) { 4653 Decl *TagD = nullptr; 4654 TagDecl *Tag = nullptr; 4655 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4656 DS.getTypeSpecType() == DeclSpec::TST_struct || 4657 DS.getTypeSpecType() == DeclSpec::TST_interface || 4658 DS.getTypeSpecType() == DeclSpec::TST_union || 4659 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4660 TagD = DS.getRepAsDecl(); 4661 4662 if (!TagD) // We probably had an error 4663 return nullptr; 4664 4665 // Note that the above type specs guarantee that the 4666 // type rep is a Decl, whereas in many of the others 4667 // it's a Type. 4668 if (isa<TagDecl>(TagD)) 4669 Tag = cast<TagDecl>(TagD); 4670 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4671 Tag = CTD->getTemplatedDecl(); 4672 } 4673 4674 if (Tag) { 4675 handleTagNumbering(Tag, S); 4676 Tag->setFreeStanding(); 4677 if (Tag->isInvalidDecl()) 4678 return Tag; 4679 } 4680 4681 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4682 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4683 // or incomplete types shall not be restrict-qualified." 4684 if (TypeQuals & DeclSpec::TQ_restrict) 4685 Diag(DS.getRestrictSpecLoc(), 4686 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4687 << DS.getSourceRange(); 4688 } 4689 4690 if (DS.isInlineSpecified()) 4691 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4692 << getLangOpts().CPlusPlus17; 4693 4694 if (DS.hasConstexprSpecifier()) { 4695 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4696 // and definitions of functions and variables. 4697 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4698 // the declaration of a function or function template 4699 if (Tag) 4700 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4701 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4702 << static_cast<int>(DS.getConstexprSpecifier()); 4703 else 4704 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4705 << static_cast<int>(DS.getConstexprSpecifier()); 4706 // Don't emit warnings after this error. 4707 return TagD; 4708 } 4709 4710 DiagnoseFunctionSpecifiers(DS); 4711 4712 if (DS.isFriendSpecified()) { 4713 // If we're dealing with a decl but not a TagDecl, assume that 4714 // whatever routines created it handled the friendship aspect. 4715 if (TagD && !Tag) 4716 return nullptr; 4717 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4718 } 4719 4720 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4721 bool IsExplicitSpecialization = 4722 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4723 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4724 !IsExplicitInstantiation && !IsExplicitSpecialization && 4725 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4726 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4727 // nested-name-specifier unless it is an explicit instantiation 4728 // or an explicit specialization. 4729 // 4730 // FIXME: We allow class template partial specializations here too, per the 4731 // obvious intent of DR1819. 4732 // 4733 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4734 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4735 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4736 return nullptr; 4737 } 4738 4739 // Track whether this decl-specifier declares anything. 4740 bool DeclaresAnything = true; 4741 4742 // Handle anonymous struct definitions. 4743 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4744 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4745 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4746 if (getLangOpts().CPlusPlus || 4747 Record->getDeclContext()->isRecord()) { 4748 // If CurContext is a DeclContext that can contain statements, 4749 // RecursiveASTVisitor won't visit the decls that 4750 // BuildAnonymousStructOrUnion() will put into CurContext. 4751 // Also store them here so that they can be part of the 4752 // DeclStmt that gets created in this case. 4753 // FIXME: Also return the IndirectFieldDecls created by 4754 // BuildAnonymousStructOr union, for the same reason? 4755 if (CurContext->isFunctionOrMethod()) 4756 AnonRecord = Record; 4757 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4758 Context.getPrintingPolicy()); 4759 } 4760 4761 DeclaresAnything = false; 4762 } 4763 } 4764 4765 // C11 6.7.2.1p2: 4766 // A struct-declaration that does not declare an anonymous structure or 4767 // anonymous union shall contain a struct-declarator-list. 4768 // 4769 // This rule also existed in C89 and C99; the grammar for struct-declaration 4770 // did not permit a struct-declaration without a struct-declarator-list. 4771 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4772 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4773 // Check for Microsoft C extension: anonymous struct/union member. 4774 // Handle 2 kinds of anonymous struct/union: 4775 // struct STRUCT; 4776 // union UNION; 4777 // and 4778 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4779 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4780 if ((Tag && Tag->getDeclName()) || 4781 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4782 RecordDecl *Record = nullptr; 4783 if (Tag) 4784 Record = dyn_cast<RecordDecl>(Tag); 4785 else if (const RecordType *RT = 4786 DS.getRepAsType().get()->getAsStructureType()) 4787 Record = RT->getDecl(); 4788 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4789 Record = UT->getDecl(); 4790 4791 if (Record && getLangOpts().MicrosoftExt) { 4792 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4793 << Record->isUnion() << DS.getSourceRange(); 4794 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4795 } 4796 4797 DeclaresAnything = false; 4798 } 4799 } 4800 4801 // Skip all the checks below if we have a type error. 4802 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4803 (TagD && TagD->isInvalidDecl())) 4804 return TagD; 4805 4806 if (getLangOpts().CPlusPlus && 4807 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4808 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4809 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4810 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4811 DeclaresAnything = false; 4812 4813 if (!DS.isMissingDeclaratorOk()) { 4814 // Customize diagnostic for a typedef missing a name. 4815 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4816 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4817 << DS.getSourceRange(); 4818 else 4819 DeclaresAnything = false; 4820 } 4821 4822 if (DS.isModulePrivateSpecified() && 4823 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4824 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4825 << Tag->getTagKind() 4826 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4827 4828 ActOnDocumentableDecl(TagD); 4829 4830 // C 6.7/2: 4831 // A declaration [...] shall declare at least a declarator [...], a tag, 4832 // or the members of an enumeration. 4833 // C++ [dcl.dcl]p3: 4834 // [If there are no declarators], and except for the declaration of an 4835 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4836 // names into the program, or shall redeclare a name introduced by a 4837 // previous declaration. 4838 if (!DeclaresAnything) { 4839 // In C, we allow this as a (popular) extension / bug. Don't bother 4840 // producing further diagnostics for redundant qualifiers after this. 4841 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 4842 ? diag::err_no_declarators 4843 : diag::ext_no_declarators) 4844 << DS.getSourceRange(); 4845 return TagD; 4846 } 4847 4848 // C++ [dcl.stc]p1: 4849 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4850 // init-declarator-list of the declaration shall not be empty. 4851 // C++ [dcl.fct.spec]p1: 4852 // If a cv-qualifier appears in a decl-specifier-seq, the 4853 // init-declarator-list of the declaration shall not be empty. 4854 // 4855 // Spurious qualifiers here appear to be valid in C. 4856 unsigned DiagID = diag::warn_standalone_specifier; 4857 if (getLangOpts().CPlusPlus) 4858 DiagID = diag::ext_standalone_specifier; 4859 4860 // Note that a linkage-specification sets a storage class, but 4861 // 'extern "C" struct foo;' is actually valid and not theoretically 4862 // useless. 4863 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4864 if (SCS == DeclSpec::SCS_mutable) 4865 // Since mutable is not a viable storage class specifier in C, there is 4866 // no reason to treat it as an extension. Instead, diagnose as an error. 4867 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4868 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4869 Diag(DS.getStorageClassSpecLoc(), DiagID) 4870 << DeclSpec::getSpecifierName(SCS); 4871 } 4872 4873 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4874 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4875 << DeclSpec::getSpecifierName(TSCS); 4876 if (DS.getTypeQualifiers()) { 4877 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4878 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4879 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4880 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4881 // Restrict is covered above. 4882 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4883 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4884 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4885 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4886 } 4887 4888 // Warn about ignored type attributes, for example: 4889 // __attribute__((aligned)) struct A; 4890 // Attributes should be placed after tag to apply to type declaration. 4891 if (!DS.getAttributes().empty()) { 4892 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4893 if (TypeSpecType == DeclSpec::TST_class || 4894 TypeSpecType == DeclSpec::TST_struct || 4895 TypeSpecType == DeclSpec::TST_interface || 4896 TypeSpecType == DeclSpec::TST_union || 4897 TypeSpecType == DeclSpec::TST_enum) { 4898 for (const ParsedAttr &AL : DS.getAttributes()) 4899 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4900 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4901 } 4902 } 4903 4904 return TagD; 4905 } 4906 4907 /// We are trying to inject an anonymous member into the given scope; 4908 /// check if there's an existing declaration that can't be overloaded. 4909 /// 4910 /// \return true if this is a forbidden redeclaration 4911 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4912 Scope *S, 4913 DeclContext *Owner, 4914 DeclarationName Name, 4915 SourceLocation NameLoc, 4916 bool IsUnion) { 4917 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4918 Sema::ForVisibleRedeclaration); 4919 if (!SemaRef.LookupName(R, S)) return false; 4920 4921 // Pick a representative declaration. 4922 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4923 assert(PrevDecl && "Expected a non-null Decl"); 4924 4925 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4926 return false; 4927 4928 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4929 << IsUnion << Name; 4930 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4931 4932 return true; 4933 } 4934 4935 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4936 /// anonymous struct or union AnonRecord into the owning context Owner 4937 /// and scope S. This routine will be invoked just after we realize 4938 /// that an unnamed union or struct is actually an anonymous union or 4939 /// struct, e.g., 4940 /// 4941 /// @code 4942 /// union { 4943 /// int i; 4944 /// float f; 4945 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4946 /// // f into the surrounding scope.x 4947 /// @endcode 4948 /// 4949 /// This routine is recursive, injecting the names of nested anonymous 4950 /// structs/unions into the owning context and scope as well. 4951 static bool 4952 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4953 RecordDecl *AnonRecord, AccessSpecifier AS, 4954 SmallVectorImpl<NamedDecl *> &Chaining) { 4955 bool Invalid = false; 4956 4957 // Look every FieldDecl and IndirectFieldDecl with a name. 4958 for (auto *D : AnonRecord->decls()) { 4959 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4960 cast<NamedDecl>(D)->getDeclName()) { 4961 ValueDecl *VD = cast<ValueDecl>(D); 4962 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4963 VD->getLocation(), 4964 AnonRecord->isUnion())) { 4965 // C++ [class.union]p2: 4966 // The names of the members of an anonymous union shall be 4967 // distinct from the names of any other entity in the 4968 // scope in which the anonymous union is declared. 4969 Invalid = true; 4970 } else { 4971 // C++ [class.union]p2: 4972 // For the purpose of name lookup, after the anonymous union 4973 // definition, the members of the anonymous union are 4974 // considered to have been defined in the scope in which the 4975 // anonymous union is declared. 4976 unsigned OldChainingSize = Chaining.size(); 4977 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4978 Chaining.append(IF->chain_begin(), IF->chain_end()); 4979 else 4980 Chaining.push_back(VD); 4981 4982 assert(Chaining.size() >= 2); 4983 NamedDecl **NamedChain = 4984 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4985 for (unsigned i = 0; i < Chaining.size(); i++) 4986 NamedChain[i] = Chaining[i]; 4987 4988 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4989 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4990 VD->getType(), {NamedChain, Chaining.size()}); 4991 4992 for (const auto *Attr : VD->attrs()) 4993 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4994 4995 IndirectField->setAccess(AS); 4996 IndirectField->setImplicit(); 4997 SemaRef.PushOnScopeChains(IndirectField, S); 4998 4999 // That includes picking up the appropriate access specifier. 5000 if (AS != AS_none) IndirectField->setAccess(AS); 5001 5002 Chaining.resize(OldChainingSize); 5003 } 5004 } 5005 } 5006 5007 return Invalid; 5008 } 5009 5010 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 5011 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 5012 /// illegal input values are mapped to SC_None. 5013 static StorageClass 5014 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 5015 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 5016 assert(StorageClassSpec != DeclSpec::SCS_typedef && 5017 "Parser allowed 'typedef' as storage class VarDecl."); 5018 switch (StorageClassSpec) { 5019 case DeclSpec::SCS_unspecified: return SC_None; 5020 case DeclSpec::SCS_extern: 5021 if (DS.isExternInLinkageSpec()) 5022 return SC_None; 5023 return SC_Extern; 5024 case DeclSpec::SCS_static: return SC_Static; 5025 case DeclSpec::SCS_auto: return SC_Auto; 5026 case DeclSpec::SCS_register: return SC_Register; 5027 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5028 // Illegal SCSs map to None: error reporting is up to the caller. 5029 case DeclSpec::SCS_mutable: // Fall through. 5030 case DeclSpec::SCS_typedef: return SC_None; 5031 } 5032 llvm_unreachable("unknown storage class specifier"); 5033 } 5034 5035 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 5036 assert(Record->hasInClassInitializer()); 5037 5038 for (const auto *I : Record->decls()) { 5039 const auto *FD = dyn_cast<FieldDecl>(I); 5040 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 5041 FD = IFD->getAnonField(); 5042 if (FD && FD->hasInClassInitializer()) 5043 return FD->getLocation(); 5044 } 5045 5046 llvm_unreachable("couldn't find in-class initializer"); 5047 } 5048 5049 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5050 SourceLocation DefaultInitLoc) { 5051 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5052 return; 5053 5054 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 5055 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 5056 } 5057 5058 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5059 CXXRecordDecl *AnonUnion) { 5060 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5061 return; 5062 5063 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 5064 } 5065 5066 /// BuildAnonymousStructOrUnion - Handle the declaration of an 5067 /// anonymous structure or union. Anonymous unions are a C++ feature 5068 /// (C++ [class.union]) and a C11 feature; anonymous structures 5069 /// are a C11 feature and GNU C++ extension. 5070 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 5071 AccessSpecifier AS, 5072 RecordDecl *Record, 5073 const PrintingPolicy &Policy) { 5074 DeclContext *Owner = Record->getDeclContext(); 5075 5076 // Diagnose whether this anonymous struct/union is an extension. 5077 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 5078 Diag(Record->getLocation(), diag::ext_anonymous_union); 5079 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 5080 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 5081 else if (!Record->isUnion() && !getLangOpts().C11) 5082 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 5083 5084 // C and C++ require different kinds of checks for anonymous 5085 // structs/unions. 5086 bool Invalid = false; 5087 if (getLangOpts().CPlusPlus) { 5088 const char *PrevSpec = nullptr; 5089 if (Record->isUnion()) { 5090 // C++ [class.union]p6: 5091 // C++17 [class.union.anon]p2: 5092 // Anonymous unions declared in a named namespace or in the 5093 // global namespace shall be declared static. 5094 unsigned DiagID; 5095 DeclContext *OwnerScope = Owner->getRedeclContext(); 5096 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5097 (OwnerScope->isTranslationUnit() || 5098 (OwnerScope->isNamespace() && 5099 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5100 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5101 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5102 5103 // Recover by adding 'static'. 5104 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5105 PrevSpec, DiagID, Policy); 5106 } 5107 // C++ [class.union]p6: 5108 // A storage class is not allowed in a declaration of an 5109 // anonymous union in a class scope. 5110 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5111 isa<RecordDecl>(Owner)) { 5112 Diag(DS.getStorageClassSpecLoc(), 5113 diag::err_anonymous_union_with_storage_spec) 5114 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5115 5116 // Recover by removing the storage specifier. 5117 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5118 SourceLocation(), 5119 PrevSpec, DiagID, Context.getPrintingPolicy()); 5120 } 5121 } 5122 5123 // Ignore const/volatile/restrict qualifiers. 5124 if (DS.getTypeQualifiers()) { 5125 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5126 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5127 << Record->isUnion() << "const" 5128 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5129 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5130 Diag(DS.getVolatileSpecLoc(), 5131 diag::ext_anonymous_struct_union_qualified) 5132 << Record->isUnion() << "volatile" 5133 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5134 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5135 Diag(DS.getRestrictSpecLoc(), 5136 diag::ext_anonymous_struct_union_qualified) 5137 << Record->isUnion() << "restrict" 5138 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5139 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5140 Diag(DS.getAtomicSpecLoc(), 5141 diag::ext_anonymous_struct_union_qualified) 5142 << Record->isUnion() << "_Atomic" 5143 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5144 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5145 Diag(DS.getUnalignedSpecLoc(), 5146 diag::ext_anonymous_struct_union_qualified) 5147 << Record->isUnion() << "__unaligned" 5148 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5149 5150 DS.ClearTypeQualifiers(); 5151 } 5152 5153 // C++ [class.union]p2: 5154 // The member-specification of an anonymous union shall only 5155 // define non-static data members. [Note: nested types and 5156 // functions cannot be declared within an anonymous union. ] 5157 for (auto *Mem : Record->decls()) { 5158 // Ignore invalid declarations; we already diagnosed them. 5159 if (Mem->isInvalidDecl()) 5160 continue; 5161 5162 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5163 // C++ [class.union]p3: 5164 // An anonymous union shall not have private or protected 5165 // members (clause 11). 5166 assert(FD->getAccess() != AS_none); 5167 if (FD->getAccess() != AS_public) { 5168 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5169 << Record->isUnion() << (FD->getAccess() == AS_protected); 5170 Invalid = true; 5171 } 5172 5173 // C++ [class.union]p1 5174 // An object of a class with a non-trivial constructor, a non-trivial 5175 // copy constructor, a non-trivial destructor, or a non-trivial copy 5176 // assignment operator cannot be a member of a union, nor can an 5177 // array of such objects. 5178 if (CheckNontrivialField(FD)) 5179 Invalid = true; 5180 } else if (Mem->isImplicit()) { 5181 // Any implicit members are fine. 5182 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5183 // This is a type that showed up in an 5184 // elaborated-type-specifier inside the anonymous struct or 5185 // union, but which actually declares a type outside of the 5186 // anonymous struct or union. It's okay. 5187 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5188 if (!MemRecord->isAnonymousStructOrUnion() && 5189 MemRecord->getDeclName()) { 5190 // Visual C++ allows type definition in anonymous struct or union. 5191 if (getLangOpts().MicrosoftExt) 5192 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5193 << Record->isUnion(); 5194 else { 5195 // This is a nested type declaration. 5196 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5197 << Record->isUnion(); 5198 Invalid = true; 5199 } 5200 } else { 5201 // This is an anonymous type definition within another anonymous type. 5202 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5203 // not part of standard C++. 5204 Diag(MemRecord->getLocation(), 5205 diag::ext_anonymous_record_with_anonymous_type) 5206 << Record->isUnion(); 5207 } 5208 } else if (isa<AccessSpecDecl>(Mem)) { 5209 // Any access specifier is fine. 5210 } else if (isa<StaticAssertDecl>(Mem)) { 5211 // In C++1z, static_assert declarations are also fine. 5212 } else { 5213 // We have something that isn't a non-static data 5214 // member. Complain about it. 5215 unsigned DK = diag::err_anonymous_record_bad_member; 5216 if (isa<TypeDecl>(Mem)) 5217 DK = diag::err_anonymous_record_with_type; 5218 else if (isa<FunctionDecl>(Mem)) 5219 DK = diag::err_anonymous_record_with_function; 5220 else if (isa<VarDecl>(Mem)) 5221 DK = diag::err_anonymous_record_with_static; 5222 5223 // Visual C++ allows type definition in anonymous struct or union. 5224 if (getLangOpts().MicrosoftExt && 5225 DK == diag::err_anonymous_record_with_type) 5226 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5227 << Record->isUnion(); 5228 else { 5229 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5230 Invalid = true; 5231 } 5232 } 5233 } 5234 5235 // C++11 [class.union]p8 (DR1460): 5236 // At most one variant member of a union may have a 5237 // brace-or-equal-initializer. 5238 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5239 Owner->isRecord()) 5240 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5241 cast<CXXRecordDecl>(Record)); 5242 } 5243 5244 if (!Record->isUnion() && !Owner->isRecord()) { 5245 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5246 << getLangOpts().CPlusPlus; 5247 Invalid = true; 5248 } 5249 5250 // C++ [dcl.dcl]p3: 5251 // [If there are no declarators], and except for the declaration of an 5252 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5253 // names into the program 5254 // C++ [class.mem]p2: 5255 // each such member-declaration shall either declare at least one member 5256 // name of the class or declare at least one unnamed bit-field 5257 // 5258 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5259 if (getLangOpts().CPlusPlus && Record->field_empty()) 5260 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5261 5262 // Mock up a declarator. 5263 Declarator Dc(DS, DeclaratorContext::Member); 5264 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5265 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5266 5267 // Create a declaration for this anonymous struct/union. 5268 NamedDecl *Anon = nullptr; 5269 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5270 Anon = FieldDecl::Create( 5271 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5272 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5273 /*BitWidth=*/nullptr, /*Mutable=*/false, 5274 /*InitStyle=*/ICIS_NoInit); 5275 Anon->setAccess(AS); 5276 ProcessDeclAttributes(S, Anon, Dc); 5277 5278 if (getLangOpts().CPlusPlus) 5279 FieldCollector->Add(cast<FieldDecl>(Anon)); 5280 } else { 5281 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5282 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5283 if (SCSpec == DeclSpec::SCS_mutable) { 5284 // mutable can only appear on non-static class members, so it's always 5285 // an error here 5286 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5287 Invalid = true; 5288 SC = SC_None; 5289 } 5290 5291 assert(DS.getAttributes().empty() && "No attribute expected"); 5292 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5293 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5294 Context.getTypeDeclType(Record), TInfo, SC); 5295 5296 // Default-initialize the implicit variable. This initialization will be 5297 // trivial in almost all cases, except if a union member has an in-class 5298 // initializer: 5299 // union { int n = 0; }; 5300 if (!Invalid) 5301 ActOnUninitializedDecl(Anon); 5302 } 5303 Anon->setImplicit(); 5304 5305 // Mark this as an anonymous struct/union type. 5306 Record->setAnonymousStructOrUnion(true); 5307 5308 // Add the anonymous struct/union object to the current 5309 // context. We'll be referencing this object when we refer to one of 5310 // its members. 5311 Owner->addDecl(Anon); 5312 5313 // Inject the members of the anonymous struct/union into the owning 5314 // context and into the identifier resolver chain for name lookup 5315 // purposes. 5316 SmallVector<NamedDecl*, 2> Chain; 5317 Chain.push_back(Anon); 5318 5319 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5320 Invalid = true; 5321 5322 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5323 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5324 MangleNumberingContext *MCtx; 5325 Decl *ManglingContextDecl; 5326 std::tie(MCtx, ManglingContextDecl) = 5327 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5328 if (MCtx) { 5329 Context.setManglingNumber( 5330 NewVD, MCtx->getManglingNumber( 5331 NewVD, getMSManglingNumber(getLangOpts(), S))); 5332 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5333 } 5334 } 5335 } 5336 5337 if (Invalid) 5338 Anon->setInvalidDecl(); 5339 5340 return Anon; 5341 } 5342 5343 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5344 /// Microsoft C anonymous structure. 5345 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5346 /// Example: 5347 /// 5348 /// struct A { int a; }; 5349 /// struct B { struct A; int b; }; 5350 /// 5351 /// void foo() { 5352 /// B var; 5353 /// var.a = 3; 5354 /// } 5355 /// 5356 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5357 RecordDecl *Record) { 5358 assert(Record && "expected a record!"); 5359 5360 // Mock up a declarator. 5361 Declarator Dc(DS, DeclaratorContext::TypeName); 5362 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5363 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5364 5365 auto *ParentDecl = cast<RecordDecl>(CurContext); 5366 QualType RecTy = Context.getTypeDeclType(Record); 5367 5368 // Create a declaration for this anonymous struct. 5369 NamedDecl *Anon = 5370 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5371 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5372 /*BitWidth=*/nullptr, /*Mutable=*/false, 5373 /*InitStyle=*/ICIS_NoInit); 5374 Anon->setImplicit(); 5375 5376 // Add the anonymous struct object to the current context. 5377 CurContext->addDecl(Anon); 5378 5379 // Inject the members of the anonymous struct into the current 5380 // context and into the identifier resolver chain for name lookup 5381 // purposes. 5382 SmallVector<NamedDecl*, 2> Chain; 5383 Chain.push_back(Anon); 5384 5385 RecordDecl *RecordDef = Record->getDefinition(); 5386 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5387 diag::err_field_incomplete_or_sizeless) || 5388 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5389 AS_none, Chain)) { 5390 Anon->setInvalidDecl(); 5391 ParentDecl->setInvalidDecl(); 5392 } 5393 5394 return Anon; 5395 } 5396 5397 /// GetNameForDeclarator - Determine the full declaration name for the 5398 /// given Declarator. 5399 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5400 return GetNameFromUnqualifiedId(D.getName()); 5401 } 5402 5403 /// Retrieves the declaration name from a parsed unqualified-id. 5404 DeclarationNameInfo 5405 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5406 DeclarationNameInfo NameInfo; 5407 NameInfo.setLoc(Name.StartLocation); 5408 5409 switch (Name.getKind()) { 5410 5411 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5412 case UnqualifiedIdKind::IK_Identifier: 5413 NameInfo.setName(Name.Identifier); 5414 return NameInfo; 5415 5416 case UnqualifiedIdKind::IK_DeductionGuideName: { 5417 // C++ [temp.deduct.guide]p3: 5418 // The simple-template-id shall name a class template specialization. 5419 // The template-name shall be the same identifier as the template-name 5420 // of the simple-template-id. 5421 // These together intend to imply that the template-name shall name a 5422 // class template. 5423 // FIXME: template<typename T> struct X {}; 5424 // template<typename T> using Y = X<T>; 5425 // Y(int) -> Y<int>; 5426 // satisfies these rules but does not name a class template. 5427 TemplateName TN = Name.TemplateName.get().get(); 5428 auto *Template = TN.getAsTemplateDecl(); 5429 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5430 Diag(Name.StartLocation, 5431 diag::err_deduction_guide_name_not_class_template) 5432 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5433 if (Template) 5434 Diag(Template->getLocation(), diag::note_template_decl_here); 5435 return DeclarationNameInfo(); 5436 } 5437 5438 NameInfo.setName( 5439 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5440 return NameInfo; 5441 } 5442 5443 case UnqualifiedIdKind::IK_OperatorFunctionId: 5444 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5445 Name.OperatorFunctionId.Operator)); 5446 NameInfo.setCXXOperatorNameRange(SourceRange( 5447 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5448 return NameInfo; 5449 5450 case UnqualifiedIdKind::IK_LiteralOperatorId: 5451 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5452 Name.Identifier)); 5453 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5454 return NameInfo; 5455 5456 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5457 TypeSourceInfo *TInfo; 5458 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5459 if (Ty.isNull()) 5460 return DeclarationNameInfo(); 5461 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5462 Context.getCanonicalType(Ty))); 5463 NameInfo.setNamedTypeInfo(TInfo); 5464 return NameInfo; 5465 } 5466 5467 case UnqualifiedIdKind::IK_ConstructorName: { 5468 TypeSourceInfo *TInfo; 5469 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5470 if (Ty.isNull()) 5471 return DeclarationNameInfo(); 5472 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5473 Context.getCanonicalType(Ty))); 5474 NameInfo.setNamedTypeInfo(TInfo); 5475 return NameInfo; 5476 } 5477 5478 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5479 // In well-formed code, we can only have a constructor 5480 // template-id that refers to the current context, so go there 5481 // to find the actual type being constructed. 5482 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5483 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5484 return DeclarationNameInfo(); 5485 5486 // Determine the type of the class being constructed. 5487 QualType CurClassType = Context.getTypeDeclType(CurClass); 5488 5489 // FIXME: Check two things: that the template-id names the same type as 5490 // CurClassType, and that the template-id does not occur when the name 5491 // was qualified. 5492 5493 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5494 Context.getCanonicalType(CurClassType))); 5495 // FIXME: should we retrieve TypeSourceInfo? 5496 NameInfo.setNamedTypeInfo(nullptr); 5497 return NameInfo; 5498 } 5499 5500 case UnqualifiedIdKind::IK_DestructorName: { 5501 TypeSourceInfo *TInfo; 5502 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5503 if (Ty.isNull()) 5504 return DeclarationNameInfo(); 5505 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5506 Context.getCanonicalType(Ty))); 5507 NameInfo.setNamedTypeInfo(TInfo); 5508 return NameInfo; 5509 } 5510 5511 case UnqualifiedIdKind::IK_TemplateId: { 5512 TemplateName TName = Name.TemplateId->Template.get(); 5513 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5514 return Context.getNameForTemplate(TName, TNameLoc); 5515 } 5516 5517 } // switch (Name.getKind()) 5518 5519 llvm_unreachable("Unknown name kind"); 5520 } 5521 5522 static QualType getCoreType(QualType Ty) { 5523 do { 5524 if (Ty->isPointerType() || Ty->isReferenceType()) 5525 Ty = Ty->getPointeeType(); 5526 else if (Ty->isArrayType()) 5527 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5528 else 5529 return Ty.withoutLocalFastQualifiers(); 5530 } while (true); 5531 } 5532 5533 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5534 /// and Definition have "nearly" matching parameters. This heuristic is 5535 /// used to improve diagnostics in the case where an out-of-line function 5536 /// definition doesn't match any declaration within the class or namespace. 5537 /// Also sets Params to the list of indices to the parameters that differ 5538 /// between the declaration and the definition. If hasSimilarParameters 5539 /// returns true and Params is empty, then all of the parameters match. 5540 static bool hasSimilarParameters(ASTContext &Context, 5541 FunctionDecl *Declaration, 5542 FunctionDecl *Definition, 5543 SmallVectorImpl<unsigned> &Params) { 5544 Params.clear(); 5545 if (Declaration->param_size() != Definition->param_size()) 5546 return false; 5547 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5548 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5549 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5550 5551 // The parameter types are identical 5552 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5553 continue; 5554 5555 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5556 QualType DefParamBaseTy = getCoreType(DefParamTy); 5557 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5558 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5559 5560 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5561 (DeclTyName && DeclTyName == DefTyName)) 5562 Params.push_back(Idx); 5563 else // The two parameters aren't even close 5564 return false; 5565 } 5566 5567 return true; 5568 } 5569 5570 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5571 /// declarator needs to be rebuilt in the current instantiation. 5572 /// Any bits of declarator which appear before the name are valid for 5573 /// consideration here. That's specifically the type in the decl spec 5574 /// and the base type in any member-pointer chunks. 5575 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5576 DeclarationName Name) { 5577 // The types we specifically need to rebuild are: 5578 // - typenames, typeofs, and decltypes 5579 // - types which will become injected class names 5580 // Of course, we also need to rebuild any type referencing such a 5581 // type. It's safest to just say "dependent", but we call out a 5582 // few cases here. 5583 5584 DeclSpec &DS = D.getMutableDeclSpec(); 5585 switch (DS.getTypeSpecType()) { 5586 case DeclSpec::TST_typename: 5587 case DeclSpec::TST_typeofType: 5588 case DeclSpec::TST_underlyingType: 5589 case DeclSpec::TST_atomic: { 5590 // Grab the type from the parser. 5591 TypeSourceInfo *TSI = nullptr; 5592 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5593 if (T.isNull() || !T->isInstantiationDependentType()) break; 5594 5595 // Make sure there's a type source info. This isn't really much 5596 // of a waste; most dependent types should have type source info 5597 // attached already. 5598 if (!TSI) 5599 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5600 5601 // Rebuild the type in the current instantiation. 5602 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5603 if (!TSI) return true; 5604 5605 // Store the new type back in the decl spec. 5606 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5607 DS.UpdateTypeRep(LocType); 5608 break; 5609 } 5610 5611 case DeclSpec::TST_decltype: 5612 case DeclSpec::TST_typeofExpr: { 5613 Expr *E = DS.getRepAsExpr(); 5614 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5615 if (Result.isInvalid()) return true; 5616 DS.UpdateExprRep(Result.get()); 5617 break; 5618 } 5619 5620 default: 5621 // Nothing to do for these decl specs. 5622 break; 5623 } 5624 5625 // It doesn't matter what order we do this in. 5626 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5627 DeclaratorChunk &Chunk = D.getTypeObject(I); 5628 5629 // The only type information in the declarator which can come 5630 // before the declaration name is the base type of a member 5631 // pointer. 5632 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5633 continue; 5634 5635 // Rebuild the scope specifier in-place. 5636 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5637 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5638 return true; 5639 } 5640 5641 return false; 5642 } 5643 5644 void Sema::warnOnReservedIdentifier(const NamedDecl *D) { 5645 // Avoid warning twice on the same identifier, and don't warn on redeclaration 5646 // of system decl. 5647 if (D->getPreviousDecl() || D->isImplicit()) 5648 return; 5649 ReservedIdentifierStatus Status = D->isReserved(getLangOpts()); 5650 if (Status != ReservedIdentifierStatus::NotReserved && 5651 !Context.getSourceManager().isInSystemHeader(D->getLocation())) 5652 Diag(D->getLocation(), diag::warn_reserved_extern_symbol) 5653 << D << static_cast<int>(Status); 5654 } 5655 5656 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5657 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 5658 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5659 5660 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5661 Dcl && Dcl->getDeclContext()->isFileContext()) 5662 Dcl->setTopLevelDeclInObjCContainer(); 5663 5664 return Dcl; 5665 } 5666 5667 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5668 /// If T is the name of a class, then each of the following shall have a 5669 /// name different from T: 5670 /// - every static data member of class T; 5671 /// - every member function of class T 5672 /// - every member of class T that is itself a type; 5673 /// \returns true if the declaration name violates these rules. 5674 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5675 DeclarationNameInfo NameInfo) { 5676 DeclarationName Name = NameInfo.getName(); 5677 5678 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5679 while (Record && Record->isAnonymousStructOrUnion()) 5680 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5681 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5682 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5683 return true; 5684 } 5685 5686 return false; 5687 } 5688 5689 /// Diagnose a declaration whose declarator-id has the given 5690 /// nested-name-specifier. 5691 /// 5692 /// \param SS The nested-name-specifier of the declarator-id. 5693 /// 5694 /// \param DC The declaration context to which the nested-name-specifier 5695 /// resolves. 5696 /// 5697 /// \param Name The name of the entity being declared. 5698 /// 5699 /// \param Loc The location of the name of the entity being declared. 5700 /// 5701 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5702 /// we're declaring an explicit / partial specialization / instantiation. 5703 /// 5704 /// \returns true if we cannot safely recover from this error, false otherwise. 5705 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5706 DeclarationName Name, 5707 SourceLocation Loc, bool IsTemplateId) { 5708 DeclContext *Cur = CurContext; 5709 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5710 Cur = Cur->getParent(); 5711 5712 // If the user provided a superfluous scope specifier that refers back to the 5713 // class in which the entity is already declared, diagnose and ignore it. 5714 // 5715 // class X { 5716 // void X::f(); 5717 // }; 5718 // 5719 // Note, it was once ill-formed to give redundant qualification in all 5720 // contexts, but that rule was removed by DR482. 5721 if (Cur->Equals(DC)) { 5722 if (Cur->isRecord()) { 5723 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5724 : diag::err_member_extra_qualification) 5725 << Name << FixItHint::CreateRemoval(SS.getRange()); 5726 SS.clear(); 5727 } else { 5728 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5729 } 5730 return false; 5731 } 5732 5733 // Check whether the qualifying scope encloses the scope of the original 5734 // declaration. For a template-id, we perform the checks in 5735 // CheckTemplateSpecializationScope. 5736 if (!Cur->Encloses(DC) && !IsTemplateId) { 5737 if (Cur->isRecord()) 5738 Diag(Loc, diag::err_member_qualification) 5739 << Name << SS.getRange(); 5740 else if (isa<TranslationUnitDecl>(DC)) 5741 Diag(Loc, diag::err_invalid_declarator_global_scope) 5742 << Name << SS.getRange(); 5743 else if (isa<FunctionDecl>(Cur)) 5744 Diag(Loc, diag::err_invalid_declarator_in_function) 5745 << Name << SS.getRange(); 5746 else if (isa<BlockDecl>(Cur)) 5747 Diag(Loc, diag::err_invalid_declarator_in_block) 5748 << Name << SS.getRange(); 5749 else 5750 Diag(Loc, diag::err_invalid_declarator_scope) 5751 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5752 5753 return true; 5754 } 5755 5756 if (Cur->isRecord()) { 5757 // Cannot qualify members within a class. 5758 Diag(Loc, diag::err_member_qualification) 5759 << Name << SS.getRange(); 5760 SS.clear(); 5761 5762 // C++ constructors and destructors with incorrect scopes can break 5763 // our AST invariants by having the wrong underlying types. If 5764 // that's the case, then drop this declaration entirely. 5765 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5766 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5767 !Context.hasSameType(Name.getCXXNameType(), 5768 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5769 return true; 5770 5771 return false; 5772 } 5773 5774 // C++11 [dcl.meaning]p1: 5775 // [...] "The nested-name-specifier of the qualified declarator-id shall 5776 // not begin with a decltype-specifer" 5777 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5778 while (SpecLoc.getPrefix()) 5779 SpecLoc = SpecLoc.getPrefix(); 5780 if (dyn_cast_or_null<DecltypeType>( 5781 SpecLoc.getNestedNameSpecifier()->getAsType())) 5782 Diag(Loc, diag::err_decltype_in_declarator) 5783 << SpecLoc.getTypeLoc().getSourceRange(); 5784 5785 return false; 5786 } 5787 5788 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5789 MultiTemplateParamsArg TemplateParamLists) { 5790 // TODO: consider using NameInfo for diagnostic. 5791 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5792 DeclarationName Name = NameInfo.getName(); 5793 5794 // All of these full declarators require an identifier. If it doesn't have 5795 // one, the ParsedFreeStandingDeclSpec action should be used. 5796 if (D.isDecompositionDeclarator()) { 5797 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5798 } else if (!Name) { 5799 if (!D.isInvalidType()) // Reject this if we think it is valid. 5800 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5801 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5802 return nullptr; 5803 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5804 return nullptr; 5805 5806 // The scope passed in may not be a decl scope. Zip up the scope tree until 5807 // we find one that is. 5808 while ((S->getFlags() & Scope::DeclScope) == 0 || 5809 (S->getFlags() & Scope::TemplateParamScope) != 0) 5810 S = S->getParent(); 5811 5812 DeclContext *DC = CurContext; 5813 if (D.getCXXScopeSpec().isInvalid()) 5814 D.setInvalidType(); 5815 else if (D.getCXXScopeSpec().isSet()) { 5816 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5817 UPPC_DeclarationQualifier)) 5818 return nullptr; 5819 5820 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5821 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5822 if (!DC || isa<EnumDecl>(DC)) { 5823 // If we could not compute the declaration context, it's because the 5824 // declaration context is dependent but does not refer to a class, 5825 // class template, or class template partial specialization. Complain 5826 // and return early, to avoid the coming semantic disaster. 5827 Diag(D.getIdentifierLoc(), 5828 diag::err_template_qualified_declarator_no_match) 5829 << D.getCXXScopeSpec().getScopeRep() 5830 << D.getCXXScopeSpec().getRange(); 5831 return nullptr; 5832 } 5833 bool IsDependentContext = DC->isDependentContext(); 5834 5835 if (!IsDependentContext && 5836 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5837 return nullptr; 5838 5839 // If a class is incomplete, do not parse entities inside it. 5840 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5841 Diag(D.getIdentifierLoc(), 5842 diag::err_member_def_undefined_record) 5843 << Name << DC << D.getCXXScopeSpec().getRange(); 5844 return nullptr; 5845 } 5846 if (!D.getDeclSpec().isFriendSpecified()) { 5847 if (diagnoseQualifiedDeclaration( 5848 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5849 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5850 if (DC->isRecord()) 5851 return nullptr; 5852 5853 D.setInvalidType(); 5854 } 5855 } 5856 5857 // Check whether we need to rebuild the type of the given 5858 // declaration in the current instantiation. 5859 if (EnteringContext && IsDependentContext && 5860 TemplateParamLists.size() != 0) { 5861 ContextRAII SavedContext(*this, DC); 5862 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5863 D.setInvalidType(); 5864 } 5865 } 5866 5867 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5868 QualType R = TInfo->getType(); 5869 5870 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5871 UPPC_DeclarationType)) 5872 D.setInvalidType(); 5873 5874 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5875 forRedeclarationInCurContext()); 5876 5877 // See if this is a redefinition of a variable in the same scope. 5878 if (!D.getCXXScopeSpec().isSet()) { 5879 bool IsLinkageLookup = false; 5880 bool CreateBuiltins = false; 5881 5882 // If the declaration we're planning to build will be a function 5883 // or object with linkage, then look for another declaration with 5884 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5885 // 5886 // If the declaration we're planning to build will be declared with 5887 // external linkage in the translation unit, create any builtin with 5888 // the same name. 5889 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5890 /* Do nothing*/; 5891 else if (CurContext->isFunctionOrMethod() && 5892 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5893 R->isFunctionType())) { 5894 IsLinkageLookup = true; 5895 CreateBuiltins = 5896 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5897 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5898 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5899 CreateBuiltins = true; 5900 5901 if (IsLinkageLookup) { 5902 Previous.clear(LookupRedeclarationWithLinkage); 5903 Previous.setRedeclarationKind(ForExternalRedeclaration); 5904 } 5905 5906 LookupName(Previous, S, CreateBuiltins); 5907 } else { // Something like "int foo::x;" 5908 LookupQualifiedName(Previous, DC); 5909 5910 // C++ [dcl.meaning]p1: 5911 // When the declarator-id is qualified, the declaration shall refer to a 5912 // previously declared member of the class or namespace to which the 5913 // qualifier refers (or, in the case of a namespace, of an element of the 5914 // inline namespace set of that namespace (7.3.1)) or to a specialization 5915 // thereof; [...] 5916 // 5917 // Note that we already checked the context above, and that we do not have 5918 // enough information to make sure that Previous contains the declaration 5919 // we want to match. For example, given: 5920 // 5921 // class X { 5922 // void f(); 5923 // void f(float); 5924 // }; 5925 // 5926 // void X::f(int) { } // ill-formed 5927 // 5928 // In this case, Previous will point to the overload set 5929 // containing the two f's declared in X, but neither of them 5930 // matches. 5931 5932 // C++ [dcl.meaning]p1: 5933 // [...] the member shall not merely have been introduced by a 5934 // using-declaration in the scope of the class or namespace nominated by 5935 // the nested-name-specifier of the declarator-id. 5936 RemoveUsingDecls(Previous); 5937 } 5938 5939 if (Previous.isSingleResult() && 5940 Previous.getFoundDecl()->isTemplateParameter()) { 5941 // Maybe we will complain about the shadowed template parameter. 5942 if (!D.isInvalidType()) 5943 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5944 Previous.getFoundDecl()); 5945 5946 // Just pretend that we didn't see the previous declaration. 5947 Previous.clear(); 5948 } 5949 5950 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5951 // Forget that the previous declaration is the injected-class-name. 5952 Previous.clear(); 5953 5954 // In C++, the previous declaration we find might be a tag type 5955 // (class or enum). In this case, the new declaration will hide the 5956 // tag type. Note that this applies to functions, function templates, and 5957 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5958 if (Previous.isSingleTagDecl() && 5959 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5960 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5961 Previous.clear(); 5962 5963 // Check that there are no default arguments other than in the parameters 5964 // of a function declaration (C++ only). 5965 if (getLangOpts().CPlusPlus) 5966 CheckExtraCXXDefaultArguments(D); 5967 5968 NamedDecl *New; 5969 5970 bool AddToScope = true; 5971 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5972 if (TemplateParamLists.size()) { 5973 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5974 return nullptr; 5975 } 5976 5977 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5978 } else if (R->isFunctionType()) { 5979 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5980 TemplateParamLists, 5981 AddToScope); 5982 } else { 5983 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5984 AddToScope); 5985 } 5986 5987 if (!New) 5988 return nullptr; 5989 5990 // If this has an identifier and is not a function template specialization, 5991 // add it to the scope stack. 5992 if (New->getDeclName() && AddToScope) 5993 PushOnScopeChains(New, S); 5994 5995 if (isInOpenMPDeclareTargetContext()) 5996 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5997 5998 return New; 5999 } 6000 6001 /// Helper method to turn variable array types into constant array 6002 /// types in certain situations which would otherwise be errors (for 6003 /// GCC compatibility). 6004 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 6005 ASTContext &Context, 6006 bool &SizeIsNegative, 6007 llvm::APSInt &Oversized) { 6008 // This method tries to turn a variable array into a constant 6009 // array even when the size isn't an ICE. This is necessary 6010 // for compatibility with code that depends on gcc's buggy 6011 // constant expression folding, like struct {char x[(int)(char*)2];} 6012 SizeIsNegative = false; 6013 Oversized = 0; 6014 6015 if (T->isDependentType()) 6016 return QualType(); 6017 6018 QualifierCollector Qs; 6019 const Type *Ty = Qs.strip(T); 6020 6021 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 6022 QualType Pointee = PTy->getPointeeType(); 6023 QualType FixedType = 6024 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 6025 Oversized); 6026 if (FixedType.isNull()) return FixedType; 6027 FixedType = Context.getPointerType(FixedType); 6028 return Qs.apply(Context, FixedType); 6029 } 6030 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 6031 QualType Inner = PTy->getInnerType(); 6032 QualType FixedType = 6033 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 6034 Oversized); 6035 if (FixedType.isNull()) return FixedType; 6036 FixedType = Context.getParenType(FixedType); 6037 return Qs.apply(Context, FixedType); 6038 } 6039 6040 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 6041 if (!VLATy) 6042 return QualType(); 6043 6044 QualType ElemTy = VLATy->getElementType(); 6045 if (ElemTy->isVariablyModifiedType()) { 6046 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 6047 SizeIsNegative, Oversized); 6048 if (ElemTy.isNull()) 6049 return QualType(); 6050 } 6051 6052 Expr::EvalResult Result; 6053 if (!VLATy->getSizeExpr() || 6054 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 6055 return QualType(); 6056 6057 llvm::APSInt Res = Result.Val.getInt(); 6058 6059 // Check whether the array size is negative. 6060 if (Res.isSigned() && Res.isNegative()) { 6061 SizeIsNegative = true; 6062 return QualType(); 6063 } 6064 6065 // Check whether the array is too large to be addressed. 6066 unsigned ActiveSizeBits = 6067 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 6068 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 6069 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 6070 : Res.getActiveBits(); 6071 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 6072 Oversized = Res; 6073 return QualType(); 6074 } 6075 6076 QualType FoldedArrayType = Context.getConstantArrayType( 6077 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 6078 return Qs.apply(Context, FoldedArrayType); 6079 } 6080 6081 static void 6082 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 6083 SrcTL = SrcTL.getUnqualifiedLoc(); 6084 DstTL = DstTL.getUnqualifiedLoc(); 6085 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 6086 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 6087 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 6088 DstPTL.getPointeeLoc()); 6089 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 6090 return; 6091 } 6092 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 6093 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 6094 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 6095 DstPTL.getInnerLoc()); 6096 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 6097 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 6098 return; 6099 } 6100 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6101 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6102 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6103 TypeLoc DstElemTL = DstATL.getElementLoc(); 6104 if (VariableArrayTypeLoc SrcElemATL = 6105 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6106 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6107 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6108 } else { 6109 DstElemTL.initializeFullCopy(SrcElemTL); 6110 } 6111 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6112 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6113 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6114 } 6115 6116 /// Helper method to turn variable array types into constant array 6117 /// types in certain situations which would otherwise be errors (for 6118 /// GCC compatibility). 6119 static TypeSourceInfo* 6120 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6121 ASTContext &Context, 6122 bool &SizeIsNegative, 6123 llvm::APSInt &Oversized) { 6124 QualType FixedTy 6125 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6126 SizeIsNegative, Oversized); 6127 if (FixedTy.isNull()) 6128 return nullptr; 6129 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6130 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6131 FixedTInfo->getTypeLoc()); 6132 return FixedTInfo; 6133 } 6134 6135 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6136 /// true if we were successful. 6137 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, 6138 QualType &T, SourceLocation Loc, 6139 unsigned FailedFoldDiagID) { 6140 bool SizeIsNegative; 6141 llvm::APSInt Oversized; 6142 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6143 TInfo, Context, SizeIsNegative, Oversized); 6144 if (FixedTInfo) { 6145 Diag(Loc, diag::ext_vla_folded_to_constant); 6146 TInfo = FixedTInfo; 6147 T = FixedTInfo->getType(); 6148 return true; 6149 } 6150 6151 if (SizeIsNegative) 6152 Diag(Loc, diag::err_typecheck_negative_array_size); 6153 else if (Oversized.getBoolValue()) 6154 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10); 6155 else if (FailedFoldDiagID) 6156 Diag(Loc, FailedFoldDiagID); 6157 return false; 6158 } 6159 6160 /// Register the given locally-scoped extern "C" declaration so 6161 /// that it can be found later for redeclarations. We include any extern "C" 6162 /// declaration that is not visible in the translation unit here, not just 6163 /// function-scope declarations. 6164 void 6165 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6166 if (!getLangOpts().CPlusPlus && 6167 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6168 // Don't need to track declarations in the TU in C. 6169 return; 6170 6171 // Note that we have a locally-scoped external with this name. 6172 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6173 } 6174 6175 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6176 // FIXME: We can have multiple results via __attribute__((overloadable)). 6177 auto Result = Context.getExternCContextDecl()->lookup(Name); 6178 return Result.empty() ? nullptr : *Result.begin(); 6179 } 6180 6181 /// Diagnose function specifiers on a declaration of an identifier that 6182 /// does not identify a function. 6183 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6184 // FIXME: We should probably indicate the identifier in question to avoid 6185 // confusion for constructs like "virtual int a(), b;" 6186 if (DS.isVirtualSpecified()) 6187 Diag(DS.getVirtualSpecLoc(), 6188 diag::err_virtual_non_function); 6189 6190 if (DS.hasExplicitSpecifier()) 6191 Diag(DS.getExplicitSpecLoc(), 6192 diag::err_explicit_non_function); 6193 6194 if (DS.isNoreturnSpecified()) 6195 Diag(DS.getNoreturnSpecLoc(), 6196 diag::err_noreturn_non_function); 6197 } 6198 6199 NamedDecl* 6200 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6201 TypeSourceInfo *TInfo, LookupResult &Previous) { 6202 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6203 if (D.getCXXScopeSpec().isSet()) { 6204 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6205 << D.getCXXScopeSpec().getRange(); 6206 D.setInvalidType(); 6207 // Pretend we didn't see the scope specifier. 6208 DC = CurContext; 6209 Previous.clear(); 6210 } 6211 6212 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6213 6214 if (D.getDeclSpec().isInlineSpecified()) 6215 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6216 << getLangOpts().CPlusPlus17; 6217 if (D.getDeclSpec().hasConstexprSpecifier()) 6218 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6219 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6220 6221 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6222 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6223 Diag(D.getName().StartLocation, 6224 diag::err_deduction_guide_invalid_specifier) 6225 << "typedef"; 6226 else 6227 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6228 << D.getName().getSourceRange(); 6229 return nullptr; 6230 } 6231 6232 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6233 if (!NewTD) return nullptr; 6234 6235 // Handle attributes prior to checking for duplicates in MergeVarDecl 6236 ProcessDeclAttributes(S, NewTD, D); 6237 6238 CheckTypedefForVariablyModifiedType(S, NewTD); 6239 6240 bool Redeclaration = D.isRedeclaration(); 6241 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6242 D.setRedeclaration(Redeclaration); 6243 return ND; 6244 } 6245 6246 void 6247 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6248 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6249 // then it shall have block scope. 6250 // Note that variably modified types must be fixed before merging the decl so 6251 // that redeclarations will match. 6252 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6253 QualType T = TInfo->getType(); 6254 if (T->isVariablyModifiedType()) { 6255 setFunctionHasBranchProtectedScope(); 6256 6257 if (S->getFnParent() == nullptr) { 6258 bool SizeIsNegative; 6259 llvm::APSInt Oversized; 6260 TypeSourceInfo *FixedTInfo = 6261 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6262 SizeIsNegative, 6263 Oversized); 6264 if (FixedTInfo) { 6265 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6266 NewTD->setTypeSourceInfo(FixedTInfo); 6267 } else { 6268 if (SizeIsNegative) 6269 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6270 else if (T->isVariableArrayType()) 6271 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6272 else if (Oversized.getBoolValue()) 6273 Diag(NewTD->getLocation(), diag::err_array_too_large) 6274 << toString(Oversized, 10); 6275 else 6276 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6277 NewTD->setInvalidDecl(); 6278 } 6279 } 6280 } 6281 } 6282 6283 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6284 /// declares a typedef-name, either using the 'typedef' type specifier or via 6285 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6286 NamedDecl* 6287 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6288 LookupResult &Previous, bool &Redeclaration) { 6289 6290 // Find the shadowed declaration before filtering for scope. 6291 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6292 6293 // Merge the decl with the existing one if appropriate. If the decl is 6294 // in an outer scope, it isn't the same thing. 6295 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6296 /*AllowInlineNamespace*/false); 6297 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6298 if (!Previous.empty()) { 6299 Redeclaration = true; 6300 MergeTypedefNameDecl(S, NewTD, Previous); 6301 } else { 6302 inferGslPointerAttribute(NewTD); 6303 } 6304 6305 if (ShadowedDecl && !Redeclaration) 6306 CheckShadow(NewTD, ShadowedDecl, Previous); 6307 6308 // If this is the C FILE type, notify the AST context. 6309 if (IdentifierInfo *II = NewTD->getIdentifier()) 6310 if (!NewTD->isInvalidDecl() && 6311 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6312 if (II->isStr("FILE")) 6313 Context.setFILEDecl(NewTD); 6314 else if (II->isStr("jmp_buf")) 6315 Context.setjmp_bufDecl(NewTD); 6316 else if (II->isStr("sigjmp_buf")) 6317 Context.setsigjmp_bufDecl(NewTD); 6318 else if (II->isStr("ucontext_t")) 6319 Context.setucontext_tDecl(NewTD); 6320 } 6321 6322 return NewTD; 6323 } 6324 6325 /// Determines whether the given declaration is an out-of-scope 6326 /// previous declaration. 6327 /// 6328 /// This routine should be invoked when name lookup has found a 6329 /// previous declaration (PrevDecl) that is not in the scope where a 6330 /// new declaration by the same name is being introduced. If the new 6331 /// declaration occurs in a local scope, previous declarations with 6332 /// linkage may still be considered previous declarations (C99 6333 /// 6.2.2p4-5, C++ [basic.link]p6). 6334 /// 6335 /// \param PrevDecl the previous declaration found by name 6336 /// lookup 6337 /// 6338 /// \param DC the context in which the new declaration is being 6339 /// declared. 6340 /// 6341 /// \returns true if PrevDecl is an out-of-scope previous declaration 6342 /// for a new delcaration with the same name. 6343 static bool 6344 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6345 ASTContext &Context) { 6346 if (!PrevDecl) 6347 return false; 6348 6349 if (!PrevDecl->hasLinkage()) 6350 return false; 6351 6352 if (Context.getLangOpts().CPlusPlus) { 6353 // C++ [basic.link]p6: 6354 // If there is a visible declaration of an entity with linkage 6355 // having the same name and type, ignoring entities declared 6356 // outside the innermost enclosing namespace scope, the block 6357 // scope declaration declares that same entity and receives the 6358 // linkage of the previous declaration. 6359 DeclContext *OuterContext = DC->getRedeclContext(); 6360 if (!OuterContext->isFunctionOrMethod()) 6361 // This rule only applies to block-scope declarations. 6362 return false; 6363 6364 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6365 if (PrevOuterContext->isRecord()) 6366 // We found a member function: ignore it. 6367 return false; 6368 6369 // Find the innermost enclosing namespace for the new and 6370 // previous declarations. 6371 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6372 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6373 6374 // The previous declaration is in a different namespace, so it 6375 // isn't the same function. 6376 if (!OuterContext->Equals(PrevOuterContext)) 6377 return false; 6378 } 6379 6380 return true; 6381 } 6382 6383 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6384 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6385 if (!SS.isSet()) return; 6386 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6387 } 6388 6389 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6390 QualType type = decl->getType(); 6391 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6392 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6393 // Various kinds of declaration aren't allowed to be __autoreleasing. 6394 unsigned kind = -1U; 6395 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6396 if (var->hasAttr<BlocksAttr>()) 6397 kind = 0; // __block 6398 else if (!var->hasLocalStorage()) 6399 kind = 1; // global 6400 } else if (isa<ObjCIvarDecl>(decl)) { 6401 kind = 3; // ivar 6402 } else if (isa<FieldDecl>(decl)) { 6403 kind = 2; // field 6404 } 6405 6406 if (kind != -1U) { 6407 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6408 << kind; 6409 } 6410 } else if (lifetime == Qualifiers::OCL_None) { 6411 // Try to infer lifetime. 6412 if (!type->isObjCLifetimeType()) 6413 return false; 6414 6415 lifetime = type->getObjCARCImplicitLifetime(); 6416 type = Context.getLifetimeQualifiedType(type, lifetime); 6417 decl->setType(type); 6418 } 6419 6420 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6421 // Thread-local variables cannot have lifetime. 6422 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6423 var->getTLSKind()) { 6424 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6425 << var->getType(); 6426 return true; 6427 } 6428 } 6429 6430 return false; 6431 } 6432 6433 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6434 if (Decl->getType().hasAddressSpace()) 6435 return; 6436 if (Decl->getType()->isDependentType()) 6437 return; 6438 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6439 QualType Type = Var->getType(); 6440 if (Type->isSamplerT() || Type->isVoidType()) 6441 return; 6442 LangAS ImplAS = LangAS::opencl_private; 6443 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the 6444 // __opencl_c_program_scope_global_variables feature, the address space 6445 // for a variable at program scope or a static or extern variable inside 6446 // a function are inferred to be __global. 6447 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) && 6448 Var->hasGlobalStorage()) 6449 ImplAS = LangAS::opencl_global; 6450 // If the original type from a decayed type is an array type and that array 6451 // type has no address space yet, deduce it now. 6452 if (auto DT = dyn_cast<DecayedType>(Type)) { 6453 auto OrigTy = DT->getOriginalType(); 6454 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6455 // Add the address space to the original array type and then propagate 6456 // that to the element type through `getAsArrayType`. 6457 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6458 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6459 // Re-generate the decayed type. 6460 Type = Context.getDecayedType(OrigTy); 6461 } 6462 } 6463 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6464 // Apply any qualifiers (including address space) from the array type to 6465 // the element type. This implements C99 6.7.3p8: "If the specification of 6466 // an array type includes any type qualifiers, the element type is so 6467 // qualified, not the array type." 6468 if (Type->isArrayType()) 6469 Type = QualType(Context.getAsArrayType(Type), 0); 6470 Decl->setType(Type); 6471 } 6472 } 6473 6474 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6475 // Ensure that an auto decl is deduced otherwise the checks below might cache 6476 // the wrong linkage. 6477 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6478 6479 // 'weak' only applies to declarations with external linkage. 6480 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6481 if (!ND.isExternallyVisible()) { 6482 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6483 ND.dropAttr<WeakAttr>(); 6484 } 6485 } 6486 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6487 if (ND.isExternallyVisible()) { 6488 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6489 ND.dropAttr<WeakRefAttr>(); 6490 ND.dropAttr<AliasAttr>(); 6491 } 6492 } 6493 6494 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6495 if (VD->hasInit()) { 6496 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6497 assert(VD->isThisDeclarationADefinition() && 6498 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6499 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6500 VD->dropAttr<AliasAttr>(); 6501 } 6502 } 6503 } 6504 6505 // 'selectany' only applies to externally visible variable declarations. 6506 // It does not apply to functions. 6507 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6508 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6509 S.Diag(Attr->getLocation(), 6510 diag::err_attribute_selectany_non_extern_data); 6511 ND.dropAttr<SelectAnyAttr>(); 6512 } 6513 } 6514 6515 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6516 auto *VD = dyn_cast<VarDecl>(&ND); 6517 bool IsAnonymousNS = false; 6518 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6519 if (VD) { 6520 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6521 while (NS && !IsAnonymousNS) { 6522 IsAnonymousNS = NS->isAnonymousNamespace(); 6523 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6524 } 6525 } 6526 // dll attributes require external linkage. Static locals may have external 6527 // linkage but still cannot be explicitly imported or exported. 6528 // In Microsoft mode, a variable defined in anonymous namespace must have 6529 // external linkage in order to be exported. 6530 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6531 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6532 (!AnonNSInMicrosoftMode && 6533 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6534 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6535 << &ND << Attr; 6536 ND.setInvalidDecl(); 6537 } 6538 } 6539 6540 // Check the attributes on the function type, if any. 6541 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6542 // Don't declare this variable in the second operand of the for-statement; 6543 // GCC miscompiles that by ending its lifetime before evaluating the 6544 // third operand. See gcc.gnu.org/PR86769. 6545 AttributedTypeLoc ATL; 6546 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6547 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6548 TL = ATL.getModifiedLoc()) { 6549 // The [[lifetimebound]] attribute can be applied to the implicit object 6550 // parameter of a non-static member function (other than a ctor or dtor) 6551 // by applying it to the function type. 6552 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6553 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6554 if (!MD || MD->isStatic()) { 6555 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6556 << !MD << A->getRange(); 6557 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6558 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6559 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6560 } 6561 } 6562 } 6563 } 6564 } 6565 6566 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6567 NamedDecl *NewDecl, 6568 bool IsSpecialization, 6569 bool IsDefinition) { 6570 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6571 return; 6572 6573 bool IsTemplate = false; 6574 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6575 OldDecl = OldTD->getTemplatedDecl(); 6576 IsTemplate = true; 6577 if (!IsSpecialization) 6578 IsDefinition = false; 6579 } 6580 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6581 NewDecl = NewTD->getTemplatedDecl(); 6582 IsTemplate = true; 6583 } 6584 6585 if (!OldDecl || !NewDecl) 6586 return; 6587 6588 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6589 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6590 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6591 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6592 6593 // dllimport and dllexport are inheritable attributes so we have to exclude 6594 // inherited attribute instances. 6595 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6596 (NewExportAttr && !NewExportAttr->isInherited()); 6597 6598 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6599 // the only exception being explicit specializations. 6600 // Implicitly generated declarations are also excluded for now because there 6601 // is no other way to switch these to use dllimport or dllexport. 6602 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6603 6604 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6605 // Allow with a warning for free functions and global variables. 6606 bool JustWarn = false; 6607 if (!OldDecl->isCXXClassMember()) { 6608 auto *VD = dyn_cast<VarDecl>(OldDecl); 6609 if (VD && !VD->getDescribedVarTemplate()) 6610 JustWarn = true; 6611 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6612 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6613 JustWarn = true; 6614 } 6615 6616 // We cannot change a declaration that's been used because IR has already 6617 // been emitted. Dllimported functions will still work though (modulo 6618 // address equality) as they can use the thunk. 6619 if (OldDecl->isUsed()) 6620 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6621 JustWarn = false; 6622 6623 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6624 : diag::err_attribute_dll_redeclaration; 6625 S.Diag(NewDecl->getLocation(), DiagID) 6626 << NewDecl 6627 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6628 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6629 if (!JustWarn) { 6630 NewDecl->setInvalidDecl(); 6631 return; 6632 } 6633 } 6634 6635 // A redeclaration is not allowed to drop a dllimport attribute, the only 6636 // exceptions being inline function definitions (except for function 6637 // templates), local extern declarations, qualified friend declarations or 6638 // special MSVC extension: in the last case, the declaration is treated as if 6639 // it were marked dllexport. 6640 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6641 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 6642 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6643 // Ignore static data because out-of-line definitions are diagnosed 6644 // separately. 6645 IsStaticDataMember = VD->isStaticDataMember(); 6646 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6647 VarDecl::DeclarationOnly; 6648 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6649 IsInline = FD->isInlined(); 6650 IsQualifiedFriend = FD->getQualifier() && 6651 FD->getFriendObjectKind() == Decl::FOK_Declared; 6652 } 6653 6654 if (OldImportAttr && !HasNewAttr && 6655 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 6656 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6657 if (IsMicrosoftABI && IsDefinition) { 6658 S.Diag(NewDecl->getLocation(), 6659 diag::warn_redeclaration_without_import_attribute) 6660 << NewDecl; 6661 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6662 NewDecl->dropAttr<DLLImportAttr>(); 6663 NewDecl->addAttr( 6664 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6665 } else { 6666 S.Diag(NewDecl->getLocation(), 6667 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6668 << NewDecl << OldImportAttr; 6669 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6670 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6671 OldDecl->dropAttr<DLLImportAttr>(); 6672 NewDecl->dropAttr<DLLImportAttr>(); 6673 } 6674 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 6675 // In MinGW, seeing a function declared inline drops the dllimport 6676 // attribute. 6677 OldDecl->dropAttr<DLLImportAttr>(); 6678 NewDecl->dropAttr<DLLImportAttr>(); 6679 S.Diag(NewDecl->getLocation(), 6680 diag::warn_dllimport_dropped_from_inline_function) 6681 << NewDecl << OldImportAttr; 6682 } 6683 6684 // A specialization of a class template member function is processed here 6685 // since it's a redeclaration. If the parent class is dllexport, the 6686 // specialization inherits that attribute. This doesn't happen automatically 6687 // since the parent class isn't instantiated until later. 6688 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6689 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6690 !NewImportAttr && !NewExportAttr) { 6691 if (const DLLExportAttr *ParentExportAttr = 6692 MD->getParent()->getAttr<DLLExportAttr>()) { 6693 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6694 NewAttr->setInherited(true); 6695 NewDecl->addAttr(NewAttr); 6696 } 6697 } 6698 } 6699 } 6700 6701 /// Given that we are within the definition of the given function, 6702 /// will that definition behave like C99's 'inline', where the 6703 /// definition is discarded except for optimization purposes? 6704 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6705 // Try to avoid calling GetGVALinkageForFunction. 6706 6707 // All cases of this require the 'inline' keyword. 6708 if (!FD->isInlined()) return false; 6709 6710 // This is only possible in C++ with the gnu_inline attribute. 6711 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6712 return false; 6713 6714 // Okay, go ahead and call the relatively-more-expensive function. 6715 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6716 } 6717 6718 /// Determine whether a variable is extern "C" prior to attaching 6719 /// an initializer. We can't just call isExternC() here, because that 6720 /// will also compute and cache whether the declaration is externally 6721 /// visible, which might change when we attach the initializer. 6722 /// 6723 /// This can only be used if the declaration is known to not be a 6724 /// redeclaration of an internal linkage declaration. 6725 /// 6726 /// For instance: 6727 /// 6728 /// auto x = []{}; 6729 /// 6730 /// Attaching the initializer here makes this declaration not externally 6731 /// visible, because its type has internal linkage. 6732 /// 6733 /// FIXME: This is a hack. 6734 template<typename T> 6735 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6736 if (S.getLangOpts().CPlusPlus) { 6737 // In C++, the overloadable attribute negates the effects of extern "C". 6738 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6739 return false; 6740 6741 // So do CUDA's host/device attributes. 6742 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6743 D->template hasAttr<CUDAHostAttr>())) 6744 return false; 6745 } 6746 return D->isExternC(); 6747 } 6748 6749 static bool shouldConsiderLinkage(const VarDecl *VD) { 6750 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6751 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6752 isa<OMPDeclareMapperDecl>(DC)) 6753 return VD->hasExternalStorage(); 6754 if (DC->isFileContext()) 6755 return true; 6756 if (DC->isRecord()) 6757 return false; 6758 if (isa<RequiresExprBodyDecl>(DC)) 6759 return false; 6760 llvm_unreachable("Unexpected context"); 6761 } 6762 6763 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6764 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6765 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6766 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6767 return true; 6768 if (DC->isRecord()) 6769 return false; 6770 llvm_unreachable("Unexpected context"); 6771 } 6772 6773 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6774 ParsedAttr::Kind Kind) { 6775 // Check decl attributes on the DeclSpec. 6776 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6777 return true; 6778 6779 // Walk the declarator structure, checking decl attributes that were in a type 6780 // position to the decl itself. 6781 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6782 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6783 return true; 6784 } 6785 6786 // Finally, check attributes on the decl itself. 6787 return PD.getAttributes().hasAttribute(Kind); 6788 } 6789 6790 /// Adjust the \c DeclContext for a function or variable that might be a 6791 /// function-local external declaration. 6792 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6793 if (!DC->isFunctionOrMethod()) 6794 return false; 6795 6796 // If this is a local extern function or variable declared within a function 6797 // template, don't add it into the enclosing namespace scope until it is 6798 // instantiated; it might have a dependent type right now. 6799 if (DC->isDependentContext()) 6800 return true; 6801 6802 // C++11 [basic.link]p7: 6803 // When a block scope declaration of an entity with linkage is not found to 6804 // refer to some other declaration, then that entity is a member of the 6805 // innermost enclosing namespace. 6806 // 6807 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6808 // semantically-enclosing namespace, not a lexically-enclosing one. 6809 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6810 DC = DC->getParent(); 6811 return true; 6812 } 6813 6814 /// Returns true if given declaration has external C language linkage. 6815 static bool isDeclExternC(const Decl *D) { 6816 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6817 return FD->isExternC(); 6818 if (const auto *VD = dyn_cast<VarDecl>(D)) 6819 return VD->isExternC(); 6820 6821 llvm_unreachable("Unknown type of decl!"); 6822 } 6823 6824 /// Returns true if there hasn't been any invalid type diagnosed. 6825 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { 6826 DeclContext *DC = NewVD->getDeclContext(); 6827 QualType R = NewVD->getType(); 6828 6829 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6830 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6831 // argument. 6832 if (R->isImageType() || R->isPipeType()) { 6833 Se.Diag(NewVD->getLocation(), 6834 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6835 << R; 6836 NewVD->setInvalidDecl(); 6837 return false; 6838 } 6839 6840 // OpenCL v1.2 s6.9.r: 6841 // The event type cannot be used to declare a program scope variable. 6842 // OpenCL v2.0 s6.9.q: 6843 // The clk_event_t and reserve_id_t types cannot be declared in program 6844 // scope. 6845 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { 6846 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6847 Se.Diag(NewVD->getLocation(), 6848 diag::err_invalid_type_for_program_scope_var) 6849 << R; 6850 NewVD->setInvalidDecl(); 6851 return false; 6852 } 6853 } 6854 6855 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6856 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 6857 Se.getLangOpts())) { 6858 QualType NR = R.getCanonicalType(); 6859 while (NR->isPointerType() || NR->isMemberFunctionPointerType() || 6860 NR->isReferenceType()) { 6861 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || 6862 NR->isFunctionReferenceType()) { 6863 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer) 6864 << NR->isReferenceType(); 6865 NewVD->setInvalidDecl(); 6866 return false; 6867 } 6868 NR = NR->getPointeeType(); 6869 } 6870 } 6871 6872 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 6873 Se.getLangOpts())) { 6874 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6875 // half array type (unless the cl_khr_fp16 extension is enabled). 6876 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6877 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R; 6878 NewVD->setInvalidDecl(); 6879 return false; 6880 } 6881 } 6882 6883 // OpenCL v1.2 s6.9.r: 6884 // The event type cannot be used with the __local, __constant and __global 6885 // address space qualifiers. 6886 if (R->isEventT()) { 6887 if (R.getAddressSpace() != LangAS::opencl_private) { 6888 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual); 6889 NewVD->setInvalidDecl(); 6890 return false; 6891 } 6892 } 6893 6894 if (R->isSamplerT()) { 6895 // OpenCL v1.2 s6.9.b p4: 6896 // The sampler type cannot be used with the __local and __global address 6897 // space qualifiers. 6898 if (R.getAddressSpace() == LangAS::opencl_local || 6899 R.getAddressSpace() == LangAS::opencl_global) { 6900 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace); 6901 NewVD->setInvalidDecl(); 6902 } 6903 6904 // OpenCL v1.2 s6.12.14.1: 6905 // A global sampler must be declared with either the constant address 6906 // space qualifier or with the const qualifier. 6907 if (DC->isTranslationUnit() && 6908 !(R.getAddressSpace() == LangAS::opencl_constant || 6909 R.isConstQualified())) { 6910 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler); 6911 NewVD->setInvalidDecl(); 6912 } 6913 if (NewVD->isInvalidDecl()) 6914 return false; 6915 } 6916 6917 return true; 6918 } 6919 6920 template <typename AttrTy> 6921 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { 6922 const TypedefNameDecl *TND = TT->getDecl(); 6923 if (const auto *Attribute = TND->getAttr<AttrTy>()) { 6924 AttrTy *Clone = Attribute->clone(S.Context); 6925 Clone->setInherited(true); 6926 D->addAttr(Clone); 6927 } 6928 } 6929 6930 NamedDecl *Sema::ActOnVariableDeclarator( 6931 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6932 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6933 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6934 QualType R = TInfo->getType(); 6935 DeclarationName Name = GetNameForDeclarator(D).getName(); 6936 6937 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6938 6939 if (D.isDecompositionDeclarator()) { 6940 // Take the name of the first declarator as our name for diagnostic 6941 // purposes. 6942 auto &Decomp = D.getDecompositionDeclarator(); 6943 if (!Decomp.bindings().empty()) { 6944 II = Decomp.bindings()[0].Name; 6945 Name = II; 6946 } 6947 } else if (!II) { 6948 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6949 return nullptr; 6950 } 6951 6952 6953 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6954 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6955 6956 // dllimport globals without explicit storage class are treated as extern. We 6957 // have to change the storage class this early to get the right DeclContext. 6958 if (SC == SC_None && !DC->isRecord() && 6959 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6960 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6961 SC = SC_Extern; 6962 6963 DeclContext *OriginalDC = DC; 6964 bool IsLocalExternDecl = SC == SC_Extern && 6965 adjustContextForLocalExternDecl(DC); 6966 6967 if (SCSpec == DeclSpec::SCS_mutable) { 6968 // mutable can only appear on non-static class members, so it's always 6969 // an error here 6970 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6971 D.setInvalidType(); 6972 SC = SC_None; 6973 } 6974 6975 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6976 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6977 D.getDeclSpec().getStorageClassSpecLoc())) { 6978 // In C++11, the 'register' storage class specifier is deprecated. 6979 // Suppress the warning in system macros, it's used in macros in some 6980 // popular C system headers, such as in glibc's htonl() macro. 6981 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6982 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6983 : diag::warn_deprecated_register) 6984 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6985 } 6986 6987 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6988 6989 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6990 // C99 6.9p2: The storage-class specifiers auto and register shall not 6991 // appear in the declaration specifiers in an external declaration. 6992 // Global Register+Asm is a GNU extension we support. 6993 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6994 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6995 D.setInvalidType(); 6996 } 6997 } 6998 6999 // If this variable has a VLA type and an initializer, try to 7000 // fold to a constant-sized type. This is otherwise invalid. 7001 if (D.hasInitializer() && R->isVariableArrayType()) 7002 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(), 7003 /*DiagID=*/0); 7004 7005 bool IsMemberSpecialization = false; 7006 bool IsVariableTemplateSpecialization = false; 7007 bool IsPartialSpecialization = false; 7008 bool IsVariableTemplate = false; 7009 VarDecl *NewVD = nullptr; 7010 VarTemplateDecl *NewTemplate = nullptr; 7011 TemplateParameterList *TemplateParams = nullptr; 7012 if (!getLangOpts().CPlusPlus) { 7013 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 7014 II, R, TInfo, SC); 7015 7016 if (R->getContainedDeducedType()) 7017 ParsingInitForAutoVars.insert(NewVD); 7018 7019 if (D.isInvalidType()) 7020 NewVD->setInvalidDecl(); 7021 7022 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 7023 NewVD->hasLocalStorage()) 7024 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 7025 NTCUC_AutoVar, NTCUK_Destruct); 7026 } else { 7027 bool Invalid = false; 7028 7029 if (DC->isRecord() && !CurContext->isRecord()) { 7030 // This is an out-of-line definition of a static data member. 7031 switch (SC) { 7032 case SC_None: 7033 break; 7034 case SC_Static: 7035 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7036 diag::err_static_out_of_line) 7037 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7038 break; 7039 case SC_Auto: 7040 case SC_Register: 7041 case SC_Extern: 7042 // [dcl.stc] p2: The auto or register specifiers shall be applied only 7043 // to names of variables declared in a block or to function parameters. 7044 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 7045 // of class members 7046 7047 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7048 diag::err_storage_class_for_static_member) 7049 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7050 break; 7051 case SC_PrivateExtern: 7052 llvm_unreachable("C storage class in c++!"); 7053 } 7054 } 7055 7056 if (SC == SC_Static && CurContext->isRecord()) { 7057 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 7058 // Walk up the enclosing DeclContexts to check for any that are 7059 // incompatible with static data members. 7060 const DeclContext *FunctionOrMethod = nullptr; 7061 const CXXRecordDecl *AnonStruct = nullptr; 7062 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 7063 if (Ctxt->isFunctionOrMethod()) { 7064 FunctionOrMethod = Ctxt; 7065 break; 7066 } 7067 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 7068 if (ParentDecl && !ParentDecl->getDeclName()) { 7069 AnonStruct = ParentDecl; 7070 break; 7071 } 7072 } 7073 if (FunctionOrMethod) { 7074 // C++ [class.static.data]p5: A local class shall not have static data 7075 // members. 7076 Diag(D.getIdentifierLoc(), 7077 diag::err_static_data_member_not_allowed_in_local_class) 7078 << Name << RD->getDeclName() << RD->getTagKind(); 7079 } else if (AnonStruct) { 7080 // C++ [class.static.data]p4: Unnamed classes and classes contained 7081 // directly or indirectly within unnamed classes shall not contain 7082 // static data members. 7083 Diag(D.getIdentifierLoc(), 7084 diag::err_static_data_member_not_allowed_in_anon_struct) 7085 << Name << AnonStruct->getTagKind(); 7086 Invalid = true; 7087 } else if (RD->isUnion()) { 7088 // C++98 [class.union]p1: If a union contains a static data member, 7089 // the program is ill-formed. C++11 drops this restriction. 7090 Diag(D.getIdentifierLoc(), 7091 getLangOpts().CPlusPlus11 7092 ? diag::warn_cxx98_compat_static_data_member_in_union 7093 : diag::ext_static_data_member_in_union) << Name; 7094 } 7095 } 7096 } 7097 7098 // Match up the template parameter lists with the scope specifier, then 7099 // determine whether we have a template or a template specialization. 7100 bool InvalidScope = false; 7101 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7102 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7103 D.getCXXScopeSpec(), 7104 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7105 ? D.getName().TemplateId 7106 : nullptr, 7107 TemplateParamLists, 7108 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7109 Invalid |= InvalidScope; 7110 7111 if (TemplateParams) { 7112 if (!TemplateParams->size() && 7113 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7114 // There is an extraneous 'template<>' for this variable. Complain 7115 // about it, but allow the declaration of the variable. 7116 Diag(TemplateParams->getTemplateLoc(), 7117 diag::err_template_variable_noparams) 7118 << II 7119 << SourceRange(TemplateParams->getTemplateLoc(), 7120 TemplateParams->getRAngleLoc()); 7121 TemplateParams = nullptr; 7122 } else { 7123 // Check that we can declare a template here. 7124 if (CheckTemplateDeclScope(S, TemplateParams)) 7125 return nullptr; 7126 7127 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7128 // This is an explicit specialization or a partial specialization. 7129 IsVariableTemplateSpecialization = true; 7130 IsPartialSpecialization = TemplateParams->size() > 0; 7131 } else { // if (TemplateParams->size() > 0) 7132 // This is a template declaration. 7133 IsVariableTemplate = true; 7134 7135 // Only C++1y supports variable templates (N3651). 7136 Diag(D.getIdentifierLoc(), 7137 getLangOpts().CPlusPlus14 7138 ? diag::warn_cxx11_compat_variable_template 7139 : diag::ext_variable_template); 7140 } 7141 } 7142 } else { 7143 // Check that we can declare a member specialization here. 7144 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7145 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7146 return nullptr; 7147 assert((Invalid || 7148 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7149 "should have a 'template<>' for this decl"); 7150 } 7151 7152 if (IsVariableTemplateSpecialization) { 7153 SourceLocation TemplateKWLoc = 7154 TemplateParamLists.size() > 0 7155 ? TemplateParamLists[0]->getTemplateLoc() 7156 : SourceLocation(); 7157 DeclResult Res = ActOnVarTemplateSpecialization( 7158 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7159 IsPartialSpecialization); 7160 if (Res.isInvalid()) 7161 return nullptr; 7162 NewVD = cast<VarDecl>(Res.get()); 7163 AddToScope = false; 7164 } else if (D.isDecompositionDeclarator()) { 7165 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7166 D.getIdentifierLoc(), R, TInfo, SC, 7167 Bindings); 7168 } else 7169 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7170 D.getIdentifierLoc(), II, R, TInfo, SC); 7171 7172 // If this is supposed to be a variable template, create it as such. 7173 if (IsVariableTemplate) { 7174 NewTemplate = 7175 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7176 TemplateParams, NewVD); 7177 NewVD->setDescribedVarTemplate(NewTemplate); 7178 } 7179 7180 // If this decl has an auto type in need of deduction, make a note of the 7181 // Decl so we can diagnose uses of it in its own initializer. 7182 if (R->getContainedDeducedType()) 7183 ParsingInitForAutoVars.insert(NewVD); 7184 7185 if (D.isInvalidType() || Invalid) { 7186 NewVD->setInvalidDecl(); 7187 if (NewTemplate) 7188 NewTemplate->setInvalidDecl(); 7189 } 7190 7191 SetNestedNameSpecifier(*this, NewVD, D); 7192 7193 // If we have any template parameter lists that don't directly belong to 7194 // the variable (matching the scope specifier), store them. 7195 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7196 if (TemplateParamLists.size() > VDTemplateParamLists) 7197 NewVD->setTemplateParameterListsInfo( 7198 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7199 } 7200 7201 if (D.getDeclSpec().isInlineSpecified()) { 7202 if (!getLangOpts().CPlusPlus) { 7203 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7204 << 0; 7205 } else if (CurContext->isFunctionOrMethod()) { 7206 // 'inline' is not allowed on block scope variable declaration. 7207 Diag(D.getDeclSpec().getInlineSpecLoc(), 7208 diag::err_inline_declaration_block_scope) << Name 7209 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7210 } else { 7211 Diag(D.getDeclSpec().getInlineSpecLoc(), 7212 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7213 : diag::ext_inline_variable); 7214 NewVD->setInlineSpecified(); 7215 } 7216 } 7217 7218 // Set the lexical context. If the declarator has a C++ scope specifier, the 7219 // lexical context will be different from the semantic context. 7220 NewVD->setLexicalDeclContext(CurContext); 7221 if (NewTemplate) 7222 NewTemplate->setLexicalDeclContext(CurContext); 7223 7224 if (IsLocalExternDecl) { 7225 if (D.isDecompositionDeclarator()) 7226 for (auto *B : Bindings) 7227 B->setLocalExternDecl(); 7228 else 7229 NewVD->setLocalExternDecl(); 7230 } 7231 7232 bool EmitTLSUnsupportedError = false; 7233 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7234 // C++11 [dcl.stc]p4: 7235 // When thread_local is applied to a variable of block scope the 7236 // storage-class-specifier static is implied if it does not appear 7237 // explicitly. 7238 // Core issue: 'static' is not implied if the variable is declared 7239 // 'extern'. 7240 if (NewVD->hasLocalStorage() && 7241 (SCSpec != DeclSpec::SCS_unspecified || 7242 TSCS != DeclSpec::TSCS_thread_local || 7243 !DC->isFunctionOrMethod())) 7244 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7245 diag::err_thread_non_global) 7246 << DeclSpec::getSpecifierName(TSCS); 7247 else if (!Context.getTargetInfo().isTLSSupported()) { 7248 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7249 getLangOpts().SYCLIsDevice) { 7250 // Postpone error emission until we've collected attributes required to 7251 // figure out whether it's a host or device variable and whether the 7252 // error should be ignored. 7253 EmitTLSUnsupportedError = true; 7254 // We still need to mark the variable as TLS so it shows up in AST with 7255 // proper storage class for other tools to use even if we're not going 7256 // to emit any code for it. 7257 NewVD->setTSCSpec(TSCS); 7258 } else 7259 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7260 diag::err_thread_unsupported); 7261 } else 7262 NewVD->setTSCSpec(TSCS); 7263 } 7264 7265 switch (D.getDeclSpec().getConstexprSpecifier()) { 7266 case ConstexprSpecKind::Unspecified: 7267 break; 7268 7269 case ConstexprSpecKind::Consteval: 7270 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7271 diag::err_constexpr_wrong_decl_kind) 7272 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7273 LLVM_FALLTHROUGH; 7274 7275 case ConstexprSpecKind::Constexpr: 7276 NewVD->setConstexpr(true); 7277 // C++1z [dcl.spec.constexpr]p1: 7278 // A static data member declared with the constexpr specifier is 7279 // implicitly an inline variable. 7280 if (NewVD->isStaticDataMember() && 7281 (getLangOpts().CPlusPlus17 || 7282 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7283 NewVD->setImplicitlyInline(); 7284 break; 7285 7286 case ConstexprSpecKind::Constinit: 7287 if (!NewVD->hasGlobalStorage()) 7288 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7289 diag::err_constinit_local_variable); 7290 else 7291 NewVD->addAttr(ConstInitAttr::Create( 7292 Context, D.getDeclSpec().getConstexprSpecLoc(), 7293 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7294 break; 7295 } 7296 7297 // C99 6.7.4p3 7298 // An inline definition of a function with external linkage shall 7299 // not contain a definition of a modifiable object with static or 7300 // thread storage duration... 7301 // We only apply this when the function is required to be defined 7302 // elsewhere, i.e. when the function is not 'extern inline'. Note 7303 // that a local variable with thread storage duration still has to 7304 // be marked 'static'. Also note that it's possible to get these 7305 // semantics in C++ using __attribute__((gnu_inline)). 7306 if (SC == SC_Static && S->getFnParent() != nullptr && 7307 !NewVD->getType().isConstQualified()) { 7308 FunctionDecl *CurFD = getCurFunctionDecl(); 7309 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7310 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7311 diag::warn_static_local_in_extern_inline); 7312 MaybeSuggestAddingStaticToDecl(CurFD); 7313 } 7314 } 7315 7316 if (D.getDeclSpec().isModulePrivateSpecified()) { 7317 if (IsVariableTemplateSpecialization) 7318 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7319 << (IsPartialSpecialization ? 1 : 0) 7320 << FixItHint::CreateRemoval( 7321 D.getDeclSpec().getModulePrivateSpecLoc()); 7322 else if (IsMemberSpecialization) 7323 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7324 << 2 7325 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7326 else if (NewVD->hasLocalStorage()) 7327 Diag(NewVD->getLocation(), diag::err_module_private_local) 7328 << 0 << NewVD 7329 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7330 << FixItHint::CreateRemoval( 7331 D.getDeclSpec().getModulePrivateSpecLoc()); 7332 else { 7333 NewVD->setModulePrivate(); 7334 if (NewTemplate) 7335 NewTemplate->setModulePrivate(); 7336 for (auto *B : Bindings) 7337 B->setModulePrivate(); 7338 } 7339 } 7340 7341 if (getLangOpts().OpenCL) { 7342 deduceOpenCLAddressSpace(NewVD); 7343 7344 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 7345 if (TSC != TSCS_unspecified) { 7346 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7347 diag::err_opencl_unknown_type_specifier) 7348 << getLangOpts().getOpenCLVersionString() 7349 << DeclSpec::getSpecifierName(TSC) << 1; 7350 NewVD->setInvalidDecl(); 7351 } 7352 } 7353 7354 // Handle attributes prior to checking for duplicates in MergeVarDecl 7355 ProcessDeclAttributes(S, NewVD, D); 7356 7357 // FIXME: This is probably the wrong location to be doing this and we should 7358 // probably be doing this for more attributes (especially for function 7359 // pointer attributes such as format, warn_unused_result, etc.). Ideally 7360 // the code to copy attributes would be generated by TableGen. 7361 if (R->isFunctionPointerType()) 7362 if (const auto *TT = R->getAs<TypedefType>()) 7363 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT); 7364 7365 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7366 getLangOpts().SYCLIsDevice) { 7367 if (EmitTLSUnsupportedError && 7368 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7369 (getLangOpts().OpenMPIsDevice && 7370 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7371 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7372 diag::err_thread_unsupported); 7373 7374 if (EmitTLSUnsupportedError && 7375 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7376 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7377 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7378 // storage [duration]." 7379 if (SC == SC_None && S->getFnParent() != nullptr && 7380 (NewVD->hasAttr<CUDASharedAttr>() || 7381 NewVD->hasAttr<CUDAConstantAttr>())) { 7382 NewVD->setStorageClass(SC_Static); 7383 } 7384 } 7385 7386 // Ensure that dllimport globals without explicit storage class are treated as 7387 // extern. The storage class is set above using parsed attributes. Now we can 7388 // check the VarDecl itself. 7389 assert(!NewVD->hasAttr<DLLImportAttr>() || 7390 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7391 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7392 7393 // In auto-retain/release, infer strong retension for variables of 7394 // retainable type. 7395 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7396 NewVD->setInvalidDecl(); 7397 7398 // Handle GNU asm-label extension (encoded as an attribute). 7399 if (Expr *E = (Expr*)D.getAsmLabel()) { 7400 // The parser guarantees this is a string. 7401 StringLiteral *SE = cast<StringLiteral>(E); 7402 StringRef Label = SE->getString(); 7403 if (S->getFnParent() != nullptr) { 7404 switch (SC) { 7405 case SC_None: 7406 case SC_Auto: 7407 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7408 break; 7409 case SC_Register: 7410 // Local Named register 7411 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7412 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7413 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7414 break; 7415 case SC_Static: 7416 case SC_Extern: 7417 case SC_PrivateExtern: 7418 break; 7419 } 7420 } else if (SC == SC_Register) { 7421 // Global Named register 7422 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7423 const auto &TI = Context.getTargetInfo(); 7424 bool HasSizeMismatch; 7425 7426 if (!TI.isValidGCCRegisterName(Label)) 7427 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7428 else if (!TI.validateGlobalRegisterVariable(Label, 7429 Context.getTypeSize(R), 7430 HasSizeMismatch)) 7431 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7432 else if (HasSizeMismatch) 7433 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7434 } 7435 7436 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7437 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7438 NewVD->setInvalidDecl(true); 7439 } 7440 } 7441 7442 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7443 /*IsLiteralLabel=*/true, 7444 SE->getStrTokenLoc(0))); 7445 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7446 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7447 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7448 if (I != ExtnameUndeclaredIdentifiers.end()) { 7449 if (isDeclExternC(NewVD)) { 7450 NewVD->addAttr(I->second); 7451 ExtnameUndeclaredIdentifiers.erase(I); 7452 } else 7453 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7454 << /*Variable*/1 << NewVD; 7455 } 7456 } 7457 7458 // Find the shadowed declaration before filtering for scope. 7459 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7460 ? getShadowedDeclaration(NewVD, Previous) 7461 : nullptr; 7462 7463 // Don't consider existing declarations that are in a different 7464 // scope and are out-of-semantic-context declarations (if the new 7465 // declaration has linkage). 7466 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7467 D.getCXXScopeSpec().isNotEmpty() || 7468 IsMemberSpecialization || 7469 IsVariableTemplateSpecialization); 7470 7471 // Check whether the previous declaration is in the same block scope. This 7472 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7473 if (getLangOpts().CPlusPlus && 7474 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7475 NewVD->setPreviousDeclInSameBlockScope( 7476 Previous.isSingleResult() && !Previous.isShadowed() && 7477 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7478 7479 if (!getLangOpts().CPlusPlus) { 7480 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7481 } else { 7482 // If this is an explicit specialization of a static data member, check it. 7483 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7484 CheckMemberSpecialization(NewVD, Previous)) 7485 NewVD->setInvalidDecl(); 7486 7487 // Merge the decl with the existing one if appropriate. 7488 if (!Previous.empty()) { 7489 if (Previous.isSingleResult() && 7490 isa<FieldDecl>(Previous.getFoundDecl()) && 7491 D.getCXXScopeSpec().isSet()) { 7492 // The user tried to define a non-static data member 7493 // out-of-line (C++ [dcl.meaning]p1). 7494 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7495 << D.getCXXScopeSpec().getRange(); 7496 Previous.clear(); 7497 NewVD->setInvalidDecl(); 7498 } 7499 } else if (D.getCXXScopeSpec().isSet()) { 7500 // No previous declaration in the qualifying scope. 7501 Diag(D.getIdentifierLoc(), diag::err_no_member) 7502 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7503 << D.getCXXScopeSpec().getRange(); 7504 NewVD->setInvalidDecl(); 7505 } 7506 7507 if (!IsVariableTemplateSpecialization) 7508 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7509 7510 if (NewTemplate) { 7511 VarTemplateDecl *PrevVarTemplate = 7512 NewVD->getPreviousDecl() 7513 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7514 : nullptr; 7515 7516 // Check the template parameter list of this declaration, possibly 7517 // merging in the template parameter list from the previous variable 7518 // template declaration. 7519 if (CheckTemplateParameterList( 7520 TemplateParams, 7521 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7522 : nullptr, 7523 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7524 DC->isDependentContext()) 7525 ? TPC_ClassTemplateMember 7526 : TPC_VarTemplate)) 7527 NewVD->setInvalidDecl(); 7528 7529 // If we are providing an explicit specialization of a static variable 7530 // template, make a note of that. 7531 if (PrevVarTemplate && 7532 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7533 PrevVarTemplate->setMemberSpecialization(); 7534 } 7535 } 7536 7537 // Diagnose shadowed variables iff this isn't a redeclaration. 7538 if (ShadowedDecl && !D.isRedeclaration()) 7539 CheckShadow(NewVD, ShadowedDecl, Previous); 7540 7541 ProcessPragmaWeak(S, NewVD); 7542 7543 // If this is the first declaration of an extern C variable, update 7544 // the map of such variables. 7545 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7546 isIncompleteDeclExternC(*this, NewVD)) 7547 RegisterLocallyScopedExternCDecl(NewVD, S); 7548 7549 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7550 MangleNumberingContext *MCtx; 7551 Decl *ManglingContextDecl; 7552 std::tie(MCtx, ManglingContextDecl) = 7553 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7554 if (MCtx) { 7555 Context.setManglingNumber( 7556 NewVD, MCtx->getManglingNumber( 7557 NewVD, getMSManglingNumber(getLangOpts(), S))); 7558 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7559 } 7560 } 7561 7562 // Special handling of variable named 'main'. 7563 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7564 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7565 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7566 7567 // C++ [basic.start.main]p3 7568 // A program that declares a variable main at global scope is ill-formed. 7569 if (getLangOpts().CPlusPlus) 7570 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7571 7572 // In C, and external-linkage variable named main results in undefined 7573 // behavior. 7574 else if (NewVD->hasExternalFormalLinkage()) 7575 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7576 } 7577 7578 if (D.isRedeclaration() && !Previous.empty()) { 7579 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7580 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7581 D.isFunctionDefinition()); 7582 } 7583 7584 if (NewTemplate) { 7585 if (NewVD->isInvalidDecl()) 7586 NewTemplate->setInvalidDecl(); 7587 ActOnDocumentableDecl(NewTemplate); 7588 return NewTemplate; 7589 } 7590 7591 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7592 CompleteMemberSpecialization(NewVD, Previous); 7593 7594 return NewVD; 7595 } 7596 7597 /// Enum describing the %select options in diag::warn_decl_shadow. 7598 enum ShadowedDeclKind { 7599 SDK_Local, 7600 SDK_Global, 7601 SDK_StaticMember, 7602 SDK_Field, 7603 SDK_Typedef, 7604 SDK_Using, 7605 SDK_StructuredBinding 7606 }; 7607 7608 /// Determine what kind of declaration we're shadowing. 7609 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7610 const DeclContext *OldDC) { 7611 if (isa<TypeAliasDecl>(ShadowedDecl)) 7612 return SDK_Using; 7613 else if (isa<TypedefDecl>(ShadowedDecl)) 7614 return SDK_Typedef; 7615 else if (isa<BindingDecl>(ShadowedDecl)) 7616 return SDK_StructuredBinding; 7617 else if (isa<RecordDecl>(OldDC)) 7618 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7619 7620 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7621 } 7622 7623 /// Return the location of the capture if the given lambda captures the given 7624 /// variable \p VD, or an invalid source location otherwise. 7625 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7626 const VarDecl *VD) { 7627 for (const Capture &Capture : LSI->Captures) { 7628 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7629 return Capture.getLocation(); 7630 } 7631 return SourceLocation(); 7632 } 7633 7634 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7635 const LookupResult &R) { 7636 // Only diagnose if we're shadowing an unambiguous field or variable. 7637 if (R.getResultKind() != LookupResult::Found) 7638 return false; 7639 7640 // Return false if warning is ignored. 7641 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7642 } 7643 7644 /// Return the declaration shadowed by the given variable \p D, or null 7645 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7646 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7647 const LookupResult &R) { 7648 if (!shouldWarnIfShadowedDecl(Diags, R)) 7649 return nullptr; 7650 7651 // Don't diagnose declarations at file scope. 7652 if (D->hasGlobalStorage()) 7653 return nullptr; 7654 7655 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7656 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7657 : nullptr; 7658 } 7659 7660 /// Return the declaration shadowed by the given typedef \p D, or null 7661 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7662 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7663 const LookupResult &R) { 7664 // Don't warn if typedef declaration is part of a class 7665 if (D->getDeclContext()->isRecord()) 7666 return nullptr; 7667 7668 if (!shouldWarnIfShadowedDecl(Diags, R)) 7669 return nullptr; 7670 7671 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7672 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7673 } 7674 7675 /// Return the declaration shadowed by the given variable \p D, or null 7676 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7677 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, 7678 const LookupResult &R) { 7679 if (!shouldWarnIfShadowedDecl(Diags, R)) 7680 return nullptr; 7681 7682 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7683 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7684 : nullptr; 7685 } 7686 7687 /// Diagnose variable or built-in function shadowing. Implements 7688 /// -Wshadow. 7689 /// 7690 /// This method is called whenever a VarDecl is added to a "useful" 7691 /// scope. 7692 /// 7693 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7694 /// \param R the lookup of the name 7695 /// 7696 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7697 const LookupResult &R) { 7698 DeclContext *NewDC = D->getDeclContext(); 7699 7700 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7701 // Fields are not shadowed by variables in C++ static methods. 7702 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7703 if (MD->isStatic()) 7704 return; 7705 7706 // Fields shadowed by constructor parameters are a special case. Usually 7707 // the constructor initializes the field with the parameter. 7708 if (isa<CXXConstructorDecl>(NewDC)) 7709 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7710 // Remember that this was shadowed so we can either warn about its 7711 // modification or its existence depending on warning settings. 7712 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7713 return; 7714 } 7715 } 7716 7717 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7718 if (shadowedVar->isExternC()) { 7719 // For shadowing external vars, make sure that we point to the global 7720 // declaration, not a locally scoped extern declaration. 7721 for (auto I : shadowedVar->redecls()) 7722 if (I->isFileVarDecl()) { 7723 ShadowedDecl = I; 7724 break; 7725 } 7726 } 7727 7728 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7729 7730 unsigned WarningDiag = diag::warn_decl_shadow; 7731 SourceLocation CaptureLoc; 7732 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7733 isa<CXXMethodDecl>(NewDC)) { 7734 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7735 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7736 if (RD->getLambdaCaptureDefault() == LCD_None) { 7737 // Try to avoid warnings for lambdas with an explicit capture list. 7738 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7739 // Warn only when the lambda captures the shadowed decl explicitly. 7740 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7741 if (CaptureLoc.isInvalid()) 7742 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7743 } else { 7744 // Remember that this was shadowed so we can avoid the warning if the 7745 // shadowed decl isn't captured and the warning settings allow it. 7746 cast<LambdaScopeInfo>(getCurFunction()) 7747 ->ShadowingDecls.push_back( 7748 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7749 return; 7750 } 7751 } 7752 7753 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7754 // A variable can't shadow a local variable in an enclosing scope, if 7755 // they are separated by a non-capturing declaration context. 7756 for (DeclContext *ParentDC = NewDC; 7757 ParentDC && !ParentDC->Equals(OldDC); 7758 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7759 // Only block literals, captured statements, and lambda expressions 7760 // can capture; other scopes don't. 7761 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7762 !isLambdaCallOperator(ParentDC)) { 7763 return; 7764 } 7765 } 7766 } 7767 } 7768 } 7769 7770 // Only warn about certain kinds of shadowing for class members. 7771 if (NewDC && NewDC->isRecord()) { 7772 // In particular, don't warn about shadowing non-class members. 7773 if (!OldDC->isRecord()) 7774 return; 7775 7776 // TODO: should we warn about static data members shadowing 7777 // static data members from base classes? 7778 7779 // TODO: don't diagnose for inaccessible shadowed members. 7780 // This is hard to do perfectly because we might friend the 7781 // shadowing context, but that's just a false negative. 7782 } 7783 7784 7785 DeclarationName Name = R.getLookupName(); 7786 7787 // Emit warning and note. 7788 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7789 return; 7790 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7791 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7792 if (!CaptureLoc.isInvalid()) 7793 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7794 << Name << /*explicitly*/ 1; 7795 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7796 } 7797 7798 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7799 /// when these variables are captured by the lambda. 7800 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7801 for (const auto &Shadow : LSI->ShadowingDecls) { 7802 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7803 // Try to avoid the warning when the shadowed decl isn't captured. 7804 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7805 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7806 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7807 ? diag::warn_decl_shadow_uncaptured_local 7808 : diag::warn_decl_shadow) 7809 << Shadow.VD->getDeclName() 7810 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7811 if (!CaptureLoc.isInvalid()) 7812 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7813 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7814 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7815 } 7816 } 7817 7818 /// Check -Wshadow without the advantage of a previous lookup. 7819 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7820 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7821 return; 7822 7823 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7824 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7825 LookupName(R, S); 7826 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7827 CheckShadow(D, ShadowedDecl, R); 7828 } 7829 7830 /// Check if 'E', which is an expression that is about to be modified, refers 7831 /// to a constructor parameter that shadows a field. 7832 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7833 // Quickly ignore expressions that can't be shadowing ctor parameters. 7834 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7835 return; 7836 E = E->IgnoreParenImpCasts(); 7837 auto *DRE = dyn_cast<DeclRefExpr>(E); 7838 if (!DRE) 7839 return; 7840 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7841 auto I = ShadowingDecls.find(D); 7842 if (I == ShadowingDecls.end()) 7843 return; 7844 const NamedDecl *ShadowedDecl = I->second; 7845 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7846 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7847 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7848 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7849 7850 // Avoid issuing multiple warnings about the same decl. 7851 ShadowingDecls.erase(I); 7852 } 7853 7854 /// Check for conflict between this global or extern "C" declaration and 7855 /// previous global or extern "C" declarations. This is only used in C++. 7856 template<typename T> 7857 static bool checkGlobalOrExternCConflict( 7858 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7859 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7860 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7861 7862 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7863 // The common case: this global doesn't conflict with any extern "C" 7864 // declaration. 7865 return false; 7866 } 7867 7868 if (Prev) { 7869 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7870 // Both the old and new declarations have C language linkage. This is a 7871 // redeclaration. 7872 Previous.clear(); 7873 Previous.addDecl(Prev); 7874 return true; 7875 } 7876 7877 // This is a global, non-extern "C" declaration, and there is a previous 7878 // non-global extern "C" declaration. Diagnose if this is a variable 7879 // declaration. 7880 if (!isa<VarDecl>(ND)) 7881 return false; 7882 } else { 7883 // The declaration is extern "C". Check for any declaration in the 7884 // translation unit which might conflict. 7885 if (IsGlobal) { 7886 // We have already performed the lookup into the translation unit. 7887 IsGlobal = false; 7888 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7889 I != E; ++I) { 7890 if (isa<VarDecl>(*I)) { 7891 Prev = *I; 7892 break; 7893 } 7894 } 7895 } else { 7896 DeclContext::lookup_result R = 7897 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7898 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7899 I != E; ++I) { 7900 if (isa<VarDecl>(*I)) { 7901 Prev = *I; 7902 break; 7903 } 7904 // FIXME: If we have any other entity with this name in global scope, 7905 // the declaration is ill-formed, but that is a defect: it breaks the 7906 // 'stat' hack, for instance. Only variables can have mangled name 7907 // clashes with extern "C" declarations, so only they deserve a 7908 // diagnostic. 7909 } 7910 } 7911 7912 if (!Prev) 7913 return false; 7914 } 7915 7916 // Use the first declaration's location to ensure we point at something which 7917 // is lexically inside an extern "C" linkage-spec. 7918 assert(Prev && "should have found a previous declaration to diagnose"); 7919 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7920 Prev = FD->getFirstDecl(); 7921 else 7922 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7923 7924 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7925 << IsGlobal << ND; 7926 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7927 << IsGlobal; 7928 return false; 7929 } 7930 7931 /// Apply special rules for handling extern "C" declarations. Returns \c true 7932 /// if we have found that this is a redeclaration of some prior entity. 7933 /// 7934 /// Per C++ [dcl.link]p6: 7935 /// Two declarations [for a function or variable] with C language linkage 7936 /// with the same name that appear in different scopes refer to the same 7937 /// [entity]. An entity with C language linkage shall not be declared with 7938 /// the same name as an entity in global scope. 7939 template<typename T> 7940 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7941 LookupResult &Previous) { 7942 if (!S.getLangOpts().CPlusPlus) { 7943 // In C, when declaring a global variable, look for a corresponding 'extern' 7944 // variable declared in function scope. We don't need this in C++, because 7945 // we find local extern decls in the surrounding file-scope DeclContext. 7946 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7947 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7948 Previous.clear(); 7949 Previous.addDecl(Prev); 7950 return true; 7951 } 7952 } 7953 return false; 7954 } 7955 7956 // A declaration in the translation unit can conflict with an extern "C" 7957 // declaration. 7958 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7959 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7960 7961 // An extern "C" declaration can conflict with a declaration in the 7962 // translation unit or can be a redeclaration of an extern "C" declaration 7963 // in another scope. 7964 if (isIncompleteDeclExternC(S,ND)) 7965 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7966 7967 // Neither global nor extern "C": nothing to do. 7968 return false; 7969 } 7970 7971 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7972 // If the decl is already known invalid, don't check it. 7973 if (NewVD->isInvalidDecl()) 7974 return; 7975 7976 QualType T = NewVD->getType(); 7977 7978 // Defer checking an 'auto' type until its initializer is attached. 7979 if (T->isUndeducedType()) 7980 return; 7981 7982 if (NewVD->hasAttrs()) 7983 CheckAlignasUnderalignment(NewVD); 7984 7985 if (T->isObjCObjectType()) { 7986 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7987 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7988 T = Context.getObjCObjectPointerType(T); 7989 NewVD->setType(T); 7990 } 7991 7992 // Emit an error if an address space was applied to decl with local storage. 7993 // This includes arrays of objects with address space qualifiers, but not 7994 // automatic variables that point to other address spaces. 7995 // ISO/IEC TR 18037 S5.1.2 7996 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7997 T.getAddressSpace() != LangAS::Default) { 7998 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7999 NewVD->setInvalidDecl(); 8000 return; 8001 } 8002 8003 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 8004 // scope. 8005 if (getLangOpts().OpenCLVersion == 120 && 8006 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", 8007 getLangOpts()) && 8008 NewVD->isStaticLocal()) { 8009 Diag(NewVD->getLocation(), diag::err_static_function_scope); 8010 NewVD->setInvalidDecl(); 8011 return; 8012 } 8013 8014 if (getLangOpts().OpenCL) { 8015 if (!diagnoseOpenCLTypes(*this, NewVD)) 8016 return; 8017 8018 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 8019 if (NewVD->hasAttr<BlocksAttr>()) { 8020 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 8021 return; 8022 } 8023 8024 if (T->isBlockPointerType()) { 8025 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 8026 // can't use 'extern' storage class. 8027 if (!T.isConstQualified()) { 8028 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 8029 << 0 /*const*/; 8030 NewVD->setInvalidDecl(); 8031 return; 8032 } 8033 if (NewVD->hasExternalStorage()) { 8034 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 8035 NewVD->setInvalidDecl(); 8036 return; 8037 } 8038 } 8039 8040 // FIXME: Adding local AS in C++ for OpenCL might make sense. 8041 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 8042 NewVD->hasExternalStorage()) { 8043 if (!T->isSamplerT() && !T->isDependentType() && 8044 !(T.getAddressSpace() == LangAS::opencl_constant || 8045 (T.getAddressSpace() == LangAS::opencl_global && 8046 getOpenCLOptions().areProgramScopeVariablesSupported( 8047 getLangOpts())))) { 8048 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 8049 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts())) 8050 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8051 << Scope << "global or constant"; 8052 else 8053 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8054 << Scope << "constant"; 8055 NewVD->setInvalidDecl(); 8056 return; 8057 } 8058 } else { 8059 if (T.getAddressSpace() == LangAS::opencl_global) { 8060 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8061 << 1 /*is any function*/ << "global"; 8062 NewVD->setInvalidDecl(); 8063 return; 8064 } 8065 if (T.getAddressSpace() == LangAS::opencl_constant || 8066 T.getAddressSpace() == LangAS::opencl_local) { 8067 FunctionDecl *FD = getCurFunctionDecl(); 8068 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 8069 // in functions. 8070 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 8071 if (T.getAddressSpace() == LangAS::opencl_constant) 8072 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8073 << 0 /*non-kernel only*/ << "constant"; 8074 else 8075 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8076 << 0 /*non-kernel only*/ << "local"; 8077 NewVD->setInvalidDecl(); 8078 return; 8079 } 8080 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 8081 // in the outermost scope of a kernel function. 8082 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 8083 if (!getCurScope()->isFunctionScope()) { 8084 if (T.getAddressSpace() == LangAS::opencl_constant) 8085 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8086 << "constant"; 8087 else 8088 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8089 << "local"; 8090 NewVD->setInvalidDecl(); 8091 return; 8092 } 8093 } 8094 } else if (T.getAddressSpace() != LangAS::opencl_private && 8095 // If we are parsing a template we didn't deduce an addr 8096 // space yet. 8097 T.getAddressSpace() != LangAS::Default) { 8098 // Do not allow other address spaces on automatic variable. 8099 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 8100 NewVD->setInvalidDecl(); 8101 return; 8102 } 8103 } 8104 } 8105 8106 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 8107 && !NewVD->hasAttr<BlocksAttr>()) { 8108 if (getLangOpts().getGC() != LangOptions::NonGC) 8109 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 8110 else { 8111 assert(!getLangOpts().ObjCAutoRefCount); 8112 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 8113 } 8114 } 8115 8116 bool isVM = T->isVariablyModifiedType(); 8117 if (isVM || NewVD->hasAttr<CleanupAttr>() || 8118 NewVD->hasAttr<BlocksAttr>()) 8119 setFunctionHasBranchProtectedScope(); 8120 8121 if ((isVM && NewVD->hasLinkage()) || 8122 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8123 bool SizeIsNegative; 8124 llvm::APSInt Oversized; 8125 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8126 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8127 QualType FixedT; 8128 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8129 FixedT = FixedTInfo->getType(); 8130 else if (FixedTInfo) { 8131 // Type and type-as-written are canonically different. We need to fix up 8132 // both types separately. 8133 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8134 Oversized); 8135 } 8136 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8137 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8138 // FIXME: This won't give the correct result for 8139 // int a[10][n]; 8140 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8141 8142 if (NewVD->isFileVarDecl()) 8143 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8144 << SizeRange; 8145 else if (NewVD->isStaticLocal()) 8146 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8147 << SizeRange; 8148 else 8149 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8150 << SizeRange; 8151 NewVD->setInvalidDecl(); 8152 return; 8153 } 8154 8155 if (!FixedTInfo) { 8156 if (NewVD->isFileVarDecl()) 8157 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8158 else 8159 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8160 NewVD->setInvalidDecl(); 8161 return; 8162 } 8163 8164 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8165 NewVD->setType(FixedT); 8166 NewVD->setTypeSourceInfo(FixedTInfo); 8167 } 8168 8169 if (T->isVoidType()) { 8170 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8171 // of objects and functions. 8172 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8173 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8174 << T; 8175 NewVD->setInvalidDecl(); 8176 return; 8177 } 8178 } 8179 8180 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8181 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8182 NewVD->setInvalidDecl(); 8183 return; 8184 } 8185 8186 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8187 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8188 NewVD->setInvalidDecl(); 8189 return; 8190 } 8191 8192 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8193 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8194 NewVD->setInvalidDecl(); 8195 return; 8196 } 8197 8198 if (NewVD->isConstexpr() && !T->isDependentType() && 8199 RequireLiteralType(NewVD->getLocation(), T, 8200 diag::err_constexpr_var_non_literal)) { 8201 NewVD->setInvalidDecl(); 8202 return; 8203 } 8204 8205 // PPC MMA non-pointer types are not allowed as non-local variable types. 8206 if (Context.getTargetInfo().getTriple().isPPC64() && 8207 !NewVD->isLocalVarDecl() && 8208 CheckPPCMMAType(T, NewVD->getLocation())) { 8209 NewVD->setInvalidDecl(); 8210 return; 8211 } 8212 } 8213 8214 /// Perform semantic checking on a newly-created variable 8215 /// declaration. 8216 /// 8217 /// This routine performs all of the type-checking required for a 8218 /// variable declaration once it has been built. It is used both to 8219 /// check variables after they have been parsed and their declarators 8220 /// have been translated into a declaration, and to check variables 8221 /// that have been instantiated from a template. 8222 /// 8223 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8224 /// 8225 /// Returns true if the variable declaration is a redeclaration. 8226 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8227 CheckVariableDeclarationType(NewVD); 8228 8229 // If the decl is already known invalid, don't check it. 8230 if (NewVD->isInvalidDecl()) 8231 return false; 8232 8233 // If we did not find anything by this name, look for a non-visible 8234 // extern "C" declaration with the same name. 8235 if (Previous.empty() && 8236 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8237 Previous.setShadowed(); 8238 8239 if (!Previous.empty()) { 8240 MergeVarDecl(NewVD, Previous); 8241 return true; 8242 } 8243 return false; 8244 } 8245 8246 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8247 /// and if so, check that it's a valid override and remember it. 8248 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8249 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8250 8251 // Look for methods in base classes that this method might override. 8252 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8253 /*DetectVirtual=*/false); 8254 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8255 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8256 DeclarationName Name = MD->getDeclName(); 8257 8258 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8259 // We really want to find the base class destructor here. 8260 QualType T = Context.getTypeDeclType(BaseRecord); 8261 CanQualType CT = Context.getCanonicalType(T); 8262 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8263 } 8264 8265 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8266 CXXMethodDecl *BaseMD = 8267 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8268 if (!BaseMD || !BaseMD->isVirtual() || 8269 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8270 /*ConsiderCudaAttrs=*/true, 8271 // C++2a [class.virtual]p2 does not consider requires 8272 // clauses when overriding. 8273 /*ConsiderRequiresClauses=*/false)) 8274 continue; 8275 8276 if (Overridden.insert(BaseMD).second) { 8277 MD->addOverriddenMethod(BaseMD); 8278 CheckOverridingFunctionReturnType(MD, BaseMD); 8279 CheckOverridingFunctionAttributes(MD, BaseMD); 8280 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8281 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8282 } 8283 8284 // A method can only override one function from each base class. We 8285 // don't track indirectly overridden methods from bases of bases. 8286 return true; 8287 } 8288 8289 return false; 8290 }; 8291 8292 DC->lookupInBases(VisitBase, Paths); 8293 return !Overridden.empty(); 8294 } 8295 8296 namespace { 8297 // Struct for holding all of the extra arguments needed by 8298 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8299 struct ActOnFDArgs { 8300 Scope *S; 8301 Declarator &D; 8302 MultiTemplateParamsArg TemplateParamLists; 8303 bool AddToScope; 8304 }; 8305 } // end anonymous namespace 8306 8307 namespace { 8308 8309 // Callback to only accept typo corrections that have a non-zero edit distance. 8310 // Also only accept corrections that have the same parent decl. 8311 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8312 public: 8313 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8314 CXXRecordDecl *Parent) 8315 : Context(Context), OriginalFD(TypoFD), 8316 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8317 8318 bool ValidateCandidate(const TypoCorrection &candidate) override { 8319 if (candidate.getEditDistance() == 0) 8320 return false; 8321 8322 SmallVector<unsigned, 1> MismatchedParams; 8323 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8324 CDeclEnd = candidate.end(); 8325 CDecl != CDeclEnd; ++CDecl) { 8326 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8327 8328 if (FD && !FD->hasBody() && 8329 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8330 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8331 CXXRecordDecl *Parent = MD->getParent(); 8332 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8333 return true; 8334 } else if (!ExpectedParent) { 8335 return true; 8336 } 8337 } 8338 } 8339 8340 return false; 8341 } 8342 8343 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8344 return std::make_unique<DifferentNameValidatorCCC>(*this); 8345 } 8346 8347 private: 8348 ASTContext &Context; 8349 FunctionDecl *OriginalFD; 8350 CXXRecordDecl *ExpectedParent; 8351 }; 8352 8353 } // end anonymous namespace 8354 8355 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8356 TypoCorrectedFunctionDefinitions.insert(F); 8357 } 8358 8359 /// Generate diagnostics for an invalid function redeclaration. 8360 /// 8361 /// This routine handles generating the diagnostic messages for an invalid 8362 /// function redeclaration, including finding possible similar declarations 8363 /// or performing typo correction if there are no previous declarations with 8364 /// the same name. 8365 /// 8366 /// Returns a NamedDecl iff typo correction was performed and substituting in 8367 /// the new declaration name does not cause new errors. 8368 static NamedDecl *DiagnoseInvalidRedeclaration( 8369 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8370 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8371 DeclarationName Name = NewFD->getDeclName(); 8372 DeclContext *NewDC = NewFD->getDeclContext(); 8373 SmallVector<unsigned, 1> MismatchedParams; 8374 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8375 TypoCorrection Correction; 8376 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8377 unsigned DiagMsg = 8378 IsLocalFriend ? diag::err_no_matching_local_friend : 8379 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8380 diag::err_member_decl_does_not_match; 8381 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8382 IsLocalFriend ? Sema::LookupLocalFriendName 8383 : Sema::LookupOrdinaryName, 8384 Sema::ForVisibleRedeclaration); 8385 8386 NewFD->setInvalidDecl(); 8387 if (IsLocalFriend) 8388 SemaRef.LookupName(Prev, S); 8389 else 8390 SemaRef.LookupQualifiedName(Prev, NewDC); 8391 assert(!Prev.isAmbiguous() && 8392 "Cannot have an ambiguity in previous-declaration lookup"); 8393 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8394 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8395 MD ? MD->getParent() : nullptr); 8396 if (!Prev.empty()) { 8397 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8398 Func != FuncEnd; ++Func) { 8399 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8400 if (FD && 8401 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8402 // Add 1 to the index so that 0 can mean the mismatch didn't 8403 // involve a parameter 8404 unsigned ParamNum = 8405 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8406 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8407 } 8408 } 8409 // If the qualified name lookup yielded nothing, try typo correction 8410 } else if ((Correction = SemaRef.CorrectTypo( 8411 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8412 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8413 IsLocalFriend ? nullptr : NewDC))) { 8414 // Set up everything for the call to ActOnFunctionDeclarator 8415 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8416 ExtraArgs.D.getIdentifierLoc()); 8417 Previous.clear(); 8418 Previous.setLookupName(Correction.getCorrection()); 8419 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8420 CDeclEnd = Correction.end(); 8421 CDecl != CDeclEnd; ++CDecl) { 8422 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8423 if (FD && !FD->hasBody() && 8424 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8425 Previous.addDecl(FD); 8426 } 8427 } 8428 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8429 8430 NamedDecl *Result; 8431 // Retry building the function declaration with the new previous 8432 // declarations, and with errors suppressed. 8433 { 8434 // Trap errors. 8435 Sema::SFINAETrap Trap(SemaRef); 8436 8437 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8438 // pieces need to verify the typo-corrected C++ declaration and hopefully 8439 // eliminate the need for the parameter pack ExtraArgs. 8440 Result = SemaRef.ActOnFunctionDeclarator( 8441 ExtraArgs.S, ExtraArgs.D, 8442 Correction.getCorrectionDecl()->getDeclContext(), 8443 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8444 ExtraArgs.AddToScope); 8445 8446 if (Trap.hasErrorOccurred()) 8447 Result = nullptr; 8448 } 8449 8450 if (Result) { 8451 // Determine which correction we picked. 8452 Decl *Canonical = Result->getCanonicalDecl(); 8453 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8454 I != E; ++I) 8455 if ((*I)->getCanonicalDecl() == Canonical) 8456 Correction.setCorrectionDecl(*I); 8457 8458 // Let Sema know about the correction. 8459 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8460 SemaRef.diagnoseTypo( 8461 Correction, 8462 SemaRef.PDiag(IsLocalFriend 8463 ? diag::err_no_matching_local_friend_suggest 8464 : diag::err_member_decl_does_not_match_suggest) 8465 << Name << NewDC << IsDefinition); 8466 return Result; 8467 } 8468 8469 // Pretend the typo correction never occurred 8470 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8471 ExtraArgs.D.getIdentifierLoc()); 8472 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8473 Previous.clear(); 8474 Previous.setLookupName(Name); 8475 } 8476 8477 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8478 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8479 8480 bool NewFDisConst = false; 8481 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8482 NewFDisConst = NewMD->isConst(); 8483 8484 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8485 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8486 NearMatch != NearMatchEnd; ++NearMatch) { 8487 FunctionDecl *FD = NearMatch->first; 8488 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8489 bool FDisConst = MD && MD->isConst(); 8490 bool IsMember = MD || !IsLocalFriend; 8491 8492 // FIXME: These notes are poorly worded for the local friend case. 8493 if (unsigned Idx = NearMatch->second) { 8494 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8495 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8496 if (Loc.isInvalid()) Loc = FD->getLocation(); 8497 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8498 : diag::note_local_decl_close_param_match) 8499 << Idx << FDParam->getType() 8500 << NewFD->getParamDecl(Idx - 1)->getType(); 8501 } else if (FDisConst != NewFDisConst) { 8502 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8503 << NewFDisConst << FD->getSourceRange().getEnd(); 8504 } else 8505 SemaRef.Diag(FD->getLocation(), 8506 IsMember ? diag::note_member_def_close_match 8507 : diag::note_local_decl_close_match); 8508 } 8509 return nullptr; 8510 } 8511 8512 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8513 switch (D.getDeclSpec().getStorageClassSpec()) { 8514 default: llvm_unreachable("Unknown storage class!"); 8515 case DeclSpec::SCS_auto: 8516 case DeclSpec::SCS_register: 8517 case DeclSpec::SCS_mutable: 8518 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8519 diag::err_typecheck_sclass_func); 8520 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8521 D.setInvalidType(); 8522 break; 8523 case DeclSpec::SCS_unspecified: break; 8524 case DeclSpec::SCS_extern: 8525 if (D.getDeclSpec().isExternInLinkageSpec()) 8526 return SC_None; 8527 return SC_Extern; 8528 case DeclSpec::SCS_static: { 8529 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8530 // C99 6.7.1p5: 8531 // The declaration of an identifier for a function that has 8532 // block scope shall have no explicit storage-class specifier 8533 // other than extern 8534 // See also (C++ [dcl.stc]p4). 8535 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8536 diag::err_static_block_func); 8537 break; 8538 } else 8539 return SC_Static; 8540 } 8541 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8542 } 8543 8544 // No explicit storage class has already been returned 8545 return SC_None; 8546 } 8547 8548 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8549 DeclContext *DC, QualType &R, 8550 TypeSourceInfo *TInfo, 8551 StorageClass SC, 8552 bool &IsVirtualOkay) { 8553 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8554 DeclarationName Name = NameInfo.getName(); 8555 8556 FunctionDecl *NewFD = nullptr; 8557 bool isInline = D.getDeclSpec().isInlineSpecified(); 8558 8559 if (!SemaRef.getLangOpts().CPlusPlus) { 8560 // Determine whether the function was written with a 8561 // prototype. This true when: 8562 // - there is a prototype in the declarator, or 8563 // - the type R of the function is some kind of typedef or other non- 8564 // attributed reference to a type name (which eventually refers to a 8565 // function type). 8566 bool HasPrototype = 8567 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8568 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8569 8570 NewFD = FunctionDecl::Create( 8571 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8572 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype, 8573 ConstexprSpecKind::Unspecified, 8574 /*TrailingRequiresClause=*/nullptr); 8575 if (D.isInvalidType()) 8576 NewFD->setInvalidDecl(); 8577 8578 return NewFD; 8579 } 8580 8581 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8582 8583 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8584 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8585 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8586 diag::err_constexpr_wrong_decl_kind) 8587 << static_cast<int>(ConstexprKind); 8588 ConstexprKind = ConstexprSpecKind::Unspecified; 8589 D.getMutableDeclSpec().ClearConstexprSpec(); 8590 } 8591 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8592 8593 // Check that the return type is not an abstract class type. 8594 // For record types, this is done by the AbstractClassUsageDiagnoser once 8595 // the class has been completely parsed. 8596 if (!DC->isRecord() && 8597 SemaRef.RequireNonAbstractType( 8598 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8599 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8600 D.setInvalidType(); 8601 8602 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8603 // This is a C++ constructor declaration. 8604 assert(DC->isRecord() && 8605 "Constructors can only be declared in a member context"); 8606 8607 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8608 return CXXConstructorDecl::Create( 8609 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8610 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(), 8611 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8612 InheritedConstructor(), TrailingRequiresClause); 8613 8614 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8615 // This is a C++ destructor declaration. 8616 if (DC->isRecord()) { 8617 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8618 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8619 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8620 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8621 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8622 /*isImplicitlyDeclared=*/false, ConstexprKind, 8623 TrailingRequiresClause); 8624 8625 // If the destructor needs an implicit exception specification, set it 8626 // now. FIXME: It'd be nice to be able to create the right type to start 8627 // with, but the type needs to reference the destructor declaration. 8628 if (SemaRef.getLangOpts().CPlusPlus11) 8629 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8630 8631 IsVirtualOkay = true; 8632 return NewDD; 8633 8634 } else { 8635 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8636 D.setInvalidType(); 8637 8638 // Create a FunctionDecl to satisfy the function definition parsing 8639 // code path. 8640 return FunctionDecl::Create( 8641 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R, 8642 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8643 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause); 8644 } 8645 8646 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8647 if (!DC->isRecord()) { 8648 SemaRef.Diag(D.getIdentifierLoc(), 8649 diag::err_conv_function_not_member); 8650 return nullptr; 8651 } 8652 8653 SemaRef.CheckConversionDeclarator(D, R, SC); 8654 if (D.isInvalidType()) 8655 return nullptr; 8656 8657 IsVirtualOkay = true; 8658 return CXXConversionDecl::Create( 8659 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8660 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8661 ExplicitSpecifier, ConstexprKind, SourceLocation(), 8662 TrailingRequiresClause); 8663 8664 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8665 if (TrailingRequiresClause) 8666 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8667 diag::err_trailing_requires_clause_on_deduction_guide) 8668 << TrailingRequiresClause->getSourceRange(); 8669 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8670 8671 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8672 ExplicitSpecifier, NameInfo, R, TInfo, 8673 D.getEndLoc()); 8674 } else if (DC->isRecord()) { 8675 // If the name of the function is the same as the name of the record, 8676 // then this must be an invalid constructor that has a return type. 8677 // (The parser checks for a return type and makes the declarator a 8678 // constructor if it has no return type). 8679 if (Name.getAsIdentifierInfo() && 8680 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8681 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8682 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8683 << SourceRange(D.getIdentifierLoc()); 8684 return nullptr; 8685 } 8686 8687 // This is a C++ method declaration. 8688 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8689 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8690 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8691 ConstexprKind, SourceLocation(), TrailingRequiresClause); 8692 IsVirtualOkay = !Ret->isStatic(); 8693 return Ret; 8694 } else { 8695 bool isFriend = 8696 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8697 if (!isFriend && SemaRef.CurContext->isRecord()) 8698 return nullptr; 8699 8700 // Determine whether the function was written with a 8701 // prototype. This true when: 8702 // - we're in C++ (where every function has a prototype), 8703 return FunctionDecl::Create( 8704 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8705 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8706 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause); 8707 } 8708 } 8709 8710 enum OpenCLParamType { 8711 ValidKernelParam, 8712 PtrPtrKernelParam, 8713 PtrKernelParam, 8714 InvalidAddrSpacePtrKernelParam, 8715 InvalidKernelParam, 8716 RecordKernelParam 8717 }; 8718 8719 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8720 // Size dependent types are just typedefs to normal integer types 8721 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8722 // integers other than by their names. 8723 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8724 8725 // Remove typedefs one by one until we reach a typedef 8726 // for a size dependent type. 8727 QualType DesugaredTy = Ty; 8728 do { 8729 ArrayRef<StringRef> Names(SizeTypeNames); 8730 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8731 if (Names.end() != Match) 8732 return true; 8733 8734 Ty = DesugaredTy; 8735 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8736 } while (DesugaredTy != Ty); 8737 8738 return false; 8739 } 8740 8741 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8742 if (PT->isDependentType()) 8743 return InvalidKernelParam; 8744 8745 if (PT->isPointerType() || PT->isReferenceType()) { 8746 QualType PointeeType = PT->getPointeeType(); 8747 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8748 PointeeType.getAddressSpace() == LangAS::opencl_private || 8749 PointeeType.getAddressSpace() == LangAS::Default) 8750 return InvalidAddrSpacePtrKernelParam; 8751 8752 if (PointeeType->isPointerType()) { 8753 // This is a pointer to pointer parameter. 8754 // Recursively check inner type. 8755 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 8756 if (ParamKind == InvalidAddrSpacePtrKernelParam || 8757 ParamKind == InvalidKernelParam) 8758 return ParamKind; 8759 8760 return PtrPtrKernelParam; 8761 } 8762 8763 // C++ for OpenCL v1.0 s2.4: 8764 // Moreover the types used in parameters of the kernel functions must be: 8765 // Standard layout types for pointer parameters. The same applies to 8766 // reference if an implementation supports them in kernel parameters. 8767 if (S.getLangOpts().OpenCLCPlusPlus && 8768 !S.getOpenCLOptions().isAvailableOption( 8769 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 8770 !PointeeType->isAtomicType() && !PointeeType->isVoidType() && 8771 !PointeeType->isStandardLayoutType()) 8772 return InvalidKernelParam; 8773 8774 return PtrKernelParam; 8775 } 8776 8777 // OpenCL v1.2 s6.9.k: 8778 // Arguments to kernel functions in a program cannot be declared with the 8779 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8780 // uintptr_t or a struct and/or union that contain fields declared to be one 8781 // of these built-in scalar types. 8782 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8783 return InvalidKernelParam; 8784 8785 if (PT->isImageType()) 8786 return PtrKernelParam; 8787 8788 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8789 return InvalidKernelParam; 8790 8791 // OpenCL extension spec v1.2 s9.5: 8792 // This extension adds support for half scalar and vector types as built-in 8793 // types that can be used for arithmetic operations, conversions etc. 8794 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 8795 PT->isHalfType()) 8796 return InvalidKernelParam; 8797 8798 // Look into an array argument to check if it has a forbidden type. 8799 if (PT->isArrayType()) { 8800 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8801 // Call ourself to check an underlying type of an array. Since the 8802 // getPointeeOrArrayElementType returns an innermost type which is not an 8803 // array, this recursive call only happens once. 8804 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8805 } 8806 8807 // C++ for OpenCL v1.0 s2.4: 8808 // Moreover the types used in parameters of the kernel functions must be: 8809 // Trivial and standard-layout types C++17 [basic.types] (plain old data 8810 // types) for parameters passed by value; 8811 if (S.getLangOpts().OpenCLCPlusPlus && 8812 !S.getOpenCLOptions().isAvailableOption( 8813 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 8814 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context)) 8815 return InvalidKernelParam; 8816 8817 if (PT->isRecordType()) 8818 return RecordKernelParam; 8819 8820 return ValidKernelParam; 8821 } 8822 8823 static void checkIsValidOpenCLKernelParameter( 8824 Sema &S, 8825 Declarator &D, 8826 ParmVarDecl *Param, 8827 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8828 QualType PT = Param->getType(); 8829 8830 // Cache the valid types we encounter to avoid rechecking structs that are 8831 // used again 8832 if (ValidTypes.count(PT.getTypePtr())) 8833 return; 8834 8835 switch (getOpenCLKernelParameterType(S, PT)) { 8836 case PtrPtrKernelParam: 8837 // OpenCL v3.0 s6.11.a: 8838 // A kernel function argument cannot be declared as a pointer to a pointer 8839 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 8840 if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) { 8841 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8842 D.setInvalidType(); 8843 return; 8844 } 8845 8846 ValidTypes.insert(PT.getTypePtr()); 8847 return; 8848 8849 case InvalidAddrSpacePtrKernelParam: 8850 // OpenCL v1.0 s6.5: 8851 // __kernel function arguments declared to be a pointer of a type can point 8852 // to one of the following address spaces only : __global, __local or 8853 // __constant. 8854 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8855 D.setInvalidType(); 8856 return; 8857 8858 // OpenCL v1.2 s6.9.k: 8859 // Arguments to kernel functions in a program cannot be declared with the 8860 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8861 // uintptr_t or a struct and/or union that contain fields declared to be 8862 // one of these built-in scalar types. 8863 8864 case InvalidKernelParam: 8865 // OpenCL v1.2 s6.8 n: 8866 // A kernel function argument cannot be declared 8867 // of event_t type. 8868 // Do not diagnose half type since it is diagnosed as invalid argument 8869 // type for any function elsewhere. 8870 if (!PT->isHalfType()) { 8871 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8872 8873 // Explain what typedefs are involved. 8874 const TypedefType *Typedef = nullptr; 8875 while ((Typedef = PT->getAs<TypedefType>())) { 8876 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8877 // SourceLocation may be invalid for a built-in type. 8878 if (Loc.isValid()) 8879 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8880 PT = Typedef->desugar(); 8881 } 8882 } 8883 8884 D.setInvalidType(); 8885 return; 8886 8887 case PtrKernelParam: 8888 case ValidKernelParam: 8889 ValidTypes.insert(PT.getTypePtr()); 8890 return; 8891 8892 case RecordKernelParam: 8893 break; 8894 } 8895 8896 // Track nested structs we will inspect 8897 SmallVector<const Decl *, 4> VisitStack; 8898 8899 // Track where we are in the nested structs. Items will migrate from 8900 // VisitStack to HistoryStack as we do the DFS for bad field. 8901 SmallVector<const FieldDecl *, 4> HistoryStack; 8902 HistoryStack.push_back(nullptr); 8903 8904 // At this point we already handled everything except of a RecordType or 8905 // an ArrayType of a RecordType. 8906 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8907 const RecordType *RecTy = 8908 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8909 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8910 8911 VisitStack.push_back(RecTy->getDecl()); 8912 assert(VisitStack.back() && "First decl null?"); 8913 8914 do { 8915 const Decl *Next = VisitStack.pop_back_val(); 8916 if (!Next) { 8917 assert(!HistoryStack.empty()); 8918 // Found a marker, we have gone up a level 8919 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8920 ValidTypes.insert(Hist->getType().getTypePtr()); 8921 8922 continue; 8923 } 8924 8925 // Adds everything except the original parameter declaration (which is not a 8926 // field itself) to the history stack. 8927 const RecordDecl *RD; 8928 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8929 HistoryStack.push_back(Field); 8930 8931 QualType FieldTy = Field->getType(); 8932 // Other field types (known to be valid or invalid) are handled while we 8933 // walk around RecordDecl::fields(). 8934 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8935 "Unexpected type."); 8936 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8937 8938 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8939 } else { 8940 RD = cast<RecordDecl>(Next); 8941 } 8942 8943 // Add a null marker so we know when we've gone back up a level 8944 VisitStack.push_back(nullptr); 8945 8946 for (const auto *FD : RD->fields()) { 8947 QualType QT = FD->getType(); 8948 8949 if (ValidTypes.count(QT.getTypePtr())) 8950 continue; 8951 8952 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8953 if (ParamType == ValidKernelParam) 8954 continue; 8955 8956 if (ParamType == RecordKernelParam) { 8957 VisitStack.push_back(FD); 8958 continue; 8959 } 8960 8961 // OpenCL v1.2 s6.9.p: 8962 // Arguments to kernel functions that are declared to be a struct or union 8963 // do not allow OpenCL objects to be passed as elements of the struct or 8964 // union. 8965 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8966 ParamType == InvalidAddrSpacePtrKernelParam) { 8967 S.Diag(Param->getLocation(), 8968 diag::err_record_with_pointers_kernel_param) 8969 << PT->isUnionType() 8970 << PT; 8971 } else { 8972 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8973 } 8974 8975 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8976 << OrigRecDecl->getDeclName(); 8977 8978 // We have an error, now let's go back up through history and show where 8979 // the offending field came from 8980 for (ArrayRef<const FieldDecl *>::const_iterator 8981 I = HistoryStack.begin() + 1, 8982 E = HistoryStack.end(); 8983 I != E; ++I) { 8984 const FieldDecl *OuterField = *I; 8985 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8986 << OuterField->getType(); 8987 } 8988 8989 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8990 << QT->isPointerType() 8991 << QT; 8992 D.setInvalidType(); 8993 return; 8994 } 8995 } while (!VisitStack.empty()); 8996 } 8997 8998 /// Find the DeclContext in which a tag is implicitly declared if we see an 8999 /// elaborated type specifier in the specified context, and lookup finds 9000 /// nothing. 9001 static DeclContext *getTagInjectionContext(DeclContext *DC) { 9002 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 9003 DC = DC->getParent(); 9004 return DC; 9005 } 9006 9007 /// Find the Scope in which a tag is implicitly declared if we see an 9008 /// elaborated type specifier in the specified context, and lookup finds 9009 /// nothing. 9010 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 9011 while (S->isClassScope() || 9012 (LangOpts.CPlusPlus && 9013 S->isFunctionPrototypeScope()) || 9014 ((S->getFlags() & Scope::DeclScope) == 0) || 9015 (S->getEntity() && S->getEntity()->isTransparentContext())) 9016 S = S->getParent(); 9017 return S; 9018 } 9019 9020 NamedDecl* 9021 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 9022 TypeSourceInfo *TInfo, LookupResult &Previous, 9023 MultiTemplateParamsArg TemplateParamListsRef, 9024 bool &AddToScope) { 9025 QualType R = TInfo->getType(); 9026 9027 assert(R->isFunctionType()); 9028 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 9029 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 9030 9031 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 9032 for (TemplateParameterList *TPL : TemplateParamListsRef) 9033 TemplateParamLists.push_back(TPL); 9034 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 9035 if (!TemplateParamLists.empty() && 9036 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 9037 TemplateParamLists.back() = Invented; 9038 else 9039 TemplateParamLists.push_back(Invented); 9040 } 9041 9042 // TODO: consider using NameInfo for diagnostic. 9043 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 9044 DeclarationName Name = NameInfo.getName(); 9045 StorageClass SC = getFunctionStorageClass(*this, D); 9046 9047 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 9048 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 9049 diag::err_invalid_thread) 9050 << DeclSpec::getSpecifierName(TSCS); 9051 9052 if (D.isFirstDeclarationOfMember()) 9053 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 9054 D.getIdentifierLoc()); 9055 9056 bool isFriend = false; 9057 FunctionTemplateDecl *FunctionTemplate = nullptr; 9058 bool isMemberSpecialization = false; 9059 bool isFunctionTemplateSpecialization = false; 9060 9061 bool isDependentClassScopeExplicitSpecialization = false; 9062 bool HasExplicitTemplateArgs = false; 9063 TemplateArgumentListInfo TemplateArgs; 9064 9065 bool isVirtualOkay = false; 9066 9067 DeclContext *OriginalDC = DC; 9068 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 9069 9070 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 9071 isVirtualOkay); 9072 if (!NewFD) return nullptr; 9073 9074 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 9075 NewFD->setTopLevelDeclInObjCContainer(); 9076 9077 // Set the lexical context. If this is a function-scope declaration, or has a 9078 // C++ scope specifier, or is the object of a friend declaration, the lexical 9079 // context will be different from the semantic context. 9080 NewFD->setLexicalDeclContext(CurContext); 9081 9082 if (IsLocalExternDecl) 9083 NewFD->setLocalExternDecl(); 9084 9085 if (getLangOpts().CPlusPlus) { 9086 bool isInline = D.getDeclSpec().isInlineSpecified(); 9087 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9088 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 9089 isFriend = D.getDeclSpec().isFriendSpecified(); 9090 if (isFriend && !isInline && D.isFunctionDefinition()) { 9091 // C++ [class.friend]p5 9092 // A function can be defined in a friend declaration of a 9093 // class . . . . Such a function is implicitly inline. 9094 NewFD->setImplicitlyInline(); 9095 } 9096 9097 // If this is a method defined in an __interface, and is not a constructor 9098 // or an overloaded operator, then set the pure flag (isVirtual will already 9099 // return true). 9100 if (const CXXRecordDecl *Parent = 9101 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 9102 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 9103 NewFD->setPure(true); 9104 9105 // C++ [class.union]p2 9106 // A union can have member functions, but not virtual functions. 9107 if (isVirtual && Parent->isUnion()) 9108 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 9109 } 9110 9111 SetNestedNameSpecifier(*this, NewFD, D); 9112 isMemberSpecialization = false; 9113 isFunctionTemplateSpecialization = false; 9114 if (D.isInvalidType()) 9115 NewFD->setInvalidDecl(); 9116 9117 // Match up the template parameter lists with the scope specifier, then 9118 // determine whether we have a template or a template specialization. 9119 bool Invalid = false; 9120 TemplateParameterList *TemplateParams = 9121 MatchTemplateParametersToScopeSpecifier( 9122 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 9123 D.getCXXScopeSpec(), 9124 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 9125 ? D.getName().TemplateId 9126 : nullptr, 9127 TemplateParamLists, isFriend, isMemberSpecialization, 9128 Invalid); 9129 if (TemplateParams) { 9130 // Check that we can declare a template here. 9131 if (CheckTemplateDeclScope(S, TemplateParams)) 9132 NewFD->setInvalidDecl(); 9133 9134 if (TemplateParams->size() > 0) { 9135 // This is a function template 9136 9137 // A destructor cannot be a template. 9138 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9139 Diag(NewFD->getLocation(), diag::err_destructor_template); 9140 NewFD->setInvalidDecl(); 9141 } 9142 9143 // If we're adding a template to a dependent context, we may need to 9144 // rebuilding some of the types used within the template parameter list, 9145 // now that we know what the current instantiation is. 9146 if (DC->isDependentContext()) { 9147 ContextRAII SavedContext(*this, DC); 9148 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9149 Invalid = true; 9150 } 9151 9152 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9153 NewFD->getLocation(), 9154 Name, TemplateParams, 9155 NewFD); 9156 FunctionTemplate->setLexicalDeclContext(CurContext); 9157 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9158 9159 // For source fidelity, store the other template param lists. 9160 if (TemplateParamLists.size() > 1) { 9161 NewFD->setTemplateParameterListsInfo(Context, 9162 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9163 .drop_back(1)); 9164 } 9165 } else { 9166 // This is a function template specialization. 9167 isFunctionTemplateSpecialization = true; 9168 // For source fidelity, store all the template param lists. 9169 if (TemplateParamLists.size() > 0) 9170 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9171 9172 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9173 if (isFriend) { 9174 // We want to remove the "template<>", found here. 9175 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9176 9177 // If we remove the template<> and the name is not a 9178 // template-id, we're actually silently creating a problem: 9179 // the friend declaration will refer to an untemplated decl, 9180 // and clearly the user wants a template specialization. So 9181 // we need to insert '<>' after the name. 9182 SourceLocation InsertLoc; 9183 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9184 InsertLoc = D.getName().getSourceRange().getEnd(); 9185 InsertLoc = getLocForEndOfToken(InsertLoc); 9186 } 9187 9188 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9189 << Name << RemoveRange 9190 << FixItHint::CreateRemoval(RemoveRange) 9191 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9192 } 9193 } 9194 } else { 9195 // Check that we can declare a template here. 9196 if (!TemplateParamLists.empty() && isMemberSpecialization && 9197 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9198 NewFD->setInvalidDecl(); 9199 9200 // All template param lists were matched against the scope specifier: 9201 // this is NOT (an explicit specialization of) a template. 9202 if (TemplateParamLists.size() > 0) 9203 // For source fidelity, store all the template param lists. 9204 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9205 } 9206 9207 if (Invalid) { 9208 NewFD->setInvalidDecl(); 9209 if (FunctionTemplate) 9210 FunctionTemplate->setInvalidDecl(); 9211 } 9212 9213 // C++ [dcl.fct.spec]p5: 9214 // The virtual specifier shall only be used in declarations of 9215 // nonstatic class member functions that appear within a 9216 // member-specification of a class declaration; see 10.3. 9217 // 9218 if (isVirtual && !NewFD->isInvalidDecl()) { 9219 if (!isVirtualOkay) { 9220 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9221 diag::err_virtual_non_function); 9222 } else if (!CurContext->isRecord()) { 9223 // 'virtual' was specified outside of the class. 9224 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9225 diag::err_virtual_out_of_class) 9226 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9227 } else if (NewFD->getDescribedFunctionTemplate()) { 9228 // C++ [temp.mem]p3: 9229 // A member function template shall not be virtual. 9230 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9231 diag::err_virtual_member_function_template) 9232 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9233 } else { 9234 // Okay: Add virtual to the method. 9235 NewFD->setVirtualAsWritten(true); 9236 } 9237 9238 if (getLangOpts().CPlusPlus14 && 9239 NewFD->getReturnType()->isUndeducedType()) 9240 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9241 } 9242 9243 if (getLangOpts().CPlusPlus14 && 9244 (NewFD->isDependentContext() || 9245 (isFriend && CurContext->isDependentContext())) && 9246 NewFD->getReturnType()->isUndeducedType()) { 9247 // If the function template is referenced directly (for instance, as a 9248 // member of the current instantiation), pretend it has a dependent type. 9249 // This is not really justified by the standard, but is the only sane 9250 // thing to do. 9251 // FIXME: For a friend function, we have not marked the function as being 9252 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9253 const FunctionProtoType *FPT = 9254 NewFD->getType()->castAs<FunctionProtoType>(); 9255 QualType Result = 9256 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9257 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9258 FPT->getExtProtoInfo())); 9259 } 9260 9261 // C++ [dcl.fct.spec]p3: 9262 // The inline specifier shall not appear on a block scope function 9263 // declaration. 9264 if (isInline && !NewFD->isInvalidDecl()) { 9265 if (CurContext->isFunctionOrMethod()) { 9266 // 'inline' is not allowed on block scope function declaration. 9267 Diag(D.getDeclSpec().getInlineSpecLoc(), 9268 diag::err_inline_declaration_block_scope) << Name 9269 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9270 } 9271 } 9272 9273 // C++ [dcl.fct.spec]p6: 9274 // The explicit specifier shall be used only in the declaration of a 9275 // constructor or conversion function within its class definition; 9276 // see 12.3.1 and 12.3.2. 9277 if (hasExplicit && !NewFD->isInvalidDecl() && 9278 !isa<CXXDeductionGuideDecl>(NewFD)) { 9279 if (!CurContext->isRecord()) { 9280 // 'explicit' was specified outside of the class. 9281 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9282 diag::err_explicit_out_of_class) 9283 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9284 } else if (!isa<CXXConstructorDecl>(NewFD) && 9285 !isa<CXXConversionDecl>(NewFD)) { 9286 // 'explicit' was specified on a function that wasn't a constructor 9287 // or conversion function. 9288 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9289 diag::err_explicit_non_ctor_or_conv_function) 9290 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9291 } 9292 } 9293 9294 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9295 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9296 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9297 // are implicitly inline. 9298 NewFD->setImplicitlyInline(); 9299 9300 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9301 // be either constructors or to return a literal type. Therefore, 9302 // destructors cannot be declared constexpr. 9303 if (isa<CXXDestructorDecl>(NewFD) && 9304 (!getLangOpts().CPlusPlus20 || 9305 ConstexprKind == ConstexprSpecKind::Consteval)) { 9306 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9307 << static_cast<int>(ConstexprKind); 9308 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9309 ? ConstexprSpecKind::Unspecified 9310 : ConstexprSpecKind::Constexpr); 9311 } 9312 // C++20 [dcl.constexpr]p2: An allocation function, or a 9313 // deallocation function shall not be declared with the consteval 9314 // specifier. 9315 if (ConstexprKind == ConstexprSpecKind::Consteval && 9316 (NewFD->getOverloadedOperator() == OO_New || 9317 NewFD->getOverloadedOperator() == OO_Array_New || 9318 NewFD->getOverloadedOperator() == OO_Delete || 9319 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9320 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9321 diag::err_invalid_consteval_decl_kind) 9322 << NewFD; 9323 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9324 } 9325 } 9326 9327 // If __module_private__ was specified, mark the function accordingly. 9328 if (D.getDeclSpec().isModulePrivateSpecified()) { 9329 if (isFunctionTemplateSpecialization) { 9330 SourceLocation ModulePrivateLoc 9331 = D.getDeclSpec().getModulePrivateSpecLoc(); 9332 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9333 << 0 9334 << FixItHint::CreateRemoval(ModulePrivateLoc); 9335 } else { 9336 NewFD->setModulePrivate(); 9337 if (FunctionTemplate) 9338 FunctionTemplate->setModulePrivate(); 9339 } 9340 } 9341 9342 if (isFriend) { 9343 if (FunctionTemplate) { 9344 FunctionTemplate->setObjectOfFriendDecl(); 9345 FunctionTemplate->setAccess(AS_public); 9346 } 9347 NewFD->setObjectOfFriendDecl(); 9348 NewFD->setAccess(AS_public); 9349 } 9350 9351 // If a function is defined as defaulted or deleted, mark it as such now. 9352 // We'll do the relevant checks on defaulted / deleted functions later. 9353 switch (D.getFunctionDefinitionKind()) { 9354 case FunctionDefinitionKind::Declaration: 9355 case FunctionDefinitionKind::Definition: 9356 break; 9357 9358 case FunctionDefinitionKind::Defaulted: 9359 NewFD->setDefaulted(); 9360 break; 9361 9362 case FunctionDefinitionKind::Deleted: 9363 NewFD->setDeletedAsWritten(); 9364 break; 9365 } 9366 9367 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9368 D.isFunctionDefinition()) { 9369 // C++ [class.mfct]p2: 9370 // A member function may be defined (8.4) in its class definition, in 9371 // which case it is an inline member function (7.1.2) 9372 NewFD->setImplicitlyInline(); 9373 } 9374 9375 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9376 !CurContext->isRecord()) { 9377 // C++ [class.static]p1: 9378 // A data or function member of a class may be declared static 9379 // in a class definition, in which case it is a static member of 9380 // the class. 9381 9382 // Complain about the 'static' specifier if it's on an out-of-line 9383 // member function definition. 9384 9385 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9386 // member function template declaration and class member template 9387 // declaration (MSVC versions before 2015), warn about this. 9388 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9389 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9390 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9391 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9392 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9393 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9394 } 9395 9396 // C++11 [except.spec]p15: 9397 // A deallocation function with no exception-specification is treated 9398 // as if it were specified with noexcept(true). 9399 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9400 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9401 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9402 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9403 NewFD->setType(Context.getFunctionType( 9404 FPT->getReturnType(), FPT->getParamTypes(), 9405 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9406 } 9407 9408 // Filter out previous declarations that don't match the scope. 9409 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9410 D.getCXXScopeSpec().isNotEmpty() || 9411 isMemberSpecialization || 9412 isFunctionTemplateSpecialization); 9413 9414 // Handle GNU asm-label extension (encoded as an attribute). 9415 if (Expr *E = (Expr*) D.getAsmLabel()) { 9416 // The parser guarantees this is a string. 9417 StringLiteral *SE = cast<StringLiteral>(E); 9418 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9419 /*IsLiteralLabel=*/true, 9420 SE->getStrTokenLoc(0))); 9421 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9422 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9423 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9424 if (I != ExtnameUndeclaredIdentifiers.end()) { 9425 if (isDeclExternC(NewFD)) { 9426 NewFD->addAttr(I->second); 9427 ExtnameUndeclaredIdentifiers.erase(I); 9428 } else 9429 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9430 << /*Variable*/0 << NewFD; 9431 } 9432 } 9433 9434 // Copy the parameter declarations from the declarator D to the function 9435 // declaration NewFD, if they are available. First scavenge them into Params. 9436 SmallVector<ParmVarDecl*, 16> Params; 9437 unsigned FTIIdx; 9438 if (D.isFunctionDeclarator(FTIIdx)) { 9439 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9440 9441 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9442 // function that takes no arguments, not a function that takes a 9443 // single void argument. 9444 // We let through "const void" here because Sema::GetTypeForDeclarator 9445 // already checks for that case. 9446 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9447 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9448 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9449 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9450 Param->setDeclContext(NewFD); 9451 Params.push_back(Param); 9452 9453 if (Param->isInvalidDecl()) 9454 NewFD->setInvalidDecl(); 9455 } 9456 } 9457 9458 if (!getLangOpts().CPlusPlus) { 9459 // In C, find all the tag declarations from the prototype and move them 9460 // into the function DeclContext. Remove them from the surrounding tag 9461 // injection context of the function, which is typically but not always 9462 // the TU. 9463 DeclContext *PrototypeTagContext = 9464 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9465 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9466 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9467 9468 // We don't want to reparent enumerators. Look at their parent enum 9469 // instead. 9470 if (!TD) { 9471 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9472 TD = cast<EnumDecl>(ECD->getDeclContext()); 9473 } 9474 if (!TD) 9475 continue; 9476 DeclContext *TagDC = TD->getLexicalDeclContext(); 9477 if (!TagDC->containsDecl(TD)) 9478 continue; 9479 TagDC->removeDecl(TD); 9480 TD->setDeclContext(NewFD); 9481 NewFD->addDecl(TD); 9482 9483 // Preserve the lexical DeclContext if it is not the surrounding tag 9484 // injection context of the FD. In this example, the semantic context of 9485 // E will be f and the lexical context will be S, while both the 9486 // semantic and lexical contexts of S will be f: 9487 // void f(struct S { enum E { a } f; } s); 9488 if (TagDC != PrototypeTagContext) 9489 TD->setLexicalDeclContext(TagDC); 9490 } 9491 } 9492 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9493 // When we're declaring a function with a typedef, typeof, etc as in the 9494 // following example, we'll need to synthesize (unnamed) 9495 // parameters for use in the declaration. 9496 // 9497 // @code 9498 // typedef void fn(int); 9499 // fn f; 9500 // @endcode 9501 9502 // Synthesize a parameter for each argument type. 9503 for (const auto &AI : FT->param_types()) { 9504 ParmVarDecl *Param = 9505 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9506 Param->setScopeInfo(0, Params.size()); 9507 Params.push_back(Param); 9508 } 9509 } else { 9510 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9511 "Should not need args for typedef of non-prototype fn"); 9512 } 9513 9514 // Finally, we know we have the right number of parameters, install them. 9515 NewFD->setParams(Params); 9516 9517 if (D.getDeclSpec().isNoreturnSpecified()) 9518 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9519 D.getDeclSpec().getNoreturnSpecLoc(), 9520 AttributeCommonInfo::AS_Keyword)); 9521 9522 // Functions returning a variably modified type violate C99 6.7.5.2p2 9523 // because all functions have linkage. 9524 if (!NewFD->isInvalidDecl() && 9525 NewFD->getReturnType()->isVariablyModifiedType()) { 9526 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9527 NewFD->setInvalidDecl(); 9528 } 9529 9530 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9531 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9532 !NewFD->hasAttr<SectionAttr>()) 9533 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9534 Context, PragmaClangTextSection.SectionName, 9535 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9536 9537 // Apply an implicit SectionAttr if #pragma code_seg is active. 9538 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9539 !NewFD->hasAttr<SectionAttr>()) { 9540 NewFD->addAttr(SectionAttr::CreateImplicit( 9541 Context, CodeSegStack.CurrentValue->getString(), 9542 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9543 SectionAttr::Declspec_allocate)); 9544 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9545 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9546 ASTContext::PSF_Read, 9547 NewFD)) 9548 NewFD->dropAttr<SectionAttr>(); 9549 } 9550 9551 // Apply an implicit CodeSegAttr from class declspec or 9552 // apply an implicit SectionAttr from #pragma code_seg if active. 9553 if (!NewFD->hasAttr<CodeSegAttr>()) { 9554 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9555 D.isFunctionDefinition())) { 9556 NewFD->addAttr(SAttr); 9557 } 9558 } 9559 9560 // Handle attributes. 9561 ProcessDeclAttributes(S, NewFD, D); 9562 9563 if (getLangOpts().OpenCL) { 9564 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9565 // type declaration will generate a compilation error. 9566 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9567 if (AddressSpace != LangAS::Default) { 9568 Diag(NewFD->getLocation(), 9569 diag::err_opencl_return_value_with_address_space); 9570 NewFD->setInvalidDecl(); 9571 } 9572 } 9573 9574 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) 9575 checkDeviceDecl(NewFD, D.getBeginLoc()); 9576 9577 if (!getLangOpts().CPlusPlus) { 9578 // Perform semantic checking on the function declaration. 9579 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9580 CheckMain(NewFD, D.getDeclSpec()); 9581 9582 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9583 CheckMSVCRTEntryPoint(NewFD); 9584 9585 if (!NewFD->isInvalidDecl()) 9586 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9587 isMemberSpecialization)); 9588 else if (!Previous.empty()) 9589 // Recover gracefully from an invalid redeclaration. 9590 D.setRedeclaration(true); 9591 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9592 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9593 "previous declaration set still overloaded"); 9594 9595 // Diagnose no-prototype function declarations with calling conventions that 9596 // don't support variadic calls. Only do this in C and do it after merging 9597 // possibly prototyped redeclarations. 9598 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9599 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9600 CallingConv CC = FT->getExtInfo().getCC(); 9601 if (!supportsVariadicCall(CC)) { 9602 // Windows system headers sometimes accidentally use stdcall without 9603 // (void) parameters, so we relax this to a warning. 9604 int DiagID = 9605 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9606 Diag(NewFD->getLocation(), DiagID) 9607 << FunctionType::getNameForCallConv(CC); 9608 } 9609 } 9610 9611 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9612 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9613 checkNonTrivialCUnion(NewFD->getReturnType(), 9614 NewFD->getReturnTypeSourceRange().getBegin(), 9615 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9616 } else { 9617 // C++11 [replacement.functions]p3: 9618 // The program's definitions shall not be specified as inline. 9619 // 9620 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9621 // 9622 // Suppress the diagnostic if the function is __attribute__((used)), since 9623 // that forces an external definition to be emitted. 9624 if (D.getDeclSpec().isInlineSpecified() && 9625 NewFD->isReplaceableGlobalAllocationFunction() && 9626 !NewFD->hasAttr<UsedAttr>()) 9627 Diag(D.getDeclSpec().getInlineSpecLoc(), 9628 diag::ext_operator_new_delete_declared_inline) 9629 << NewFD->getDeclName(); 9630 9631 // If the declarator is a template-id, translate the parser's template 9632 // argument list into our AST format. 9633 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9634 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9635 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9636 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9637 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9638 TemplateId->NumArgs); 9639 translateTemplateArguments(TemplateArgsPtr, 9640 TemplateArgs); 9641 9642 HasExplicitTemplateArgs = true; 9643 9644 if (NewFD->isInvalidDecl()) { 9645 HasExplicitTemplateArgs = false; 9646 } else if (FunctionTemplate) { 9647 // Function template with explicit template arguments. 9648 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9649 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9650 9651 HasExplicitTemplateArgs = false; 9652 } else { 9653 assert((isFunctionTemplateSpecialization || 9654 D.getDeclSpec().isFriendSpecified()) && 9655 "should have a 'template<>' for this decl"); 9656 // "friend void foo<>(int);" is an implicit specialization decl. 9657 isFunctionTemplateSpecialization = true; 9658 } 9659 } else if (isFriend && isFunctionTemplateSpecialization) { 9660 // This combination is only possible in a recovery case; the user 9661 // wrote something like: 9662 // template <> friend void foo(int); 9663 // which we're recovering from as if the user had written: 9664 // friend void foo<>(int); 9665 // Go ahead and fake up a template id. 9666 HasExplicitTemplateArgs = true; 9667 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9668 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9669 } 9670 9671 // We do not add HD attributes to specializations here because 9672 // they may have different constexpr-ness compared to their 9673 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9674 // may end up with different effective targets. Instead, a 9675 // specialization inherits its target attributes from its template 9676 // in the CheckFunctionTemplateSpecialization() call below. 9677 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9678 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9679 9680 // If it's a friend (and only if it's a friend), it's possible 9681 // that either the specialized function type or the specialized 9682 // template is dependent, and therefore matching will fail. In 9683 // this case, don't check the specialization yet. 9684 if (isFunctionTemplateSpecialization && isFriend && 9685 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9686 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 9687 TemplateArgs.arguments()))) { 9688 assert(HasExplicitTemplateArgs && 9689 "friend function specialization without template args"); 9690 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9691 Previous)) 9692 NewFD->setInvalidDecl(); 9693 } else if (isFunctionTemplateSpecialization) { 9694 if (CurContext->isDependentContext() && CurContext->isRecord() 9695 && !isFriend) { 9696 isDependentClassScopeExplicitSpecialization = true; 9697 } else if (!NewFD->isInvalidDecl() && 9698 CheckFunctionTemplateSpecialization( 9699 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9700 Previous)) 9701 NewFD->setInvalidDecl(); 9702 9703 // C++ [dcl.stc]p1: 9704 // A storage-class-specifier shall not be specified in an explicit 9705 // specialization (14.7.3) 9706 FunctionTemplateSpecializationInfo *Info = 9707 NewFD->getTemplateSpecializationInfo(); 9708 if (Info && SC != SC_None) { 9709 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9710 Diag(NewFD->getLocation(), 9711 diag::err_explicit_specialization_inconsistent_storage_class) 9712 << SC 9713 << FixItHint::CreateRemoval( 9714 D.getDeclSpec().getStorageClassSpecLoc()); 9715 9716 else 9717 Diag(NewFD->getLocation(), 9718 diag::ext_explicit_specialization_storage_class) 9719 << FixItHint::CreateRemoval( 9720 D.getDeclSpec().getStorageClassSpecLoc()); 9721 } 9722 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9723 if (CheckMemberSpecialization(NewFD, Previous)) 9724 NewFD->setInvalidDecl(); 9725 } 9726 9727 // Perform semantic checking on the function declaration. 9728 if (!isDependentClassScopeExplicitSpecialization) { 9729 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9730 CheckMain(NewFD, D.getDeclSpec()); 9731 9732 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9733 CheckMSVCRTEntryPoint(NewFD); 9734 9735 if (!NewFD->isInvalidDecl()) 9736 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9737 isMemberSpecialization)); 9738 else if (!Previous.empty()) 9739 // Recover gracefully from an invalid redeclaration. 9740 D.setRedeclaration(true); 9741 } 9742 9743 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9744 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9745 "previous declaration set still overloaded"); 9746 9747 NamedDecl *PrincipalDecl = (FunctionTemplate 9748 ? cast<NamedDecl>(FunctionTemplate) 9749 : NewFD); 9750 9751 if (isFriend && NewFD->getPreviousDecl()) { 9752 AccessSpecifier Access = AS_public; 9753 if (!NewFD->isInvalidDecl()) 9754 Access = NewFD->getPreviousDecl()->getAccess(); 9755 9756 NewFD->setAccess(Access); 9757 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9758 } 9759 9760 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9761 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9762 PrincipalDecl->setNonMemberOperator(); 9763 9764 // If we have a function template, check the template parameter 9765 // list. This will check and merge default template arguments. 9766 if (FunctionTemplate) { 9767 FunctionTemplateDecl *PrevTemplate = 9768 FunctionTemplate->getPreviousDecl(); 9769 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9770 PrevTemplate ? PrevTemplate->getTemplateParameters() 9771 : nullptr, 9772 D.getDeclSpec().isFriendSpecified() 9773 ? (D.isFunctionDefinition() 9774 ? TPC_FriendFunctionTemplateDefinition 9775 : TPC_FriendFunctionTemplate) 9776 : (D.getCXXScopeSpec().isSet() && 9777 DC && DC->isRecord() && 9778 DC->isDependentContext()) 9779 ? TPC_ClassTemplateMember 9780 : TPC_FunctionTemplate); 9781 } 9782 9783 if (NewFD->isInvalidDecl()) { 9784 // Ignore all the rest of this. 9785 } else if (!D.isRedeclaration()) { 9786 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9787 AddToScope }; 9788 // Fake up an access specifier if it's supposed to be a class member. 9789 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9790 NewFD->setAccess(AS_public); 9791 9792 // Qualified decls generally require a previous declaration. 9793 if (D.getCXXScopeSpec().isSet()) { 9794 // ...with the major exception of templated-scope or 9795 // dependent-scope friend declarations. 9796 9797 // TODO: we currently also suppress this check in dependent 9798 // contexts because (1) the parameter depth will be off when 9799 // matching friend templates and (2) we might actually be 9800 // selecting a friend based on a dependent factor. But there 9801 // are situations where these conditions don't apply and we 9802 // can actually do this check immediately. 9803 // 9804 // Unless the scope is dependent, it's always an error if qualified 9805 // redeclaration lookup found nothing at all. Diagnose that now; 9806 // nothing will diagnose that error later. 9807 if (isFriend && 9808 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9809 (!Previous.empty() && CurContext->isDependentContext()))) { 9810 // ignore these 9811 } else if (NewFD->isCPUDispatchMultiVersion() || 9812 NewFD->isCPUSpecificMultiVersion()) { 9813 // ignore this, we allow the redeclaration behavior here to create new 9814 // versions of the function. 9815 } else { 9816 // The user tried to provide an out-of-line definition for a 9817 // function that is a member of a class or namespace, but there 9818 // was no such member function declared (C++ [class.mfct]p2, 9819 // C++ [namespace.memdef]p2). For example: 9820 // 9821 // class X { 9822 // void f() const; 9823 // }; 9824 // 9825 // void X::f() { } // ill-formed 9826 // 9827 // Complain about this problem, and attempt to suggest close 9828 // matches (e.g., those that differ only in cv-qualifiers and 9829 // whether the parameter types are references). 9830 9831 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9832 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9833 AddToScope = ExtraArgs.AddToScope; 9834 return Result; 9835 } 9836 } 9837 9838 // Unqualified local friend declarations are required to resolve 9839 // to something. 9840 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9841 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9842 *this, Previous, NewFD, ExtraArgs, true, S)) { 9843 AddToScope = ExtraArgs.AddToScope; 9844 return Result; 9845 } 9846 } 9847 } else if (!D.isFunctionDefinition() && 9848 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9849 !isFriend && !isFunctionTemplateSpecialization && 9850 !isMemberSpecialization) { 9851 // An out-of-line member function declaration must also be a 9852 // definition (C++ [class.mfct]p2). 9853 // Note that this is not the case for explicit specializations of 9854 // function templates or member functions of class templates, per 9855 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9856 // extension for compatibility with old SWIG code which likes to 9857 // generate them. 9858 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9859 << D.getCXXScopeSpec().getRange(); 9860 } 9861 } 9862 9863 // If this is the first declaration of a library builtin function, add 9864 // attributes as appropriate. 9865 if (!D.isRedeclaration() && 9866 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 9867 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 9868 if (unsigned BuiltinID = II->getBuiltinID()) { 9869 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 9870 // Validate the type matches unless this builtin is specified as 9871 // matching regardless of its declared type. 9872 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 9873 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9874 } else { 9875 ASTContext::GetBuiltinTypeError Error; 9876 LookupNecessaryTypesForBuiltin(S, BuiltinID); 9877 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 9878 9879 if (!Error && !BuiltinType.isNull() && 9880 Context.hasSameFunctionTypeIgnoringExceptionSpec( 9881 NewFD->getType(), BuiltinType)) 9882 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9883 } 9884 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 9885 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9886 // FIXME: We should consider this a builtin only in the std namespace. 9887 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9888 } 9889 } 9890 } 9891 } 9892 9893 ProcessPragmaWeak(S, NewFD); 9894 checkAttributesAfterMerging(*this, *NewFD); 9895 9896 AddKnownFunctionAttributes(NewFD); 9897 9898 if (NewFD->hasAttr<OverloadableAttr>() && 9899 !NewFD->getType()->getAs<FunctionProtoType>()) { 9900 Diag(NewFD->getLocation(), 9901 diag::err_attribute_overloadable_no_prototype) 9902 << NewFD; 9903 9904 // Turn this into a variadic function with no parameters. 9905 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9906 FunctionProtoType::ExtProtoInfo EPI( 9907 Context.getDefaultCallingConvention(true, false)); 9908 EPI.Variadic = true; 9909 EPI.ExtInfo = FT->getExtInfo(); 9910 9911 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9912 NewFD->setType(R); 9913 } 9914 9915 // If there's a #pragma GCC visibility in scope, and this isn't a class 9916 // member, set the visibility of this function. 9917 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9918 AddPushedVisibilityAttribute(NewFD); 9919 9920 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9921 // marking the function. 9922 AddCFAuditedAttribute(NewFD); 9923 9924 // If this is a function definition, check if we have to apply optnone due to 9925 // a pragma. 9926 if(D.isFunctionDefinition()) 9927 AddRangeBasedOptnone(NewFD); 9928 9929 // If this is the first declaration of an extern C variable, update 9930 // the map of such variables. 9931 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9932 isIncompleteDeclExternC(*this, NewFD)) 9933 RegisterLocallyScopedExternCDecl(NewFD, S); 9934 9935 // Set this FunctionDecl's range up to the right paren. 9936 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9937 9938 if (D.isRedeclaration() && !Previous.empty()) { 9939 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9940 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9941 isMemberSpecialization || 9942 isFunctionTemplateSpecialization, 9943 D.isFunctionDefinition()); 9944 } 9945 9946 if (getLangOpts().CUDA) { 9947 IdentifierInfo *II = NewFD->getIdentifier(); 9948 if (II && II->isStr(getCudaConfigureFuncName()) && 9949 !NewFD->isInvalidDecl() && 9950 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9951 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) 9952 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9953 << getCudaConfigureFuncName(); 9954 Context.setcudaConfigureCallDecl(NewFD); 9955 } 9956 9957 // Variadic functions, other than a *declaration* of printf, are not allowed 9958 // in device-side CUDA code, unless someone passed 9959 // -fcuda-allow-variadic-functions. 9960 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9961 (NewFD->hasAttr<CUDADeviceAttr>() || 9962 NewFD->hasAttr<CUDAGlobalAttr>()) && 9963 !(II && II->isStr("printf") && NewFD->isExternC() && 9964 !D.isFunctionDefinition())) { 9965 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9966 } 9967 } 9968 9969 MarkUnusedFileScopedDecl(NewFD); 9970 9971 9972 9973 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9974 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9975 if (SC == SC_Static) { 9976 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9977 D.setInvalidType(); 9978 } 9979 9980 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9981 if (!NewFD->getReturnType()->isVoidType()) { 9982 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9983 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9984 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9985 : FixItHint()); 9986 D.setInvalidType(); 9987 } 9988 9989 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9990 for (auto Param : NewFD->parameters()) 9991 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9992 9993 if (getLangOpts().OpenCLCPlusPlus) { 9994 if (DC->isRecord()) { 9995 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9996 D.setInvalidType(); 9997 } 9998 if (FunctionTemplate) { 9999 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 10000 D.setInvalidType(); 10001 } 10002 } 10003 } 10004 10005 if (getLangOpts().CPlusPlus) { 10006 if (FunctionTemplate) { 10007 if (NewFD->isInvalidDecl()) 10008 FunctionTemplate->setInvalidDecl(); 10009 return FunctionTemplate; 10010 } 10011 10012 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 10013 CompleteMemberSpecialization(NewFD, Previous); 10014 } 10015 10016 for (const ParmVarDecl *Param : NewFD->parameters()) { 10017 QualType PT = Param->getType(); 10018 10019 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 10020 // types. 10021 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 10022 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 10023 QualType ElemTy = PipeTy->getElementType(); 10024 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 10025 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 10026 D.setInvalidType(); 10027 } 10028 } 10029 } 10030 } 10031 10032 // Here we have an function template explicit specialization at class scope. 10033 // The actual specialization will be postponed to template instatiation 10034 // time via the ClassScopeFunctionSpecializationDecl node. 10035 if (isDependentClassScopeExplicitSpecialization) { 10036 ClassScopeFunctionSpecializationDecl *NewSpec = 10037 ClassScopeFunctionSpecializationDecl::Create( 10038 Context, CurContext, NewFD->getLocation(), 10039 cast<CXXMethodDecl>(NewFD), 10040 HasExplicitTemplateArgs, TemplateArgs); 10041 CurContext->addDecl(NewSpec); 10042 AddToScope = false; 10043 } 10044 10045 // Diagnose availability attributes. Availability cannot be used on functions 10046 // that are run during load/unload. 10047 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 10048 if (NewFD->hasAttr<ConstructorAttr>()) { 10049 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10050 << 1; 10051 NewFD->dropAttr<AvailabilityAttr>(); 10052 } 10053 if (NewFD->hasAttr<DestructorAttr>()) { 10054 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10055 << 2; 10056 NewFD->dropAttr<AvailabilityAttr>(); 10057 } 10058 } 10059 10060 // Diagnose no_builtin attribute on function declaration that are not a 10061 // definition. 10062 // FIXME: We should really be doing this in 10063 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 10064 // the FunctionDecl and at this point of the code 10065 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 10066 // because Sema::ActOnStartOfFunctionDef has not been called yet. 10067 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 10068 switch (D.getFunctionDefinitionKind()) { 10069 case FunctionDefinitionKind::Defaulted: 10070 case FunctionDefinitionKind::Deleted: 10071 Diag(NBA->getLocation(), 10072 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 10073 << NBA->getSpelling(); 10074 break; 10075 case FunctionDefinitionKind::Declaration: 10076 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 10077 << NBA->getSpelling(); 10078 break; 10079 case FunctionDefinitionKind::Definition: 10080 break; 10081 } 10082 10083 return NewFD; 10084 } 10085 10086 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 10087 /// when __declspec(code_seg) "is applied to a class, all member functions of 10088 /// the class and nested classes -- this includes compiler-generated special 10089 /// member functions -- are put in the specified segment." 10090 /// The actual behavior is a little more complicated. The Microsoft compiler 10091 /// won't check outer classes if there is an active value from #pragma code_seg. 10092 /// The CodeSeg is always applied from the direct parent but only from outer 10093 /// classes when the #pragma code_seg stack is empty. See: 10094 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 10095 /// available since MS has removed the page. 10096 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 10097 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 10098 if (!Method) 10099 return nullptr; 10100 const CXXRecordDecl *Parent = Method->getParent(); 10101 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10102 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10103 NewAttr->setImplicit(true); 10104 return NewAttr; 10105 } 10106 10107 // The Microsoft compiler won't check outer classes for the CodeSeg 10108 // when the #pragma code_seg stack is active. 10109 if (S.CodeSegStack.CurrentValue) 10110 return nullptr; 10111 10112 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 10113 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10114 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10115 NewAttr->setImplicit(true); 10116 return NewAttr; 10117 } 10118 } 10119 return nullptr; 10120 } 10121 10122 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 10123 /// containing class. Otherwise it will return implicit SectionAttr if the 10124 /// function is a definition and there is an active value on CodeSegStack 10125 /// (from the current #pragma code-seg value). 10126 /// 10127 /// \param FD Function being declared. 10128 /// \param IsDefinition Whether it is a definition or just a declarartion. 10129 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 10130 /// nullptr if no attribute should be added. 10131 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 10132 bool IsDefinition) { 10133 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 10134 return A; 10135 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 10136 CodeSegStack.CurrentValue) 10137 return SectionAttr::CreateImplicit( 10138 getASTContext(), CodeSegStack.CurrentValue->getString(), 10139 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 10140 SectionAttr::Declspec_allocate); 10141 return nullptr; 10142 } 10143 10144 /// Determines if we can perform a correct type check for \p D as a 10145 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 10146 /// best-effort check. 10147 /// 10148 /// \param NewD The new declaration. 10149 /// \param OldD The old declaration. 10150 /// \param NewT The portion of the type of the new declaration to check. 10151 /// \param OldT The portion of the type of the old declaration to check. 10152 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 10153 QualType NewT, QualType OldT) { 10154 if (!NewD->getLexicalDeclContext()->isDependentContext()) 10155 return true; 10156 10157 // For dependently-typed local extern declarations and friends, we can't 10158 // perform a correct type check in general until instantiation: 10159 // 10160 // int f(); 10161 // template<typename T> void g() { T f(); } 10162 // 10163 // (valid if g() is only instantiated with T = int). 10164 if (NewT->isDependentType() && 10165 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10166 return false; 10167 10168 // Similarly, if the previous declaration was a dependent local extern 10169 // declaration, we don't really know its type yet. 10170 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10171 return false; 10172 10173 return true; 10174 } 10175 10176 /// Checks if the new declaration declared in dependent context must be 10177 /// put in the same redeclaration chain as the specified declaration. 10178 /// 10179 /// \param D Declaration that is checked. 10180 /// \param PrevDecl Previous declaration found with proper lookup method for the 10181 /// same declaration name. 10182 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10183 /// belongs to. 10184 /// 10185 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10186 if (!D->getLexicalDeclContext()->isDependentContext()) 10187 return true; 10188 10189 // Don't chain dependent friend function definitions until instantiation, to 10190 // permit cases like 10191 // 10192 // void func(); 10193 // template<typename T> class C1 { friend void func() {} }; 10194 // template<typename T> class C2 { friend void func() {} }; 10195 // 10196 // ... which is valid if only one of C1 and C2 is ever instantiated. 10197 // 10198 // FIXME: This need only apply to function definitions. For now, we proxy 10199 // this by checking for a file-scope function. We do not want this to apply 10200 // to friend declarations nominating member functions, because that gets in 10201 // the way of access checks. 10202 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10203 return false; 10204 10205 auto *VD = dyn_cast<ValueDecl>(D); 10206 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10207 return !VD || !PrevVD || 10208 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10209 PrevVD->getType()); 10210 } 10211 10212 /// Check the target attribute of the function for MultiVersion 10213 /// validity. 10214 /// 10215 /// Returns true if there was an error, false otherwise. 10216 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10217 const auto *TA = FD->getAttr<TargetAttr>(); 10218 assert(TA && "MultiVersion Candidate requires a target attribute"); 10219 ParsedTargetAttr ParseInfo = TA->parse(); 10220 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10221 enum ErrType { Feature = 0, Architecture = 1 }; 10222 10223 if (!ParseInfo.Architecture.empty() && 10224 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10225 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10226 << Architecture << ParseInfo.Architecture; 10227 return true; 10228 } 10229 10230 for (const auto &Feat : ParseInfo.Features) { 10231 auto BareFeat = StringRef{Feat}.substr(1); 10232 if (Feat[0] == '-') { 10233 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10234 << Feature << ("no-" + BareFeat).str(); 10235 return true; 10236 } 10237 10238 if (!TargetInfo.validateCpuSupports(BareFeat) || 10239 !TargetInfo.isValidFeatureName(BareFeat)) { 10240 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10241 << Feature << BareFeat; 10242 return true; 10243 } 10244 } 10245 return false; 10246 } 10247 10248 // Provide a white-list of attributes that are allowed to be combined with 10249 // multiversion functions. 10250 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10251 MultiVersionKind MVType) { 10252 // Note: this list/diagnosis must match the list in 10253 // checkMultiversionAttributesAllSame. 10254 switch (Kind) { 10255 default: 10256 return false; 10257 case attr::Used: 10258 return MVType == MultiVersionKind::Target; 10259 case attr::NonNull: 10260 case attr::NoThrow: 10261 return true; 10262 } 10263 } 10264 10265 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10266 const FunctionDecl *FD, 10267 const FunctionDecl *CausedFD, 10268 MultiVersionKind MVType) { 10269 bool IsCPUSpecificCPUDispatchMVType = 10270 MVType == MultiVersionKind::CPUDispatch || 10271 MVType == MultiVersionKind::CPUSpecific; 10272 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType]( 10273 Sema &S, const Attr *A) { 10274 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10275 << IsCPUSpecificCPUDispatchMVType << A; 10276 if (CausedFD) 10277 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10278 return true; 10279 }; 10280 10281 for (const Attr *A : FD->attrs()) { 10282 switch (A->getKind()) { 10283 case attr::CPUDispatch: 10284 case attr::CPUSpecific: 10285 if (MVType != MultiVersionKind::CPUDispatch && 10286 MVType != MultiVersionKind::CPUSpecific) 10287 return Diagnose(S, A); 10288 break; 10289 case attr::Target: 10290 if (MVType != MultiVersionKind::Target) 10291 return Diagnose(S, A); 10292 break; 10293 default: 10294 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10295 return Diagnose(S, A); 10296 break; 10297 } 10298 } 10299 return false; 10300 } 10301 10302 bool Sema::areMultiversionVariantFunctionsCompatible( 10303 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10304 const PartialDiagnostic &NoProtoDiagID, 10305 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10306 const PartialDiagnosticAt &NoSupportDiagIDAt, 10307 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10308 bool ConstexprSupported, bool CLinkageMayDiffer) { 10309 enum DoesntSupport { 10310 FuncTemplates = 0, 10311 VirtFuncs = 1, 10312 DeducedReturn = 2, 10313 Constructors = 3, 10314 Destructors = 4, 10315 DeletedFuncs = 5, 10316 DefaultedFuncs = 6, 10317 ConstexprFuncs = 7, 10318 ConstevalFuncs = 8, 10319 }; 10320 enum Different { 10321 CallingConv = 0, 10322 ReturnType = 1, 10323 ConstexprSpec = 2, 10324 InlineSpec = 3, 10325 Linkage = 4, 10326 LanguageLinkage = 5, 10327 }; 10328 10329 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10330 !OldFD->getType()->getAs<FunctionProtoType>()) { 10331 Diag(OldFD->getLocation(), NoProtoDiagID); 10332 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10333 return true; 10334 } 10335 10336 if (NoProtoDiagID.getDiagID() != 0 && 10337 !NewFD->getType()->getAs<FunctionProtoType>()) 10338 return Diag(NewFD->getLocation(), NoProtoDiagID); 10339 10340 if (!TemplatesSupported && 10341 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10342 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10343 << FuncTemplates; 10344 10345 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10346 if (NewCXXFD->isVirtual()) 10347 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10348 << VirtFuncs; 10349 10350 if (isa<CXXConstructorDecl>(NewCXXFD)) 10351 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10352 << Constructors; 10353 10354 if (isa<CXXDestructorDecl>(NewCXXFD)) 10355 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10356 << Destructors; 10357 } 10358 10359 if (NewFD->isDeleted()) 10360 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10361 << DeletedFuncs; 10362 10363 if (NewFD->isDefaulted()) 10364 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10365 << DefaultedFuncs; 10366 10367 if (!ConstexprSupported && NewFD->isConstexpr()) 10368 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10369 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10370 10371 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10372 const auto *NewType = cast<FunctionType>(NewQType); 10373 QualType NewReturnType = NewType->getReturnType(); 10374 10375 if (NewReturnType->isUndeducedType()) 10376 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10377 << DeducedReturn; 10378 10379 // Ensure the return type is identical. 10380 if (OldFD) { 10381 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10382 const auto *OldType = cast<FunctionType>(OldQType); 10383 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10384 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10385 10386 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10387 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10388 10389 QualType OldReturnType = OldType->getReturnType(); 10390 10391 if (OldReturnType != NewReturnType) 10392 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10393 10394 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10395 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10396 10397 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10398 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10399 10400 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage()) 10401 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10402 10403 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10404 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage; 10405 10406 if (CheckEquivalentExceptionSpec( 10407 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10408 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10409 return true; 10410 } 10411 return false; 10412 } 10413 10414 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10415 const FunctionDecl *NewFD, 10416 bool CausesMV, 10417 MultiVersionKind MVType) { 10418 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10419 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10420 if (OldFD) 10421 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10422 return true; 10423 } 10424 10425 bool IsCPUSpecificCPUDispatchMVType = 10426 MVType == MultiVersionKind::CPUDispatch || 10427 MVType == MultiVersionKind::CPUSpecific; 10428 10429 if (CausesMV && OldFD && 10430 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType)) 10431 return true; 10432 10433 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType)) 10434 return true; 10435 10436 // Only allow transition to MultiVersion if it hasn't been used. 10437 if (OldFD && CausesMV && OldFD->isUsed(false)) 10438 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10439 10440 return S.areMultiversionVariantFunctionsCompatible( 10441 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10442 PartialDiagnosticAt(NewFD->getLocation(), 10443 S.PDiag(diag::note_multiversioning_caused_here)), 10444 PartialDiagnosticAt(NewFD->getLocation(), 10445 S.PDiag(diag::err_multiversion_doesnt_support) 10446 << IsCPUSpecificCPUDispatchMVType), 10447 PartialDiagnosticAt(NewFD->getLocation(), 10448 S.PDiag(diag::err_multiversion_diff)), 10449 /*TemplatesSupported=*/false, 10450 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10451 /*CLinkageMayDiffer=*/false); 10452 } 10453 10454 /// Check the validity of a multiversion function declaration that is the 10455 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10456 /// 10457 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10458 /// 10459 /// Returns true if there was an error, false otherwise. 10460 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10461 MultiVersionKind MVType, 10462 const TargetAttr *TA) { 10463 assert(MVType != MultiVersionKind::None && 10464 "Function lacks multiversion attribute"); 10465 10466 // Target only causes MV if it is default, otherwise this is a normal 10467 // function. 10468 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10469 return false; 10470 10471 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10472 FD->setInvalidDecl(); 10473 return true; 10474 } 10475 10476 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10477 FD->setInvalidDecl(); 10478 return true; 10479 } 10480 10481 FD->setIsMultiVersion(); 10482 return false; 10483 } 10484 10485 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10486 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10487 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10488 return true; 10489 } 10490 10491 return false; 10492 } 10493 10494 static bool CheckTargetCausesMultiVersioning( 10495 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10496 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10497 LookupResult &Previous) { 10498 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10499 ParsedTargetAttr NewParsed = NewTA->parse(); 10500 // Sort order doesn't matter, it just needs to be consistent. 10501 llvm::sort(NewParsed.Features); 10502 10503 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10504 // to change, this is a simple redeclaration. 10505 if (!NewTA->isDefaultVersion() && 10506 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10507 return false; 10508 10509 // Otherwise, this decl causes MultiVersioning. 10510 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10511 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10512 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10513 NewFD->setInvalidDecl(); 10514 return true; 10515 } 10516 10517 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10518 MultiVersionKind::Target)) { 10519 NewFD->setInvalidDecl(); 10520 return true; 10521 } 10522 10523 if (CheckMultiVersionValue(S, NewFD)) { 10524 NewFD->setInvalidDecl(); 10525 return true; 10526 } 10527 10528 // If this is 'default', permit the forward declaration. 10529 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10530 Redeclaration = true; 10531 OldDecl = OldFD; 10532 OldFD->setIsMultiVersion(); 10533 NewFD->setIsMultiVersion(); 10534 return false; 10535 } 10536 10537 if (CheckMultiVersionValue(S, OldFD)) { 10538 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10539 NewFD->setInvalidDecl(); 10540 return true; 10541 } 10542 10543 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10544 10545 if (OldParsed == NewParsed) { 10546 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10547 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10548 NewFD->setInvalidDecl(); 10549 return true; 10550 } 10551 10552 for (const auto *FD : OldFD->redecls()) { 10553 const auto *CurTA = FD->getAttr<TargetAttr>(); 10554 // We allow forward declarations before ANY multiversioning attributes, but 10555 // nothing after the fact. 10556 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10557 (!CurTA || CurTA->isInherited())) { 10558 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10559 << 0; 10560 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10561 NewFD->setInvalidDecl(); 10562 return true; 10563 } 10564 } 10565 10566 OldFD->setIsMultiVersion(); 10567 NewFD->setIsMultiVersion(); 10568 Redeclaration = false; 10569 MergeTypeWithPrevious = false; 10570 OldDecl = nullptr; 10571 Previous.clear(); 10572 return false; 10573 } 10574 10575 /// Check the validity of a new function declaration being added to an existing 10576 /// multiversioned declaration collection. 10577 static bool CheckMultiVersionAdditionalDecl( 10578 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10579 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10580 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10581 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10582 LookupResult &Previous) { 10583 10584 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10585 // Disallow mixing of multiversioning types. 10586 if ((OldMVType == MultiVersionKind::Target && 10587 NewMVType != MultiVersionKind::Target) || 10588 (NewMVType == MultiVersionKind::Target && 10589 OldMVType != MultiVersionKind::Target)) { 10590 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10591 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10592 NewFD->setInvalidDecl(); 10593 return true; 10594 } 10595 10596 ParsedTargetAttr NewParsed; 10597 if (NewTA) { 10598 NewParsed = NewTA->parse(); 10599 llvm::sort(NewParsed.Features); 10600 } 10601 10602 bool UseMemberUsingDeclRules = 10603 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10604 10605 // Next, check ALL non-overloads to see if this is a redeclaration of a 10606 // previous member of the MultiVersion set. 10607 for (NamedDecl *ND : Previous) { 10608 FunctionDecl *CurFD = ND->getAsFunction(); 10609 if (!CurFD) 10610 continue; 10611 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10612 continue; 10613 10614 if (NewMVType == MultiVersionKind::Target) { 10615 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10616 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10617 NewFD->setIsMultiVersion(); 10618 Redeclaration = true; 10619 OldDecl = ND; 10620 return false; 10621 } 10622 10623 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10624 if (CurParsed == NewParsed) { 10625 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10626 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10627 NewFD->setInvalidDecl(); 10628 return true; 10629 } 10630 } else { 10631 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10632 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10633 // Handle CPUDispatch/CPUSpecific versions. 10634 // Only 1 CPUDispatch function is allowed, this will make it go through 10635 // the redeclaration errors. 10636 if (NewMVType == MultiVersionKind::CPUDispatch && 10637 CurFD->hasAttr<CPUDispatchAttr>()) { 10638 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10639 std::equal( 10640 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10641 NewCPUDisp->cpus_begin(), 10642 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10643 return Cur->getName() == New->getName(); 10644 })) { 10645 NewFD->setIsMultiVersion(); 10646 Redeclaration = true; 10647 OldDecl = ND; 10648 return false; 10649 } 10650 10651 // If the declarations don't match, this is an error condition. 10652 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10653 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10654 NewFD->setInvalidDecl(); 10655 return true; 10656 } 10657 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10658 10659 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10660 std::equal( 10661 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10662 NewCPUSpec->cpus_begin(), 10663 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10664 return Cur->getName() == New->getName(); 10665 })) { 10666 NewFD->setIsMultiVersion(); 10667 Redeclaration = true; 10668 OldDecl = ND; 10669 return false; 10670 } 10671 10672 // Only 1 version of CPUSpecific is allowed for each CPU. 10673 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10674 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10675 if (CurII == NewII) { 10676 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10677 << NewII; 10678 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10679 NewFD->setInvalidDecl(); 10680 return true; 10681 } 10682 } 10683 } 10684 } 10685 // If the two decls aren't the same MVType, there is no possible error 10686 // condition. 10687 } 10688 } 10689 10690 // Else, this is simply a non-redecl case. Checking the 'value' is only 10691 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10692 // handled in the attribute adding step. 10693 if (NewMVType == MultiVersionKind::Target && 10694 CheckMultiVersionValue(S, NewFD)) { 10695 NewFD->setInvalidDecl(); 10696 return true; 10697 } 10698 10699 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10700 !OldFD->isMultiVersion(), NewMVType)) { 10701 NewFD->setInvalidDecl(); 10702 return true; 10703 } 10704 10705 // Permit forward declarations in the case where these two are compatible. 10706 if (!OldFD->isMultiVersion()) { 10707 OldFD->setIsMultiVersion(); 10708 NewFD->setIsMultiVersion(); 10709 Redeclaration = true; 10710 OldDecl = OldFD; 10711 return false; 10712 } 10713 10714 NewFD->setIsMultiVersion(); 10715 Redeclaration = false; 10716 MergeTypeWithPrevious = false; 10717 OldDecl = nullptr; 10718 Previous.clear(); 10719 return false; 10720 } 10721 10722 10723 /// Check the validity of a mulitversion function declaration. 10724 /// Also sets the multiversion'ness' of the function itself. 10725 /// 10726 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10727 /// 10728 /// Returns true if there was an error, false otherwise. 10729 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10730 bool &Redeclaration, NamedDecl *&OldDecl, 10731 bool &MergeTypeWithPrevious, 10732 LookupResult &Previous) { 10733 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10734 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10735 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10736 10737 // Mixing Multiversioning types is prohibited. 10738 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10739 (NewCPUDisp && NewCPUSpec)) { 10740 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10741 NewFD->setInvalidDecl(); 10742 return true; 10743 } 10744 10745 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10746 10747 // Main isn't allowed to become a multiversion function, however it IS 10748 // permitted to have 'main' be marked with the 'target' optimization hint. 10749 if (NewFD->isMain()) { 10750 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10751 MVType == MultiVersionKind::CPUDispatch || 10752 MVType == MultiVersionKind::CPUSpecific) { 10753 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10754 NewFD->setInvalidDecl(); 10755 return true; 10756 } 10757 return false; 10758 } 10759 10760 if (!OldDecl || !OldDecl->getAsFunction() || 10761 OldDecl->getDeclContext()->getRedeclContext() != 10762 NewFD->getDeclContext()->getRedeclContext()) { 10763 // If there's no previous declaration, AND this isn't attempting to cause 10764 // multiversioning, this isn't an error condition. 10765 if (MVType == MultiVersionKind::None) 10766 return false; 10767 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10768 } 10769 10770 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10771 10772 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10773 return false; 10774 10775 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10776 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10777 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10778 NewFD->setInvalidDecl(); 10779 return true; 10780 } 10781 10782 // Handle the target potentially causes multiversioning case. 10783 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10784 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10785 Redeclaration, OldDecl, 10786 MergeTypeWithPrevious, Previous); 10787 10788 // At this point, we have a multiversion function decl (in OldFD) AND an 10789 // appropriate attribute in the current function decl. Resolve that these are 10790 // still compatible with previous declarations. 10791 return CheckMultiVersionAdditionalDecl( 10792 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10793 OldDecl, MergeTypeWithPrevious, Previous); 10794 } 10795 10796 /// Perform semantic checking of a new function declaration. 10797 /// 10798 /// Performs semantic analysis of the new function declaration 10799 /// NewFD. This routine performs all semantic checking that does not 10800 /// require the actual declarator involved in the declaration, and is 10801 /// used both for the declaration of functions as they are parsed 10802 /// (called via ActOnDeclarator) and for the declaration of functions 10803 /// that have been instantiated via C++ template instantiation (called 10804 /// via InstantiateDecl). 10805 /// 10806 /// \param IsMemberSpecialization whether this new function declaration is 10807 /// a member specialization (that replaces any definition provided by the 10808 /// previous declaration). 10809 /// 10810 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10811 /// 10812 /// \returns true if the function declaration is a redeclaration. 10813 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10814 LookupResult &Previous, 10815 bool IsMemberSpecialization) { 10816 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10817 "Variably modified return types are not handled here"); 10818 10819 // Determine whether the type of this function should be merged with 10820 // a previous visible declaration. This never happens for functions in C++, 10821 // and always happens in C if the previous declaration was visible. 10822 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10823 !Previous.isShadowed(); 10824 10825 bool Redeclaration = false; 10826 NamedDecl *OldDecl = nullptr; 10827 bool MayNeedOverloadableChecks = false; 10828 10829 // Merge or overload the declaration with an existing declaration of 10830 // the same name, if appropriate. 10831 if (!Previous.empty()) { 10832 // Determine whether NewFD is an overload of PrevDecl or 10833 // a declaration that requires merging. If it's an overload, 10834 // there's no more work to do here; we'll just add the new 10835 // function to the scope. 10836 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10837 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10838 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10839 Redeclaration = true; 10840 OldDecl = Candidate; 10841 } 10842 } else { 10843 MayNeedOverloadableChecks = true; 10844 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10845 /*NewIsUsingDecl*/ false)) { 10846 case Ovl_Match: 10847 Redeclaration = true; 10848 break; 10849 10850 case Ovl_NonFunction: 10851 Redeclaration = true; 10852 break; 10853 10854 case Ovl_Overload: 10855 Redeclaration = false; 10856 break; 10857 } 10858 } 10859 } 10860 10861 // Check for a previous extern "C" declaration with this name. 10862 if (!Redeclaration && 10863 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10864 if (!Previous.empty()) { 10865 // This is an extern "C" declaration with the same name as a previous 10866 // declaration, and thus redeclares that entity... 10867 Redeclaration = true; 10868 OldDecl = Previous.getFoundDecl(); 10869 MergeTypeWithPrevious = false; 10870 10871 // ... except in the presence of __attribute__((overloadable)). 10872 if (OldDecl->hasAttr<OverloadableAttr>() || 10873 NewFD->hasAttr<OverloadableAttr>()) { 10874 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10875 MayNeedOverloadableChecks = true; 10876 Redeclaration = false; 10877 OldDecl = nullptr; 10878 } 10879 } 10880 } 10881 } 10882 10883 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10884 MergeTypeWithPrevious, Previous)) 10885 return Redeclaration; 10886 10887 // PPC MMA non-pointer types are not allowed as function return types. 10888 if (Context.getTargetInfo().getTriple().isPPC64() && 10889 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 10890 NewFD->setInvalidDecl(); 10891 } 10892 10893 // C++11 [dcl.constexpr]p8: 10894 // A constexpr specifier for a non-static member function that is not 10895 // a constructor declares that member function to be const. 10896 // 10897 // This needs to be delayed until we know whether this is an out-of-line 10898 // definition of a static member function. 10899 // 10900 // This rule is not present in C++1y, so we produce a backwards 10901 // compatibility warning whenever it happens in C++11. 10902 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10903 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10904 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10905 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10906 CXXMethodDecl *OldMD = nullptr; 10907 if (OldDecl) 10908 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10909 if (!OldMD || !OldMD->isStatic()) { 10910 const FunctionProtoType *FPT = 10911 MD->getType()->castAs<FunctionProtoType>(); 10912 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10913 EPI.TypeQuals.addConst(); 10914 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10915 FPT->getParamTypes(), EPI)); 10916 10917 // Warn that we did this, if we're not performing template instantiation. 10918 // In that case, we'll have warned already when the template was defined. 10919 if (!inTemplateInstantiation()) { 10920 SourceLocation AddConstLoc; 10921 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10922 .IgnoreParens().getAs<FunctionTypeLoc>()) 10923 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10924 10925 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10926 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10927 } 10928 } 10929 } 10930 10931 if (Redeclaration) { 10932 // NewFD and OldDecl represent declarations that need to be 10933 // merged. 10934 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10935 NewFD->setInvalidDecl(); 10936 return Redeclaration; 10937 } 10938 10939 Previous.clear(); 10940 Previous.addDecl(OldDecl); 10941 10942 if (FunctionTemplateDecl *OldTemplateDecl = 10943 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10944 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10945 FunctionTemplateDecl *NewTemplateDecl 10946 = NewFD->getDescribedFunctionTemplate(); 10947 assert(NewTemplateDecl && "Template/non-template mismatch"); 10948 10949 // The call to MergeFunctionDecl above may have created some state in 10950 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10951 // can add it as a redeclaration. 10952 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10953 10954 NewFD->setPreviousDeclaration(OldFD); 10955 if (NewFD->isCXXClassMember()) { 10956 NewFD->setAccess(OldTemplateDecl->getAccess()); 10957 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10958 } 10959 10960 // If this is an explicit specialization of a member that is a function 10961 // template, mark it as a member specialization. 10962 if (IsMemberSpecialization && 10963 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10964 NewTemplateDecl->setMemberSpecialization(); 10965 assert(OldTemplateDecl->isMemberSpecialization()); 10966 // Explicit specializations of a member template do not inherit deleted 10967 // status from the parent member template that they are specializing. 10968 if (OldFD->isDeleted()) { 10969 // FIXME: This assert will not hold in the presence of modules. 10970 assert(OldFD->getCanonicalDecl() == OldFD); 10971 // FIXME: We need an update record for this AST mutation. 10972 OldFD->setDeletedAsWritten(false); 10973 } 10974 } 10975 10976 } else { 10977 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10978 auto *OldFD = cast<FunctionDecl>(OldDecl); 10979 // This needs to happen first so that 'inline' propagates. 10980 NewFD->setPreviousDeclaration(OldFD); 10981 if (NewFD->isCXXClassMember()) 10982 NewFD->setAccess(OldFD->getAccess()); 10983 } 10984 } 10985 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10986 !NewFD->getAttr<OverloadableAttr>()) { 10987 assert((Previous.empty() || 10988 llvm::any_of(Previous, 10989 [](const NamedDecl *ND) { 10990 return ND->hasAttr<OverloadableAttr>(); 10991 })) && 10992 "Non-redecls shouldn't happen without overloadable present"); 10993 10994 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10995 const auto *FD = dyn_cast<FunctionDecl>(ND); 10996 return FD && !FD->hasAttr<OverloadableAttr>(); 10997 }); 10998 10999 if (OtherUnmarkedIter != Previous.end()) { 11000 Diag(NewFD->getLocation(), 11001 diag::err_attribute_overloadable_multiple_unmarked_overloads); 11002 Diag((*OtherUnmarkedIter)->getLocation(), 11003 diag::note_attribute_overloadable_prev_overload) 11004 << false; 11005 11006 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 11007 } 11008 } 11009 11010 if (LangOpts.OpenMP) 11011 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 11012 11013 // Semantic checking for this function declaration (in isolation). 11014 11015 if (getLangOpts().CPlusPlus) { 11016 // C++-specific checks. 11017 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 11018 CheckConstructor(Constructor); 11019 } else if (CXXDestructorDecl *Destructor = 11020 dyn_cast<CXXDestructorDecl>(NewFD)) { 11021 CXXRecordDecl *Record = Destructor->getParent(); 11022 QualType ClassType = Context.getTypeDeclType(Record); 11023 11024 // FIXME: Shouldn't we be able to perform this check even when the class 11025 // type is dependent? Both gcc and edg can handle that. 11026 if (!ClassType->isDependentType()) { 11027 DeclarationName Name 11028 = Context.DeclarationNames.getCXXDestructorName( 11029 Context.getCanonicalType(ClassType)); 11030 if (NewFD->getDeclName() != Name) { 11031 Diag(NewFD->getLocation(), diag::err_destructor_name); 11032 NewFD->setInvalidDecl(); 11033 return Redeclaration; 11034 } 11035 } 11036 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 11037 if (auto *TD = Guide->getDescribedFunctionTemplate()) 11038 CheckDeductionGuideTemplate(TD); 11039 11040 // A deduction guide is not on the list of entities that can be 11041 // explicitly specialized. 11042 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 11043 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 11044 << /*explicit specialization*/ 1; 11045 } 11046 11047 // Find any virtual functions that this function overrides. 11048 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 11049 if (!Method->isFunctionTemplateSpecialization() && 11050 !Method->getDescribedFunctionTemplate() && 11051 Method->isCanonicalDecl()) { 11052 AddOverriddenMethods(Method->getParent(), Method); 11053 } 11054 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 11055 // C++2a [class.virtual]p6 11056 // A virtual method shall not have a requires-clause. 11057 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 11058 diag::err_constrained_virtual_method); 11059 11060 if (Method->isStatic()) 11061 checkThisInStaticMemberFunctionType(Method); 11062 } 11063 11064 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 11065 ActOnConversionDeclarator(Conversion); 11066 11067 // Extra checking for C++ overloaded operators (C++ [over.oper]). 11068 if (NewFD->isOverloadedOperator() && 11069 CheckOverloadedOperatorDeclaration(NewFD)) { 11070 NewFD->setInvalidDecl(); 11071 return Redeclaration; 11072 } 11073 11074 // Extra checking for C++0x literal operators (C++0x [over.literal]). 11075 if (NewFD->getLiteralIdentifier() && 11076 CheckLiteralOperatorDeclaration(NewFD)) { 11077 NewFD->setInvalidDecl(); 11078 return Redeclaration; 11079 } 11080 11081 // In C++, check default arguments now that we have merged decls. Unless 11082 // the lexical context is the class, because in this case this is done 11083 // during delayed parsing anyway. 11084 if (!CurContext->isRecord()) 11085 CheckCXXDefaultArguments(NewFD); 11086 11087 // If this function is declared as being extern "C", then check to see if 11088 // the function returns a UDT (class, struct, or union type) that is not C 11089 // compatible, and if it does, warn the user. 11090 // But, issue any diagnostic on the first declaration only. 11091 if (Previous.empty() && NewFD->isExternC()) { 11092 QualType R = NewFD->getReturnType(); 11093 if (R->isIncompleteType() && !R->isVoidType()) 11094 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 11095 << NewFD << R; 11096 else if (!R.isPODType(Context) && !R->isVoidType() && 11097 !R->isObjCObjectPointerType()) 11098 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 11099 } 11100 11101 // C++1z [dcl.fct]p6: 11102 // [...] whether the function has a non-throwing exception-specification 11103 // [is] part of the function type 11104 // 11105 // This results in an ABI break between C++14 and C++17 for functions whose 11106 // declared type includes an exception-specification in a parameter or 11107 // return type. (Exception specifications on the function itself are OK in 11108 // most cases, and exception specifications are not permitted in most other 11109 // contexts where they could make it into a mangling.) 11110 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 11111 auto HasNoexcept = [&](QualType T) -> bool { 11112 // Strip off declarator chunks that could be between us and a function 11113 // type. We don't need to look far, exception specifications are very 11114 // restricted prior to C++17. 11115 if (auto *RT = T->getAs<ReferenceType>()) 11116 T = RT->getPointeeType(); 11117 else if (T->isAnyPointerType()) 11118 T = T->getPointeeType(); 11119 else if (auto *MPT = T->getAs<MemberPointerType>()) 11120 T = MPT->getPointeeType(); 11121 if (auto *FPT = T->getAs<FunctionProtoType>()) 11122 if (FPT->isNothrow()) 11123 return true; 11124 return false; 11125 }; 11126 11127 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 11128 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 11129 for (QualType T : FPT->param_types()) 11130 AnyNoexcept |= HasNoexcept(T); 11131 if (AnyNoexcept) 11132 Diag(NewFD->getLocation(), 11133 diag::warn_cxx17_compat_exception_spec_in_signature) 11134 << NewFD; 11135 } 11136 11137 if (!Redeclaration && LangOpts.CUDA) 11138 checkCUDATargetOverload(NewFD, Previous); 11139 } 11140 return Redeclaration; 11141 } 11142 11143 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11144 // C++11 [basic.start.main]p3: 11145 // A program that [...] declares main to be inline, static or 11146 // constexpr is ill-formed. 11147 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11148 // appear in a declaration of main. 11149 // static main is not an error under C99, but we should warn about it. 11150 // We accept _Noreturn main as an extension. 11151 if (FD->getStorageClass() == SC_Static) 11152 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11153 ? diag::err_static_main : diag::warn_static_main) 11154 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11155 if (FD->isInlineSpecified()) 11156 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11157 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11158 if (DS.isNoreturnSpecified()) { 11159 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11160 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11161 Diag(NoreturnLoc, diag::ext_noreturn_main); 11162 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11163 << FixItHint::CreateRemoval(NoreturnRange); 11164 } 11165 if (FD->isConstexpr()) { 11166 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11167 << FD->isConsteval() 11168 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11169 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11170 } 11171 11172 if (getLangOpts().OpenCL) { 11173 Diag(FD->getLocation(), diag::err_opencl_no_main) 11174 << FD->hasAttr<OpenCLKernelAttr>(); 11175 FD->setInvalidDecl(); 11176 return; 11177 } 11178 11179 QualType T = FD->getType(); 11180 assert(T->isFunctionType() && "function decl is not of function type"); 11181 const FunctionType* FT = T->castAs<FunctionType>(); 11182 11183 // Set default calling convention for main() 11184 if (FT->getCallConv() != CC_C) { 11185 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11186 FD->setType(QualType(FT, 0)); 11187 T = Context.getCanonicalType(FD->getType()); 11188 } 11189 11190 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11191 // In C with GNU extensions we allow main() to have non-integer return 11192 // type, but we should warn about the extension, and we disable the 11193 // implicit-return-zero rule. 11194 11195 // GCC in C mode accepts qualified 'int'. 11196 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11197 FD->setHasImplicitReturnZero(true); 11198 else { 11199 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11200 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11201 if (RTRange.isValid()) 11202 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11203 << FixItHint::CreateReplacement(RTRange, "int"); 11204 } 11205 } else { 11206 // In C and C++, main magically returns 0 if you fall off the end; 11207 // set the flag which tells us that. 11208 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11209 11210 // All the standards say that main() should return 'int'. 11211 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11212 FD->setHasImplicitReturnZero(true); 11213 else { 11214 // Otherwise, this is just a flat-out error. 11215 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11216 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11217 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11218 : FixItHint()); 11219 FD->setInvalidDecl(true); 11220 } 11221 } 11222 11223 // Treat protoless main() as nullary. 11224 if (isa<FunctionNoProtoType>(FT)) return; 11225 11226 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11227 unsigned nparams = FTP->getNumParams(); 11228 assert(FD->getNumParams() == nparams); 11229 11230 bool HasExtraParameters = (nparams > 3); 11231 11232 if (FTP->isVariadic()) { 11233 Diag(FD->getLocation(), diag::ext_variadic_main); 11234 // FIXME: if we had information about the location of the ellipsis, we 11235 // could add a FixIt hint to remove it as a parameter. 11236 } 11237 11238 // Darwin passes an undocumented fourth argument of type char**. If 11239 // other platforms start sprouting these, the logic below will start 11240 // getting shifty. 11241 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11242 HasExtraParameters = false; 11243 11244 if (HasExtraParameters) { 11245 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11246 FD->setInvalidDecl(true); 11247 nparams = 3; 11248 } 11249 11250 // FIXME: a lot of the following diagnostics would be improved 11251 // if we had some location information about types. 11252 11253 QualType CharPP = 11254 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11255 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11256 11257 for (unsigned i = 0; i < nparams; ++i) { 11258 QualType AT = FTP->getParamType(i); 11259 11260 bool mismatch = true; 11261 11262 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11263 mismatch = false; 11264 else if (Expected[i] == CharPP) { 11265 // As an extension, the following forms are okay: 11266 // char const ** 11267 // char const * const * 11268 // char * const * 11269 11270 QualifierCollector qs; 11271 const PointerType* PT; 11272 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11273 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11274 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11275 Context.CharTy)) { 11276 qs.removeConst(); 11277 mismatch = !qs.empty(); 11278 } 11279 } 11280 11281 if (mismatch) { 11282 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11283 // TODO: suggest replacing given type with expected type 11284 FD->setInvalidDecl(true); 11285 } 11286 } 11287 11288 if (nparams == 1 && !FD->isInvalidDecl()) { 11289 Diag(FD->getLocation(), diag::warn_main_one_arg); 11290 } 11291 11292 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11293 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11294 FD->setInvalidDecl(); 11295 } 11296 } 11297 11298 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 11299 11300 // Default calling convention for main and wmain is __cdecl 11301 if (FD->getName() == "main" || FD->getName() == "wmain") 11302 return false; 11303 11304 // Default calling convention for MinGW is __cdecl 11305 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 11306 if (T.isWindowsGNUEnvironment()) 11307 return false; 11308 11309 // Default calling convention for WinMain, wWinMain and DllMain 11310 // is __stdcall on 32 bit Windows 11311 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 11312 return true; 11313 11314 return false; 11315 } 11316 11317 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11318 QualType T = FD->getType(); 11319 assert(T->isFunctionType() && "function decl is not of function type"); 11320 const FunctionType *FT = T->castAs<FunctionType>(); 11321 11322 // Set an implicit return of 'zero' if the function can return some integral, 11323 // enumeration, pointer or nullptr type. 11324 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11325 FT->getReturnType()->isAnyPointerType() || 11326 FT->getReturnType()->isNullPtrType()) 11327 // DllMain is exempt because a return value of zero means it failed. 11328 if (FD->getName() != "DllMain") 11329 FD->setHasImplicitReturnZero(true); 11330 11331 // Explicity specified calling conventions are applied to MSVC entry points 11332 if (!hasExplicitCallingConv(T)) { 11333 if (isDefaultStdCall(FD, *this)) { 11334 if (FT->getCallConv() != CC_X86StdCall) { 11335 FT = Context.adjustFunctionType( 11336 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 11337 FD->setType(QualType(FT, 0)); 11338 } 11339 } else if (FT->getCallConv() != CC_C) { 11340 FT = Context.adjustFunctionType(FT, 11341 FT->getExtInfo().withCallingConv(CC_C)); 11342 FD->setType(QualType(FT, 0)); 11343 } 11344 } 11345 11346 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11347 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11348 FD->setInvalidDecl(); 11349 } 11350 } 11351 11352 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11353 // FIXME: Need strict checking. In C89, we need to check for 11354 // any assignment, increment, decrement, function-calls, or 11355 // commas outside of a sizeof. In C99, it's the same list, 11356 // except that the aforementioned are allowed in unevaluated 11357 // expressions. Everything else falls under the 11358 // "may accept other forms of constant expressions" exception. 11359 // 11360 // Regular C++ code will not end up here (exceptions: language extensions, 11361 // OpenCL C++ etc), so the constant expression rules there don't matter. 11362 if (Init->isValueDependent()) { 11363 assert(Init->containsErrors() && 11364 "Dependent code should only occur in error-recovery path."); 11365 return true; 11366 } 11367 const Expr *Culprit; 11368 if (Init->isConstantInitializer(Context, false, &Culprit)) 11369 return false; 11370 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11371 << Culprit->getSourceRange(); 11372 return true; 11373 } 11374 11375 namespace { 11376 // Visits an initialization expression to see if OrigDecl is evaluated in 11377 // its own initialization and throws a warning if it does. 11378 class SelfReferenceChecker 11379 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11380 Sema &S; 11381 Decl *OrigDecl; 11382 bool isRecordType; 11383 bool isPODType; 11384 bool isReferenceType; 11385 11386 bool isInitList; 11387 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11388 11389 public: 11390 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11391 11392 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11393 S(S), OrigDecl(OrigDecl) { 11394 isPODType = false; 11395 isRecordType = false; 11396 isReferenceType = false; 11397 isInitList = false; 11398 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11399 isPODType = VD->getType().isPODType(S.Context); 11400 isRecordType = VD->getType()->isRecordType(); 11401 isReferenceType = VD->getType()->isReferenceType(); 11402 } 11403 } 11404 11405 // For most expressions, just call the visitor. For initializer lists, 11406 // track the index of the field being initialized since fields are 11407 // initialized in order allowing use of previously initialized fields. 11408 void CheckExpr(Expr *E) { 11409 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11410 if (!InitList) { 11411 Visit(E); 11412 return; 11413 } 11414 11415 // Track and increment the index here. 11416 isInitList = true; 11417 InitFieldIndex.push_back(0); 11418 for (auto Child : InitList->children()) { 11419 CheckExpr(cast<Expr>(Child)); 11420 ++InitFieldIndex.back(); 11421 } 11422 InitFieldIndex.pop_back(); 11423 } 11424 11425 // Returns true if MemberExpr is checked and no further checking is needed. 11426 // Returns false if additional checking is required. 11427 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11428 llvm::SmallVector<FieldDecl*, 4> Fields; 11429 Expr *Base = E; 11430 bool ReferenceField = false; 11431 11432 // Get the field members used. 11433 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11434 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11435 if (!FD) 11436 return false; 11437 Fields.push_back(FD); 11438 if (FD->getType()->isReferenceType()) 11439 ReferenceField = true; 11440 Base = ME->getBase()->IgnoreParenImpCasts(); 11441 } 11442 11443 // Keep checking only if the base Decl is the same. 11444 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11445 if (!DRE || DRE->getDecl() != OrigDecl) 11446 return false; 11447 11448 // A reference field can be bound to an unininitialized field. 11449 if (CheckReference && !ReferenceField) 11450 return true; 11451 11452 // Convert FieldDecls to their index number. 11453 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11454 for (const FieldDecl *I : llvm::reverse(Fields)) 11455 UsedFieldIndex.push_back(I->getFieldIndex()); 11456 11457 // See if a warning is needed by checking the first difference in index 11458 // numbers. If field being used has index less than the field being 11459 // initialized, then the use is safe. 11460 for (auto UsedIter = UsedFieldIndex.begin(), 11461 UsedEnd = UsedFieldIndex.end(), 11462 OrigIter = InitFieldIndex.begin(), 11463 OrigEnd = InitFieldIndex.end(); 11464 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11465 if (*UsedIter < *OrigIter) 11466 return true; 11467 if (*UsedIter > *OrigIter) 11468 break; 11469 } 11470 11471 // TODO: Add a different warning which will print the field names. 11472 HandleDeclRefExpr(DRE); 11473 return true; 11474 } 11475 11476 // For most expressions, the cast is directly above the DeclRefExpr. 11477 // For conditional operators, the cast can be outside the conditional 11478 // operator if both expressions are DeclRefExpr's. 11479 void HandleValue(Expr *E) { 11480 E = E->IgnoreParens(); 11481 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11482 HandleDeclRefExpr(DRE); 11483 return; 11484 } 11485 11486 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11487 Visit(CO->getCond()); 11488 HandleValue(CO->getTrueExpr()); 11489 HandleValue(CO->getFalseExpr()); 11490 return; 11491 } 11492 11493 if (BinaryConditionalOperator *BCO = 11494 dyn_cast<BinaryConditionalOperator>(E)) { 11495 Visit(BCO->getCond()); 11496 HandleValue(BCO->getFalseExpr()); 11497 return; 11498 } 11499 11500 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11501 HandleValue(OVE->getSourceExpr()); 11502 return; 11503 } 11504 11505 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11506 if (BO->getOpcode() == BO_Comma) { 11507 Visit(BO->getLHS()); 11508 HandleValue(BO->getRHS()); 11509 return; 11510 } 11511 } 11512 11513 if (isa<MemberExpr>(E)) { 11514 if (isInitList) { 11515 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11516 false /*CheckReference*/)) 11517 return; 11518 } 11519 11520 Expr *Base = E->IgnoreParenImpCasts(); 11521 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11522 // Check for static member variables and don't warn on them. 11523 if (!isa<FieldDecl>(ME->getMemberDecl())) 11524 return; 11525 Base = ME->getBase()->IgnoreParenImpCasts(); 11526 } 11527 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11528 HandleDeclRefExpr(DRE); 11529 return; 11530 } 11531 11532 Visit(E); 11533 } 11534 11535 // Reference types not handled in HandleValue are handled here since all 11536 // uses of references are bad, not just r-value uses. 11537 void VisitDeclRefExpr(DeclRefExpr *E) { 11538 if (isReferenceType) 11539 HandleDeclRefExpr(E); 11540 } 11541 11542 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11543 if (E->getCastKind() == CK_LValueToRValue) { 11544 HandleValue(E->getSubExpr()); 11545 return; 11546 } 11547 11548 Inherited::VisitImplicitCastExpr(E); 11549 } 11550 11551 void VisitMemberExpr(MemberExpr *E) { 11552 if (isInitList) { 11553 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11554 return; 11555 } 11556 11557 // Don't warn on arrays since they can be treated as pointers. 11558 if (E->getType()->canDecayToPointerType()) return; 11559 11560 // Warn when a non-static method call is followed by non-static member 11561 // field accesses, which is followed by a DeclRefExpr. 11562 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11563 bool Warn = (MD && !MD->isStatic()); 11564 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11565 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11566 if (!isa<FieldDecl>(ME->getMemberDecl())) 11567 Warn = false; 11568 Base = ME->getBase()->IgnoreParenImpCasts(); 11569 } 11570 11571 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11572 if (Warn) 11573 HandleDeclRefExpr(DRE); 11574 return; 11575 } 11576 11577 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11578 // Visit that expression. 11579 Visit(Base); 11580 } 11581 11582 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11583 Expr *Callee = E->getCallee(); 11584 11585 if (isa<UnresolvedLookupExpr>(Callee)) 11586 return Inherited::VisitCXXOperatorCallExpr(E); 11587 11588 Visit(Callee); 11589 for (auto Arg: E->arguments()) 11590 HandleValue(Arg->IgnoreParenImpCasts()); 11591 } 11592 11593 void VisitUnaryOperator(UnaryOperator *E) { 11594 // For POD record types, addresses of its own members are well-defined. 11595 if (E->getOpcode() == UO_AddrOf && isRecordType && 11596 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11597 if (!isPODType) 11598 HandleValue(E->getSubExpr()); 11599 return; 11600 } 11601 11602 if (E->isIncrementDecrementOp()) { 11603 HandleValue(E->getSubExpr()); 11604 return; 11605 } 11606 11607 Inherited::VisitUnaryOperator(E); 11608 } 11609 11610 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11611 11612 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11613 if (E->getConstructor()->isCopyConstructor()) { 11614 Expr *ArgExpr = E->getArg(0); 11615 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11616 if (ILE->getNumInits() == 1) 11617 ArgExpr = ILE->getInit(0); 11618 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11619 if (ICE->getCastKind() == CK_NoOp) 11620 ArgExpr = ICE->getSubExpr(); 11621 HandleValue(ArgExpr); 11622 return; 11623 } 11624 Inherited::VisitCXXConstructExpr(E); 11625 } 11626 11627 void VisitCallExpr(CallExpr *E) { 11628 // Treat std::move as a use. 11629 if (E->isCallToStdMove()) { 11630 HandleValue(E->getArg(0)); 11631 return; 11632 } 11633 11634 Inherited::VisitCallExpr(E); 11635 } 11636 11637 void VisitBinaryOperator(BinaryOperator *E) { 11638 if (E->isCompoundAssignmentOp()) { 11639 HandleValue(E->getLHS()); 11640 Visit(E->getRHS()); 11641 return; 11642 } 11643 11644 Inherited::VisitBinaryOperator(E); 11645 } 11646 11647 // A custom visitor for BinaryConditionalOperator is needed because the 11648 // regular visitor would check the condition and true expression separately 11649 // but both point to the same place giving duplicate diagnostics. 11650 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11651 Visit(E->getCond()); 11652 Visit(E->getFalseExpr()); 11653 } 11654 11655 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11656 Decl* ReferenceDecl = DRE->getDecl(); 11657 if (OrigDecl != ReferenceDecl) return; 11658 unsigned diag; 11659 if (isReferenceType) { 11660 diag = diag::warn_uninit_self_reference_in_reference_init; 11661 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11662 diag = diag::warn_static_self_reference_in_init; 11663 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11664 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11665 DRE->getDecl()->getType()->isRecordType()) { 11666 diag = diag::warn_uninit_self_reference_in_init; 11667 } else { 11668 // Local variables will be handled by the CFG analysis. 11669 return; 11670 } 11671 11672 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11673 S.PDiag(diag) 11674 << DRE->getDecl() << OrigDecl->getLocation() 11675 << DRE->getSourceRange()); 11676 } 11677 }; 11678 11679 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11680 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11681 bool DirectInit) { 11682 // Parameters arguments are occassionially constructed with itself, 11683 // for instance, in recursive functions. Skip them. 11684 if (isa<ParmVarDecl>(OrigDecl)) 11685 return; 11686 11687 E = E->IgnoreParens(); 11688 11689 // Skip checking T a = a where T is not a record or reference type. 11690 // Doing so is a way to silence uninitialized warnings. 11691 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11692 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11693 if (ICE->getCastKind() == CK_LValueToRValue) 11694 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11695 if (DRE->getDecl() == OrigDecl) 11696 return; 11697 11698 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11699 } 11700 } // end anonymous namespace 11701 11702 namespace { 11703 // Simple wrapper to add the name of a variable or (if no variable is 11704 // available) a DeclarationName into a diagnostic. 11705 struct VarDeclOrName { 11706 VarDecl *VDecl; 11707 DeclarationName Name; 11708 11709 friend const Sema::SemaDiagnosticBuilder & 11710 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11711 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11712 } 11713 }; 11714 } // end anonymous namespace 11715 11716 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11717 DeclarationName Name, QualType Type, 11718 TypeSourceInfo *TSI, 11719 SourceRange Range, bool DirectInit, 11720 Expr *Init) { 11721 bool IsInitCapture = !VDecl; 11722 assert((!VDecl || !VDecl->isInitCapture()) && 11723 "init captures are expected to be deduced prior to initialization"); 11724 11725 VarDeclOrName VN{VDecl, Name}; 11726 11727 DeducedType *Deduced = Type->getContainedDeducedType(); 11728 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11729 11730 // C++11 [dcl.spec.auto]p3 11731 if (!Init) { 11732 assert(VDecl && "no init for init capture deduction?"); 11733 11734 // Except for class argument deduction, and then for an initializing 11735 // declaration only, i.e. no static at class scope or extern. 11736 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11737 VDecl->hasExternalStorage() || 11738 VDecl->isStaticDataMember()) { 11739 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11740 << VDecl->getDeclName() << Type; 11741 return QualType(); 11742 } 11743 } 11744 11745 ArrayRef<Expr*> DeduceInits; 11746 if (Init) 11747 DeduceInits = Init; 11748 11749 if (DirectInit) { 11750 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11751 DeduceInits = PL->exprs(); 11752 } 11753 11754 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11755 assert(VDecl && "non-auto type for init capture deduction?"); 11756 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11757 InitializationKind Kind = InitializationKind::CreateForInit( 11758 VDecl->getLocation(), DirectInit, Init); 11759 // FIXME: Initialization should not be taking a mutable list of inits. 11760 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11761 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11762 InitsCopy); 11763 } 11764 11765 if (DirectInit) { 11766 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11767 DeduceInits = IL->inits(); 11768 } 11769 11770 // Deduction only works if we have exactly one source expression. 11771 if (DeduceInits.empty()) { 11772 // It isn't possible to write this directly, but it is possible to 11773 // end up in this situation with "auto x(some_pack...);" 11774 Diag(Init->getBeginLoc(), IsInitCapture 11775 ? diag::err_init_capture_no_expression 11776 : diag::err_auto_var_init_no_expression) 11777 << VN << Type << Range; 11778 return QualType(); 11779 } 11780 11781 if (DeduceInits.size() > 1) { 11782 Diag(DeduceInits[1]->getBeginLoc(), 11783 IsInitCapture ? diag::err_init_capture_multiple_expressions 11784 : diag::err_auto_var_init_multiple_expressions) 11785 << VN << Type << Range; 11786 return QualType(); 11787 } 11788 11789 Expr *DeduceInit = DeduceInits[0]; 11790 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11791 Diag(Init->getBeginLoc(), IsInitCapture 11792 ? diag::err_init_capture_paren_braces 11793 : diag::err_auto_var_init_paren_braces) 11794 << isa<InitListExpr>(Init) << VN << Type << Range; 11795 return QualType(); 11796 } 11797 11798 // Expressions default to 'id' when we're in a debugger. 11799 bool DefaultedAnyToId = false; 11800 if (getLangOpts().DebuggerCastResultToId && 11801 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11802 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11803 if (Result.isInvalid()) { 11804 return QualType(); 11805 } 11806 Init = Result.get(); 11807 DefaultedAnyToId = true; 11808 } 11809 11810 // C++ [dcl.decomp]p1: 11811 // If the assignment-expression [...] has array type A and no ref-qualifier 11812 // is present, e has type cv A 11813 if (VDecl && isa<DecompositionDecl>(VDecl) && 11814 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11815 DeduceInit->getType()->isConstantArrayType()) 11816 return Context.getQualifiedType(DeduceInit->getType(), 11817 Type.getQualifiers()); 11818 11819 QualType DeducedType; 11820 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11821 if (!IsInitCapture) 11822 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11823 else if (isa<InitListExpr>(Init)) 11824 Diag(Range.getBegin(), 11825 diag::err_init_capture_deduction_failure_from_init_list) 11826 << VN 11827 << (DeduceInit->getType().isNull() ? TSI->getType() 11828 : DeduceInit->getType()) 11829 << DeduceInit->getSourceRange(); 11830 else 11831 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11832 << VN << TSI->getType() 11833 << (DeduceInit->getType().isNull() ? TSI->getType() 11834 : DeduceInit->getType()) 11835 << DeduceInit->getSourceRange(); 11836 } 11837 11838 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11839 // 'id' instead of a specific object type prevents most of our usual 11840 // checks. 11841 // We only want to warn outside of template instantiations, though: 11842 // inside a template, the 'id' could have come from a parameter. 11843 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11844 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11845 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11846 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11847 } 11848 11849 return DeducedType; 11850 } 11851 11852 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11853 Expr *Init) { 11854 assert(!Init || !Init->containsErrors()); 11855 QualType DeducedType = deduceVarTypeFromInitializer( 11856 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11857 VDecl->getSourceRange(), DirectInit, Init); 11858 if (DeducedType.isNull()) { 11859 VDecl->setInvalidDecl(); 11860 return true; 11861 } 11862 11863 VDecl->setType(DeducedType); 11864 assert(VDecl->isLinkageValid()); 11865 11866 // In ARC, infer lifetime. 11867 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11868 VDecl->setInvalidDecl(); 11869 11870 if (getLangOpts().OpenCL) 11871 deduceOpenCLAddressSpace(VDecl); 11872 11873 // If this is a redeclaration, check that the type we just deduced matches 11874 // the previously declared type. 11875 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11876 // We never need to merge the type, because we cannot form an incomplete 11877 // array of auto, nor deduce such a type. 11878 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11879 } 11880 11881 // Check the deduced type is valid for a variable declaration. 11882 CheckVariableDeclarationType(VDecl); 11883 return VDecl->isInvalidDecl(); 11884 } 11885 11886 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11887 SourceLocation Loc) { 11888 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11889 Init = EWC->getSubExpr(); 11890 11891 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11892 Init = CE->getSubExpr(); 11893 11894 QualType InitType = Init->getType(); 11895 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11896 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11897 "shouldn't be called if type doesn't have a non-trivial C struct"); 11898 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11899 for (auto I : ILE->inits()) { 11900 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11901 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11902 continue; 11903 SourceLocation SL = I->getExprLoc(); 11904 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11905 } 11906 return; 11907 } 11908 11909 if (isa<ImplicitValueInitExpr>(Init)) { 11910 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11911 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11912 NTCUK_Init); 11913 } else { 11914 // Assume all other explicit initializers involving copying some existing 11915 // object. 11916 // TODO: ignore any explicit initializers where we can guarantee 11917 // copy-elision. 11918 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11919 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11920 } 11921 } 11922 11923 namespace { 11924 11925 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11926 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11927 // in the source code or implicitly by the compiler if it is in a union 11928 // defined in a system header and has non-trivial ObjC ownership 11929 // qualifications. We don't want those fields to participate in determining 11930 // whether the containing union is non-trivial. 11931 return FD->hasAttr<UnavailableAttr>(); 11932 } 11933 11934 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11935 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11936 void> { 11937 using Super = 11938 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11939 void>; 11940 11941 DiagNonTrivalCUnionDefaultInitializeVisitor( 11942 QualType OrigTy, SourceLocation OrigLoc, 11943 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11944 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11945 11946 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11947 const FieldDecl *FD, bool InNonTrivialUnion) { 11948 if (const auto *AT = S.Context.getAsArrayType(QT)) 11949 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11950 InNonTrivialUnion); 11951 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11952 } 11953 11954 void visitARCStrong(QualType QT, const FieldDecl *FD, 11955 bool InNonTrivialUnion) { 11956 if (InNonTrivialUnion) 11957 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11958 << 1 << 0 << QT << FD->getName(); 11959 } 11960 11961 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11962 if (InNonTrivialUnion) 11963 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11964 << 1 << 0 << QT << FD->getName(); 11965 } 11966 11967 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11968 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11969 if (RD->isUnion()) { 11970 if (OrigLoc.isValid()) { 11971 bool IsUnion = false; 11972 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11973 IsUnion = OrigRD->isUnion(); 11974 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11975 << 0 << OrigTy << IsUnion << UseContext; 11976 // Reset OrigLoc so that this diagnostic is emitted only once. 11977 OrigLoc = SourceLocation(); 11978 } 11979 InNonTrivialUnion = true; 11980 } 11981 11982 if (InNonTrivialUnion) 11983 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11984 << 0 << 0 << QT.getUnqualifiedType() << ""; 11985 11986 for (const FieldDecl *FD : RD->fields()) 11987 if (!shouldIgnoreForRecordTriviality(FD)) 11988 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11989 } 11990 11991 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11992 11993 // The non-trivial C union type or the struct/union type that contains a 11994 // non-trivial C union. 11995 QualType OrigTy; 11996 SourceLocation OrigLoc; 11997 Sema::NonTrivialCUnionContext UseContext; 11998 Sema &S; 11999 }; 12000 12001 struct DiagNonTrivalCUnionDestructedTypeVisitor 12002 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 12003 using Super = 12004 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 12005 12006 DiagNonTrivalCUnionDestructedTypeVisitor( 12007 QualType OrigTy, SourceLocation OrigLoc, 12008 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12009 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12010 12011 void visitWithKind(QualType::DestructionKind DK, QualType QT, 12012 const FieldDecl *FD, bool InNonTrivialUnion) { 12013 if (const auto *AT = S.Context.getAsArrayType(QT)) 12014 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12015 InNonTrivialUnion); 12016 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 12017 } 12018 12019 void visitARCStrong(QualType QT, const FieldDecl *FD, 12020 bool InNonTrivialUnion) { 12021 if (InNonTrivialUnion) 12022 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12023 << 1 << 1 << QT << FD->getName(); 12024 } 12025 12026 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12027 if (InNonTrivialUnion) 12028 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12029 << 1 << 1 << QT << FD->getName(); 12030 } 12031 12032 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12033 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12034 if (RD->isUnion()) { 12035 if (OrigLoc.isValid()) { 12036 bool IsUnion = false; 12037 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12038 IsUnion = OrigRD->isUnion(); 12039 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12040 << 1 << OrigTy << IsUnion << UseContext; 12041 // Reset OrigLoc so that this diagnostic is emitted only once. 12042 OrigLoc = SourceLocation(); 12043 } 12044 InNonTrivialUnion = true; 12045 } 12046 12047 if (InNonTrivialUnion) 12048 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12049 << 0 << 1 << QT.getUnqualifiedType() << ""; 12050 12051 for (const FieldDecl *FD : RD->fields()) 12052 if (!shouldIgnoreForRecordTriviality(FD)) 12053 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12054 } 12055 12056 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12057 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 12058 bool InNonTrivialUnion) {} 12059 12060 // The non-trivial C union type or the struct/union type that contains a 12061 // non-trivial C union. 12062 QualType OrigTy; 12063 SourceLocation OrigLoc; 12064 Sema::NonTrivialCUnionContext UseContext; 12065 Sema &S; 12066 }; 12067 12068 struct DiagNonTrivalCUnionCopyVisitor 12069 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 12070 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 12071 12072 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 12073 Sema::NonTrivialCUnionContext UseContext, 12074 Sema &S) 12075 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12076 12077 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 12078 const FieldDecl *FD, bool InNonTrivialUnion) { 12079 if (const auto *AT = S.Context.getAsArrayType(QT)) 12080 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12081 InNonTrivialUnion); 12082 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 12083 } 12084 12085 void visitARCStrong(QualType QT, const FieldDecl *FD, 12086 bool InNonTrivialUnion) { 12087 if (InNonTrivialUnion) 12088 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12089 << 1 << 2 << QT << FD->getName(); 12090 } 12091 12092 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12093 if (InNonTrivialUnion) 12094 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12095 << 1 << 2 << QT << FD->getName(); 12096 } 12097 12098 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12099 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12100 if (RD->isUnion()) { 12101 if (OrigLoc.isValid()) { 12102 bool IsUnion = false; 12103 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12104 IsUnion = OrigRD->isUnion(); 12105 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12106 << 2 << OrigTy << IsUnion << UseContext; 12107 // Reset OrigLoc so that this diagnostic is emitted only once. 12108 OrigLoc = SourceLocation(); 12109 } 12110 InNonTrivialUnion = true; 12111 } 12112 12113 if (InNonTrivialUnion) 12114 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12115 << 0 << 2 << QT.getUnqualifiedType() << ""; 12116 12117 for (const FieldDecl *FD : RD->fields()) 12118 if (!shouldIgnoreForRecordTriviality(FD)) 12119 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12120 } 12121 12122 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 12123 const FieldDecl *FD, bool InNonTrivialUnion) {} 12124 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12125 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 12126 bool InNonTrivialUnion) {} 12127 12128 // The non-trivial C union type or the struct/union type that contains a 12129 // non-trivial C union. 12130 QualType OrigTy; 12131 SourceLocation OrigLoc; 12132 Sema::NonTrivialCUnionContext UseContext; 12133 Sema &S; 12134 }; 12135 12136 } // namespace 12137 12138 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 12139 NonTrivialCUnionContext UseContext, 12140 unsigned NonTrivialKind) { 12141 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12142 QT.hasNonTrivialToPrimitiveDestructCUnion() || 12143 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 12144 "shouldn't be called if type doesn't have a non-trivial C union"); 12145 12146 if ((NonTrivialKind & NTCUK_Init) && 12147 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12148 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 12149 .visit(QT, nullptr, false); 12150 if ((NonTrivialKind & NTCUK_Destruct) && 12151 QT.hasNonTrivialToPrimitiveDestructCUnion()) 12152 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 12153 .visit(QT, nullptr, false); 12154 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 12155 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 12156 .visit(QT, nullptr, false); 12157 } 12158 12159 /// AddInitializerToDecl - Adds the initializer Init to the 12160 /// declaration dcl. If DirectInit is true, this is C++ direct 12161 /// initialization rather than copy initialization. 12162 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 12163 // If there is no declaration, there was an error parsing it. Just ignore 12164 // the initializer. 12165 if (!RealDecl || RealDecl->isInvalidDecl()) { 12166 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 12167 return; 12168 } 12169 12170 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 12171 // Pure-specifiers are handled in ActOnPureSpecifier. 12172 Diag(Method->getLocation(), diag::err_member_function_initialization) 12173 << Method->getDeclName() << Init->getSourceRange(); 12174 Method->setInvalidDecl(); 12175 return; 12176 } 12177 12178 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12179 if (!VDecl) { 12180 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 12181 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12182 RealDecl->setInvalidDecl(); 12183 return; 12184 } 12185 12186 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12187 if (VDecl->getType()->isUndeducedType()) { 12188 // Attempt typo correction early so that the type of the init expression can 12189 // be deduced based on the chosen correction if the original init contains a 12190 // TypoExpr. 12191 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12192 if (!Res.isUsable()) { 12193 // There are unresolved typos in Init, just drop them. 12194 // FIXME: improve the recovery strategy to preserve the Init. 12195 RealDecl->setInvalidDecl(); 12196 return; 12197 } 12198 if (Res.get()->containsErrors()) { 12199 // Invalidate the decl as we don't know the type for recovery-expr yet. 12200 RealDecl->setInvalidDecl(); 12201 VDecl->setInit(Res.get()); 12202 return; 12203 } 12204 Init = Res.get(); 12205 12206 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12207 return; 12208 } 12209 12210 // dllimport cannot be used on variable definitions. 12211 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12212 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12213 VDecl->setInvalidDecl(); 12214 return; 12215 } 12216 12217 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12218 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12219 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12220 VDecl->setInvalidDecl(); 12221 return; 12222 } 12223 12224 if (!VDecl->getType()->isDependentType()) { 12225 // A definition must end up with a complete type, which means it must be 12226 // complete with the restriction that an array type might be completed by 12227 // the initializer; note that later code assumes this restriction. 12228 QualType BaseDeclType = VDecl->getType(); 12229 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12230 BaseDeclType = Array->getElementType(); 12231 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12232 diag::err_typecheck_decl_incomplete_type)) { 12233 RealDecl->setInvalidDecl(); 12234 return; 12235 } 12236 12237 // The variable can not have an abstract class type. 12238 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12239 diag::err_abstract_type_in_decl, 12240 AbstractVariableType)) 12241 VDecl->setInvalidDecl(); 12242 } 12243 12244 // If adding the initializer will turn this declaration into a definition, 12245 // and we already have a definition for this variable, diagnose or otherwise 12246 // handle the situation. 12247 if (VarDecl *Def = VDecl->getDefinition()) 12248 if (Def != VDecl && 12249 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12250 !VDecl->isThisDeclarationADemotedDefinition() && 12251 checkVarDeclRedefinition(Def, VDecl)) 12252 return; 12253 12254 if (getLangOpts().CPlusPlus) { 12255 // C++ [class.static.data]p4 12256 // If a static data member is of const integral or const 12257 // enumeration type, its declaration in the class definition can 12258 // specify a constant-initializer which shall be an integral 12259 // constant expression (5.19). In that case, the member can appear 12260 // in integral constant expressions. The member shall still be 12261 // defined in a namespace scope if it is used in the program and the 12262 // namespace scope definition shall not contain an initializer. 12263 // 12264 // We already performed a redefinition check above, but for static 12265 // data members we also need to check whether there was an in-class 12266 // declaration with an initializer. 12267 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12268 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12269 << VDecl->getDeclName(); 12270 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12271 diag::note_previous_initializer) 12272 << 0; 12273 return; 12274 } 12275 12276 if (VDecl->hasLocalStorage()) 12277 setFunctionHasBranchProtectedScope(); 12278 12279 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12280 VDecl->setInvalidDecl(); 12281 return; 12282 } 12283 } 12284 12285 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12286 // a kernel function cannot be initialized." 12287 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12288 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12289 VDecl->setInvalidDecl(); 12290 return; 12291 } 12292 12293 // The LoaderUninitialized attribute acts as a definition (of undef). 12294 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12295 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12296 VDecl->setInvalidDecl(); 12297 return; 12298 } 12299 12300 // Get the decls type and save a reference for later, since 12301 // CheckInitializerTypes may change it. 12302 QualType DclT = VDecl->getType(), SavT = DclT; 12303 12304 // Expressions default to 'id' when we're in a debugger 12305 // and we are assigning it to a variable of Objective-C pointer type. 12306 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12307 Init->getType() == Context.UnknownAnyTy) { 12308 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12309 if (Result.isInvalid()) { 12310 VDecl->setInvalidDecl(); 12311 return; 12312 } 12313 Init = Result.get(); 12314 } 12315 12316 // Perform the initialization. 12317 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12318 if (!VDecl->isInvalidDecl()) { 12319 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12320 InitializationKind Kind = InitializationKind::CreateForInit( 12321 VDecl->getLocation(), DirectInit, Init); 12322 12323 MultiExprArg Args = Init; 12324 if (CXXDirectInit) 12325 Args = MultiExprArg(CXXDirectInit->getExprs(), 12326 CXXDirectInit->getNumExprs()); 12327 12328 // Try to correct any TypoExprs in the initialization arguments. 12329 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12330 ExprResult Res = CorrectDelayedTyposInExpr( 12331 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12332 [this, Entity, Kind](Expr *E) { 12333 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12334 return Init.Failed() ? ExprError() : E; 12335 }); 12336 if (Res.isInvalid()) { 12337 VDecl->setInvalidDecl(); 12338 } else if (Res.get() != Args[Idx]) { 12339 Args[Idx] = Res.get(); 12340 } 12341 } 12342 if (VDecl->isInvalidDecl()) 12343 return; 12344 12345 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12346 /*TopLevelOfInitList=*/false, 12347 /*TreatUnavailableAsInvalid=*/false); 12348 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12349 if (Result.isInvalid()) { 12350 // If the provied initializer fails to initialize the var decl, 12351 // we attach a recovery expr for better recovery. 12352 auto RecoveryExpr = 12353 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12354 if (RecoveryExpr.get()) 12355 VDecl->setInit(RecoveryExpr.get()); 12356 return; 12357 } 12358 12359 Init = Result.getAs<Expr>(); 12360 } 12361 12362 // Check for self-references within variable initializers. 12363 // Variables declared within a function/method body (except for references) 12364 // are handled by a dataflow analysis. 12365 // This is undefined behavior in C++, but valid in C. 12366 if (getLangOpts().CPlusPlus) 12367 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12368 VDecl->getType()->isReferenceType()) 12369 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12370 12371 // If the type changed, it means we had an incomplete type that was 12372 // completed by the initializer. For example: 12373 // int ary[] = { 1, 3, 5 }; 12374 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12375 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12376 VDecl->setType(DclT); 12377 12378 if (!VDecl->isInvalidDecl()) { 12379 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12380 12381 if (VDecl->hasAttr<BlocksAttr>()) 12382 checkRetainCycles(VDecl, Init); 12383 12384 // It is safe to assign a weak reference into a strong variable. 12385 // Although this code can still have problems: 12386 // id x = self.weakProp; 12387 // id y = self.weakProp; 12388 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12389 // paths through the function. This should be revisited if 12390 // -Wrepeated-use-of-weak is made flow-sensitive. 12391 if (FunctionScopeInfo *FSI = getCurFunction()) 12392 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12393 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12394 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12395 Init->getBeginLoc())) 12396 FSI->markSafeWeakUse(Init); 12397 } 12398 12399 // The initialization is usually a full-expression. 12400 // 12401 // FIXME: If this is a braced initialization of an aggregate, it is not 12402 // an expression, and each individual field initializer is a separate 12403 // full-expression. For instance, in: 12404 // 12405 // struct Temp { ~Temp(); }; 12406 // struct S { S(Temp); }; 12407 // struct T { S a, b; } t = { Temp(), Temp() } 12408 // 12409 // we should destroy the first Temp before constructing the second. 12410 ExprResult Result = 12411 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12412 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12413 if (Result.isInvalid()) { 12414 VDecl->setInvalidDecl(); 12415 return; 12416 } 12417 Init = Result.get(); 12418 12419 // Attach the initializer to the decl. 12420 VDecl->setInit(Init); 12421 12422 if (VDecl->isLocalVarDecl()) { 12423 // Don't check the initializer if the declaration is malformed. 12424 if (VDecl->isInvalidDecl()) { 12425 // do nothing 12426 12427 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12428 // This is true even in C++ for OpenCL. 12429 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12430 CheckForConstantInitializer(Init, DclT); 12431 12432 // Otherwise, C++ does not restrict the initializer. 12433 } else if (getLangOpts().CPlusPlus) { 12434 // do nothing 12435 12436 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12437 // static storage duration shall be constant expressions or string literals. 12438 } else if (VDecl->getStorageClass() == SC_Static) { 12439 CheckForConstantInitializer(Init, DclT); 12440 12441 // C89 is stricter than C99 for aggregate initializers. 12442 // C89 6.5.7p3: All the expressions [...] in an initializer list 12443 // for an object that has aggregate or union type shall be 12444 // constant expressions. 12445 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12446 isa<InitListExpr>(Init)) { 12447 const Expr *Culprit; 12448 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12449 Diag(Culprit->getExprLoc(), 12450 diag::ext_aggregate_init_not_constant) 12451 << Culprit->getSourceRange(); 12452 } 12453 } 12454 12455 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12456 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12457 if (VDecl->hasLocalStorage()) 12458 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12459 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12460 VDecl->getLexicalDeclContext()->isRecord()) { 12461 // This is an in-class initialization for a static data member, e.g., 12462 // 12463 // struct S { 12464 // static const int value = 17; 12465 // }; 12466 12467 // C++ [class.mem]p4: 12468 // A member-declarator can contain a constant-initializer only 12469 // if it declares a static member (9.4) of const integral or 12470 // const enumeration type, see 9.4.2. 12471 // 12472 // C++11 [class.static.data]p3: 12473 // If a non-volatile non-inline const static data member is of integral 12474 // or enumeration type, its declaration in the class definition can 12475 // specify a brace-or-equal-initializer in which every initializer-clause 12476 // that is an assignment-expression is a constant expression. A static 12477 // data member of literal type can be declared in the class definition 12478 // with the constexpr specifier; if so, its declaration shall specify a 12479 // brace-or-equal-initializer in which every initializer-clause that is 12480 // an assignment-expression is a constant expression. 12481 12482 // Do nothing on dependent types. 12483 if (DclT->isDependentType()) { 12484 12485 // Allow any 'static constexpr' members, whether or not they are of literal 12486 // type. We separately check that every constexpr variable is of literal 12487 // type. 12488 } else if (VDecl->isConstexpr()) { 12489 12490 // Require constness. 12491 } else if (!DclT.isConstQualified()) { 12492 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12493 << Init->getSourceRange(); 12494 VDecl->setInvalidDecl(); 12495 12496 // We allow integer constant expressions in all cases. 12497 } else if (DclT->isIntegralOrEnumerationType()) { 12498 // Check whether the expression is a constant expression. 12499 SourceLocation Loc; 12500 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12501 // In C++11, a non-constexpr const static data member with an 12502 // in-class initializer cannot be volatile. 12503 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12504 else if (Init->isValueDependent()) 12505 ; // Nothing to check. 12506 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12507 ; // Ok, it's an ICE! 12508 else if (Init->getType()->isScopedEnumeralType() && 12509 Init->isCXX11ConstantExpr(Context)) 12510 ; // Ok, it is a scoped-enum constant expression. 12511 else if (Init->isEvaluatable(Context)) { 12512 // If we can constant fold the initializer through heroics, accept it, 12513 // but report this as a use of an extension for -pedantic. 12514 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12515 << Init->getSourceRange(); 12516 } else { 12517 // Otherwise, this is some crazy unknown case. Report the issue at the 12518 // location provided by the isIntegerConstantExpr failed check. 12519 Diag(Loc, diag::err_in_class_initializer_non_constant) 12520 << Init->getSourceRange(); 12521 VDecl->setInvalidDecl(); 12522 } 12523 12524 // We allow foldable floating-point constants as an extension. 12525 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12526 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12527 // it anyway and provide a fixit to add the 'constexpr'. 12528 if (getLangOpts().CPlusPlus11) { 12529 Diag(VDecl->getLocation(), 12530 diag::ext_in_class_initializer_float_type_cxx11) 12531 << DclT << Init->getSourceRange(); 12532 Diag(VDecl->getBeginLoc(), 12533 diag::note_in_class_initializer_float_type_cxx11) 12534 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12535 } else { 12536 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12537 << DclT << Init->getSourceRange(); 12538 12539 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12540 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12541 << Init->getSourceRange(); 12542 VDecl->setInvalidDecl(); 12543 } 12544 } 12545 12546 // Suggest adding 'constexpr' in C++11 for literal types. 12547 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12548 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12549 << DclT << Init->getSourceRange() 12550 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12551 VDecl->setConstexpr(true); 12552 12553 } else { 12554 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12555 << DclT << Init->getSourceRange(); 12556 VDecl->setInvalidDecl(); 12557 } 12558 } else if (VDecl->isFileVarDecl()) { 12559 // In C, extern is typically used to avoid tentative definitions when 12560 // declaring variables in headers, but adding an intializer makes it a 12561 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12562 // In C++, extern is often used to give implictly static const variables 12563 // external linkage, so don't warn in that case. If selectany is present, 12564 // this might be header code intended for C and C++ inclusion, so apply the 12565 // C++ rules. 12566 if (VDecl->getStorageClass() == SC_Extern && 12567 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12568 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12569 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12570 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12571 Diag(VDecl->getLocation(), diag::warn_extern_init); 12572 12573 // In Microsoft C++ mode, a const variable defined in namespace scope has 12574 // external linkage by default if the variable is declared with 12575 // __declspec(dllexport). 12576 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12577 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12578 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12579 VDecl->setStorageClass(SC_Extern); 12580 12581 // C99 6.7.8p4. All file scoped initializers need to be constant. 12582 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12583 CheckForConstantInitializer(Init, DclT); 12584 } 12585 12586 QualType InitType = Init->getType(); 12587 if (!InitType.isNull() && 12588 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12589 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12590 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12591 12592 // We will represent direct-initialization similarly to copy-initialization: 12593 // int x(1); -as-> int x = 1; 12594 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12595 // 12596 // Clients that want to distinguish between the two forms, can check for 12597 // direct initializer using VarDecl::getInitStyle(). 12598 // A major benefit is that clients that don't particularly care about which 12599 // exactly form was it (like the CodeGen) can handle both cases without 12600 // special case code. 12601 12602 // C++ 8.5p11: 12603 // The form of initialization (using parentheses or '=') is generally 12604 // insignificant, but does matter when the entity being initialized has a 12605 // class type. 12606 if (CXXDirectInit) { 12607 assert(DirectInit && "Call-style initializer must be direct init."); 12608 VDecl->setInitStyle(VarDecl::CallInit); 12609 } else if (DirectInit) { 12610 // This must be list-initialization. No other way is direct-initialization. 12611 VDecl->setInitStyle(VarDecl::ListInit); 12612 } 12613 12614 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12615 DeclsToCheckForDeferredDiags.insert(VDecl); 12616 CheckCompleteVariableDeclaration(VDecl); 12617 } 12618 12619 /// ActOnInitializerError - Given that there was an error parsing an 12620 /// initializer for the given declaration, try to return to some form 12621 /// of sanity. 12622 void Sema::ActOnInitializerError(Decl *D) { 12623 // Our main concern here is re-establishing invariants like "a 12624 // variable's type is either dependent or complete". 12625 if (!D || D->isInvalidDecl()) return; 12626 12627 VarDecl *VD = dyn_cast<VarDecl>(D); 12628 if (!VD) return; 12629 12630 // Bindings are not usable if we can't make sense of the initializer. 12631 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12632 for (auto *BD : DD->bindings()) 12633 BD->setInvalidDecl(); 12634 12635 // Auto types are meaningless if we can't make sense of the initializer. 12636 if (VD->getType()->isUndeducedType()) { 12637 D->setInvalidDecl(); 12638 return; 12639 } 12640 12641 QualType Ty = VD->getType(); 12642 if (Ty->isDependentType()) return; 12643 12644 // Require a complete type. 12645 if (RequireCompleteType(VD->getLocation(), 12646 Context.getBaseElementType(Ty), 12647 diag::err_typecheck_decl_incomplete_type)) { 12648 VD->setInvalidDecl(); 12649 return; 12650 } 12651 12652 // Require a non-abstract type. 12653 if (RequireNonAbstractType(VD->getLocation(), Ty, 12654 diag::err_abstract_type_in_decl, 12655 AbstractVariableType)) { 12656 VD->setInvalidDecl(); 12657 return; 12658 } 12659 12660 // Don't bother complaining about constructors or destructors, 12661 // though. 12662 } 12663 12664 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12665 // If there is no declaration, there was an error parsing it. Just ignore it. 12666 if (!RealDecl) 12667 return; 12668 12669 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12670 QualType Type = Var->getType(); 12671 12672 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12673 if (isa<DecompositionDecl>(RealDecl)) { 12674 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12675 Var->setInvalidDecl(); 12676 return; 12677 } 12678 12679 if (Type->isUndeducedType() && 12680 DeduceVariableDeclarationType(Var, false, nullptr)) 12681 return; 12682 12683 // C++11 [class.static.data]p3: A static data member can be declared with 12684 // the constexpr specifier; if so, its declaration shall specify 12685 // a brace-or-equal-initializer. 12686 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12687 // the definition of a variable [...] or the declaration of a static data 12688 // member. 12689 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12690 !Var->isThisDeclarationADemotedDefinition()) { 12691 if (Var->isStaticDataMember()) { 12692 // C++1z removes the relevant rule; the in-class declaration is always 12693 // a definition there. 12694 if (!getLangOpts().CPlusPlus17 && 12695 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12696 Diag(Var->getLocation(), 12697 diag::err_constexpr_static_mem_var_requires_init) 12698 << Var; 12699 Var->setInvalidDecl(); 12700 return; 12701 } 12702 } else { 12703 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12704 Var->setInvalidDecl(); 12705 return; 12706 } 12707 } 12708 12709 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12710 // be initialized. 12711 if (!Var->isInvalidDecl() && 12712 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12713 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12714 bool HasConstExprDefaultConstructor = false; 12715 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12716 for (auto *Ctor : RD->ctors()) { 12717 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && 12718 Ctor->getMethodQualifiers().getAddressSpace() == 12719 LangAS::opencl_constant) { 12720 HasConstExprDefaultConstructor = true; 12721 } 12722 } 12723 } 12724 if (!HasConstExprDefaultConstructor) { 12725 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12726 Var->setInvalidDecl(); 12727 return; 12728 } 12729 } 12730 12731 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12732 if (Var->getStorageClass() == SC_Extern) { 12733 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12734 << Var; 12735 Var->setInvalidDecl(); 12736 return; 12737 } 12738 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12739 diag::err_typecheck_decl_incomplete_type)) { 12740 Var->setInvalidDecl(); 12741 return; 12742 } 12743 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12744 if (!RD->hasTrivialDefaultConstructor()) { 12745 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12746 Var->setInvalidDecl(); 12747 return; 12748 } 12749 } 12750 // The declaration is unitialized, no need for further checks. 12751 return; 12752 } 12753 12754 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12755 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12756 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12757 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12758 NTCUC_DefaultInitializedObject, NTCUK_Init); 12759 12760 12761 switch (DefKind) { 12762 case VarDecl::Definition: 12763 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12764 break; 12765 12766 // We have an out-of-line definition of a static data member 12767 // that has an in-class initializer, so we type-check this like 12768 // a declaration. 12769 // 12770 LLVM_FALLTHROUGH; 12771 12772 case VarDecl::DeclarationOnly: 12773 // It's only a declaration. 12774 12775 // Block scope. C99 6.7p7: If an identifier for an object is 12776 // declared with no linkage (C99 6.2.2p6), the type for the 12777 // object shall be complete. 12778 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12779 !Var->hasLinkage() && !Var->isInvalidDecl() && 12780 RequireCompleteType(Var->getLocation(), Type, 12781 diag::err_typecheck_decl_incomplete_type)) 12782 Var->setInvalidDecl(); 12783 12784 // Make sure that the type is not abstract. 12785 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12786 RequireNonAbstractType(Var->getLocation(), Type, 12787 diag::err_abstract_type_in_decl, 12788 AbstractVariableType)) 12789 Var->setInvalidDecl(); 12790 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12791 Var->getStorageClass() == SC_PrivateExtern) { 12792 Diag(Var->getLocation(), diag::warn_private_extern); 12793 Diag(Var->getLocation(), diag::note_private_extern); 12794 } 12795 12796 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 12797 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12798 ExternalDeclarations.push_back(Var); 12799 12800 return; 12801 12802 case VarDecl::TentativeDefinition: 12803 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12804 // object that has file scope without an initializer, and without a 12805 // storage-class specifier or with the storage-class specifier "static", 12806 // constitutes a tentative definition. Note: A tentative definition with 12807 // external linkage is valid (C99 6.2.2p5). 12808 if (!Var->isInvalidDecl()) { 12809 if (const IncompleteArrayType *ArrayT 12810 = Context.getAsIncompleteArrayType(Type)) { 12811 if (RequireCompleteSizedType( 12812 Var->getLocation(), ArrayT->getElementType(), 12813 diag::err_array_incomplete_or_sizeless_type)) 12814 Var->setInvalidDecl(); 12815 } else if (Var->getStorageClass() == SC_Static) { 12816 // C99 6.9.2p3: If the declaration of an identifier for an object is 12817 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12818 // declared type shall not be an incomplete type. 12819 // NOTE: code such as the following 12820 // static struct s; 12821 // struct s { int a; }; 12822 // is accepted by gcc. Hence here we issue a warning instead of 12823 // an error and we do not invalidate the static declaration. 12824 // NOTE: to avoid multiple warnings, only check the first declaration. 12825 if (Var->isFirstDecl()) 12826 RequireCompleteType(Var->getLocation(), Type, 12827 diag::ext_typecheck_decl_incomplete_type); 12828 } 12829 } 12830 12831 // Record the tentative definition; we're done. 12832 if (!Var->isInvalidDecl()) 12833 TentativeDefinitions.push_back(Var); 12834 return; 12835 } 12836 12837 // Provide a specific diagnostic for uninitialized variable 12838 // definitions with incomplete array type. 12839 if (Type->isIncompleteArrayType()) { 12840 Diag(Var->getLocation(), 12841 diag::err_typecheck_incomplete_array_needs_initializer); 12842 Var->setInvalidDecl(); 12843 return; 12844 } 12845 12846 // Provide a specific diagnostic for uninitialized variable 12847 // definitions with reference type. 12848 if (Type->isReferenceType()) { 12849 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12850 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 12851 Var->setInvalidDecl(); 12852 return; 12853 } 12854 12855 // Do not attempt to type-check the default initializer for a 12856 // variable with dependent type. 12857 if (Type->isDependentType()) 12858 return; 12859 12860 if (Var->isInvalidDecl()) 12861 return; 12862 12863 if (!Var->hasAttr<AliasAttr>()) { 12864 if (RequireCompleteType(Var->getLocation(), 12865 Context.getBaseElementType(Type), 12866 diag::err_typecheck_decl_incomplete_type)) { 12867 Var->setInvalidDecl(); 12868 return; 12869 } 12870 } else { 12871 return; 12872 } 12873 12874 // The variable can not have an abstract class type. 12875 if (RequireNonAbstractType(Var->getLocation(), Type, 12876 diag::err_abstract_type_in_decl, 12877 AbstractVariableType)) { 12878 Var->setInvalidDecl(); 12879 return; 12880 } 12881 12882 // Check for jumps past the implicit initializer. C++0x 12883 // clarifies that this applies to a "variable with automatic 12884 // storage duration", not a "local variable". 12885 // C++11 [stmt.dcl]p3 12886 // A program that jumps from a point where a variable with automatic 12887 // storage duration is not in scope to a point where it is in scope is 12888 // ill-formed unless the variable has scalar type, class type with a 12889 // trivial default constructor and a trivial destructor, a cv-qualified 12890 // version of one of these types, or an array of one of the preceding 12891 // types and is declared without an initializer. 12892 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12893 if (const RecordType *Record 12894 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12895 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12896 // Mark the function (if we're in one) for further checking even if the 12897 // looser rules of C++11 do not require such checks, so that we can 12898 // diagnose incompatibilities with C++98. 12899 if (!CXXRecord->isPOD()) 12900 setFunctionHasBranchProtectedScope(); 12901 } 12902 } 12903 // In OpenCL, we can't initialize objects in the __local address space, 12904 // even implicitly, so don't synthesize an implicit initializer. 12905 if (getLangOpts().OpenCL && 12906 Var->getType().getAddressSpace() == LangAS::opencl_local) 12907 return; 12908 // C++03 [dcl.init]p9: 12909 // If no initializer is specified for an object, and the 12910 // object is of (possibly cv-qualified) non-POD class type (or 12911 // array thereof), the object shall be default-initialized; if 12912 // the object is of const-qualified type, the underlying class 12913 // type shall have a user-declared default 12914 // constructor. Otherwise, if no initializer is specified for 12915 // a non- static object, the object and its subobjects, if 12916 // any, have an indeterminate initial value); if the object 12917 // or any of its subobjects are of const-qualified type, the 12918 // program is ill-formed. 12919 // C++0x [dcl.init]p11: 12920 // If no initializer is specified for an object, the object is 12921 // default-initialized; [...]. 12922 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12923 InitializationKind Kind 12924 = InitializationKind::CreateDefault(Var->getLocation()); 12925 12926 InitializationSequence InitSeq(*this, Entity, Kind, None); 12927 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12928 12929 if (Init.get()) { 12930 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12931 // This is important for template substitution. 12932 Var->setInitStyle(VarDecl::CallInit); 12933 } else if (Init.isInvalid()) { 12934 // If default-init fails, attach a recovery-expr initializer to track 12935 // that initialization was attempted and failed. 12936 auto RecoveryExpr = 12937 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12938 if (RecoveryExpr.get()) 12939 Var->setInit(RecoveryExpr.get()); 12940 } 12941 12942 CheckCompleteVariableDeclaration(Var); 12943 } 12944 } 12945 12946 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12947 // If there is no declaration, there was an error parsing it. Ignore it. 12948 if (!D) 12949 return; 12950 12951 VarDecl *VD = dyn_cast<VarDecl>(D); 12952 if (!VD) { 12953 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12954 D->setInvalidDecl(); 12955 return; 12956 } 12957 12958 VD->setCXXForRangeDecl(true); 12959 12960 // for-range-declaration cannot be given a storage class specifier. 12961 int Error = -1; 12962 switch (VD->getStorageClass()) { 12963 case SC_None: 12964 break; 12965 case SC_Extern: 12966 Error = 0; 12967 break; 12968 case SC_Static: 12969 Error = 1; 12970 break; 12971 case SC_PrivateExtern: 12972 Error = 2; 12973 break; 12974 case SC_Auto: 12975 Error = 3; 12976 break; 12977 case SC_Register: 12978 Error = 4; 12979 break; 12980 } 12981 12982 // for-range-declaration cannot be given a storage class specifier con't. 12983 switch (VD->getTSCSpec()) { 12984 case TSCS_thread_local: 12985 Error = 6; 12986 break; 12987 case TSCS___thread: 12988 case TSCS__Thread_local: 12989 case TSCS_unspecified: 12990 break; 12991 } 12992 12993 if (Error != -1) { 12994 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12995 << VD << Error; 12996 D->setInvalidDecl(); 12997 } 12998 } 12999 13000 StmtResult 13001 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 13002 IdentifierInfo *Ident, 13003 ParsedAttributes &Attrs, 13004 SourceLocation AttrEnd) { 13005 // C++1y [stmt.iter]p1: 13006 // A range-based for statement of the form 13007 // for ( for-range-identifier : for-range-initializer ) statement 13008 // is equivalent to 13009 // for ( auto&& for-range-identifier : for-range-initializer ) statement 13010 DeclSpec DS(Attrs.getPool().getFactory()); 13011 13012 const char *PrevSpec; 13013 unsigned DiagID; 13014 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 13015 getPrintingPolicy()); 13016 13017 Declarator D(DS, DeclaratorContext::ForInit); 13018 D.SetIdentifier(Ident, IdentLoc); 13019 D.takeAttributes(Attrs, AttrEnd); 13020 13021 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 13022 IdentLoc); 13023 Decl *Var = ActOnDeclarator(S, D); 13024 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 13025 FinalizeDeclaration(Var); 13026 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 13027 AttrEnd.isValid() ? AttrEnd : IdentLoc); 13028 } 13029 13030 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 13031 if (var->isInvalidDecl()) return; 13032 13033 MaybeAddCUDAConstantAttr(var); 13034 13035 if (getLangOpts().OpenCL) { 13036 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 13037 // initialiser 13038 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 13039 !var->hasInit()) { 13040 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 13041 << 1 /*Init*/; 13042 var->setInvalidDecl(); 13043 return; 13044 } 13045 } 13046 13047 // In Objective-C, don't allow jumps past the implicit initialization of a 13048 // local retaining variable. 13049 if (getLangOpts().ObjC && 13050 var->hasLocalStorage()) { 13051 switch (var->getType().getObjCLifetime()) { 13052 case Qualifiers::OCL_None: 13053 case Qualifiers::OCL_ExplicitNone: 13054 case Qualifiers::OCL_Autoreleasing: 13055 break; 13056 13057 case Qualifiers::OCL_Weak: 13058 case Qualifiers::OCL_Strong: 13059 setFunctionHasBranchProtectedScope(); 13060 break; 13061 } 13062 } 13063 13064 if (var->hasLocalStorage() && 13065 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 13066 setFunctionHasBranchProtectedScope(); 13067 13068 // Warn about externally-visible variables being defined without a 13069 // prior declaration. We only want to do this for global 13070 // declarations, but we also specifically need to avoid doing it for 13071 // class members because the linkage of an anonymous class can 13072 // change if it's later given a typedef name. 13073 if (var->isThisDeclarationADefinition() && 13074 var->getDeclContext()->getRedeclContext()->isFileContext() && 13075 var->isExternallyVisible() && var->hasLinkage() && 13076 !var->isInline() && !var->getDescribedVarTemplate() && 13077 !isa<VarTemplatePartialSpecializationDecl>(var) && 13078 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 13079 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 13080 var->getLocation())) { 13081 // Find a previous declaration that's not a definition. 13082 VarDecl *prev = var->getPreviousDecl(); 13083 while (prev && prev->isThisDeclarationADefinition()) 13084 prev = prev->getPreviousDecl(); 13085 13086 if (!prev) { 13087 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 13088 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 13089 << /* variable */ 0; 13090 } 13091 } 13092 13093 // Cache the result of checking for constant initialization. 13094 Optional<bool> CacheHasConstInit; 13095 const Expr *CacheCulprit = nullptr; 13096 auto checkConstInit = [&]() mutable { 13097 if (!CacheHasConstInit) 13098 CacheHasConstInit = var->getInit()->isConstantInitializer( 13099 Context, var->getType()->isReferenceType(), &CacheCulprit); 13100 return *CacheHasConstInit; 13101 }; 13102 13103 if (var->getTLSKind() == VarDecl::TLS_Static) { 13104 if (var->getType().isDestructedType()) { 13105 // GNU C++98 edits for __thread, [basic.start.term]p3: 13106 // The type of an object with thread storage duration shall not 13107 // have a non-trivial destructor. 13108 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 13109 if (getLangOpts().CPlusPlus11) 13110 Diag(var->getLocation(), diag::note_use_thread_local); 13111 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 13112 if (!checkConstInit()) { 13113 // GNU C++98 edits for __thread, [basic.start.init]p4: 13114 // An object of thread storage duration shall not require dynamic 13115 // initialization. 13116 // FIXME: Need strict checking here. 13117 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 13118 << CacheCulprit->getSourceRange(); 13119 if (getLangOpts().CPlusPlus11) 13120 Diag(var->getLocation(), diag::note_use_thread_local); 13121 } 13122 } 13123 } 13124 13125 13126 if (!var->getType()->isStructureType() && var->hasInit() && 13127 isa<InitListExpr>(var->getInit())) { 13128 const auto *ILE = cast<InitListExpr>(var->getInit()); 13129 unsigned NumInits = ILE->getNumInits(); 13130 if (NumInits > 2) 13131 for (unsigned I = 0; I < NumInits; ++I) { 13132 const auto *Init = ILE->getInit(I); 13133 if (!Init) 13134 break; 13135 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13136 if (!SL) 13137 break; 13138 13139 unsigned NumConcat = SL->getNumConcatenated(); 13140 // Diagnose missing comma in string array initialization. 13141 // Do not warn when all the elements in the initializer are concatenated 13142 // together. Do not warn for macros too. 13143 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 13144 bool OnlyOneMissingComma = true; 13145 for (unsigned J = I + 1; J < NumInits; ++J) { 13146 const auto *Init = ILE->getInit(J); 13147 if (!Init) 13148 break; 13149 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13150 if (!SLJ || SLJ->getNumConcatenated() > 1) { 13151 OnlyOneMissingComma = false; 13152 break; 13153 } 13154 } 13155 13156 if (OnlyOneMissingComma) { 13157 SmallVector<FixItHint, 1> Hints; 13158 for (unsigned i = 0; i < NumConcat - 1; ++i) 13159 Hints.push_back(FixItHint::CreateInsertion( 13160 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13161 13162 Diag(SL->getStrTokenLoc(1), 13163 diag::warn_concatenated_literal_array_init) 13164 << Hints; 13165 Diag(SL->getBeginLoc(), 13166 diag::note_concatenated_string_literal_silence); 13167 } 13168 // In any case, stop now. 13169 break; 13170 } 13171 } 13172 } 13173 13174 13175 QualType type = var->getType(); 13176 13177 if (var->hasAttr<BlocksAttr>()) 13178 getCurFunction()->addByrefBlockVar(var); 13179 13180 Expr *Init = var->getInit(); 13181 bool GlobalStorage = var->hasGlobalStorage(); 13182 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13183 QualType baseType = Context.getBaseElementType(type); 13184 bool HasConstInit = true; 13185 13186 // Check whether the initializer is sufficiently constant. 13187 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init && 13188 !Init->isValueDependent() && 13189 (GlobalStorage || var->isConstexpr() || 13190 var->mightBeUsableInConstantExpressions(Context))) { 13191 // If this variable might have a constant initializer or might be usable in 13192 // constant expressions, check whether or not it actually is now. We can't 13193 // do this lazily, because the result might depend on things that change 13194 // later, such as which constexpr functions happen to be defined. 13195 SmallVector<PartialDiagnosticAt, 8> Notes; 13196 if (!getLangOpts().CPlusPlus11) { 13197 // Prior to C++11, in contexts where a constant initializer is required, 13198 // the set of valid constant initializers is described by syntactic rules 13199 // in [expr.const]p2-6. 13200 // FIXME: Stricter checking for these rules would be useful for constinit / 13201 // -Wglobal-constructors. 13202 HasConstInit = checkConstInit(); 13203 13204 // Compute and cache the constant value, and remember that we have a 13205 // constant initializer. 13206 if (HasConstInit) { 13207 (void)var->checkForConstantInitialization(Notes); 13208 Notes.clear(); 13209 } else if (CacheCulprit) { 13210 Notes.emplace_back(CacheCulprit->getExprLoc(), 13211 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13212 Notes.back().second << CacheCulprit->getSourceRange(); 13213 } 13214 } else { 13215 // Evaluate the initializer to see if it's a constant initializer. 13216 HasConstInit = var->checkForConstantInitialization(Notes); 13217 } 13218 13219 if (HasConstInit) { 13220 // FIXME: Consider replacing the initializer with a ConstantExpr. 13221 } else if (var->isConstexpr()) { 13222 SourceLocation DiagLoc = var->getLocation(); 13223 // If the note doesn't add any useful information other than a source 13224 // location, fold it into the primary diagnostic. 13225 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13226 diag::note_invalid_subexpr_in_const_expr) { 13227 DiagLoc = Notes[0].first; 13228 Notes.clear(); 13229 } 13230 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13231 << var << Init->getSourceRange(); 13232 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13233 Diag(Notes[I].first, Notes[I].second); 13234 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13235 auto *Attr = var->getAttr<ConstInitAttr>(); 13236 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13237 << Init->getSourceRange(); 13238 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13239 << Attr->getRange() << Attr->isConstinit(); 13240 for (auto &it : Notes) 13241 Diag(it.first, it.second); 13242 } else if (IsGlobal && 13243 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13244 var->getLocation())) { 13245 // Warn about globals which don't have a constant initializer. Don't 13246 // warn about globals with a non-trivial destructor because we already 13247 // warned about them. 13248 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13249 if (!(RD && !RD->hasTrivialDestructor())) { 13250 // checkConstInit() here permits trivial default initialization even in 13251 // C++11 onwards, where such an initializer is not a constant initializer 13252 // but nonetheless doesn't require a global constructor. 13253 if (!checkConstInit()) 13254 Diag(var->getLocation(), diag::warn_global_constructor) 13255 << Init->getSourceRange(); 13256 } 13257 } 13258 } 13259 13260 // Apply section attributes and pragmas to global variables. 13261 if (GlobalStorage && var->isThisDeclarationADefinition() && 13262 !inTemplateInstantiation()) { 13263 PragmaStack<StringLiteral *> *Stack = nullptr; 13264 int SectionFlags = ASTContext::PSF_Read; 13265 if (var->getType().isConstQualified()) { 13266 if (HasConstInit) 13267 Stack = &ConstSegStack; 13268 else { 13269 Stack = &BSSSegStack; 13270 SectionFlags |= ASTContext::PSF_Write; 13271 } 13272 } else if (var->hasInit() && HasConstInit) { 13273 Stack = &DataSegStack; 13274 SectionFlags |= ASTContext::PSF_Write; 13275 } else { 13276 Stack = &BSSSegStack; 13277 SectionFlags |= ASTContext::PSF_Write; 13278 } 13279 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 13280 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 13281 SectionFlags |= ASTContext::PSF_Implicit; 13282 UnifySection(SA->getName(), SectionFlags, var); 13283 } else if (Stack->CurrentValue) { 13284 SectionFlags |= ASTContext::PSF_Implicit; 13285 auto SectionName = Stack->CurrentValue->getString(); 13286 var->addAttr(SectionAttr::CreateImplicit( 13287 Context, SectionName, Stack->CurrentPragmaLocation, 13288 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 13289 if (UnifySection(SectionName, SectionFlags, var)) 13290 var->dropAttr<SectionAttr>(); 13291 } 13292 13293 // Apply the init_seg attribute if this has an initializer. If the 13294 // initializer turns out to not be dynamic, we'll end up ignoring this 13295 // attribute. 13296 if (CurInitSeg && var->getInit()) 13297 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 13298 CurInitSegLoc, 13299 AttributeCommonInfo::AS_Pragma)); 13300 } 13301 13302 // All the following checks are C++ only. 13303 if (!getLangOpts().CPlusPlus) { 13304 // If this variable must be emitted, add it as an initializer for the 13305 // current module. 13306 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13307 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13308 return; 13309 } 13310 13311 // Require the destructor. 13312 if (!type->isDependentType()) 13313 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13314 FinalizeVarWithDestructor(var, recordType); 13315 13316 // If this variable must be emitted, add it as an initializer for the current 13317 // module. 13318 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13319 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13320 13321 // Build the bindings if this is a structured binding declaration. 13322 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13323 CheckCompleteDecompositionDeclaration(DD); 13324 } 13325 13326 /// Check if VD needs to be dllexport/dllimport due to being in a 13327 /// dllexport/import function. 13328 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13329 assert(VD->isStaticLocal()); 13330 13331 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13332 13333 // Find outermost function when VD is in lambda function. 13334 while (FD && !getDLLAttr(FD) && 13335 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13336 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13337 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13338 } 13339 13340 if (!FD) 13341 return; 13342 13343 // Static locals inherit dll attributes from their function. 13344 if (Attr *A = getDLLAttr(FD)) { 13345 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13346 NewAttr->setInherited(true); 13347 VD->addAttr(NewAttr); 13348 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13349 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13350 NewAttr->setInherited(true); 13351 VD->addAttr(NewAttr); 13352 13353 // Export this function to enforce exporting this static variable even 13354 // if it is not used in this compilation unit. 13355 if (!FD->hasAttr<DLLExportAttr>()) 13356 FD->addAttr(NewAttr); 13357 13358 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13359 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13360 NewAttr->setInherited(true); 13361 VD->addAttr(NewAttr); 13362 } 13363 } 13364 13365 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13366 /// any semantic actions necessary after any initializer has been attached. 13367 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13368 // Note that we are no longer parsing the initializer for this declaration. 13369 ParsingInitForAutoVars.erase(ThisDecl); 13370 13371 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13372 if (!VD) 13373 return; 13374 13375 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13376 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13377 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13378 if (PragmaClangBSSSection.Valid) 13379 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13380 Context, PragmaClangBSSSection.SectionName, 13381 PragmaClangBSSSection.PragmaLocation, 13382 AttributeCommonInfo::AS_Pragma)); 13383 if (PragmaClangDataSection.Valid) 13384 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13385 Context, PragmaClangDataSection.SectionName, 13386 PragmaClangDataSection.PragmaLocation, 13387 AttributeCommonInfo::AS_Pragma)); 13388 if (PragmaClangRodataSection.Valid) 13389 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13390 Context, PragmaClangRodataSection.SectionName, 13391 PragmaClangRodataSection.PragmaLocation, 13392 AttributeCommonInfo::AS_Pragma)); 13393 if (PragmaClangRelroSection.Valid) 13394 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13395 Context, PragmaClangRelroSection.SectionName, 13396 PragmaClangRelroSection.PragmaLocation, 13397 AttributeCommonInfo::AS_Pragma)); 13398 } 13399 13400 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13401 for (auto *BD : DD->bindings()) { 13402 FinalizeDeclaration(BD); 13403 } 13404 } 13405 13406 checkAttributesAfterMerging(*this, *VD); 13407 13408 // Perform TLS alignment check here after attributes attached to the variable 13409 // which may affect the alignment have been processed. Only perform the check 13410 // if the target has a maximum TLS alignment (zero means no constraints). 13411 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13412 // Protect the check so that it's not performed on dependent types and 13413 // dependent alignments (we can't determine the alignment in that case). 13414 if (VD->getTLSKind() && !VD->hasDependentAlignment()) { 13415 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13416 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13417 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13418 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13419 << (unsigned)MaxAlignChars.getQuantity(); 13420 } 13421 } 13422 } 13423 13424 if (VD->isStaticLocal()) 13425 CheckStaticLocalForDllExport(VD); 13426 13427 // Perform check for initializers of device-side global variables. 13428 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13429 // 7.5). We must also apply the same checks to all __shared__ 13430 // variables whether they are local or not. CUDA also allows 13431 // constant initializers for __constant__ and __device__ variables. 13432 if (getLangOpts().CUDA) 13433 checkAllowedCUDAInitializer(VD); 13434 13435 // Grab the dllimport or dllexport attribute off of the VarDecl. 13436 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13437 13438 // Imported static data members cannot be defined out-of-line. 13439 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13440 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13441 VD->isThisDeclarationADefinition()) { 13442 // We allow definitions of dllimport class template static data members 13443 // with a warning. 13444 CXXRecordDecl *Context = 13445 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13446 bool IsClassTemplateMember = 13447 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13448 Context->getDescribedClassTemplate(); 13449 13450 Diag(VD->getLocation(), 13451 IsClassTemplateMember 13452 ? diag::warn_attribute_dllimport_static_field_definition 13453 : diag::err_attribute_dllimport_static_field_definition); 13454 Diag(IA->getLocation(), diag::note_attribute); 13455 if (!IsClassTemplateMember) 13456 VD->setInvalidDecl(); 13457 } 13458 } 13459 13460 // dllimport/dllexport variables cannot be thread local, their TLS index 13461 // isn't exported with the variable. 13462 if (DLLAttr && VD->getTLSKind()) { 13463 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13464 if (F && getDLLAttr(F)) { 13465 assert(VD->isStaticLocal()); 13466 // But if this is a static local in a dlimport/dllexport function, the 13467 // function will never be inlined, which means the var would never be 13468 // imported, so having it marked import/export is safe. 13469 } else { 13470 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13471 << DLLAttr; 13472 VD->setInvalidDecl(); 13473 } 13474 } 13475 13476 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13477 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13478 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13479 << Attr; 13480 VD->dropAttr<UsedAttr>(); 13481 } 13482 } 13483 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 13484 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13485 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13486 << Attr; 13487 VD->dropAttr<RetainAttr>(); 13488 } 13489 } 13490 13491 const DeclContext *DC = VD->getDeclContext(); 13492 // If there's a #pragma GCC visibility in scope, and this isn't a class 13493 // member, set the visibility of this variable. 13494 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13495 AddPushedVisibilityAttribute(VD); 13496 13497 // FIXME: Warn on unused var template partial specializations. 13498 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13499 MarkUnusedFileScopedDecl(VD); 13500 13501 // Now we have parsed the initializer and can update the table of magic 13502 // tag values. 13503 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13504 !VD->getType()->isIntegralOrEnumerationType()) 13505 return; 13506 13507 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13508 const Expr *MagicValueExpr = VD->getInit(); 13509 if (!MagicValueExpr) { 13510 continue; 13511 } 13512 Optional<llvm::APSInt> MagicValueInt; 13513 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13514 Diag(I->getRange().getBegin(), 13515 diag::err_type_tag_for_datatype_not_ice) 13516 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13517 continue; 13518 } 13519 if (MagicValueInt->getActiveBits() > 64) { 13520 Diag(I->getRange().getBegin(), 13521 diag::err_type_tag_for_datatype_too_large) 13522 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13523 continue; 13524 } 13525 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13526 RegisterTypeTagForDatatype(I->getArgumentKind(), 13527 MagicValue, 13528 I->getMatchingCType(), 13529 I->getLayoutCompatible(), 13530 I->getMustBeNull()); 13531 } 13532 } 13533 13534 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13535 auto *VD = dyn_cast<VarDecl>(DD); 13536 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13537 } 13538 13539 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13540 ArrayRef<Decl *> Group) { 13541 SmallVector<Decl*, 8> Decls; 13542 13543 if (DS.isTypeSpecOwned()) 13544 Decls.push_back(DS.getRepAsDecl()); 13545 13546 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13547 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13548 bool DiagnosedMultipleDecomps = false; 13549 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13550 bool DiagnosedNonDeducedAuto = false; 13551 13552 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13553 if (Decl *D = Group[i]) { 13554 // For declarators, there are some additional syntactic-ish checks we need 13555 // to perform. 13556 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13557 if (!FirstDeclaratorInGroup) 13558 FirstDeclaratorInGroup = DD; 13559 if (!FirstDecompDeclaratorInGroup) 13560 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13561 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13562 !hasDeducedAuto(DD)) 13563 FirstNonDeducedAutoInGroup = DD; 13564 13565 if (FirstDeclaratorInGroup != DD) { 13566 // A decomposition declaration cannot be combined with any other 13567 // declaration in the same group. 13568 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13569 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13570 diag::err_decomp_decl_not_alone) 13571 << FirstDeclaratorInGroup->getSourceRange() 13572 << DD->getSourceRange(); 13573 DiagnosedMultipleDecomps = true; 13574 } 13575 13576 // A declarator that uses 'auto' in any way other than to declare a 13577 // variable with a deduced type cannot be combined with any other 13578 // declarator in the same group. 13579 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13580 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13581 diag::err_auto_non_deduced_not_alone) 13582 << FirstNonDeducedAutoInGroup->getType() 13583 ->hasAutoForTrailingReturnType() 13584 << FirstDeclaratorInGroup->getSourceRange() 13585 << DD->getSourceRange(); 13586 DiagnosedNonDeducedAuto = true; 13587 } 13588 } 13589 } 13590 13591 Decls.push_back(D); 13592 } 13593 } 13594 13595 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13596 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13597 handleTagNumbering(Tag, S); 13598 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13599 getLangOpts().CPlusPlus) 13600 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13601 } 13602 } 13603 13604 return BuildDeclaratorGroup(Decls); 13605 } 13606 13607 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13608 /// group, performing any necessary semantic checking. 13609 Sema::DeclGroupPtrTy 13610 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13611 // C++14 [dcl.spec.auto]p7: (DR1347) 13612 // If the type that replaces the placeholder type is not the same in each 13613 // deduction, the program is ill-formed. 13614 if (Group.size() > 1) { 13615 QualType Deduced; 13616 VarDecl *DeducedDecl = nullptr; 13617 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13618 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13619 if (!D || D->isInvalidDecl()) 13620 break; 13621 DeducedType *DT = D->getType()->getContainedDeducedType(); 13622 if (!DT || DT->getDeducedType().isNull()) 13623 continue; 13624 if (Deduced.isNull()) { 13625 Deduced = DT->getDeducedType(); 13626 DeducedDecl = D; 13627 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13628 auto *AT = dyn_cast<AutoType>(DT); 13629 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13630 diag::err_auto_different_deductions) 13631 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13632 << DeducedDecl->getDeclName() << DT->getDeducedType() 13633 << D->getDeclName(); 13634 if (DeducedDecl->hasInit()) 13635 Dia << DeducedDecl->getInit()->getSourceRange(); 13636 if (D->getInit()) 13637 Dia << D->getInit()->getSourceRange(); 13638 D->setInvalidDecl(); 13639 break; 13640 } 13641 } 13642 } 13643 13644 ActOnDocumentableDecls(Group); 13645 13646 return DeclGroupPtrTy::make( 13647 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13648 } 13649 13650 void Sema::ActOnDocumentableDecl(Decl *D) { 13651 ActOnDocumentableDecls(D); 13652 } 13653 13654 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13655 // Don't parse the comment if Doxygen diagnostics are ignored. 13656 if (Group.empty() || !Group[0]) 13657 return; 13658 13659 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13660 Group[0]->getLocation()) && 13661 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13662 Group[0]->getLocation())) 13663 return; 13664 13665 if (Group.size() >= 2) { 13666 // This is a decl group. Normally it will contain only declarations 13667 // produced from declarator list. But in case we have any definitions or 13668 // additional declaration references: 13669 // 'typedef struct S {} S;' 13670 // 'typedef struct S *S;' 13671 // 'struct S *pS;' 13672 // FinalizeDeclaratorGroup adds these as separate declarations. 13673 Decl *MaybeTagDecl = Group[0]; 13674 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13675 Group = Group.slice(1); 13676 } 13677 } 13678 13679 // FIMXE: We assume every Decl in the group is in the same file. 13680 // This is false when preprocessor constructs the group from decls in 13681 // different files (e. g. macros or #include). 13682 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13683 } 13684 13685 /// Common checks for a parameter-declaration that should apply to both function 13686 /// parameters and non-type template parameters. 13687 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13688 // Check that there are no default arguments inside the type of this 13689 // parameter. 13690 if (getLangOpts().CPlusPlus) 13691 CheckExtraCXXDefaultArguments(D); 13692 13693 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13694 if (D.getCXXScopeSpec().isSet()) { 13695 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13696 << D.getCXXScopeSpec().getRange(); 13697 } 13698 13699 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13700 // simple identifier except [...irrelevant cases...]. 13701 switch (D.getName().getKind()) { 13702 case UnqualifiedIdKind::IK_Identifier: 13703 break; 13704 13705 case UnqualifiedIdKind::IK_OperatorFunctionId: 13706 case UnqualifiedIdKind::IK_ConversionFunctionId: 13707 case UnqualifiedIdKind::IK_LiteralOperatorId: 13708 case UnqualifiedIdKind::IK_ConstructorName: 13709 case UnqualifiedIdKind::IK_DestructorName: 13710 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13711 case UnqualifiedIdKind::IK_DeductionGuideName: 13712 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13713 << GetNameForDeclarator(D).getName(); 13714 break; 13715 13716 case UnqualifiedIdKind::IK_TemplateId: 13717 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13718 // GetNameForDeclarator would not produce a useful name in this case. 13719 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13720 break; 13721 } 13722 } 13723 13724 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13725 /// to introduce parameters into function prototype scope. 13726 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13727 const DeclSpec &DS = D.getDeclSpec(); 13728 13729 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13730 13731 // C++03 [dcl.stc]p2 also permits 'auto'. 13732 StorageClass SC = SC_None; 13733 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13734 SC = SC_Register; 13735 // In C++11, the 'register' storage class specifier is deprecated. 13736 // In C++17, it is not allowed, but we tolerate it as an extension. 13737 if (getLangOpts().CPlusPlus11) { 13738 Diag(DS.getStorageClassSpecLoc(), 13739 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13740 : diag::warn_deprecated_register) 13741 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13742 } 13743 } else if (getLangOpts().CPlusPlus && 13744 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13745 SC = SC_Auto; 13746 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13747 Diag(DS.getStorageClassSpecLoc(), 13748 diag::err_invalid_storage_class_in_func_decl); 13749 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13750 } 13751 13752 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13753 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13754 << DeclSpec::getSpecifierName(TSCS); 13755 if (DS.isInlineSpecified()) 13756 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13757 << getLangOpts().CPlusPlus17; 13758 if (DS.hasConstexprSpecifier()) 13759 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13760 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 13761 13762 DiagnoseFunctionSpecifiers(DS); 13763 13764 CheckFunctionOrTemplateParamDeclarator(S, D); 13765 13766 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13767 QualType parmDeclType = TInfo->getType(); 13768 13769 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13770 IdentifierInfo *II = D.getIdentifier(); 13771 if (II) { 13772 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13773 ForVisibleRedeclaration); 13774 LookupName(R, S); 13775 if (R.isSingleResult()) { 13776 NamedDecl *PrevDecl = R.getFoundDecl(); 13777 if (PrevDecl->isTemplateParameter()) { 13778 // Maybe we will complain about the shadowed template parameter. 13779 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13780 // Just pretend that we didn't see the previous declaration. 13781 PrevDecl = nullptr; 13782 } else if (S->isDeclScope(PrevDecl)) { 13783 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13784 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13785 13786 // Recover by removing the name 13787 II = nullptr; 13788 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13789 D.setInvalidType(true); 13790 } 13791 } 13792 } 13793 13794 // Temporarily put parameter variables in the translation unit, not 13795 // the enclosing context. This prevents them from accidentally 13796 // looking like class members in C++. 13797 ParmVarDecl *New = 13798 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13799 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13800 13801 if (D.isInvalidType()) 13802 New->setInvalidDecl(); 13803 13804 assert(S->isFunctionPrototypeScope()); 13805 assert(S->getFunctionPrototypeDepth() >= 1); 13806 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13807 S->getNextFunctionPrototypeIndex()); 13808 13809 // Add the parameter declaration into this scope. 13810 S->AddDecl(New); 13811 if (II) 13812 IdResolver.AddDecl(New); 13813 13814 ProcessDeclAttributes(S, New, D); 13815 13816 if (D.getDeclSpec().isModulePrivateSpecified()) 13817 Diag(New->getLocation(), diag::err_module_private_local) 13818 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13819 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13820 13821 if (New->hasAttr<BlocksAttr>()) { 13822 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13823 } 13824 13825 if (getLangOpts().OpenCL) 13826 deduceOpenCLAddressSpace(New); 13827 13828 return New; 13829 } 13830 13831 /// Synthesizes a variable for a parameter arising from a 13832 /// typedef. 13833 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13834 SourceLocation Loc, 13835 QualType T) { 13836 /* FIXME: setting StartLoc == Loc. 13837 Would it be worth to modify callers so as to provide proper source 13838 location for the unnamed parameters, embedding the parameter's type? */ 13839 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13840 T, Context.getTrivialTypeSourceInfo(T, Loc), 13841 SC_None, nullptr); 13842 Param->setImplicit(); 13843 return Param; 13844 } 13845 13846 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13847 // Don't diagnose unused-parameter errors in template instantiations; we 13848 // will already have done so in the template itself. 13849 if (inTemplateInstantiation()) 13850 return; 13851 13852 for (const ParmVarDecl *Parameter : Parameters) { 13853 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13854 !Parameter->hasAttr<UnusedAttr>()) { 13855 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13856 << Parameter->getDeclName(); 13857 } 13858 } 13859 } 13860 13861 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13862 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13863 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13864 return; 13865 13866 // Warn if the return value is pass-by-value and larger than the specified 13867 // threshold. 13868 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13869 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13870 if (Size > LangOpts.NumLargeByValueCopy) 13871 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 13872 } 13873 13874 // Warn if any parameter is pass-by-value and larger than the specified 13875 // threshold. 13876 for (const ParmVarDecl *Parameter : Parameters) { 13877 QualType T = Parameter->getType(); 13878 if (T->isDependentType() || !T.isPODType(Context)) 13879 continue; 13880 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13881 if (Size > LangOpts.NumLargeByValueCopy) 13882 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13883 << Parameter << Size; 13884 } 13885 } 13886 13887 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13888 SourceLocation NameLoc, IdentifierInfo *Name, 13889 QualType T, TypeSourceInfo *TSInfo, 13890 StorageClass SC) { 13891 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13892 if (getLangOpts().ObjCAutoRefCount && 13893 T.getObjCLifetime() == Qualifiers::OCL_None && 13894 T->isObjCLifetimeType()) { 13895 13896 Qualifiers::ObjCLifetime lifetime; 13897 13898 // Special cases for arrays: 13899 // - if it's const, use __unsafe_unretained 13900 // - otherwise, it's an error 13901 if (T->isArrayType()) { 13902 if (!T.isConstQualified()) { 13903 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13904 DelayedDiagnostics.add( 13905 sema::DelayedDiagnostic::makeForbiddenType( 13906 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13907 else 13908 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13909 << TSInfo->getTypeLoc().getSourceRange(); 13910 } 13911 lifetime = Qualifiers::OCL_ExplicitNone; 13912 } else { 13913 lifetime = T->getObjCARCImplicitLifetime(); 13914 } 13915 T = Context.getLifetimeQualifiedType(T, lifetime); 13916 } 13917 13918 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13919 Context.getAdjustedParameterType(T), 13920 TSInfo, SC, nullptr); 13921 13922 // Make a note if we created a new pack in the scope of a lambda, so that 13923 // we know that references to that pack must also be expanded within the 13924 // lambda scope. 13925 if (New->isParameterPack()) 13926 if (auto *LSI = getEnclosingLambda()) 13927 LSI->LocalPacks.push_back(New); 13928 13929 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13930 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13931 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13932 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13933 13934 // Parameters can not be abstract class types. 13935 // For record types, this is done by the AbstractClassUsageDiagnoser once 13936 // the class has been completely parsed. 13937 if (!CurContext->isRecord() && 13938 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13939 AbstractParamType)) 13940 New->setInvalidDecl(); 13941 13942 // Parameter declarators cannot be interface types. All ObjC objects are 13943 // passed by reference. 13944 if (T->isObjCObjectType()) { 13945 SourceLocation TypeEndLoc = 13946 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13947 Diag(NameLoc, 13948 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13949 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13950 T = Context.getObjCObjectPointerType(T); 13951 New->setType(T); 13952 } 13953 13954 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13955 // duration shall not be qualified by an address-space qualifier." 13956 // Since all parameters have automatic store duration, they can not have 13957 // an address space. 13958 if (T.getAddressSpace() != LangAS::Default && 13959 // OpenCL allows function arguments declared to be an array of a type 13960 // to be qualified with an address space. 13961 !(getLangOpts().OpenCL && 13962 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13963 Diag(NameLoc, diag::err_arg_with_address_space); 13964 New->setInvalidDecl(); 13965 } 13966 13967 // PPC MMA non-pointer types are not allowed as function argument types. 13968 if (Context.getTargetInfo().getTriple().isPPC64() && 13969 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 13970 New->setInvalidDecl(); 13971 } 13972 13973 return New; 13974 } 13975 13976 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13977 SourceLocation LocAfterDecls) { 13978 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13979 13980 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13981 // for a K&R function. 13982 if (!FTI.hasPrototype) { 13983 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13984 --i; 13985 if (FTI.Params[i].Param == nullptr) { 13986 SmallString<256> Code; 13987 llvm::raw_svector_ostream(Code) 13988 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13989 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13990 << FTI.Params[i].Ident 13991 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13992 13993 // Implicitly declare the argument as type 'int' for lack of a better 13994 // type. 13995 AttributeFactory attrs; 13996 DeclSpec DS(attrs); 13997 const char* PrevSpec; // unused 13998 unsigned DiagID; // unused 13999 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 14000 DiagID, Context.getPrintingPolicy()); 14001 // Use the identifier location for the type source range. 14002 DS.SetRangeStart(FTI.Params[i].IdentLoc); 14003 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 14004 Declarator ParamD(DS, DeclaratorContext::KNRTypeList); 14005 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 14006 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 14007 } 14008 } 14009 } 14010 } 14011 14012 Decl * 14013 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 14014 MultiTemplateParamsArg TemplateParameterLists, 14015 SkipBodyInfo *SkipBody) { 14016 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 14017 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 14018 Scope *ParentScope = FnBodyScope->getParent(); 14019 14020 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 14021 // we define a non-templated function definition, we will create a declaration 14022 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 14023 // The base function declaration will have the equivalent of an `omp declare 14024 // variant` annotation which specifies the mangled definition as a 14025 // specialization function under the OpenMP context defined as part of the 14026 // `omp begin declare variant`. 14027 SmallVector<FunctionDecl *, 4> Bases; 14028 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 14029 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 14030 ParentScope, D, TemplateParameterLists, Bases); 14031 14032 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 14033 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 14034 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 14035 14036 if (!Bases.empty()) 14037 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 14038 14039 return Dcl; 14040 } 14041 14042 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 14043 Consumer.HandleInlineFunctionDefinition(D); 14044 } 14045 14046 static bool 14047 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 14048 const FunctionDecl *&PossiblePrototype) { 14049 // Don't warn about invalid declarations. 14050 if (FD->isInvalidDecl()) 14051 return false; 14052 14053 // Or declarations that aren't global. 14054 if (!FD->isGlobal()) 14055 return false; 14056 14057 // Don't warn about C++ member functions. 14058 if (isa<CXXMethodDecl>(FD)) 14059 return false; 14060 14061 // Don't warn about 'main'. 14062 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 14063 if (IdentifierInfo *II = FD->getIdentifier()) 14064 if (II->isStr("main") || II->isStr("efi_main")) 14065 return false; 14066 14067 // Don't warn about inline functions. 14068 if (FD->isInlined()) 14069 return false; 14070 14071 // Don't warn about function templates. 14072 if (FD->getDescribedFunctionTemplate()) 14073 return false; 14074 14075 // Don't warn about function template specializations. 14076 if (FD->isFunctionTemplateSpecialization()) 14077 return false; 14078 14079 // Don't warn for OpenCL kernels. 14080 if (FD->hasAttr<OpenCLKernelAttr>()) 14081 return false; 14082 14083 // Don't warn on explicitly deleted functions. 14084 if (FD->isDeleted()) 14085 return false; 14086 14087 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 14088 Prev; Prev = Prev->getPreviousDecl()) { 14089 // Ignore any declarations that occur in function or method 14090 // scope, because they aren't visible from the header. 14091 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 14092 continue; 14093 14094 PossiblePrototype = Prev; 14095 return Prev->getType()->isFunctionNoProtoType(); 14096 } 14097 14098 return true; 14099 } 14100 14101 void 14102 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 14103 const FunctionDecl *EffectiveDefinition, 14104 SkipBodyInfo *SkipBody) { 14105 const FunctionDecl *Definition = EffectiveDefinition; 14106 if (!Definition && 14107 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 14108 return; 14109 14110 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 14111 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 14112 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 14113 // A merged copy of the same function, instantiated as a member of 14114 // the same class, is OK. 14115 if (declaresSameEntity(OrigFD, OrigDef) && 14116 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 14117 cast<Decl>(FD->getLexicalDeclContext()))) 14118 return; 14119 } 14120 } 14121 } 14122 14123 if (canRedefineFunction(Definition, getLangOpts())) 14124 return; 14125 14126 // Don't emit an error when this is redefinition of a typo-corrected 14127 // definition. 14128 if (TypoCorrectedFunctionDefinitions.count(Definition)) 14129 return; 14130 14131 // If we don't have a visible definition of the function, and it's inline or 14132 // a template, skip the new definition. 14133 if (SkipBody && !hasVisibleDefinition(Definition) && 14134 (Definition->getFormalLinkage() == InternalLinkage || 14135 Definition->isInlined() || 14136 Definition->getDescribedFunctionTemplate() || 14137 Definition->getNumTemplateParameterLists())) { 14138 SkipBody->ShouldSkip = true; 14139 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 14140 if (auto *TD = Definition->getDescribedFunctionTemplate()) 14141 makeMergedDefinitionVisible(TD); 14142 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 14143 return; 14144 } 14145 14146 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 14147 Definition->getStorageClass() == SC_Extern) 14148 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 14149 << FD << getLangOpts().CPlusPlus; 14150 else 14151 Diag(FD->getLocation(), diag::err_redefinition) << FD; 14152 14153 Diag(Definition->getLocation(), diag::note_previous_definition); 14154 FD->setInvalidDecl(); 14155 } 14156 14157 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 14158 Sema &S) { 14159 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 14160 14161 LambdaScopeInfo *LSI = S.PushLambdaScope(); 14162 LSI->CallOperator = CallOperator; 14163 LSI->Lambda = LambdaClass; 14164 LSI->ReturnType = CallOperator->getReturnType(); 14165 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 14166 14167 if (LCD == LCD_None) 14168 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 14169 else if (LCD == LCD_ByCopy) 14170 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 14171 else if (LCD == LCD_ByRef) 14172 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 14173 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 14174 14175 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 14176 LSI->Mutable = !CallOperator->isConst(); 14177 14178 // Add the captures to the LSI so they can be noted as already 14179 // captured within tryCaptureVar. 14180 auto I = LambdaClass->field_begin(); 14181 for (const auto &C : LambdaClass->captures()) { 14182 if (C.capturesVariable()) { 14183 VarDecl *VD = C.getCapturedVar(); 14184 if (VD->isInitCapture()) 14185 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 14186 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 14187 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 14188 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 14189 /*EllipsisLoc*/C.isPackExpansion() 14190 ? C.getEllipsisLoc() : SourceLocation(), 14191 I->getType(), /*Invalid*/false); 14192 14193 } else if (C.capturesThis()) { 14194 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 14195 C.getCaptureKind() == LCK_StarThis); 14196 } else { 14197 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14198 I->getType()); 14199 } 14200 ++I; 14201 } 14202 } 14203 14204 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14205 SkipBodyInfo *SkipBody) { 14206 if (!D) { 14207 // Parsing the function declaration failed in some way. Push on a fake scope 14208 // anyway so we can try to parse the function body. 14209 PushFunctionScope(); 14210 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14211 return D; 14212 } 14213 14214 FunctionDecl *FD = nullptr; 14215 14216 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14217 FD = FunTmpl->getTemplatedDecl(); 14218 else 14219 FD = cast<FunctionDecl>(D); 14220 14221 // Do not push if it is a lambda because one is already pushed when building 14222 // the lambda in ActOnStartOfLambdaDefinition(). 14223 if (!isLambdaCallOperator(FD)) 14224 PushExpressionEvaluationContext( 14225 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14226 : ExprEvalContexts.back().Context); 14227 14228 // Check for defining attributes before the check for redefinition. 14229 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14230 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14231 FD->dropAttr<AliasAttr>(); 14232 FD->setInvalidDecl(); 14233 } 14234 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14235 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14236 FD->dropAttr<IFuncAttr>(); 14237 FD->setInvalidDecl(); 14238 } 14239 14240 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14241 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14242 Ctor->isDefaultConstructor() && 14243 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14244 // If this is an MS ABI dllexport default constructor, instantiate any 14245 // default arguments. 14246 InstantiateDefaultCtorDefaultArgs(Ctor); 14247 } 14248 } 14249 14250 // See if this is a redefinition. If 'will have body' (or similar) is already 14251 // set, then these checks were already performed when it was set. 14252 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14253 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14254 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14255 14256 // If we're skipping the body, we're done. Don't enter the scope. 14257 if (SkipBody && SkipBody->ShouldSkip) 14258 return D; 14259 } 14260 14261 // Mark this function as "will have a body eventually". This lets users to 14262 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14263 // this function. 14264 FD->setWillHaveBody(); 14265 14266 // If we are instantiating a generic lambda call operator, push 14267 // a LambdaScopeInfo onto the function stack. But use the information 14268 // that's already been calculated (ActOnLambdaExpr) to prime the current 14269 // LambdaScopeInfo. 14270 // When the template operator is being specialized, the LambdaScopeInfo, 14271 // has to be properly restored so that tryCaptureVariable doesn't try 14272 // and capture any new variables. In addition when calculating potential 14273 // captures during transformation of nested lambdas, it is necessary to 14274 // have the LSI properly restored. 14275 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14276 assert(inTemplateInstantiation() && 14277 "There should be an active template instantiation on the stack " 14278 "when instantiating a generic lambda!"); 14279 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14280 } else { 14281 // Enter a new function scope 14282 PushFunctionScope(); 14283 } 14284 14285 // Builtin functions cannot be defined. 14286 if (unsigned BuiltinID = FD->getBuiltinID()) { 14287 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14288 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14289 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14290 FD->setInvalidDecl(); 14291 } 14292 } 14293 14294 // The return type of a function definition must be complete 14295 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14296 QualType ResultType = FD->getReturnType(); 14297 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14298 !FD->isInvalidDecl() && 14299 RequireCompleteType(FD->getLocation(), ResultType, 14300 diag::err_func_def_incomplete_result)) 14301 FD->setInvalidDecl(); 14302 14303 if (FnBodyScope) 14304 PushDeclContext(FnBodyScope, FD); 14305 14306 // Check the validity of our function parameters 14307 CheckParmsForFunctionDef(FD->parameters(), 14308 /*CheckParameterNames=*/true); 14309 14310 // Add non-parameter declarations already in the function to the current 14311 // scope. 14312 if (FnBodyScope) { 14313 for (Decl *NPD : FD->decls()) { 14314 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14315 if (!NonParmDecl) 14316 continue; 14317 assert(!isa<ParmVarDecl>(NonParmDecl) && 14318 "parameters should not be in newly created FD yet"); 14319 14320 // If the decl has a name, make it accessible in the current scope. 14321 if (NonParmDecl->getDeclName()) 14322 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14323 14324 // Similarly, dive into enums and fish their constants out, making them 14325 // accessible in this scope. 14326 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14327 for (auto *EI : ED->enumerators()) 14328 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14329 } 14330 } 14331 } 14332 14333 // Introduce our parameters into the function scope 14334 for (auto Param : FD->parameters()) { 14335 Param->setOwningFunction(FD); 14336 14337 // If this has an identifier, add it to the scope stack. 14338 if (Param->getIdentifier() && FnBodyScope) { 14339 CheckShadow(FnBodyScope, Param); 14340 14341 PushOnScopeChains(Param, FnBodyScope); 14342 } 14343 } 14344 14345 // Ensure that the function's exception specification is instantiated. 14346 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14347 ResolveExceptionSpec(D->getLocation(), FPT); 14348 14349 // dllimport cannot be applied to non-inline function definitions. 14350 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14351 !FD->isTemplateInstantiation()) { 14352 assert(!FD->hasAttr<DLLExportAttr>()); 14353 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14354 FD->setInvalidDecl(); 14355 return D; 14356 } 14357 // We want to attach documentation to original Decl (which might be 14358 // a function template). 14359 ActOnDocumentableDecl(D); 14360 if (getCurLexicalContext()->isObjCContainer() && 14361 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14362 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14363 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14364 14365 return D; 14366 } 14367 14368 /// Given the set of return statements within a function body, 14369 /// compute the variables that are subject to the named return value 14370 /// optimization. 14371 /// 14372 /// Each of the variables that is subject to the named return value 14373 /// optimization will be marked as NRVO variables in the AST, and any 14374 /// return statement that has a marked NRVO variable as its NRVO candidate can 14375 /// use the named return value optimization. 14376 /// 14377 /// This function applies a very simplistic algorithm for NRVO: if every return 14378 /// statement in the scope of a variable has the same NRVO candidate, that 14379 /// candidate is an NRVO variable. 14380 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14381 ReturnStmt **Returns = Scope->Returns.data(); 14382 14383 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14384 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14385 if (!NRVOCandidate->isNRVOVariable()) 14386 Returns[I]->setNRVOCandidate(nullptr); 14387 } 14388 } 14389 } 14390 14391 bool Sema::canDelayFunctionBody(const Declarator &D) { 14392 // We can't delay parsing the body of a constexpr function template (yet). 14393 if (D.getDeclSpec().hasConstexprSpecifier()) 14394 return false; 14395 14396 // We can't delay parsing the body of a function template with a deduced 14397 // return type (yet). 14398 if (D.getDeclSpec().hasAutoTypeSpec()) { 14399 // If the placeholder introduces a non-deduced trailing return type, 14400 // we can still delay parsing it. 14401 if (D.getNumTypeObjects()) { 14402 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14403 if (Outer.Kind == DeclaratorChunk::Function && 14404 Outer.Fun.hasTrailingReturnType()) { 14405 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14406 return Ty.isNull() || !Ty->isUndeducedType(); 14407 } 14408 } 14409 return false; 14410 } 14411 14412 return true; 14413 } 14414 14415 bool Sema::canSkipFunctionBody(Decl *D) { 14416 // We cannot skip the body of a function (or function template) which is 14417 // constexpr, since we may need to evaluate its body in order to parse the 14418 // rest of the file. 14419 // We cannot skip the body of a function with an undeduced return type, 14420 // because any callers of that function need to know the type. 14421 if (const FunctionDecl *FD = D->getAsFunction()) { 14422 if (FD->isConstexpr()) 14423 return false; 14424 // We can't simply call Type::isUndeducedType here, because inside template 14425 // auto can be deduced to a dependent type, which is not considered 14426 // "undeduced". 14427 if (FD->getReturnType()->getContainedDeducedType()) 14428 return false; 14429 } 14430 return Consumer.shouldSkipFunctionBody(D); 14431 } 14432 14433 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14434 if (!Decl) 14435 return nullptr; 14436 if (FunctionDecl *FD = Decl->getAsFunction()) 14437 FD->setHasSkippedBody(); 14438 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14439 MD->setHasSkippedBody(); 14440 return Decl; 14441 } 14442 14443 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14444 return ActOnFinishFunctionBody(D, BodyArg, false); 14445 } 14446 14447 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14448 /// body. 14449 class ExitFunctionBodyRAII { 14450 public: 14451 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14452 ~ExitFunctionBodyRAII() { 14453 if (!IsLambda) 14454 S.PopExpressionEvaluationContext(); 14455 } 14456 14457 private: 14458 Sema &S; 14459 bool IsLambda = false; 14460 }; 14461 14462 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14463 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14464 14465 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14466 if (EscapeInfo.count(BD)) 14467 return EscapeInfo[BD]; 14468 14469 bool R = false; 14470 const BlockDecl *CurBD = BD; 14471 14472 do { 14473 R = !CurBD->doesNotEscape(); 14474 if (R) 14475 break; 14476 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14477 } while (CurBD); 14478 14479 return EscapeInfo[BD] = R; 14480 }; 14481 14482 // If the location where 'self' is implicitly retained is inside a escaping 14483 // block, emit a diagnostic. 14484 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14485 S.ImplicitlyRetainedSelfLocs) 14486 if (IsOrNestedInEscapingBlock(P.second)) 14487 S.Diag(P.first, diag::warn_implicitly_retains_self) 14488 << FixItHint::CreateInsertion(P.first, "self->"); 14489 } 14490 14491 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14492 bool IsInstantiation) { 14493 FunctionScopeInfo *FSI = getCurFunction(); 14494 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14495 14496 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>()) 14497 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14498 14499 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14500 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14501 14502 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14503 CheckCompletedCoroutineBody(FD, Body); 14504 14505 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14506 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14507 // meant to pop the context added in ActOnStartOfFunctionDef(). 14508 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14509 14510 if (FD) { 14511 FD->setBody(Body); 14512 FD->setWillHaveBody(false); 14513 14514 if (getLangOpts().CPlusPlus14) { 14515 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14516 FD->getReturnType()->isUndeducedType()) { 14517 // If the function has a deduced result type but contains no 'return' 14518 // statements, the result type as written must be exactly 'auto', and 14519 // the deduced result type is 'void'. 14520 if (!FD->getReturnType()->getAs<AutoType>()) { 14521 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14522 << FD->getReturnType(); 14523 FD->setInvalidDecl(); 14524 } else { 14525 // Substitute 'void' for the 'auto' in the type. 14526 TypeLoc ResultType = getReturnTypeLoc(FD); 14527 Context.adjustDeducedFunctionResultType( 14528 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14529 } 14530 } 14531 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14532 // In C++11, we don't use 'auto' deduction rules for lambda call 14533 // operators because we don't support return type deduction. 14534 auto *LSI = getCurLambda(); 14535 if (LSI->HasImplicitReturnType) { 14536 deduceClosureReturnType(*LSI); 14537 14538 // C++11 [expr.prim.lambda]p4: 14539 // [...] if there are no return statements in the compound-statement 14540 // [the deduced type is] the type void 14541 QualType RetType = 14542 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14543 14544 // Update the return type to the deduced type. 14545 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14546 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14547 Proto->getExtProtoInfo())); 14548 } 14549 } 14550 14551 // If the function implicitly returns zero (like 'main') or is naked, 14552 // don't complain about missing return statements. 14553 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14554 WP.disableCheckFallThrough(); 14555 14556 // MSVC permits the use of pure specifier (=0) on function definition, 14557 // defined at class scope, warn about this non-standard construct. 14558 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14559 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14560 14561 if (!FD->isInvalidDecl()) { 14562 // Don't diagnose unused parameters of defaulted or deleted functions. 14563 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14564 DiagnoseUnusedParameters(FD->parameters()); 14565 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14566 FD->getReturnType(), FD); 14567 14568 // If this is a structor, we need a vtable. 14569 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14570 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14571 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14572 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14573 14574 // Try to apply the named return value optimization. We have to check 14575 // if we can do this here because lambdas keep return statements around 14576 // to deduce an implicit return type. 14577 if (FD->getReturnType()->isRecordType() && 14578 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14579 computeNRVO(Body, FSI); 14580 } 14581 14582 // GNU warning -Wmissing-prototypes: 14583 // Warn if a global function is defined without a previous 14584 // prototype declaration. This warning is issued even if the 14585 // definition itself provides a prototype. The aim is to detect 14586 // global functions that fail to be declared in header files. 14587 const FunctionDecl *PossiblePrototype = nullptr; 14588 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14589 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14590 14591 if (PossiblePrototype) { 14592 // We found a declaration that is not a prototype, 14593 // but that could be a zero-parameter prototype 14594 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14595 TypeLoc TL = TI->getTypeLoc(); 14596 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14597 Diag(PossiblePrototype->getLocation(), 14598 diag::note_declaration_not_a_prototype) 14599 << (FD->getNumParams() != 0) 14600 << (FD->getNumParams() == 0 14601 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14602 : FixItHint{}); 14603 } 14604 } else { 14605 // Returns true if the token beginning at this Loc is `const`. 14606 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14607 const LangOptions &LangOpts) { 14608 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14609 if (LocInfo.first.isInvalid()) 14610 return false; 14611 14612 bool Invalid = false; 14613 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14614 if (Invalid) 14615 return false; 14616 14617 if (LocInfo.second > Buffer.size()) 14618 return false; 14619 14620 const char *LexStart = Buffer.data() + LocInfo.second; 14621 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14622 14623 return StartTok.consume_front("const") && 14624 (StartTok.empty() || isWhitespace(StartTok[0]) || 14625 StartTok.startswith("/*") || StartTok.startswith("//")); 14626 }; 14627 14628 auto findBeginLoc = [&]() { 14629 // If the return type has `const` qualifier, we want to insert 14630 // `static` before `const` (and not before the typename). 14631 if ((FD->getReturnType()->isAnyPointerType() && 14632 FD->getReturnType()->getPointeeType().isConstQualified()) || 14633 FD->getReturnType().isConstQualified()) { 14634 // But only do this if we can determine where the `const` is. 14635 14636 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14637 getLangOpts())) 14638 14639 return FD->getBeginLoc(); 14640 } 14641 return FD->getTypeSpecStartLoc(); 14642 }; 14643 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14644 << /* function */ 1 14645 << (FD->getStorageClass() == SC_None 14646 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14647 : FixItHint{}); 14648 } 14649 14650 // GNU warning -Wstrict-prototypes 14651 // Warn if K&R function is defined without a previous declaration. 14652 // This warning is issued only if the definition itself does not provide 14653 // a prototype. Only K&R definitions do not provide a prototype. 14654 if (!FD->hasWrittenPrototype()) { 14655 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14656 TypeLoc TL = TI->getTypeLoc(); 14657 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14658 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14659 } 14660 } 14661 14662 // Warn on CPUDispatch with an actual body. 14663 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14664 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14665 if (!CmpndBody->body_empty()) 14666 Diag(CmpndBody->body_front()->getBeginLoc(), 14667 diag::warn_dispatch_body_ignored); 14668 14669 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14670 const CXXMethodDecl *KeyFunction; 14671 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14672 MD->isVirtual() && 14673 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14674 MD == KeyFunction->getCanonicalDecl()) { 14675 // Update the key-function state if necessary for this ABI. 14676 if (FD->isInlined() && 14677 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14678 Context.setNonKeyFunction(MD); 14679 14680 // If the newly-chosen key function is already defined, then we 14681 // need to mark the vtable as used retroactively. 14682 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14683 const FunctionDecl *Definition; 14684 if (KeyFunction && KeyFunction->isDefined(Definition)) 14685 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14686 } else { 14687 // We just defined they key function; mark the vtable as used. 14688 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14689 } 14690 } 14691 } 14692 14693 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14694 "Function parsing confused"); 14695 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14696 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14697 MD->setBody(Body); 14698 if (!MD->isInvalidDecl()) { 14699 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14700 MD->getReturnType(), MD); 14701 14702 if (Body) 14703 computeNRVO(Body, FSI); 14704 } 14705 if (FSI->ObjCShouldCallSuper) { 14706 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14707 << MD->getSelector().getAsString(); 14708 FSI->ObjCShouldCallSuper = false; 14709 } 14710 if (FSI->ObjCWarnForNoDesignatedInitChain) { 14711 const ObjCMethodDecl *InitMethod = nullptr; 14712 bool isDesignated = 14713 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14714 assert(isDesignated && InitMethod); 14715 (void)isDesignated; 14716 14717 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14718 auto IFace = MD->getClassInterface(); 14719 if (!IFace) 14720 return false; 14721 auto SuperD = IFace->getSuperClass(); 14722 if (!SuperD) 14723 return false; 14724 return SuperD->getIdentifier() == 14725 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14726 }; 14727 // Don't issue this warning for unavailable inits or direct subclasses 14728 // of NSObject. 14729 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14730 Diag(MD->getLocation(), 14731 diag::warn_objc_designated_init_missing_super_call); 14732 Diag(InitMethod->getLocation(), 14733 diag::note_objc_designated_init_marked_here); 14734 } 14735 FSI->ObjCWarnForNoDesignatedInitChain = false; 14736 } 14737 if (FSI->ObjCWarnForNoInitDelegation) { 14738 // Don't issue this warning for unavaialable inits. 14739 if (!MD->isUnavailable()) 14740 Diag(MD->getLocation(), 14741 diag::warn_objc_secondary_init_missing_init_call); 14742 FSI->ObjCWarnForNoInitDelegation = false; 14743 } 14744 14745 diagnoseImplicitlyRetainedSelf(*this); 14746 } else { 14747 // Parsing the function declaration failed in some way. Pop the fake scope 14748 // we pushed on. 14749 PopFunctionScopeInfo(ActivePolicy, dcl); 14750 return nullptr; 14751 } 14752 14753 if (Body && FSI->HasPotentialAvailabilityViolations) 14754 DiagnoseUnguardedAvailabilityViolations(dcl); 14755 14756 assert(!FSI->ObjCShouldCallSuper && 14757 "This should only be set for ObjC methods, which should have been " 14758 "handled in the block above."); 14759 14760 // Verify and clean out per-function state. 14761 if (Body && (!FD || !FD->isDefaulted())) { 14762 // C++ constructors that have function-try-blocks can't have return 14763 // statements in the handlers of that block. (C++ [except.handle]p14) 14764 // Verify this. 14765 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14766 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14767 14768 // Verify that gotos and switch cases don't jump into scopes illegally. 14769 if (FSI->NeedsScopeChecking() && 14770 !PP.isCodeCompletionEnabled()) 14771 DiagnoseInvalidJumps(Body); 14772 14773 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14774 if (!Destructor->getParent()->isDependentType()) 14775 CheckDestructor(Destructor); 14776 14777 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14778 Destructor->getParent()); 14779 } 14780 14781 // If any errors have occurred, clear out any temporaries that may have 14782 // been leftover. This ensures that these temporaries won't be picked up for 14783 // deletion in some later function. 14784 if (hasUncompilableErrorOccurred() || 14785 getDiagnostics().getSuppressAllDiagnostics()) { 14786 DiscardCleanupsInEvaluationContext(); 14787 } 14788 if (!hasUncompilableErrorOccurred() && 14789 !isa<FunctionTemplateDecl>(dcl)) { 14790 // Since the body is valid, issue any analysis-based warnings that are 14791 // enabled. 14792 ActivePolicy = &WP; 14793 } 14794 14795 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14796 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14797 FD->setInvalidDecl(); 14798 14799 if (FD && FD->hasAttr<NakedAttr>()) { 14800 for (const Stmt *S : Body->children()) { 14801 // Allow local register variables without initializer as they don't 14802 // require prologue. 14803 bool RegisterVariables = false; 14804 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14805 for (const auto *Decl : DS->decls()) { 14806 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14807 RegisterVariables = 14808 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14809 if (!RegisterVariables) 14810 break; 14811 } 14812 } 14813 } 14814 if (RegisterVariables) 14815 continue; 14816 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14817 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14818 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14819 FD->setInvalidDecl(); 14820 break; 14821 } 14822 } 14823 } 14824 14825 assert(ExprCleanupObjects.size() == 14826 ExprEvalContexts.back().NumCleanupObjects && 14827 "Leftover temporaries in function"); 14828 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14829 assert(MaybeODRUseExprs.empty() && 14830 "Leftover expressions for odr-use checking"); 14831 } 14832 14833 if (!IsInstantiation) 14834 PopDeclContext(); 14835 14836 PopFunctionScopeInfo(ActivePolicy, dcl); 14837 // If any errors have occurred, clear out any temporaries that may have 14838 // been leftover. This ensures that these temporaries won't be picked up for 14839 // deletion in some later function. 14840 if (hasUncompilableErrorOccurred()) { 14841 DiscardCleanupsInEvaluationContext(); 14842 } 14843 14844 if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 14845 auto ES = getEmissionStatus(FD); 14846 if (ES == Sema::FunctionEmissionStatus::Emitted || 14847 ES == Sema::FunctionEmissionStatus::Unknown) 14848 DeclsToCheckForDeferredDiags.insert(FD); 14849 } 14850 14851 return dcl; 14852 } 14853 14854 /// When we finish delayed parsing of an attribute, we must attach it to the 14855 /// relevant Decl. 14856 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14857 ParsedAttributes &Attrs) { 14858 // Always attach attributes to the underlying decl. 14859 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14860 D = TD->getTemplatedDecl(); 14861 ProcessDeclAttributeList(S, D, Attrs); 14862 14863 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14864 if (Method->isStatic()) 14865 checkThisInStaticMemberFunctionAttributes(Method); 14866 } 14867 14868 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14869 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14870 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14871 IdentifierInfo &II, Scope *S) { 14872 // Find the scope in which the identifier is injected and the corresponding 14873 // DeclContext. 14874 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14875 // In that case, we inject the declaration into the translation unit scope 14876 // instead. 14877 Scope *BlockScope = S; 14878 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14879 BlockScope = BlockScope->getParent(); 14880 14881 Scope *ContextScope = BlockScope; 14882 while (!ContextScope->getEntity()) 14883 ContextScope = ContextScope->getParent(); 14884 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14885 14886 // Before we produce a declaration for an implicitly defined 14887 // function, see whether there was a locally-scoped declaration of 14888 // this name as a function or variable. If so, use that 14889 // (non-visible) declaration, and complain about it. 14890 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14891 if (ExternCPrev) { 14892 // We still need to inject the function into the enclosing block scope so 14893 // that later (non-call) uses can see it. 14894 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14895 14896 // C89 footnote 38: 14897 // If in fact it is not defined as having type "function returning int", 14898 // the behavior is undefined. 14899 if (!isa<FunctionDecl>(ExternCPrev) || 14900 !Context.typesAreCompatible( 14901 cast<FunctionDecl>(ExternCPrev)->getType(), 14902 Context.getFunctionNoProtoType(Context.IntTy))) { 14903 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14904 << ExternCPrev << !getLangOpts().C99; 14905 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14906 return ExternCPrev; 14907 } 14908 } 14909 14910 // Extension in C99. Legal in C90, but warn about it. 14911 unsigned diag_id; 14912 if (II.getName().startswith("__builtin_")) 14913 diag_id = diag::warn_builtin_unknown; 14914 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14915 else if (getLangOpts().OpenCL) 14916 diag_id = diag::err_opencl_implicit_function_decl; 14917 else if (getLangOpts().C99) 14918 diag_id = diag::ext_implicit_function_decl; 14919 else 14920 diag_id = diag::warn_implicit_function_decl; 14921 Diag(Loc, diag_id) << &II; 14922 14923 // If we found a prior declaration of this function, don't bother building 14924 // another one. We've already pushed that one into scope, so there's nothing 14925 // more to do. 14926 if (ExternCPrev) 14927 return ExternCPrev; 14928 14929 // Because typo correction is expensive, only do it if the implicit 14930 // function declaration is going to be treated as an error. 14931 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14932 TypoCorrection Corrected; 14933 DeclFilterCCC<FunctionDecl> CCC{}; 14934 if (S && (Corrected = 14935 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14936 S, nullptr, CCC, CTK_NonError))) 14937 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14938 /*ErrorRecovery*/false); 14939 } 14940 14941 // Set a Declarator for the implicit definition: int foo(); 14942 const char *Dummy; 14943 AttributeFactory attrFactory; 14944 DeclSpec DS(attrFactory); 14945 unsigned DiagID; 14946 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14947 Context.getPrintingPolicy()); 14948 (void)Error; // Silence warning. 14949 assert(!Error && "Error setting up implicit decl!"); 14950 SourceLocation NoLoc; 14951 Declarator D(DS, DeclaratorContext::Block); 14952 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14953 /*IsAmbiguous=*/false, 14954 /*LParenLoc=*/NoLoc, 14955 /*Params=*/nullptr, 14956 /*NumParams=*/0, 14957 /*EllipsisLoc=*/NoLoc, 14958 /*RParenLoc=*/NoLoc, 14959 /*RefQualifierIsLvalueRef=*/true, 14960 /*RefQualifierLoc=*/NoLoc, 14961 /*MutableLoc=*/NoLoc, EST_None, 14962 /*ESpecRange=*/SourceRange(), 14963 /*Exceptions=*/nullptr, 14964 /*ExceptionRanges=*/nullptr, 14965 /*NumExceptions=*/0, 14966 /*NoexceptExpr=*/nullptr, 14967 /*ExceptionSpecTokens=*/nullptr, 14968 /*DeclsInPrototype=*/None, Loc, 14969 Loc, D), 14970 std::move(DS.getAttributes()), SourceLocation()); 14971 D.SetIdentifier(&II, Loc); 14972 14973 // Insert this function into the enclosing block scope. 14974 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14975 FD->setImplicit(); 14976 14977 AddKnownFunctionAttributes(FD); 14978 14979 return FD; 14980 } 14981 14982 /// If this function is a C++ replaceable global allocation function 14983 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14984 /// adds any function attributes that we know a priori based on the standard. 14985 /// 14986 /// We need to check for duplicate attributes both here and where user-written 14987 /// attributes are applied to declarations. 14988 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14989 FunctionDecl *FD) { 14990 if (FD->isInvalidDecl()) 14991 return; 14992 14993 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14994 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14995 return; 14996 14997 Optional<unsigned> AlignmentParam; 14998 bool IsNothrow = false; 14999 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 15000 return; 15001 15002 // C++2a [basic.stc.dynamic.allocation]p4: 15003 // An allocation function that has a non-throwing exception specification 15004 // indicates failure by returning a null pointer value. Any other allocation 15005 // function never returns a null pointer value and indicates failure only by 15006 // throwing an exception [...] 15007 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 15008 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 15009 15010 // C++2a [basic.stc.dynamic.allocation]p2: 15011 // An allocation function attempts to allocate the requested amount of 15012 // storage. [...] If the request succeeds, the value returned by a 15013 // replaceable allocation function is a [...] pointer value p0 different 15014 // from any previously returned value p1 [...] 15015 // 15016 // However, this particular information is being added in codegen, 15017 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 15018 15019 // C++2a [basic.stc.dynamic.allocation]p2: 15020 // An allocation function attempts to allocate the requested amount of 15021 // storage. If it is successful, it returns the address of the start of a 15022 // block of storage whose length in bytes is at least as large as the 15023 // requested size. 15024 if (!FD->hasAttr<AllocSizeAttr>()) { 15025 FD->addAttr(AllocSizeAttr::CreateImplicit( 15026 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 15027 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 15028 } 15029 15030 // C++2a [basic.stc.dynamic.allocation]p3: 15031 // For an allocation function [...], the pointer returned on a successful 15032 // call shall represent the address of storage that is aligned as follows: 15033 // (3.1) If the allocation function takes an argument of type 15034 // std::align_val_t, the storage will have the alignment 15035 // specified by the value of this argument. 15036 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 15037 FD->addAttr(AllocAlignAttr::CreateImplicit( 15038 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 15039 } 15040 15041 // FIXME: 15042 // C++2a [basic.stc.dynamic.allocation]p3: 15043 // For an allocation function [...], the pointer returned on a successful 15044 // call shall represent the address of storage that is aligned as follows: 15045 // (3.2) Otherwise, if the allocation function is named operator new[], 15046 // the storage is aligned for any object that does not have 15047 // new-extended alignment ([basic.align]) and is no larger than the 15048 // requested size. 15049 // (3.3) Otherwise, the storage is aligned for any object that does not 15050 // have new-extended alignment and is of the requested size. 15051 } 15052 15053 /// Adds any function attributes that we know a priori based on 15054 /// the declaration of this function. 15055 /// 15056 /// These attributes can apply both to implicitly-declared builtins 15057 /// (like __builtin___printf_chk) or to library-declared functions 15058 /// like NSLog or printf. 15059 /// 15060 /// We need to check for duplicate attributes both here and where user-written 15061 /// attributes are applied to declarations. 15062 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 15063 if (FD->isInvalidDecl()) 15064 return; 15065 15066 // If this is a built-in function, map its builtin attributes to 15067 // actual attributes. 15068 if (unsigned BuiltinID = FD->getBuiltinID()) { 15069 // Handle printf-formatting attributes. 15070 unsigned FormatIdx; 15071 bool HasVAListArg; 15072 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 15073 if (!FD->hasAttr<FormatAttr>()) { 15074 const char *fmt = "printf"; 15075 unsigned int NumParams = FD->getNumParams(); 15076 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 15077 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 15078 fmt = "NSString"; 15079 FD->addAttr(FormatAttr::CreateImplicit(Context, 15080 &Context.Idents.get(fmt), 15081 FormatIdx+1, 15082 HasVAListArg ? 0 : FormatIdx+2, 15083 FD->getLocation())); 15084 } 15085 } 15086 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 15087 HasVAListArg)) { 15088 if (!FD->hasAttr<FormatAttr>()) 15089 FD->addAttr(FormatAttr::CreateImplicit(Context, 15090 &Context.Idents.get("scanf"), 15091 FormatIdx+1, 15092 HasVAListArg ? 0 : FormatIdx+2, 15093 FD->getLocation())); 15094 } 15095 15096 // Handle automatically recognized callbacks. 15097 SmallVector<int, 4> Encoding; 15098 if (!FD->hasAttr<CallbackAttr>() && 15099 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 15100 FD->addAttr(CallbackAttr::CreateImplicit( 15101 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 15102 15103 // Mark const if we don't care about errno and that is the only thing 15104 // preventing the function from being const. This allows IRgen to use LLVM 15105 // intrinsics for such functions. 15106 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 15107 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 15108 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15109 15110 // We make "fma" on some platforms const because we know it does not set 15111 // errno in those environments even though it could set errno based on the 15112 // C standard. 15113 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 15114 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 15115 !FD->hasAttr<ConstAttr>()) { 15116 switch (BuiltinID) { 15117 case Builtin::BI__builtin_fma: 15118 case Builtin::BI__builtin_fmaf: 15119 case Builtin::BI__builtin_fmal: 15120 case Builtin::BIfma: 15121 case Builtin::BIfmaf: 15122 case Builtin::BIfmal: 15123 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15124 break; 15125 default: 15126 break; 15127 } 15128 } 15129 15130 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 15131 !FD->hasAttr<ReturnsTwiceAttr>()) 15132 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 15133 FD->getLocation())); 15134 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 15135 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15136 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 15137 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 15138 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 15139 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15140 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 15141 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 15142 // Add the appropriate attribute, depending on the CUDA compilation mode 15143 // and which target the builtin belongs to. For example, during host 15144 // compilation, aux builtins are __device__, while the rest are __host__. 15145 if (getLangOpts().CUDAIsDevice != 15146 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 15147 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 15148 else 15149 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 15150 } 15151 15152 // Add known guaranteed alignment for allocation functions. 15153 switch (BuiltinID) { 15154 case Builtin::BIaligned_alloc: 15155 if (!FD->hasAttr<AllocAlignAttr>()) 15156 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD), 15157 FD->getLocation())); 15158 LLVM_FALLTHROUGH; 15159 case Builtin::BIcalloc: 15160 case Builtin::BImalloc: 15161 case Builtin::BImemalign: 15162 case Builtin::BIrealloc: 15163 case Builtin::BIstrdup: 15164 case Builtin::BIstrndup: { 15165 if (!FD->hasAttr<AssumeAlignedAttr>()) { 15166 unsigned NewAlign = Context.getTargetInfo().getNewAlign() / 15167 Context.getTargetInfo().getCharWidth(); 15168 IntegerLiteral *Alignment = IntegerLiteral::Create( 15169 Context, Context.MakeIntValue(NewAlign, Context.UnsignedIntTy), 15170 Context.UnsignedIntTy, FD->getLocation()); 15171 FD->addAttr(AssumeAlignedAttr::CreateImplicit( 15172 Context, Alignment, /*Offset=*/nullptr, FD->getLocation())); 15173 } 15174 break; 15175 } 15176 default: 15177 break; 15178 } 15179 } 15180 15181 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 15182 15183 // If C++ exceptions are enabled but we are told extern "C" functions cannot 15184 // throw, add an implicit nothrow attribute to any extern "C" function we come 15185 // across. 15186 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 15187 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 15188 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 15189 if (!FPT || FPT->getExceptionSpecType() == EST_None) 15190 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15191 } 15192 15193 IdentifierInfo *Name = FD->getIdentifier(); 15194 if (!Name) 15195 return; 15196 if ((!getLangOpts().CPlusPlus && 15197 FD->getDeclContext()->isTranslationUnit()) || 15198 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 15199 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 15200 LinkageSpecDecl::lang_c)) { 15201 // Okay: this could be a libc/libm/Objective-C function we know 15202 // about. 15203 } else 15204 return; 15205 15206 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 15207 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 15208 // target-specific builtins, perhaps? 15209 if (!FD->hasAttr<FormatAttr>()) 15210 FD->addAttr(FormatAttr::CreateImplicit(Context, 15211 &Context.Idents.get("printf"), 2, 15212 Name->isStr("vasprintf") ? 0 : 3, 15213 FD->getLocation())); 15214 } 15215 15216 if (Name->isStr("__CFStringMakeConstantString")) { 15217 // We already have a __builtin___CFStringMakeConstantString, 15218 // but builds that use -fno-constant-cfstrings don't go through that. 15219 if (!FD->hasAttr<FormatArgAttr>()) 15220 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 15221 FD->getLocation())); 15222 } 15223 } 15224 15225 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15226 TypeSourceInfo *TInfo) { 15227 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 15228 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15229 15230 if (!TInfo) { 15231 assert(D.isInvalidType() && "no declarator info for valid type"); 15232 TInfo = Context.getTrivialTypeSourceInfo(T); 15233 } 15234 15235 // Scope manipulation handled by caller. 15236 TypedefDecl *NewTD = 15237 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15238 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15239 15240 // Bail out immediately if we have an invalid declaration. 15241 if (D.isInvalidType()) { 15242 NewTD->setInvalidDecl(); 15243 return NewTD; 15244 } 15245 15246 if (D.getDeclSpec().isModulePrivateSpecified()) { 15247 if (CurContext->isFunctionOrMethod()) 15248 Diag(NewTD->getLocation(), diag::err_module_private_local) 15249 << 2 << NewTD 15250 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15251 << FixItHint::CreateRemoval( 15252 D.getDeclSpec().getModulePrivateSpecLoc()); 15253 else 15254 NewTD->setModulePrivate(); 15255 } 15256 15257 // C++ [dcl.typedef]p8: 15258 // If the typedef declaration defines an unnamed class (or 15259 // enum), the first typedef-name declared by the declaration 15260 // to be that class type (or enum type) is used to denote the 15261 // class type (or enum type) for linkage purposes only. 15262 // We need to check whether the type was declared in the declaration. 15263 switch (D.getDeclSpec().getTypeSpecType()) { 15264 case TST_enum: 15265 case TST_struct: 15266 case TST_interface: 15267 case TST_union: 15268 case TST_class: { 15269 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15270 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15271 break; 15272 } 15273 15274 default: 15275 break; 15276 } 15277 15278 return NewTD; 15279 } 15280 15281 /// Check that this is a valid underlying type for an enum declaration. 15282 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15283 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15284 QualType T = TI->getType(); 15285 15286 if (T->isDependentType()) 15287 return false; 15288 15289 // This doesn't use 'isIntegralType' despite the error message mentioning 15290 // integral type because isIntegralType would also allow enum types in C. 15291 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15292 if (BT->isInteger()) 15293 return false; 15294 15295 if (T->isExtIntType()) 15296 return false; 15297 15298 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15299 } 15300 15301 /// Check whether this is a valid redeclaration of a previous enumeration. 15302 /// \return true if the redeclaration was invalid. 15303 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15304 QualType EnumUnderlyingTy, bool IsFixed, 15305 const EnumDecl *Prev) { 15306 if (IsScoped != Prev->isScoped()) { 15307 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15308 << Prev->isScoped(); 15309 Diag(Prev->getLocation(), diag::note_previous_declaration); 15310 return true; 15311 } 15312 15313 if (IsFixed && Prev->isFixed()) { 15314 if (!EnumUnderlyingTy->isDependentType() && 15315 !Prev->getIntegerType()->isDependentType() && 15316 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15317 Prev->getIntegerType())) { 15318 // TODO: Highlight the underlying type of the redeclaration. 15319 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15320 << EnumUnderlyingTy << Prev->getIntegerType(); 15321 Diag(Prev->getLocation(), diag::note_previous_declaration) 15322 << Prev->getIntegerTypeRange(); 15323 return true; 15324 } 15325 } else if (IsFixed != Prev->isFixed()) { 15326 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15327 << Prev->isFixed(); 15328 Diag(Prev->getLocation(), diag::note_previous_declaration); 15329 return true; 15330 } 15331 15332 return false; 15333 } 15334 15335 /// Get diagnostic %select index for tag kind for 15336 /// redeclaration diagnostic message. 15337 /// WARNING: Indexes apply to particular diagnostics only! 15338 /// 15339 /// \returns diagnostic %select index. 15340 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15341 switch (Tag) { 15342 case TTK_Struct: return 0; 15343 case TTK_Interface: return 1; 15344 case TTK_Class: return 2; 15345 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15346 } 15347 } 15348 15349 /// Determine if tag kind is a class-key compatible with 15350 /// class for redeclaration (class, struct, or __interface). 15351 /// 15352 /// \returns true iff the tag kind is compatible. 15353 static bool isClassCompatTagKind(TagTypeKind Tag) 15354 { 15355 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15356 } 15357 15358 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15359 TagTypeKind TTK) { 15360 if (isa<TypedefDecl>(PrevDecl)) 15361 return NTK_Typedef; 15362 else if (isa<TypeAliasDecl>(PrevDecl)) 15363 return NTK_TypeAlias; 15364 else if (isa<ClassTemplateDecl>(PrevDecl)) 15365 return NTK_Template; 15366 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15367 return NTK_TypeAliasTemplate; 15368 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15369 return NTK_TemplateTemplateArgument; 15370 switch (TTK) { 15371 case TTK_Struct: 15372 case TTK_Interface: 15373 case TTK_Class: 15374 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15375 case TTK_Union: 15376 return NTK_NonUnion; 15377 case TTK_Enum: 15378 return NTK_NonEnum; 15379 } 15380 llvm_unreachable("invalid TTK"); 15381 } 15382 15383 /// Determine whether a tag with a given kind is acceptable 15384 /// as a redeclaration of the given tag declaration. 15385 /// 15386 /// \returns true if the new tag kind is acceptable, false otherwise. 15387 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15388 TagTypeKind NewTag, bool isDefinition, 15389 SourceLocation NewTagLoc, 15390 const IdentifierInfo *Name) { 15391 // C++ [dcl.type.elab]p3: 15392 // The class-key or enum keyword present in the 15393 // elaborated-type-specifier shall agree in kind with the 15394 // declaration to which the name in the elaborated-type-specifier 15395 // refers. This rule also applies to the form of 15396 // elaborated-type-specifier that declares a class-name or 15397 // friend class since it can be construed as referring to the 15398 // definition of the class. Thus, in any 15399 // elaborated-type-specifier, the enum keyword shall be used to 15400 // refer to an enumeration (7.2), the union class-key shall be 15401 // used to refer to a union (clause 9), and either the class or 15402 // struct class-key shall be used to refer to a class (clause 9) 15403 // declared using the class or struct class-key. 15404 TagTypeKind OldTag = Previous->getTagKind(); 15405 if (OldTag != NewTag && 15406 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15407 return false; 15408 15409 // Tags are compatible, but we might still want to warn on mismatched tags. 15410 // Non-class tags can't be mismatched at this point. 15411 if (!isClassCompatTagKind(NewTag)) 15412 return true; 15413 15414 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15415 // by our warning analysis. We don't want to warn about mismatches with (eg) 15416 // declarations in system headers that are designed to be specialized, but if 15417 // a user asks us to warn, we should warn if their code contains mismatched 15418 // declarations. 15419 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15420 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15421 Loc); 15422 }; 15423 if (IsIgnoredLoc(NewTagLoc)) 15424 return true; 15425 15426 auto IsIgnored = [&](const TagDecl *Tag) { 15427 return IsIgnoredLoc(Tag->getLocation()); 15428 }; 15429 while (IsIgnored(Previous)) { 15430 Previous = Previous->getPreviousDecl(); 15431 if (!Previous) 15432 return true; 15433 OldTag = Previous->getTagKind(); 15434 } 15435 15436 bool isTemplate = false; 15437 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15438 isTemplate = Record->getDescribedClassTemplate(); 15439 15440 if (inTemplateInstantiation()) { 15441 if (OldTag != NewTag) { 15442 // In a template instantiation, do not offer fix-its for tag mismatches 15443 // since they usually mess up the template instead of fixing the problem. 15444 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15445 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15446 << getRedeclDiagFromTagKind(OldTag); 15447 // FIXME: Note previous location? 15448 } 15449 return true; 15450 } 15451 15452 if (isDefinition) { 15453 // On definitions, check all previous tags and issue a fix-it for each 15454 // one that doesn't match the current tag. 15455 if (Previous->getDefinition()) { 15456 // Don't suggest fix-its for redefinitions. 15457 return true; 15458 } 15459 15460 bool previousMismatch = false; 15461 for (const TagDecl *I : Previous->redecls()) { 15462 if (I->getTagKind() != NewTag) { 15463 // Ignore previous declarations for which the warning was disabled. 15464 if (IsIgnored(I)) 15465 continue; 15466 15467 if (!previousMismatch) { 15468 previousMismatch = true; 15469 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15470 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15471 << getRedeclDiagFromTagKind(I->getTagKind()); 15472 } 15473 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15474 << getRedeclDiagFromTagKind(NewTag) 15475 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15476 TypeWithKeyword::getTagTypeKindName(NewTag)); 15477 } 15478 } 15479 return true; 15480 } 15481 15482 // Identify the prevailing tag kind: this is the kind of the definition (if 15483 // there is a non-ignored definition), or otherwise the kind of the prior 15484 // (non-ignored) declaration. 15485 const TagDecl *PrevDef = Previous->getDefinition(); 15486 if (PrevDef && IsIgnored(PrevDef)) 15487 PrevDef = nullptr; 15488 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15489 if (Redecl->getTagKind() != NewTag) { 15490 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15491 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15492 << getRedeclDiagFromTagKind(OldTag); 15493 Diag(Redecl->getLocation(), diag::note_previous_use); 15494 15495 // If there is a previous definition, suggest a fix-it. 15496 if (PrevDef) { 15497 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15498 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15499 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15500 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15501 } 15502 } 15503 15504 return true; 15505 } 15506 15507 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15508 /// from an outer enclosing namespace or file scope inside a friend declaration. 15509 /// This should provide the commented out code in the following snippet: 15510 /// namespace N { 15511 /// struct X; 15512 /// namespace M { 15513 /// struct Y { friend struct /*N::*/ X; }; 15514 /// } 15515 /// } 15516 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15517 SourceLocation NameLoc) { 15518 // While the decl is in a namespace, do repeated lookup of that name and see 15519 // if we get the same namespace back. If we do not, continue until 15520 // translation unit scope, at which point we have a fully qualified NNS. 15521 SmallVector<IdentifierInfo *, 4> Namespaces; 15522 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15523 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15524 // This tag should be declared in a namespace, which can only be enclosed by 15525 // other namespaces. Bail if there's an anonymous namespace in the chain. 15526 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15527 if (!Namespace || Namespace->isAnonymousNamespace()) 15528 return FixItHint(); 15529 IdentifierInfo *II = Namespace->getIdentifier(); 15530 Namespaces.push_back(II); 15531 NamedDecl *Lookup = SemaRef.LookupSingleName( 15532 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15533 if (Lookup == Namespace) 15534 break; 15535 } 15536 15537 // Once we have all the namespaces, reverse them to go outermost first, and 15538 // build an NNS. 15539 SmallString<64> Insertion; 15540 llvm::raw_svector_ostream OS(Insertion); 15541 if (DC->isTranslationUnit()) 15542 OS << "::"; 15543 std::reverse(Namespaces.begin(), Namespaces.end()); 15544 for (auto *II : Namespaces) 15545 OS << II->getName() << "::"; 15546 return FixItHint::CreateInsertion(NameLoc, Insertion); 15547 } 15548 15549 /// Determine whether a tag originally declared in context \p OldDC can 15550 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15551 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15552 /// using-declaration). 15553 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15554 DeclContext *NewDC) { 15555 OldDC = OldDC->getRedeclContext(); 15556 NewDC = NewDC->getRedeclContext(); 15557 15558 if (OldDC->Equals(NewDC)) 15559 return true; 15560 15561 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15562 // encloses the other). 15563 if (S.getLangOpts().MSVCCompat && 15564 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15565 return true; 15566 15567 return false; 15568 } 15569 15570 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15571 /// former case, Name will be non-null. In the later case, Name will be null. 15572 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15573 /// reference/declaration/definition of a tag. 15574 /// 15575 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15576 /// trailing-type-specifier) other than one in an alias-declaration. 15577 /// 15578 /// \param SkipBody If non-null, will be set to indicate if the caller should 15579 /// skip the definition of this tag and treat it as if it were a declaration. 15580 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15581 SourceLocation KWLoc, CXXScopeSpec &SS, 15582 IdentifierInfo *Name, SourceLocation NameLoc, 15583 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15584 SourceLocation ModulePrivateLoc, 15585 MultiTemplateParamsArg TemplateParameterLists, 15586 bool &OwnedDecl, bool &IsDependent, 15587 SourceLocation ScopedEnumKWLoc, 15588 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15589 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15590 SkipBodyInfo *SkipBody) { 15591 // If this is not a definition, it must have a name. 15592 IdentifierInfo *OrigName = Name; 15593 assert((Name != nullptr || TUK == TUK_Definition) && 15594 "Nameless record must be a definition!"); 15595 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15596 15597 OwnedDecl = false; 15598 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15599 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15600 15601 // FIXME: Check member specializations more carefully. 15602 bool isMemberSpecialization = false; 15603 bool Invalid = false; 15604 15605 // We only need to do this matching if we have template parameters 15606 // or a scope specifier, which also conveniently avoids this work 15607 // for non-C++ cases. 15608 if (TemplateParameterLists.size() > 0 || 15609 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15610 if (TemplateParameterList *TemplateParams = 15611 MatchTemplateParametersToScopeSpecifier( 15612 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15613 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15614 if (Kind == TTK_Enum) { 15615 Diag(KWLoc, diag::err_enum_template); 15616 return nullptr; 15617 } 15618 15619 if (TemplateParams->size() > 0) { 15620 // This is a declaration or definition of a class template (which may 15621 // be a member of another template). 15622 15623 if (Invalid) 15624 return nullptr; 15625 15626 OwnedDecl = false; 15627 DeclResult Result = CheckClassTemplate( 15628 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15629 AS, ModulePrivateLoc, 15630 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15631 TemplateParameterLists.data(), SkipBody); 15632 return Result.get(); 15633 } else { 15634 // The "template<>" header is extraneous. 15635 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15636 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15637 isMemberSpecialization = true; 15638 } 15639 } 15640 15641 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15642 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15643 return nullptr; 15644 } 15645 15646 // Figure out the underlying type if this a enum declaration. We need to do 15647 // this early, because it's needed to detect if this is an incompatible 15648 // redeclaration. 15649 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15650 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15651 15652 if (Kind == TTK_Enum) { 15653 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15654 // No underlying type explicitly specified, or we failed to parse the 15655 // type, default to int. 15656 EnumUnderlying = Context.IntTy.getTypePtr(); 15657 } else if (UnderlyingType.get()) { 15658 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15659 // integral type; any cv-qualification is ignored. 15660 TypeSourceInfo *TI = nullptr; 15661 GetTypeFromParser(UnderlyingType.get(), &TI); 15662 EnumUnderlying = TI; 15663 15664 if (CheckEnumUnderlyingType(TI)) 15665 // Recover by falling back to int. 15666 EnumUnderlying = Context.IntTy.getTypePtr(); 15667 15668 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15669 UPPC_FixedUnderlyingType)) 15670 EnumUnderlying = Context.IntTy.getTypePtr(); 15671 15672 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15673 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15674 // of 'int'. However, if this is an unfixed forward declaration, don't set 15675 // the underlying type unless the user enables -fms-compatibility. This 15676 // makes unfixed forward declared enums incomplete and is more conforming. 15677 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15678 EnumUnderlying = Context.IntTy.getTypePtr(); 15679 } 15680 } 15681 15682 DeclContext *SearchDC = CurContext; 15683 DeclContext *DC = CurContext; 15684 bool isStdBadAlloc = false; 15685 bool isStdAlignValT = false; 15686 15687 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15688 if (TUK == TUK_Friend || TUK == TUK_Reference) 15689 Redecl = NotForRedeclaration; 15690 15691 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15692 /// implemented asks for structural equivalence checking, the returned decl 15693 /// here is passed back to the parser, allowing the tag body to be parsed. 15694 auto createTagFromNewDecl = [&]() -> TagDecl * { 15695 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15696 // If there is an identifier, use the location of the identifier as the 15697 // location of the decl, otherwise use the location of the struct/union 15698 // keyword. 15699 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15700 TagDecl *New = nullptr; 15701 15702 if (Kind == TTK_Enum) { 15703 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15704 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15705 // If this is an undefined enum, bail. 15706 if (TUK != TUK_Definition && !Invalid) 15707 return nullptr; 15708 if (EnumUnderlying) { 15709 EnumDecl *ED = cast<EnumDecl>(New); 15710 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15711 ED->setIntegerTypeSourceInfo(TI); 15712 else 15713 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15714 ED->setPromotionType(ED->getIntegerType()); 15715 } 15716 } else { // struct/union 15717 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15718 nullptr); 15719 } 15720 15721 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15722 // Add alignment attributes if necessary; these attributes are checked 15723 // when the ASTContext lays out the structure. 15724 // 15725 // It is important for implementing the correct semantics that this 15726 // happen here (in ActOnTag). The #pragma pack stack is 15727 // maintained as a result of parser callbacks which can occur at 15728 // many points during the parsing of a struct declaration (because 15729 // the #pragma tokens are effectively skipped over during the 15730 // parsing of the struct). 15731 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15732 AddAlignmentAttributesForRecord(RD); 15733 AddMsStructLayoutForRecord(RD); 15734 } 15735 } 15736 New->setLexicalDeclContext(CurContext); 15737 return New; 15738 }; 15739 15740 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15741 if (Name && SS.isNotEmpty()) { 15742 // We have a nested-name tag ('struct foo::bar'). 15743 15744 // Check for invalid 'foo::'. 15745 if (SS.isInvalid()) { 15746 Name = nullptr; 15747 goto CreateNewDecl; 15748 } 15749 15750 // If this is a friend or a reference to a class in a dependent 15751 // context, don't try to make a decl for it. 15752 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15753 DC = computeDeclContext(SS, false); 15754 if (!DC) { 15755 IsDependent = true; 15756 return nullptr; 15757 } 15758 } else { 15759 DC = computeDeclContext(SS, true); 15760 if (!DC) { 15761 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15762 << SS.getRange(); 15763 return nullptr; 15764 } 15765 } 15766 15767 if (RequireCompleteDeclContext(SS, DC)) 15768 return nullptr; 15769 15770 SearchDC = DC; 15771 // Look-up name inside 'foo::'. 15772 LookupQualifiedName(Previous, DC); 15773 15774 if (Previous.isAmbiguous()) 15775 return nullptr; 15776 15777 if (Previous.empty()) { 15778 // Name lookup did not find anything. However, if the 15779 // nested-name-specifier refers to the current instantiation, 15780 // and that current instantiation has any dependent base 15781 // classes, we might find something at instantiation time: treat 15782 // this as a dependent elaborated-type-specifier. 15783 // But this only makes any sense for reference-like lookups. 15784 if (Previous.wasNotFoundInCurrentInstantiation() && 15785 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15786 IsDependent = true; 15787 return nullptr; 15788 } 15789 15790 // A tag 'foo::bar' must already exist. 15791 Diag(NameLoc, diag::err_not_tag_in_scope) 15792 << Kind << Name << DC << SS.getRange(); 15793 Name = nullptr; 15794 Invalid = true; 15795 goto CreateNewDecl; 15796 } 15797 } else if (Name) { 15798 // C++14 [class.mem]p14: 15799 // If T is the name of a class, then each of the following shall have a 15800 // name different from T: 15801 // -- every member of class T that is itself a type 15802 if (TUK != TUK_Reference && TUK != TUK_Friend && 15803 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15804 return nullptr; 15805 15806 // If this is a named struct, check to see if there was a previous forward 15807 // declaration or definition. 15808 // FIXME: We're looking into outer scopes here, even when we 15809 // shouldn't be. Doing so can result in ambiguities that we 15810 // shouldn't be diagnosing. 15811 LookupName(Previous, S); 15812 15813 // When declaring or defining a tag, ignore ambiguities introduced 15814 // by types using'ed into this scope. 15815 if (Previous.isAmbiguous() && 15816 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15817 LookupResult::Filter F = Previous.makeFilter(); 15818 while (F.hasNext()) { 15819 NamedDecl *ND = F.next(); 15820 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15821 SearchDC->getRedeclContext())) 15822 F.erase(); 15823 } 15824 F.done(); 15825 } 15826 15827 // C++11 [namespace.memdef]p3: 15828 // If the name in a friend declaration is neither qualified nor 15829 // a template-id and the declaration is a function or an 15830 // elaborated-type-specifier, the lookup to determine whether 15831 // the entity has been previously declared shall not consider 15832 // any scopes outside the innermost enclosing namespace. 15833 // 15834 // MSVC doesn't implement the above rule for types, so a friend tag 15835 // declaration may be a redeclaration of a type declared in an enclosing 15836 // scope. They do implement this rule for friend functions. 15837 // 15838 // Does it matter that this should be by scope instead of by 15839 // semantic context? 15840 if (!Previous.empty() && TUK == TUK_Friend) { 15841 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15842 LookupResult::Filter F = Previous.makeFilter(); 15843 bool FriendSawTagOutsideEnclosingNamespace = false; 15844 while (F.hasNext()) { 15845 NamedDecl *ND = F.next(); 15846 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15847 if (DC->isFileContext() && 15848 !EnclosingNS->Encloses(ND->getDeclContext())) { 15849 if (getLangOpts().MSVCCompat) 15850 FriendSawTagOutsideEnclosingNamespace = true; 15851 else 15852 F.erase(); 15853 } 15854 } 15855 F.done(); 15856 15857 // Diagnose this MSVC extension in the easy case where lookup would have 15858 // unambiguously found something outside the enclosing namespace. 15859 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15860 NamedDecl *ND = Previous.getFoundDecl(); 15861 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15862 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15863 } 15864 } 15865 15866 // Note: there used to be some attempt at recovery here. 15867 if (Previous.isAmbiguous()) 15868 return nullptr; 15869 15870 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15871 // FIXME: This makes sure that we ignore the contexts associated 15872 // with C structs, unions, and enums when looking for a matching 15873 // tag declaration or definition. See the similar lookup tweak 15874 // in Sema::LookupName; is there a better way to deal with this? 15875 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15876 SearchDC = SearchDC->getParent(); 15877 } 15878 } 15879 15880 if (Previous.isSingleResult() && 15881 Previous.getFoundDecl()->isTemplateParameter()) { 15882 // Maybe we will complain about the shadowed template parameter. 15883 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15884 // Just pretend that we didn't see the previous declaration. 15885 Previous.clear(); 15886 } 15887 15888 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15889 DC->Equals(getStdNamespace())) { 15890 if (Name->isStr("bad_alloc")) { 15891 // This is a declaration of or a reference to "std::bad_alloc". 15892 isStdBadAlloc = true; 15893 15894 // If std::bad_alloc has been implicitly declared (but made invisible to 15895 // name lookup), fill in this implicit declaration as the previous 15896 // declaration, so that the declarations get chained appropriately. 15897 if (Previous.empty() && StdBadAlloc) 15898 Previous.addDecl(getStdBadAlloc()); 15899 } else if (Name->isStr("align_val_t")) { 15900 isStdAlignValT = true; 15901 if (Previous.empty() && StdAlignValT) 15902 Previous.addDecl(getStdAlignValT()); 15903 } 15904 } 15905 15906 // If we didn't find a previous declaration, and this is a reference 15907 // (or friend reference), move to the correct scope. In C++, we 15908 // also need to do a redeclaration lookup there, just in case 15909 // there's a shadow friend decl. 15910 if (Name && Previous.empty() && 15911 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15912 if (Invalid) goto CreateNewDecl; 15913 assert(SS.isEmpty()); 15914 15915 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15916 // C++ [basic.scope.pdecl]p5: 15917 // -- for an elaborated-type-specifier of the form 15918 // 15919 // class-key identifier 15920 // 15921 // if the elaborated-type-specifier is used in the 15922 // decl-specifier-seq or parameter-declaration-clause of a 15923 // function defined in namespace scope, the identifier is 15924 // declared as a class-name in the namespace that contains 15925 // the declaration; otherwise, except as a friend 15926 // declaration, the identifier is declared in the smallest 15927 // non-class, non-function-prototype scope that contains the 15928 // declaration. 15929 // 15930 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15931 // C structs and unions. 15932 // 15933 // It is an error in C++ to declare (rather than define) an enum 15934 // type, including via an elaborated type specifier. We'll 15935 // diagnose that later; for now, declare the enum in the same 15936 // scope as we would have picked for any other tag type. 15937 // 15938 // GNU C also supports this behavior as part of its incomplete 15939 // enum types extension, while GNU C++ does not. 15940 // 15941 // Find the context where we'll be declaring the tag. 15942 // FIXME: We would like to maintain the current DeclContext as the 15943 // lexical context, 15944 SearchDC = getTagInjectionContext(SearchDC); 15945 15946 // Find the scope where we'll be declaring the tag. 15947 S = getTagInjectionScope(S, getLangOpts()); 15948 } else { 15949 assert(TUK == TUK_Friend); 15950 // C++ [namespace.memdef]p3: 15951 // If a friend declaration in a non-local class first declares a 15952 // class or function, the friend class or function is a member of 15953 // the innermost enclosing namespace. 15954 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15955 } 15956 15957 // In C++, we need to do a redeclaration lookup to properly 15958 // diagnose some problems. 15959 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15960 // hidden declaration so that we don't get ambiguity errors when using a 15961 // type declared by an elaborated-type-specifier. In C that is not correct 15962 // and we should instead merge compatible types found by lookup. 15963 if (getLangOpts().CPlusPlus) { 15964 // FIXME: This can perform qualified lookups into function contexts, 15965 // which are meaningless. 15966 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15967 LookupQualifiedName(Previous, SearchDC); 15968 } else { 15969 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15970 LookupName(Previous, S); 15971 } 15972 } 15973 15974 // If we have a known previous declaration to use, then use it. 15975 if (Previous.empty() && SkipBody && SkipBody->Previous) 15976 Previous.addDecl(SkipBody->Previous); 15977 15978 if (!Previous.empty()) { 15979 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15980 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15981 15982 // It's okay to have a tag decl in the same scope as a typedef 15983 // which hides a tag decl in the same scope. Finding this 15984 // insanity with a redeclaration lookup can only actually happen 15985 // in C++. 15986 // 15987 // This is also okay for elaborated-type-specifiers, which is 15988 // technically forbidden by the current standard but which is 15989 // okay according to the likely resolution of an open issue; 15990 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15991 if (getLangOpts().CPlusPlus) { 15992 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15993 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15994 TagDecl *Tag = TT->getDecl(); 15995 if (Tag->getDeclName() == Name && 15996 Tag->getDeclContext()->getRedeclContext() 15997 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15998 PrevDecl = Tag; 15999 Previous.clear(); 16000 Previous.addDecl(Tag); 16001 Previous.resolveKind(); 16002 } 16003 } 16004 } 16005 } 16006 16007 // If this is a redeclaration of a using shadow declaration, it must 16008 // declare a tag in the same context. In MSVC mode, we allow a 16009 // redefinition if either context is within the other. 16010 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 16011 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 16012 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 16013 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 16014 !(OldTag && isAcceptableTagRedeclContext( 16015 *this, OldTag->getDeclContext(), SearchDC))) { 16016 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 16017 Diag(Shadow->getTargetDecl()->getLocation(), 16018 diag::note_using_decl_target); 16019 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 16020 << 0; 16021 // Recover by ignoring the old declaration. 16022 Previous.clear(); 16023 goto CreateNewDecl; 16024 } 16025 } 16026 16027 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 16028 // If this is a use of a previous tag, or if the tag is already declared 16029 // in the same scope (so that the definition/declaration completes or 16030 // rementions the tag), reuse the decl. 16031 if (TUK == TUK_Reference || TUK == TUK_Friend || 16032 isDeclInScope(DirectPrevDecl, SearchDC, S, 16033 SS.isNotEmpty() || isMemberSpecialization)) { 16034 // Make sure that this wasn't declared as an enum and now used as a 16035 // struct or something similar. 16036 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 16037 TUK == TUK_Definition, KWLoc, 16038 Name)) { 16039 bool SafeToContinue 16040 = (PrevTagDecl->getTagKind() != TTK_Enum && 16041 Kind != TTK_Enum); 16042 if (SafeToContinue) 16043 Diag(KWLoc, diag::err_use_with_wrong_tag) 16044 << Name 16045 << FixItHint::CreateReplacement(SourceRange(KWLoc), 16046 PrevTagDecl->getKindName()); 16047 else 16048 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 16049 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 16050 16051 if (SafeToContinue) 16052 Kind = PrevTagDecl->getTagKind(); 16053 else { 16054 // Recover by making this an anonymous redefinition. 16055 Name = nullptr; 16056 Previous.clear(); 16057 Invalid = true; 16058 } 16059 } 16060 16061 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 16062 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 16063 if (TUK == TUK_Reference || TUK == TUK_Friend) 16064 return PrevTagDecl; 16065 16066 QualType EnumUnderlyingTy; 16067 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16068 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 16069 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 16070 EnumUnderlyingTy = QualType(T, 0); 16071 16072 // All conflicts with previous declarations are recovered by 16073 // returning the previous declaration, unless this is a definition, 16074 // in which case we want the caller to bail out. 16075 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 16076 ScopedEnum, EnumUnderlyingTy, 16077 IsFixed, PrevEnum)) 16078 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 16079 } 16080 16081 // C++11 [class.mem]p1: 16082 // A member shall not be declared twice in the member-specification, 16083 // except that a nested class or member class template can be declared 16084 // and then later defined. 16085 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 16086 S->isDeclScope(PrevDecl)) { 16087 Diag(NameLoc, diag::ext_member_redeclared); 16088 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 16089 } 16090 16091 if (!Invalid) { 16092 // If this is a use, just return the declaration we found, unless 16093 // we have attributes. 16094 if (TUK == TUK_Reference || TUK == TUK_Friend) { 16095 if (!Attrs.empty()) { 16096 // FIXME: Diagnose these attributes. For now, we create a new 16097 // declaration to hold them. 16098 } else if (TUK == TUK_Reference && 16099 (PrevTagDecl->getFriendObjectKind() == 16100 Decl::FOK_Undeclared || 16101 PrevDecl->getOwningModule() != getCurrentModule()) && 16102 SS.isEmpty()) { 16103 // This declaration is a reference to an existing entity, but 16104 // has different visibility from that entity: it either makes 16105 // a friend visible or it makes a type visible in a new module. 16106 // In either case, create a new declaration. We only do this if 16107 // the declaration would have meant the same thing if no prior 16108 // declaration were found, that is, if it was found in the same 16109 // scope where we would have injected a declaration. 16110 if (!getTagInjectionContext(CurContext)->getRedeclContext() 16111 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 16112 return PrevTagDecl; 16113 // This is in the injected scope, create a new declaration in 16114 // that scope. 16115 S = getTagInjectionScope(S, getLangOpts()); 16116 } else { 16117 return PrevTagDecl; 16118 } 16119 } 16120 16121 // Diagnose attempts to redefine a tag. 16122 if (TUK == TUK_Definition) { 16123 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 16124 // If we're defining a specialization and the previous definition 16125 // is from an implicit instantiation, don't emit an error 16126 // here; we'll catch this in the general case below. 16127 bool IsExplicitSpecializationAfterInstantiation = false; 16128 if (isMemberSpecialization) { 16129 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 16130 IsExplicitSpecializationAfterInstantiation = 16131 RD->getTemplateSpecializationKind() != 16132 TSK_ExplicitSpecialization; 16133 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 16134 IsExplicitSpecializationAfterInstantiation = 16135 ED->getTemplateSpecializationKind() != 16136 TSK_ExplicitSpecialization; 16137 } 16138 16139 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 16140 // not keep more that one definition around (merge them). However, 16141 // ensure the decl passes the structural compatibility check in 16142 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 16143 NamedDecl *Hidden = nullptr; 16144 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 16145 // There is a definition of this tag, but it is not visible. We 16146 // explicitly make use of C++'s one definition rule here, and 16147 // assume that this definition is identical to the hidden one 16148 // we already have. Make the existing definition visible and 16149 // use it in place of this one. 16150 if (!getLangOpts().CPlusPlus) { 16151 // Postpone making the old definition visible until after we 16152 // complete parsing the new one and do the structural 16153 // comparison. 16154 SkipBody->CheckSameAsPrevious = true; 16155 SkipBody->New = createTagFromNewDecl(); 16156 SkipBody->Previous = Def; 16157 return Def; 16158 } else { 16159 SkipBody->ShouldSkip = true; 16160 SkipBody->Previous = Def; 16161 makeMergedDefinitionVisible(Hidden); 16162 // Carry on and handle it like a normal definition. We'll 16163 // skip starting the definitiion later. 16164 } 16165 } else if (!IsExplicitSpecializationAfterInstantiation) { 16166 // A redeclaration in function prototype scope in C isn't 16167 // visible elsewhere, so merely issue a warning. 16168 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 16169 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 16170 else 16171 Diag(NameLoc, diag::err_redefinition) << Name; 16172 notePreviousDefinition(Def, 16173 NameLoc.isValid() ? NameLoc : KWLoc); 16174 // If this is a redefinition, recover by making this 16175 // struct be anonymous, which will make any later 16176 // references get the previous definition. 16177 Name = nullptr; 16178 Previous.clear(); 16179 Invalid = true; 16180 } 16181 } else { 16182 // If the type is currently being defined, complain 16183 // about a nested redefinition. 16184 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 16185 if (TD->isBeingDefined()) { 16186 Diag(NameLoc, diag::err_nested_redefinition) << Name; 16187 Diag(PrevTagDecl->getLocation(), 16188 diag::note_previous_definition); 16189 Name = nullptr; 16190 Previous.clear(); 16191 Invalid = true; 16192 } 16193 } 16194 16195 // Okay, this is definition of a previously declared or referenced 16196 // tag. We're going to create a new Decl for it. 16197 } 16198 16199 // Okay, we're going to make a redeclaration. If this is some kind 16200 // of reference, make sure we build the redeclaration in the same DC 16201 // as the original, and ignore the current access specifier. 16202 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16203 SearchDC = PrevTagDecl->getDeclContext(); 16204 AS = AS_none; 16205 } 16206 } 16207 // If we get here we have (another) forward declaration or we 16208 // have a definition. Just create a new decl. 16209 16210 } else { 16211 // If we get here, this is a definition of a new tag type in a nested 16212 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 16213 // new decl/type. We set PrevDecl to NULL so that the entities 16214 // have distinct types. 16215 Previous.clear(); 16216 } 16217 // If we get here, we're going to create a new Decl. If PrevDecl 16218 // is non-NULL, it's a definition of the tag declared by 16219 // PrevDecl. If it's NULL, we have a new definition. 16220 16221 // Otherwise, PrevDecl is not a tag, but was found with tag 16222 // lookup. This is only actually possible in C++, where a few 16223 // things like templates still live in the tag namespace. 16224 } else { 16225 // Use a better diagnostic if an elaborated-type-specifier 16226 // found the wrong kind of type on the first 16227 // (non-redeclaration) lookup. 16228 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16229 !Previous.isForRedeclaration()) { 16230 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16231 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16232 << Kind; 16233 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16234 Invalid = true; 16235 16236 // Otherwise, only diagnose if the declaration is in scope. 16237 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16238 SS.isNotEmpty() || isMemberSpecialization)) { 16239 // do nothing 16240 16241 // Diagnose implicit declarations introduced by elaborated types. 16242 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16243 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16244 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16245 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16246 Invalid = true; 16247 16248 // Otherwise it's a declaration. Call out a particularly common 16249 // case here. 16250 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16251 unsigned Kind = 0; 16252 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16253 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16254 << Name << Kind << TND->getUnderlyingType(); 16255 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16256 Invalid = true; 16257 16258 // Otherwise, diagnose. 16259 } else { 16260 // The tag name clashes with something else in the target scope, 16261 // issue an error and recover by making this tag be anonymous. 16262 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16263 notePreviousDefinition(PrevDecl, NameLoc); 16264 Name = nullptr; 16265 Invalid = true; 16266 } 16267 16268 // The existing declaration isn't relevant to us; we're in a 16269 // new scope, so clear out the previous declaration. 16270 Previous.clear(); 16271 } 16272 } 16273 16274 CreateNewDecl: 16275 16276 TagDecl *PrevDecl = nullptr; 16277 if (Previous.isSingleResult()) 16278 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16279 16280 // If there is an identifier, use the location of the identifier as the 16281 // location of the decl, otherwise use the location of the struct/union 16282 // keyword. 16283 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16284 16285 // Otherwise, create a new declaration. If there is a previous 16286 // declaration of the same entity, the two will be linked via 16287 // PrevDecl. 16288 TagDecl *New; 16289 16290 if (Kind == TTK_Enum) { 16291 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16292 // enum X { A, B, C } D; D should chain to X. 16293 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16294 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16295 ScopedEnumUsesClassTag, IsFixed); 16296 16297 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16298 StdAlignValT = cast<EnumDecl>(New); 16299 16300 // If this is an undefined enum, warn. 16301 if (TUK != TUK_Definition && !Invalid) { 16302 TagDecl *Def; 16303 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16304 // C++0x: 7.2p2: opaque-enum-declaration. 16305 // Conflicts are diagnosed above. Do nothing. 16306 } 16307 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16308 Diag(Loc, diag::ext_forward_ref_enum_def) 16309 << New; 16310 Diag(Def->getLocation(), diag::note_previous_definition); 16311 } else { 16312 unsigned DiagID = diag::ext_forward_ref_enum; 16313 if (getLangOpts().MSVCCompat) 16314 DiagID = diag::ext_ms_forward_ref_enum; 16315 else if (getLangOpts().CPlusPlus) 16316 DiagID = diag::err_forward_ref_enum; 16317 Diag(Loc, DiagID); 16318 } 16319 } 16320 16321 if (EnumUnderlying) { 16322 EnumDecl *ED = cast<EnumDecl>(New); 16323 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16324 ED->setIntegerTypeSourceInfo(TI); 16325 else 16326 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16327 ED->setPromotionType(ED->getIntegerType()); 16328 assert(ED->isComplete() && "enum with type should be complete"); 16329 } 16330 } else { 16331 // struct/union/class 16332 16333 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16334 // struct X { int A; } D; D should chain to X. 16335 if (getLangOpts().CPlusPlus) { 16336 // FIXME: Look for a way to use RecordDecl for simple structs. 16337 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16338 cast_or_null<CXXRecordDecl>(PrevDecl)); 16339 16340 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16341 StdBadAlloc = cast<CXXRecordDecl>(New); 16342 } else 16343 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16344 cast_or_null<RecordDecl>(PrevDecl)); 16345 } 16346 16347 // C++11 [dcl.type]p3: 16348 // A type-specifier-seq shall not define a class or enumeration [...]. 16349 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16350 TUK == TUK_Definition) { 16351 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16352 << Context.getTagDeclType(New); 16353 Invalid = true; 16354 } 16355 16356 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16357 DC->getDeclKind() == Decl::Enum) { 16358 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16359 << Context.getTagDeclType(New); 16360 Invalid = true; 16361 } 16362 16363 // Maybe add qualifier info. 16364 if (SS.isNotEmpty()) { 16365 if (SS.isSet()) { 16366 // If this is either a declaration or a definition, check the 16367 // nested-name-specifier against the current context. 16368 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16369 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16370 isMemberSpecialization)) 16371 Invalid = true; 16372 16373 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16374 if (TemplateParameterLists.size() > 0) { 16375 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16376 } 16377 } 16378 else 16379 Invalid = true; 16380 } 16381 16382 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16383 // Add alignment attributes if necessary; these attributes are checked when 16384 // the ASTContext lays out the structure. 16385 // 16386 // It is important for implementing the correct semantics that this 16387 // happen here (in ActOnTag). The #pragma pack stack is 16388 // maintained as a result of parser callbacks which can occur at 16389 // many points during the parsing of a struct declaration (because 16390 // the #pragma tokens are effectively skipped over during the 16391 // parsing of the struct). 16392 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16393 AddAlignmentAttributesForRecord(RD); 16394 AddMsStructLayoutForRecord(RD); 16395 } 16396 } 16397 16398 if (ModulePrivateLoc.isValid()) { 16399 if (isMemberSpecialization) 16400 Diag(New->getLocation(), diag::err_module_private_specialization) 16401 << 2 16402 << FixItHint::CreateRemoval(ModulePrivateLoc); 16403 // __module_private__ does not apply to local classes. However, we only 16404 // diagnose this as an error when the declaration specifiers are 16405 // freestanding. Here, we just ignore the __module_private__. 16406 else if (!SearchDC->isFunctionOrMethod()) 16407 New->setModulePrivate(); 16408 } 16409 16410 // If this is a specialization of a member class (of a class template), 16411 // check the specialization. 16412 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16413 Invalid = true; 16414 16415 // If we're declaring or defining a tag in function prototype scope in C, 16416 // note that this type can only be used within the function and add it to 16417 // the list of decls to inject into the function definition scope. 16418 if ((Name || Kind == TTK_Enum) && 16419 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16420 if (getLangOpts().CPlusPlus) { 16421 // C++ [dcl.fct]p6: 16422 // Types shall not be defined in return or parameter types. 16423 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16424 Diag(Loc, diag::err_type_defined_in_param_type) 16425 << Name; 16426 Invalid = true; 16427 } 16428 } else if (!PrevDecl) { 16429 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16430 } 16431 } 16432 16433 if (Invalid) 16434 New->setInvalidDecl(); 16435 16436 // Set the lexical context. If the tag has a C++ scope specifier, the 16437 // lexical context will be different from the semantic context. 16438 New->setLexicalDeclContext(CurContext); 16439 16440 // Mark this as a friend decl if applicable. 16441 // In Microsoft mode, a friend declaration also acts as a forward 16442 // declaration so we always pass true to setObjectOfFriendDecl to make 16443 // the tag name visible. 16444 if (TUK == TUK_Friend) 16445 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16446 16447 // Set the access specifier. 16448 if (!Invalid && SearchDC->isRecord()) 16449 SetMemberAccessSpecifier(New, PrevDecl, AS); 16450 16451 if (PrevDecl) 16452 CheckRedeclarationModuleOwnership(New, PrevDecl); 16453 16454 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16455 New->startDefinition(); 16456 16457 ProcessDeclAttributeList(S, New, Attrs); 16458 AddPragmaAttributes(S, New); 16459 16460 // If this has an identifier, add it to the scope stack. 16461 if (TUK == TUK_Friend) { 16462 // We might be replacing an existing declaration in the lookup tables; 16463 // if so, borrow its access specifier. 16464 if (PrevDecl) 16465 New->setAccess(PrevDecl->getAccess()); 16466 16467 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16468 DC->makeDeclVisibleInContext(New); 16469 if (Name) // can be null along some error paths 16470 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16471 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16472 } else if (Name) { 16473 S = getNonFieldDeclScope(S); 16474 PushOnScopeChains(New, S, true); 16475 } else { 16476 CurContext->addDecl(New); 16477 } 16478 16479 // If this is the C FILE type, notify the AST context. 16480 if (IdentifierInfo *II = New->getIdentifier()) 16481 if (!New->isInvalidDecl() && 16482 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16483 II->isStr("FILE")) 16484 Context.setFILEDecl(New); 16485 16486 if (PrevDecl) 16487 mergeDeclAttributes(New, PrevDecl); 16488 16489 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16490 inferGslOwnerPointerAttribute(CXXRD); 16491 16492 // If there's a #pragma GCC visibility in scope, set the visibility of this 16493 // record. 16494 AddPushedVisibilityAttribute(New); 16495 16496 if (isMemberSpecialization && !New->isInvalidDecl()) 16497 CompleteMemberSpecialization(New, Previous); 16498 16499 OwnedDecl = true; 16500 // In C++, don't return an invalid declaration. We can't recover well from 16501 // the cases where we make the type anonymous. 16502 if (Invalid && getLangOpts().CPlusPlus) { 16503 if (New->isBeingDefined()) 16504 if (auto RD = dyn_cast<RecordDecl>(New)) 16505 RD->completeDefinition(); 16506 return nullptr; 16507 } else if (SkipBody && SkipBody->ShouldSkip) { 16508 return SkipBody->Previous; 16509 } else { 16510 return New; 16511 } 16512 } 16513 16514 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16515 AdjustDeclIfTemplate(TagD); 16516 TagDecl *Tag = cast<TagDecl>(TagD); 16517 16518 // Enter the tag context. 16519 PushDeclContext(S, Tag); 16520 16521 ActOnDocumentableDecl(TagD); 16522 16523 // If there's a #pragma GCC visibility in scope, set the visibility of this 16524 // record. 16525 AddPushedVisibilityAttribute(Tag); 16526 } 16527 16528 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16529 SkipBodyInfo &SkipBody) { 16530 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16531 return false; 16532 16533 // Make the previous decl visible. 16534 makeMergedDefinitionVisible(SkipBody.Previous); 16535 return true; 16536 } 16537 16538 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16539 assert(isa<ObjCContainerDecl>(IDecl) && 16540 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16541 DeclContext *OCD = cast<DeclContext>(IDecl); 16542 assert(OCD->getLexicalParent() == CurContext && 16543 "The next DeclContext should be lexically contained in the current one."); 16544 CurContext = OCD; 16545 return IDecl; 16546 } 16547 16548 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16549 SourceLocation FinalLoc, 16550 bool IsFinalSpelledSealed, 16551 bool IsAbstract, 16552 SourceLocation LBraceLoc) { 16553 AdjustDeclIfTemplate(TagD); 16554 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16555 16556 FieldCollector->StartClass(); 16557 16558 if (!Record->getIdentifier()) 16559 return; 16560 16561 if (IsAbstract) 16562 Record->markAbstract(); 16563 16564 if (FinalLoc.isValid()) { 16565 Record->addAttr(FinalAttr::Create( 16566 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16567 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16568 } 16569 // C++ [class]p2: 16570 // [...] The class-name is also inserted into the scope of the 16571 // class itself; this is known as the injected-class-name. For 16572 // purposes of access checking, the injected-class-name is treated 16573 // as if it were a public member name. 16574 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16575 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16576 Record->getLocation(), Record->getIdentifier(), 16577 /*PrevDecl=*/nullptr, 16578 /*DelayTypeCreation=*/true); 16579 Context.getTypeDeclType(InjectedClassName, Record); 16580 InjectedClassName->setImplicit(); 16581 InjectedClassName->setAccess(AS_public); 16582 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16583 InjectedClassName->setDescribedClassTemplate(Template); 16584 PushOnScopeChains(InjectedClassName, S); 16585 assert(InjectedClassName->isInjectedClassName() && 16586 "Broken injected-class-name"); 16587 } 16588 16589 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16590 SourceRange BraceRange) { 16591 AdjustDeclIfTemplate(TagD); 16592 TagDecl *Tag = cast<TagDecl>(TagD); 16593 Tag->setBraceRange(BraceRange); 16594 16595 // Make sure we "complete" the definition even it is invalid. 16596 if (Tag->isBeingDefined()) { 16597 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16598 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16599 RD->completeDefinition(); 16600 } 16601 16602 if (isa<CXXRecordDecl>(Tag)) { 16603 FieldCollector->FinishClass(); 16604 } 16605 16606 // Exit this scope of this tag's definition. 16607 PopDeclContext(); 16608 16609 if (getCurLexicalContext()->isObjCContainer() && 16610 Tag->getDeclContext()->isFileContext()) 16611 Tag->setTopLevelDeclInObjCContainer(); 16612 16613 // Notify the consumer that we've defined a tag. 16614 if (!Tag->isInvalidDecl()) 16615 Consumer.HandleTagDeclDefinition(Tag); 16616 16617 // Clangs implementation of #pragma align(packed) differs in bitfield layout 16618 // from XLs and instead matches the XL #pragma pack(1) behavior. 16619 if (Context.getTargetInfo().getTriple().isOSAIX() && 16620 AlignPackStack.hasValue()) { 16621 AlignPackInfo APInfo = AlignPackStack.CurrentValue; 16622 // Only diagnose #pragma align(packed). 16623 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed) 16624 return; 16625 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag); 16626 if (!RD) 16627 return; 16628 // Only warn if there is at least 1 bitfield member. 16629 if (llvm::any_of(RD->fields(), 16630 [](const FieldDecl *FD) { return FD->isBitField(); })) 16631 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible); 16632 } 16633 } 16634 16635 void Sema::ActOnObjCContainerFinishDefinition() { 16636 // Exit this scope of this interface definition. 16637 PopDeclContext(); 16638 } 16639 16640 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16641 assert(DC == CurContext && "Mismatch of container contexts"); 16642 OriginalLexicalContext = DC; 16643 ActOnObjCContainerFinishDefinition(); 16644 } 16645 16646 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16647 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16648 OriginalLexicalContext = nullptr; 16649 } 16650 16651 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16652 AdjustDeclIfTemplate(TagD); 16653 TagDecl *Tag = cast<TagDecl>(TagD); 16654 Tag->setInvalidDecl(); 16655 16656 // Make sure we "complete" the definition even it is invalid. 16657 if (Tag->isBeingDefined()) { 16658 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16659 RD->completeDefinition(); 16660 } 16661 16662 // We're undoing ActOnTagStartDefinition here, not 16663 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16664 // the FieldCollector. 16665 16666 PopDeclContext(); 16667 } 16668 16669 // Note that FieldName may be null for anonymous bitfields. 16670 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16671 IdentifierInfo *FieldName, 16672 QualType FieldTy, bool IsMsStruct, 16673 Expr *BitWidth, bool *ZeroWidth) { 16674 assert(BitWidth); 16675 if (BitWidth->containsErrors()) 16676 return ExprError(); 16677 16678 // Default to true; that shouldn't confuse checks for emptiness 16679 if (ZeroWidth) 16680 *ZeroWidth = true; 16681 16682 // C99 6.7.2.1p4 - verify the field type. 16683 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16684 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16685 // Handle incomplete and sizeless types with a specific error. 16686 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16687 diag::err_field_incomplete_or_sizeless)) 16688 return ExprError(); 16689 if (FieldName) 16690 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16691 << FieldName << FieldTy << BitWidth->getSourceRange(); 16692 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16693 << FieldTy << BitWidth->getSourceRange(); 16694 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16695 UPPC_BitFieldWidth)) 16696 return ExprError(); 16697 16698 // If the bit-width is type- or value-dependent, don't try to check 16699 // it now. 16700 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16701 return BitWidth; 16702 16703 llvm::APSInt Value; 16704 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 16705 if (ICE.isInvalid()) 16706 return ICE; 16707 BitWidth = ICE.get(); 16708 16709 if (Value != 0 && ZeroWidth) 16710 *ZeroWidth = false; 16711 16712 // Zero-width bitfield is ok for anonymous field. 16713 if (Value == 0 && FieldName) 16714 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16715 16716 if (Value.isSigned() && Value.isNegative()) { 16717 if (FieldName) 16718 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16719 << FieldName << toString(Value, 10); 16720 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16721 << toString(Value, 10); 16722 } 16723 16724 // The size of the bit-field must not exceed our maximum permitted object 16725 // size. 16726 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 16727 return Diag(FieldLoc, diag::err_bitfield_too_wide) 16728 << !FieldName << FieldName << toString(Value, 10); 16729 } 16730 16731 if (!FieldTy->isDependentType()) { 16732 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16733 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16734 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16735 16736 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16737 // ABI. 16738 bool CStdConstraintViolation = 16739 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16740 bool MSBitfieldViolation = 16741 Value.ugt(TypeStorageSize) && 16742 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16743 if (CStdConstraintViolation || MSBitfieldViolation) { 16744 unsigned DiagWidth = 16745 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16746 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16747 << (bool)FieldName << FieldName << toString(Value, 10) 16748 << !CStdConstraintViolation << DiagWidth; 16749 } 16750 16751 // Warn on types where the user might conceivably expect to get all 16752 // specified bits as value bits: that's all integral types other than 16753 // 'bool'. 16754 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 16755 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16756 << FieldName << toString(Value, 10) 16757 << (unsigned)TypeWidth; 16758 } 16759 } 16760 16761 return BitWidth; 16762 } 16763 16764 /// ActOnField - Each field of a C struct/union is passed into this in order 16765 /// to create a FieldDecl object for it. 16766 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16767 Declarator &D, Expr *BitfieldWidth) { 16768 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16769 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16770 /*InitStyle=*/ICIS_NoInit, AS_public); 16771 return Res; 16772 } 16773 16774 /// HandleField - Analyze a field of a C struct or a C++ data member. 16775 /// 16776 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16777 SourceLocation DeclStart, 16778 Declarator &D, Expr *BitWidth, 16779 InClassInitStyle InitStyle, 16780 AccessSpecifier AS) { 16781 if (D.isDecompositionDeclarator()) { 16782 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16783 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16784 << Decomp.getSourceRange(); 16785 return nullptr; 16786 } 16787 16788 IdentifierInfo *II = D.getIdentifier(); 16789 SourceLocation Loc = DeclStart; 16790 if (II) Loc = D.getIdentifierLoc(); 16791 16792 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16793 QualType T = TInfo->getType(); 16794 if (getLangOpts().CPlusPlus) { 16795 CheckExtraCXXDefaultArguments(D); 16796 16797 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16798 UPPC_DataMemberType)) { 16799 D.setInvalidType(); 16800 T = Context.IntTy; 16801 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16802 } 16803 } 16804 16805 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16806 16807 if (D.getDeclSpec().isInlineSpecified()) 16808 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16809 << getLangOpts().CPlusPlus17; 16810 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16811 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16812 diag::err_invalid_thread) 16813 << DeclSpec::getSpecifierName(TSCS); 16814 16815 // Check to see if this name was declared as a member previously 16816 NamedDecl *PrevDecl = nullptr; 16817 LookupResult Previous(*this, II, Loc, LookupMemberName, 16818 ForVisibleRedeclaration); 16819 LookupName(Previous, S); 16820 switch (Previous.getResultKind()) { 16821 case LookupResult::Found: 16822 case LookupResult::FoundUnresolvedValue: 16823 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16824 break; 16825 16826 case LookupResult::FoundOverloaded: 16827 PrevDecl = Previous.getRepresentativeDecl(); 16828 break; 16829 16830 case LookupResult::NotFound: 16831 case LookupResult::NotFoundInCurrentInstantiation: 16832 case LookupResult::Ambiguous: 16833 break; 16834 } 16835 Previous.suppressDiagnostics(); 16836 16837 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16838 // Maybe we will complain about the shadowed template parameter. 16839 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16840 // Just pretend that we didn't see the previous declaration. 16841 PrevDecl = nullptr; 16842 } 16843 16844 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16845 PrevDecl = nullptr; 16846 16847 bool Mutable 16848 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16849 SourceLocation TSSL = D.getBeginLoc(); 16850 FieldDecl *NewFD 16851 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16852 TSSL, AS, PrevDecl, &D); 16853 16854 if (NewFD->isInvalidDecl()) 16855 Record->setInvalidDecl(); 16856 16857 if (D.getDeclSpec().isModulePrivateSpecified()) 16858 NewFD->setModulePrivate(); 16859 16860 if (NewFD->isInvalidDecl() && PrevDecl) { 16861 // Don't introduce NewFD into scope; there's already something 16862 // with the same name in the same scope. 16863 } else if (II) { 16864 PushOnScopeChains(NewFD, S); 16865 } else 16866 Record->addDecl(NewFD); 16867 16868 return NewFD; 16869 } 16870 16871 /// Build a new FieldDecl and check its well-formedness. 16872 /// 16873 /// This routine builds a new FieldDecl given the fields name, type, 16874 /// record, etc. \p PrevDecl should refer to any previous declaration 16875 /// with the same name and in the same scope as the field to be 16876 /// created. 16877 /// 16878 /// \returns a new FieldDecl. 16879 /// 16880 /// \todo The Declarator argument is a hack. It will be removed once 16881 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16882 TypeSourceInfo *TInfo, 16883 RecordDecl *Record, SourceLocation Loc, 16884 bool Mutable, Expr *BitWidth, 16885 InClassInitStyle InitStyle, 16886 SourceLocation TSSL, 16887 AccessSpecifier AS, NamedDecl *PrevDecl, 16888 Declarator *D) { 16889 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16890 bool InvalidDecl = false; 16891 if (D) InvalidDecl = D->isInvalidType(); 16892 16893 // If we receive a broken type, recover by assuming 'int' and 16894 // marking this declaration as invalid. 16895 if (T.isNull() || T->containsErrors()) { 16896 InvalidDecl = true; 16897 T = Context.IntTy; 16898 } 16899 16900 QualType EltTy = Context.getBaseElementType(T); 16901 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16902 if (RequireCompleteSizedType(Loc, EltTy, 16903 diag::err_field_incomplete_or_sizeless)) { 16904 // Fields of incomplete type force their record to be invalid. 16905 Record->setInvalidDecl(); 16906 InvalidDecl = true; 16907 } else { 16908 NamedDecl *Def; 16909 EltTy->isIncompleteType(&Def); 16910 if (Def && Def->isInvalidDecl()) { 16911 Record->setInvalidDecl(); 16912 InvalidDecl = true; 16913 } 16914 } 16915 } 16916 16917 // TR 18037 does not allow fields to be declared with address space 16918 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16919 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16920 Diag(Loc, diag::err_field_with_address_space); 16921 Record->setInvalidDecl(); 16922 InvalidDecl = true; 16923 } 16924 16925 if (LangOpts.OpenCL) { 16926 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16927 // used as structure or union field: image, sampler, event or block types. 16928 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16929 T->isBlockPointerType()) { 16930 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16931 Record->setInvalidDecl(); 16932 InvalidDecl = true; 16933 } 16934 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension 16935 // is enabled. 16936 if (BitWidth && !getOpenCLOptions().isAvailableOption( 16937 "__cl_clang_bitfields", LangOpts)) { 16938 Diag(Loc, diag::err_opencl_bitfields); 16939 InvalidDecl = true; 16940 } 16941 } 16942 16943 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16944 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16945 T.hasQualifiers()) { 16946 InvalidDecl = true; 16947 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16948 } 16949 16950 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16951 // than a variably modified type. 16952 if (!InvalidDecl && T->isVariablyModifiedType()) { 16953 if (!tryToFixVariablyModifiedVarType( 16954 TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 16955 InvalidDecl = true; 16956 } 16957 16958 // Fields can not have abstract class types 16959 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16960 diag::err_abstract_type_in_decl, 16961 AbstractFieldType)) 16962 InvalidDecl = true; 16963 16964 bool ZeroWidth = false; 16965 if (InvalidDecl) 16966 BitWidth = nullptr; 16967 // If this is declared as a bit-field, check the bit-field. 16968 if (BitWidth) { 16969 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16970 &ZeroWidth).get(); 16971 if (!BitWidth) { 16972 InvalidDecl = true; 16973 BitWidth = nullptr; 16974 ZeroWidth = false; 16975 } 16976 } 16977 16978 // Check that 'mutable' is consistent with the type of the declaration. 16979 if (!InvalidDecl && Mutable) { 16980 unsigned DiagID = 0; 16981 if (T->isReferenceType()) 16982 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16983 : diag::err_mutable_reference; 16984 else if (T.isConstQualified()) 16985 DiagID = diag::err_mutable_const; 16986 16987 if (DiagID) { 16988 SourceLocation ErrLoc = Loc; 16989 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16990 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16991 Diag(ErrLoc, DiagID); 16992 if (DiagID != diag::ext_mutable_reference) { 16993 Mutable = false; 16994 InvalidDecl = true; 16995 } 16996 } 16997 } 16998 16999 // C++11 [class.union]p8 (DR1460): 17000 // At most one variant member of a union may have a 17001 // brace-or-equal-initializer. 17002 if (InitStyle != ICIS_NoInit) 17003 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 17004 17005 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 17006 BitWidth, Mutable, InitStyle); 17007 if (InvalidDecl) 17008 NewFD->setInvalidDecl(); 17009 17010 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 17011 Diag(Loc, diag::err_duplicate_member) << II; 17012 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17013 NewFD->setInvalidDecl(); 17014 } 17015 17016 if (!InvalidDecl && getLangOpts().CPlusPlus) { 17017 if (Record->isUnion()) { 17018 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17019 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17020 if (RDecl->getDefinition()) { 17021 // C++ [class.union]p1: An object of a class with a non-trivial 17022 // constructor, a non-trivial copy constructor, a non-trivial 17023 // destructor, or a non-trivial copy assignment operator 17024 // cannot be a member of a union, nor can an array of such 17025 // objects. 17026 if (CheckNontrivialField(NewFD)) 17027 NewFD->setInvalidDecl(); 17028 } 17029 } 17030 17031 // C++ [class.union]p1: If a union contains a member of reference type, 17032 // the program is ill-formed, except when compiling with MSVC extensions 17033 // enabled. 17034 if (EltTy->isReferenceType()) { 17035 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 17036 diag::ext_union_member_of_reference_type : 17037 diag::err_union_member_of_reference_type) 17038 << NewFD->getDeclName() << EltTy; 17039 if (!getLangOpts().MicrosoftExt) 17040 NewFD->setInvalidDecl(); 17041 } 17042 } 17043 } 17044 17045 // FIXME: We need to pass in the attributes given an AST 17046 // representation, not a parser representation. 17047 if (D) { 17048 // FIXME: The current scope is almost... but not entirely... correct here. 17049 ProcessDeclAttributes(getCurScope(), NewFD, *D); 17050 17051 if (NewFD->hasAttrs()) 17052 CheckAlignasUnderalignment(NewFD); 17053 } 17054 17055 // In auto-retain/release, infer strong retension for fields of 17056 // retainable type. 17057 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 17058 NewFD->setInvalidDecl(); 17059 17060 if (T.isObjCGCWeak()) 17061 Diag(Loc, diag::warn_attribute_weak_on_field); 17062 17063 // PPC MMA non-pointer types are not allowed as field types. 17064 if (Context.getTargetInfo().getTriple().isPPC64() && 17065 CheckPPCMMAType(T, NewFD->getLocation())) 17066 NewFD->setInvalidDecl(); 17067 17068 NewFD->setAccess(AS); 17069 return NewFD; 17070 } 17071 17072 bool Sema::CheckNontrivialField(FieldDecl *FD) { 17073 assert(FD); 17074 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 17075 17076 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 17077 return false; 17078 17079 QualType EltTy = Context.getBaseElementType(FD->getType()); 17080 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17081 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17082 if (RDecl->getDefinition()) { 17083 // We check for copy constructors before constructors 17084 // because otherwise we'll never get complaints about 17085 // copy constructors. 17086 17087 CXXSpecialMember member = CXXInvalid; 17088 // We're required to check for any non-trivial constructors. Since the 17089 // implicit default constructor is suppressed if there are any 17090 // user-declared constructors, we just need to check that there is a 17091 // trivial default constructor and a trivial copy constructor. (We don't 17092 // worry about move constructors here, since this is a C++98 check.) 17093 if (RDecl->hasNonTrivialCopyConstructor()) 17094 member = CXXCopyConstructor; 17095 else if (!RDecl->hasTrivialDefaultConstructor()) 17096 member = CXXDefaultConstructor; 17097 else if (RDecl->hasNonTrivialCopyAssignment()) 17098 member = CXXCopyAssignment; 17099 else if (RDecl->hasNonTrivialDestructor()) 17100 member = CXXDestructor; 17101 17102 if (member != CXXInvalid) { 17103 if (!getLangOpts().CPlusPlus11 && 17104 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 17105 // Objective-C++ ARC: it is an error to have a non-trivial field of 17106 // a union. However, system headers in Objective-C programs 17107 // occasionally have Objective-C lifetime objects within unions, 17108 // and rather than cause the program to fail, we make those 17109 // members unavailable. 17110 SourceLocation Loc = FD->getLocation(); 17111 if (getSourceManager().isInSystemHeader(Loc)) { 17112 if (!FD->hasAttr<UnavailableAttr>()) 17113 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 17114 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 17115 return false; 17116 } 17117 } 17118 17119 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 17120 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 17121 diag::err_illegal_union_or_anon_struct_member) 17122 << FD->getParent()->isUnion() << FD->getDeclName() << member; 17123 DiagnoseNontrivial(RDecl, member); 17124 return !getLangOpts().CPlusPlus11; 17125 } 17126 } 17127 } 17128 17129 return false; 17130 } 17131 17132 /// TranslateIvarVisibility - Translate visibility from a token ID to an 17133 /// AST enum value. 17134 static ObjCIvarDecl::AccessControl 17135 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 17136 switch (ivarVisibility) { 17137 default: llvm_unreachable("Unknown visitibility kind"); 17138 case tok::objc_private: return ObjCIvarDecl::Private; 17139 case tok::objc_public: return ObjCIvarDecl::Public; 17140 case tok::objc_protected: return ObjCIvarDecl::Protected; 17141 case tok::objc_package: return ObjCIvarDecl::Package; 17142 } 17143 } 17144 17145 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 17146 /// in order to create an IvarDecl object for it. 17147 Decl *Sema::ActOnIvar(Scope *S, 17148 SourceLocation DeclStart, 17149 Declarator &D, Expr *BitfieldWidth, 17150 tok::ObjCKeywordKind Visibility) { 17151 17152 IdentifierInfo *II = D.getIdentifier(); 17153 Expr *BitWidth = (Expr*)BitfieldWidth; 17154 SourceLocation Loc = DeclStart; 17155 if (II) Loc = D.getIdentifierLoc(); 17156 17157 // FIXME: Unnamed fields can be handled in various different ways, for 17158 // example, unnamed unions inject all members into the struct namespace! 17159 17160 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17161 QualType T = TInfo->getType(); 17162 17163 if (BitWidth) { 17164 // 6.7.2.1p3, 6.7.2.1p4 17165 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 17166 if (!BitWidth) 17167 D.setInvalidType(); 17168 } else { 17169 // Not a bitfield. 17170 17171 // validate II. 17172 17173 } 17174 if (T->isReferenceType()) { 17175 Diag(Loc, diag::err_ivar_reference_type); 17176 D.setInvalidType(); 17177 } 17178 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17179 // than a variably modified type. 17180 else if (T->isVariablyModifiedType()) { 17181 if (!tryToFixVariablyModifiedVarType( 17182 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 17183 D.setInvalidType(); 17184 } 17185 17186 // Get the visibility (access control) for this ivar. 17187 ObjCIvarDecl::AccessControl ac = 17188 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 17189 : ObjCIvarDecl::None; 17190 // Must set ivar's DeclContext to its enclosing interface. 17191 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 17192 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 17193 return nullptr; 17194 ObjCContainerDecl *EnclosingContext; 17195 if (ObjCImplementationDecl *IMPDecl = 17196 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17197 if (LangOpts.ObjCRuntime.isFragile()) { 17198 // Case of ivar declared in an implementation. Context is that of its class. 17199 EnclosingContext = IMPDecl->getClassInterface(); 17200 assert(EnclosingContext && "Implementation has no class interface!"); 17201 } 17202 else 17203 EnclosingContext = EnclosingDecl; 17204 } else { 17205 if (ObjCCategoryDecl *CDecl = 17206 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17207 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 17208 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 17209 return nullptr; 17210 } 17211 } 17212 EnclosingContext = EnclosingDecl; 17213 } 17214 17215 // Construct the decl. 17216 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 17217 DeclStart, Loc, II, T, 17218 TInfo, ac, (Expr *)BitfieldWidth); 17219 17220 if (II) { 17221 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 17222 ForVisibleRedeclaration); 17223 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 17224 && !isa<TagDecl>(PrevDecl)) { 17225 Diag(Loc, diag::err_duplicate_member) << II; 17226 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17227 NewID->setInvalidDecl(); 17228 } 17229 } 17230 17231 // Process attributes attached to the ivar. 17232 ProcessDeclAttributes(S, NewID, D); 17233 17234 if (D.isInvalidType()) 17235 NewID->setInvalidDecl(); 17236 17237 // In ARC, infer 'retaining' for ivars of retainable type. 17238 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 17239 NewID->setInvalidDecl(); 17240 17241 if (D.getDeclSpec().isModulePrivateSpecified()) 17242 NewID->setModulePrivate(); 17243 17244 if (II) { 17245 // FIXME: When interfaces are DeclContexts, we'll need to add 17246 // these to the interface. 17247 S->AddDecl(NewID); 17248 IdResolver.AddDecl(NewID); 17249 } 17250 17251 if (LangOpts.ObjCRuntime.isNonFragile() && 17252 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17253 Diag(Loc, diag::warn_ivars_in_interface); 17254 17255 return NewID; 17256 } 17257 17258 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17259 /// class and class extensions. For every class \@interface and class 17260 /// extension \@interface, if the last ivar is a bitfield of any type, 17261 /// then add an implicit `char :0` ivar to the end of that interface. 17262 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17263 SmallVectorImpl<Decl *> &AllIvarDecls) { 17264 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17265 return; 17266 17267 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17268 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17269 17270 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17271 return; 17272 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17273 if (!ID) { 17274 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17275 if (!CD->IsClassExtension()) 17276 return; 17277 } 17278 // No need to add this to end of @implementation. 17279 else 17280 return; 17281 } 17282 // All conditions are met. Add a new bitfield to the tail end of ivars. 17283 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17284 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17285 17286 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17287 DeclLoc, DeclLoc, nullptr, 17288 Context.CharTy, 17289 Context.getTrivialTypeSourceInfo(Context.CharTy, 17290 DeclLoc), 17291 ObjCIvarDecl::Private, BW, 17292 true); 17293 AllIvarDecls.push_back(Ivar); 17294 } 17295 17296 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17297 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17298 SourceLocation RBrac, 17299 const ParsedAttributesView &Attrs) { 17300 assert(EnclosingDecl && "missing record or interface decl"); 17301 17302 // If this is an Objective-C @implementation or category and we have 17303 // new fields here we should reset the layout of the interface since 17304 // it will now change. 17305 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17306 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17307 switch (DC->getKind()) { 17308 default: break; 17309 case Decl::ObjCCategory: 17310 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17311 break; 17312 case Decl::ObjCImplementation: 17313 Context. 17314 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17315 break; 17316 } 17317 } 17318 17319 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17320 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17321 17322 // Start counting up the number of named members; make sure to include 17323 // members of anonymous structs and unions in the total. 17324 unsigned NumNamedMembers = 0; 17325 if (Record) { 17326 for (const auto *I : Record->decls()) { 17327 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17328 if (IFD->getDeclName()) 17329 ++NumNamedMembers; 17330 } 17331 } 17332 17333 // Verify that all the fields are okay. 17334 SmallVector<FieldDecl*, 32> RecFields; 17335 17336 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17337 i != end; ++i) { 17338 FieldDecl *FD = cast<FieldDecl>(*i); 17339 17340 // Get the type for the field. 17341 const Type *FDTy = FD->getType().getTypePtr(); 17342 17343 if (!FD->isAnonymousStructOrUnion()) { 17344 // Remember all fields written by the user. 17345 RecFields.push_back(FD); 17346 } 17347 17348 // If the field is already invalid for some reason, don't emit more 17349 // diagnostics about it. 17350 if (FD->isInvalidDecl()) { 17351 EnclosingDecl->setInvalidDecl(); 17352 continue; 17353 } 17354 17355 // C99 6.7.2.1p2: 17356 // A structure or union shall not contain a member with 17357 // incomplete or function type (hence, a structure shall not 17358 // contain an instance of itself, but may contain a pointer to 17359 // an instance of itself), except that the last member of a 17360 // structure with more than one named member may have incomplete 17361 // array type; such a structure (and any union containing, 17362 // possibly recursively, a member that is such a structure) 17363 // shall not be a member of a structure or an element of an 17364 // array. 17365 bool IsLastField = (i + 1 == Fields.end()); 17366 if (FDTy->isFunctionType()) { 17367 // Field declared as a function. 17368 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17369 << FD->getDeclName(); 17370 FD->setInvalidDecl(); 17371 EnclosingDecl->setInvalidDecl(); 17372 continue; 17373 } else if (FDTy->isIncompleteArrayType() && 17374 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17375 if (Record) { 17376 // Flexible array member. 17377 // Microsoft and g++ is more permissive regarding flexible array. 17378 // It will accept flexible array in union and also 17379 // as the sole element of a struct/class. 17380 unsigned DiagID = 0; 17381 if (!Record->isUnion() && !IsLastField) { 17382 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17383 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17384 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17385 FD->setInvalidDecl(); 17386 EnclosingDecl->setInvalidDecl(); 17387 continue; 17388 } else if (Record->isUnion()) 17389 DiagID = getLangOpts().MicrosoftExt 17390 ? diag::ext_flexible_array_union_ms 17391 : getLangOpts().CPlusPlus 17392 ? diag::ext_flexible_array_union_gnu 17393 : diag::err_flexible_array_union; 17394 else if (NumNamedMembers < 1) 17395 DiagID = getLangOpts().MicrosoftExt 17396 ? diag::ext_flexible_array_empty_aggregate_ms 17397 : getLangOpts().CPlusPlus 17398 ? diag::ext_flexible_array_empty_aggregate_gnu 17399 : diag::err_flexible_array_empty_aggregate; 17400 17401 if (DiagID) 17402 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17403 << Record->getTagKind(); 17404 // While the layout of types that contain virtual bases is not specified 17405 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17406 // virtual bases after the derived members. This would make a flexible 17407 // array member declared at the end of an object not adjacent to the end 17408 // of the type. 17409 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17410 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17411 << FD->getDeclName() << Record->getTagKind(); 17412 if (!getLangOpts().C99) 17413 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17414 << FD->getDeclName() << Record->getTagKind(); 17415 17416 // If the element type has a non-trivial destructor, we would not 17417 // implicitly destroy the elements, so disallow it for now. 17418 // 17419 // FIXME: GCC allows this. We should probably either implicitly delete 17420 // the destructor of the containing class, or just allow this. 17421 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17422 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17423 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17424 << FD->getDeclName() << FD->getType(); 17425 FD->setInvalidDecl(); 17426 EnclosingDecl->setInvalidDecl(); 17427 continue; 17428 } 17429 // Okay, we have a legal flexible array member at the end of the struct. 17430 Record->setHasFlexibleArrayMember(true); 17431 } else { 17432 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17433 // unless they are followed by another ivar. That check is done 17434 // elsewhere, after synthesized ivars are known. 17435 } 17436 } else if (!FDTy->isDependentType() && 17437 RequireCompleteSizedType( 17438 FD->getLocation(), FD->getType(), 17439 diag::err_field_incomplete_or_sizeless)) { 17440 // Incomplete type 17441 FD->setInvalidDecl(); 17442 EnclosingDecl->setInvalidDecl(); 17443 continue; 17444 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17445 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17446 // A type which contains a flexible array member is considered to be a 17447 // flexible array member. 17448 Record->setHasFlexibleArrayMember(true); 17449 if (!Record->isUnion()) { 17450 // If this is a struct/class and this is not the last element, reject 17451 // it. Note that GCC supports variable sized arrays in the middle of 17452 // structures. 17453 if (!IsLastField) 17454 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17455 << FD->getDeclName() << FD->getType(); 17456 else { 17457 // We support flexible arrays at the end of structs in 17458 // other structs as an extension. 17459 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17460 << FD->getDeclName(); 17461 } 17462 } 17463 } 17464 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17465 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17466 diag::err_abstract_type_in_decl, 17467 AbstractIvarType)) { 17468 // Ivars can not have abstract class types 17469 FD->setInvalidDecl(); 17470 } 17471 if (Record && FDTTy->getDecl()->hasObjectMember()) 17472 Record->setHasObjectMember(true); 17473 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17474 Record->setHasVolatileMember(true); 17475 } else if (FDTy->isObjCObjectType()) { 17476 /// A field cannot be an Objective-c object 17477 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17478 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17479 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17480 FD->setType(T); 17481 } else if (Record && Record->isUnion() && 17482 FD->getType().hasNonTrivialObjCLifetime() && 17483 getSourceManager().isInSystemHeader(FD->getLocation()) && 17484 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17485 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17486 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17487 // For backward compatibility, fields of C unions declared in system 17488 // headers that have non-trivial ObjC ownership qualifications are marked 17489 // as unavailable unless the qualifier is explicit and __strong. This can 17490 // break ABI compatibility between programs compiled with ARC and MRR, but 17491 // is a better option than rejecting programs using those unions under 17492 // ARC. 17493 FD->addAttr(UnavailableAttr::CreateImplicit( 17494 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17495 FD->getLocation())); 17496 } else if (getLangOpts().ObjC && 17497 getLangOpts().getGC() != LangOptions::NonGC && Record && 17498 !Record->hasObjectMember()) { 17499 if (FD->getType()->isObjCObjectPointerType() || 17500 FD->getType().isObjCGCStrong()) 17501 Record->setHasObjectMember(true); 17502 else if (Context.getAsArrayType(FD->getType())) { 17503 QualType BaseType = Context.getBaseElementType(FD->getType()); 17504 if (BaseType->isRecordType() && 17505 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17506 Record->setHasObjectMember(true); 17507 else if (BaseType->isObjCObjectPointerType() || 17508 BaseType.isObjCGCStrong()) 17509 Record->setHasObjectMember(true); 17510 } 17511 } 17512 17513 if (Record && !getLangOpts().CPlusPlus && 17514 !shouldIgnoreForRecordTriviality(FD)) { 17515 QualType FT = FD->getType(); 17516 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17517 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17518 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17519 Record->isUnion()) 17520 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17521 } 17522 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17523 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17524 Record->setNonTrivialToPrimitiveCopy(true); 17525 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17526 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17527 } 17528 if (FT.isDestructedType()) { 17529 Record->setNonTrivialToPrimitiveDestroy(true); 17530 Record->setParamDestroyedInCallee(true); 17531 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17532 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17533 } 17534 17535 if (const auto *RT = FT->getAs<RecordType>()) { 17536 if (RT->getDecl()->getArgPassingRestrictions() == 17537 RecordDecl::APK_CanNeverPassInRegs) 17538 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17539 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17540 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17541 } 17542 17543 if (Record && FD->getType().isVolatileQualified()) 17544 Record->setHasVolatileMember(true); 17545 // Keep track of the number of named members. 17546 if (FD->getIdentifier()) 17547 ++NumNamedMembers; 17548 } 17549 17550 // Okay, we successfully defined 'Record'. 17551 if (Record) { 17552 bool Completed = false; 17553 if (CXXRecord) { 17554 if (!CXXRecord->isInvalidDecl()) { 17555 // Set access bits correctly on the directly-declared conversions. 17556 for (CXXRecordDecl::conversion_iterator 17557 I = CXXRecord->conversion_begin(), 17558 E = CXXRecord->conversion_end(); I != E; ++I) 17559 I.setAccess((*I)->getAccess()); 17560 } 17561 17562 // Add any implicitly-declared members to this class. 17563 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17564 17565 if (!CXXRecord->isDependentType()) { 17566 if (!CXXRecord->isInvalidDecl()) { 17567 // If we have virtual base classes, we may end up finding multiple 17568 // final overriders for a given virtual function. Check for this 17569 // problem now. 17570 if (CXXRecord->getNumVBases()) { 17571 CXXFinalOverriderMap FinalOverriders; 17572 CXXRecord->getFinalOverriders(FinalOverriders); 17573 17574 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17575 MEnd = FinalOverriders.end(); 17576 M != MEnd; ++M) { 17577 for (OverridingMethods::iterator SO = M->second.begin(), 17578 SOEnd = M->second.end(); 17579 SO != SOEnd; ++SO) { 17580 assert(SO->second.size() > 0 && 17581 "Virtual function without overriding functions?"); 17582 if (SO->second.size() == 1) 17583 continue; 17584 17585 // C++ [class.virtual]p2: 17586 // In a derived class, if a virtual member function of a base 17587 // class subobject has more than one final overrider the 17588 // program is ill-formed. 17589 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17590 << (const NamedDecl *)M->first << Record; 17591 Diag(M->first->getLocation(), 17592 diag::note_overridden_virtual_function); 17593 for (OverridingMethods::overriding_iterator 17594 OM = SO->second.begin(), 17595 OMEnd = SO->second.end(); 17596 OM != OMEnd; ++OM) 17597 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17598 << (const NamedDecl *)M->first << OM->Method->getParent(); 17599 17600 Record->setInvalidDecl(); 17601 } 17602 } 17603 CXXRecord->completeDefinition(&FinalOverriders); 17604 Completed = true; 17605 } 17606 } 17607 } 17608 } 17609 17610 if (!Completed) 17611 Record->completeDefinition(); 17612 17613 // Handle attributes before checking the layout. 17614 ProcessDeclAttributeList(S, Record, Attrs); 17615 17616 // We may have deferred checking for a deleted destructor. Check now. 17617 if (CXXRecord) { 17618 auto *Dtor = CXXRecord->getDestructor(); 17619 if (Dtor && Dtor->isImplicit() && 17620 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17621 CXXRecord->setImplicitDestructorIsDeleted(); 17622 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17623 } 17624 } 17625 17626 if (Record->hasAttrs()) { 17627 CheckAlignasUnderalignment(Record); 17628 17629 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17630 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17631 IA->getRange(), IA->getBestCase(), 17632 IA->getInheritanceModel()); 17633 } 17634 17635 // Check if the structure/union declaration is a type that can have zero 17636 // size in C. For C this is a language extension, for C++ it may cause 17637 // compatibility problems. 17638 bool CheckForZeroSize; 17639 if (!getLangOpts().CPlusPlus) { 17640 CheckForZeroSize = true; 17641 } else { 17642 // For C++ filter out types that cannot be referenced in C code. 17643 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17644 CheckForZeroSize = 17645 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17646 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 17647 CXXRecord->isCLike(); 17648 } 17649 if (CheckForZeroSize) { 17650 bool ZeroSize = true; 17651 bool IsEmpty = true; 17652 unsigned NonBitFields = 0; 17653 for (RecordDecl::field_iterator I = Record->field_begin(), 17654 E = Record->field_end(); 17655 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17656 IsEmpty = false; 17657 if (I->isUnnamedBitfield()) { 17658 if (!I->isZeroLengthBitField(Context)) 17659 ZeroSize = false; 17660 } else { 17661 ++NonBitFields; 17662 QualType FieldType = I->getType(); 17663 if (FieldType->isIncompleteType() || 17664 !Context.getTypeSizeInChars(FieldType).isZero()) 17665 ZeroSize = false; 17666 } 17667 } 17668 17669 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17670 // allowed in C++, but warn if its declaration is inside 17671 // extern "C" block. 17672 if (ZeroSize) { 17673 Diag(RecLoc, getLangOpts().CPlusPlus ? 17674 diag::warn_zero_size_struct_union_in_extern_c : 17675 diag::warn_zero_size_struct_union_compat) 17676 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17677 } 17678 17679 // Structs without named members are extension in C (C99 6.7.2.1p7), 17680 // but are accepted by GCC. 17681 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17682 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17683 diag::ext_no_named_members_in_struct_union) 17684 << Record->isUnion(); 17685 } 17686 } 17687 } else { 17688 ObjCIvarDecl **ClsFields = 17689 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17690 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17691 ID->setEndOfDefinitionLoc(RBrac); 17692 // Add ivar's to class's DeclContext. 17693 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17694 ClsFields[i]->setLexicalDeclContext(ID); 17695 ID->addDecl(ClsFields[i]); 17696 } 17697 // Must enforce the rule that ivars in the base classes may not be 17698 // duplicates. 17699 if (ID->getSuperClass()) 17700 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17701 } else if (ObjCImplementationDecl *IMPDecl = 17702 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17703 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17704 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17705 // Ivar declared in @implementation never belongs to the implementation. 17706 // Only it is in implementation's lexical context. 17707 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17708 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17709 IMPDecl->setIvarLBraceLoc(LBrac); 17710 IMPDecl->setIvarRBraceLoc(RBrac); 17711 } else if (ObjCCategoryDecl *CDecl = 17712 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17713 // case of ivars in class extension; all other cases have been 17714 // reported as errors elsewhere. 17715 // FIXME. Class extension does not have a LocEnd field. 17716 // CDecl->setLocEnd(RBrac); 17717 // Add ivar's to class extension's DeclContext. 17718 // Diagnose redeclaration of private ivars. 17719 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17720 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17721 if (IDecl) { 17722 if (const ObjCIvarDecl *ClsIvar = 17723 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17724 Diag(ClsFields[i]->getLocation(), 17725 diag::err_duplicate_ivar_declaration); 17726 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17727 continue; 17728 } 17729 for (const auto *Ext : IDecl->known_extensions()) { 17730 if (const ObjCIvarDecl *ClsExtIvar 17731 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17732 Diag(ClsFields[i]->getLocation(), 17733 diag::err_duplicate_ivar_declaration); 17734 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17735 continue; 17736 } 17737 } 17738 } 17739 ClsFields[i]->setLexicalDeclContext(CDecl); 17740 CDecl->addDecl(ClsFields[i]); 17741 } 17742 CDecl->setIvarLBraceLoc(LBrac); 17743 CDecl->setIvarRBraceLoc(RBrac); 17744 } 17745 } 17746 } 17747 17748 /// Determine whether the given integral value is representable within 17749 /// the given type T. 17750 static bool isRepresentableIntegerValue(ASTContext &Context, 17751 llvm::APSInt &Value, 17752 QualType T) { 17753 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17754 "Integral type required!"); 17755 unsigned BitWidth = Context.getIntWidth(T); 17756 17757 if (Value.isUnsigned() || Value.isNonNegative()) { 17758 if (T->isSignedIntegerOrEnumerationType()) 17759 --BitWidth; 17760 return Value.getActiveBits() <= BitWidth; 17761 } 17762 return Value.getMinSignedBits() <= BitWidth; 17763 } 17764 17765 // Given an integral type, return the next larger integral type 17766 // (or a NULL type of no such type exists). 17767 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17768 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17769 // enum checking below. 17770 assert((T->isIntegralType(Context) || 17771 T->isEnumeralType()) && "Integral type required!"); 17772 const unsigned NumTypes = 4; 17773 QualType SignedIntegralTypes[NumTypes] = { 17774 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17775 }; 17776 QualType UnsignedIntegralTypes[NumTypes] = { 17777 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17778 Context.UnsignedLongLongTy 17779 }; 17780 17781 unsigned BitWidth = Context.getTypeSize(T); 17782 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17783 : UnsignedIntegralTypes; 17784 for (unsigned I = 0; I != NumTypes; ++I) 17785 if (Context.getTypeSize(Types[I]) > BitWidth) 17786 return Types[I]; 17787 17788 return QualType(); 17789 } 17790 17791 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17792 EnumConstantDecl *LastEnumConst, 17793 SourceLocation IdLoc, 17794 IdentifierInfo *Id, 17795 Expr *Val) { 17796 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17797 llvm::APSInt EnumVal(IntWidth); 17798 QualType EltTy; 17799 17800 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17801 Val = nullptr; 17802 17803 if (Val) 17804 Val = DefaultLvalueConversion(Val).get(); 17805 17806 if (Val) { 17807 if (Enum->isDependentType() || Val->isTypeDependent()) 17808 EltTy = Context.DependentTy; 17809 else { 17810 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 17811 // underlying type, but do allow it in all other contexts. 17812 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17813 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17814 // constant-expression in the enumerator-definition shall be a converted 17815 // constant expression of the underlying type. 17816 EltTy = Enum->getIntegerType(); 17817 ExprResult Converted = 17818 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17819 CCEK_Enumerator); 17820 if (Converted.isInvalid()) 17821 Val = nullptr; 17822 else 17823 Val = Converted.get(); 17824 } else if (!Val->isValueDependent() && 17825 !(Val = 17826 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 17827 .get())) { 17828 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17829 } else { 17830 if (Enum->isComplete()) { 17831 EltTy = Enum->getIntegerType(); 17832 17833 // In Obj-C and Microsoft mode, require the enumeration value to be 17834 // representable in the underlying type of the enumeration. In C++11, 17835 // we perform a non-narrowing conversion as part of converted constant 17836 // expression checking. 17837 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17838 if (Context.getTargetInfo() 17839 .getTriple() 17840 .isWindowsMSVCEnvironment()) { 17841 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17842 } else { 17843 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17844 } 17845 } 17846 17847 // Cast to the underlying type. 17848 Val = ImpCastExprToType(Val, EltTy, 17849 EltTy->isBooleanType() ? CK_IntegralToBoolean 17850 : CK_IntegralCast) 17851 .get(); 17852 } else if (getLangOpts().CPlusPlus) { 17853 // C++11 [dcl.enum]p5: 17854 // If the underlying type is not fixed, the type of each enumerator 17855 // is the type of its initializing value: 17856 // - If an initializer is specified for an enumerator, the 17857 // initializing value has the same type as the expression. 17858 EltTy = Val->getType(); 17859 } else { 17860 // C99 6.7.2.2p2: 17861 // The expression that defines the value of an enumeration constant 17862 // shall be an integer constant expression that has a value 17863 // representable as an int. 17864 17865 // Complain if the value is not representable in an int. 17866 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17867 Diag(IdLoc, diag::ext_enum_value_not_int) 17868 << toString(EnumVal, 10) << Val->getSourceRange() 17869 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17870 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17871 // Force the type of the expression to 'int'. 17872 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17873 } 17874 EltTy = Val->getType(); 17875 } 17876 } 17877 } 17878 } 17879 17880 if (!Val) { 17881 if (Enum->isDependentType()) 17882 EltTy = Context.DependentTy; 17883 else if (!LastEnumConst) { 17884 // C++0x [dcl.enum]p5: 17885 // If the underlying type is not fixed, the type of each enumerator 17886 // is the type of its initializing value: 17887 // - If no initializer is specified for the first enumerator, the 17888 // initializing value has an unspecified integral type. 17889 // 17890 // GCC uses 'int' for its unspecified integral type, as does 17891 // C99 6.7.2.2p3. 17892 if (Enum->isFixed()) { 17893 EltTy = Enum->getIntegerType(); 17894 } 17895 else { 17896 EltTy = Context.IntTy; 17897 } 17898 } else { 17899 // Assign the last value + 1. 17900 EnumVal = LastEnumConst->getInitVal(); 17901 ++EnumVal; 17902 EltTy = LastEnumConst->getType(); 17903 17904 // Check for overflow on increment. 17905 if (EnumVal < LastEnumConst->getInitVal()) { 17906 // C++0x [dcl.enum]p5: 17907 // If the underlying type is not fixed, the type of each enumerator 17908 // is the type of its initializing value: 17909 // 17910 // - Otherwise the type of the initializing value is the same as 17911 // the type of the initializing value of the preceding enumerator 17912 // unless the incremented value is not representable in that type, 17913 // in which case the type is an unspecified integral type 17914 // sufficient to contain the incremented value. If no such type 17915 // exists, the program is ill-formed. 17916 QualType T = getNextLargerIntegralType(Context, EltTy); 17917 if (T.isNull() || Enum->isFixed()) { 17918 // There is no integral type larger enough to represent this 17919 // value. Complain, then allow the value to wrap around. 17920 EnumVal = LastEnumConst->getInitVal(); 17921 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17922 ++EnumVal; 17923 if (Enum->isFixed()) 17924 // When the underlying type is fixed, this is ill-formed. 17925 Diag(IdLoc, diag::err_enumerator_wrapped) 17926 << toString(EnumVal, 10) 17927 << EltTy; 17928 else 17929 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17930 << toString(EnumVal, 10); 17931 } else { 17932 EltTy = T; 17933 } 17934 17935 // Retrieve the last enumerator's value, extent that type to the 17936 // type that is supposed to be large enough to represent the incremented 17937 // value, then increment. 17938 EnumVal = LastEnumConst->getInitVal(); 17939 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17940 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17941 ++EnumVal; 17942 17943 // If we're not in C++, diagnose the overflow of enumerator values, 17944 // which in C99 means that the enumerator value is not representable in 17945 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17946 // permits enumerator values that are representable in some larger 17947 // integral type. 17948 if (!getLangOpts().CPlusPlus && !T.isNull()) 17949 Diag(IdLoc, diag::warn_enum_value_overflow); 17950 } else if (!getLangOpts().CPlusPlus && 17951 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17952 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17953 Diag(IdLoc, diag::ext_enum_value_not_int) 17954 << toString(EnumVal, 10) << 1; 17955 } 17956 } 17957 } 17958 17959 if (!EltTy->isDependentType()) { 17960 // Make the enumerator value match the signedness and size of the 17961 // enumerator's type. 17962 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17963 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17964 } 17965 17966 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17967 Val, EnumVal); 17968 } 17969 17970 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17971 SourceLocation IILoc) { 17972 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17973 !getLangOpts().CPlusPlus) 17974 return SkipBodyInfo(); 17975 17976 // We have an anonymous enum definition. Look up the first enumerator to 17977 // determine if we should merge the definition with an existing one and 17978 // skip the body. 17979 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17980 forRedeclarationInCurContext()); 17981 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17982 if (!PrevECD) 17983 return SkipBodyInfo(); 17984 17985 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17986 NamedDecl *Hidden; 17987 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17988 SkipBodyInfo Skip; 17989 Skip.Previous = Hidden; 17990 return Skip; 17991 } 17992 17993 return SkipBodyInfo(); 17994 } 17995 17996 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17997 SourceLocation IdLoc, IdentifierInfo *Id, 17998 const ParsedAttributesView &Attrs, 17999 SourceLocation EqualLoc, Expr *Val) { 18000 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 18001 EnumConstantDecl *LastEnumConst = 18002 cast_or_null<EnumConstantDecl>(lastEnumConst); 18003 18004 // The scope passed in may not be a decl scope. Zip up the scope tree until 18005 // we find one that is. 18006 S = getNonFieldDeclScope(S); 18007 18008 // Verify that there isn't already something declared with this name in this 18009 // scope. 18010 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 18011 LookupName(R, S); 18012 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 18013 18014 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18015 // Maybe we will complain about the shadowed template parameter. 18016 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 18017 // Just pretend that we didn't see the previous declaration. 18018 PrevDecl = nullptr; 18019 } 18020 18021 // C++ [class.mem]p15: 18022 // If T is the name of a class, then each of the following shall have a name 18023 // different from T: 18024 // - every enumerator of every member of class T that is an unscoped 18025 // enumerated type 18026 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 18027 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 18028 DeclarationNameInfo(Id, IdLoc)); 18029 18030 EnumConstantDecl *New = 18031 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 18032 if (!New) 18033 return nullptr; 18034 18035 if (PrevDecl) { 18036 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 18037 // Check for other kinds of shadowing not already handled. 18038 CheckShadow(New, PrevDecl, R); 18039 } 18040 18041 // When in C++, we may get a TagDecl with the same name; in this case the 18042 // enum constant will 'hide' the tag. 18043 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 18044 "Received TagDecl when not in C++!"); 18045 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 18046 if (isa<EnumConstantDecl>(PrevDecl)) 18047 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 18048 else 18049 Diag(IdLoc, diag::err_redefinition) << Id; 18050 notePreviousDefinition(PrevDecl, IdLoc); 18051 return nullptr; 18052 } 18053 } 18054 18055 // Process attributes. 18056 ProcessDeclAttributeList(S, New, Attrs); 18057 AddPragmaAttributes(S, New); 18058 18059 // Register this decl in the current scope stack. 18060 New->setAccess(TheEnumDecl->getAccess()); 18061 PushOnScopeChains(New, S); 18062 18063 ActOnDocumentableDecl(New); 18064 18065 return New; 18066 } 18067 18068 // Returns true when the enum initial expression does not trigger the 18069 // duplicate enum warning. A few common cases are exempted as follows: 18070 // Element2 = Element1 18071 // Element2 = Element1 + 1 18072 // Element2 = Element1 - 1 18073 // Where Element2 and Element1 are from the same enum. 18074 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 18075 Expr *InitExpr = ECD->getInitExpr(); 18076 if (!InitExpr) 18077 return true; 18078 InitExpr = InitExpr->IgnoreImpCasts(); 18079 18080 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 18081 if (!BO->isAdditiveOp()) 18082 return true; 18083 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 18084 if (!IL) 18085 return true; 18086 if (IL->getValue() != 1) 18087 return true; 18088 18089 InitExpr = BO->getLHS(); 18090 } 18091 18092 // This checks if the elements are from the same enum. 18093 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 18094 if (!DRE) 18095 return true; 18096 18097 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 18098 if (!EnumConstant) 18099 return true; 18100 18101 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 18102 Enum) 18103 return true; 18104 18105 return false; 18106 } 18107 18108 // Emits a warning when an element is implicitly set a value that 18109 // a previous element has already been set to. 18110 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 18111 EnumDecl *Enum, QualType EnumType) { 18112 // Avoid anonymous enums 18113 if (!Enum->getIdentifier()) 18114 return; 18115 18116 // Only check for small enums. 18117 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 18118 return; 18119 18120 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 18121 return; 18122 18123 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 18124 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 18125 18126 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 18127 18128 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 18129 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 18130 18131 // Use int64_t as a key to avoid needing special handling for map keys. 18132 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 18133 llvm::APSInt Val = D->getInitVal(); 18134 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 18135 }; 18136 18137 DuplicatesVector DupVector; 18138 ValueToVectorMap EnumMap; 18139 18140 // Populate the EnumMap with all values represented by enum constants without 18141 // an initializer. 18142 for (auto *Element : Elements) { 18143 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 18144 18145 // Null EnumConstantDecl means a previous diagnostic has been emitted for 18146 // this constant. Skip this enum since it may be ill-formed. 18147 if (!ECD) { 18148 return; 18149 } 18150 18151 // Constants with initalizers are handled in the next loop. 18152 if (ECD->getInitExpr()) 18153 continue; 18154 18155 // Duplicate values are handled in the next loop. 18156 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 18157 } 18158 18159 if (EnumMap.size() == 0) 18160 return; 18161 18162 // Create vectors for any values that has duplicates. 18163 for (auto *Element : Elements) { 18164 // The last loop returned if any constant was null. 18165 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 18166 if (!ValidDuplicateEnum(ECD, Enum)) 18167 continue; 18168 18169 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 18170 if (Iter == EnumMap.end()) 18171 continue; 18172 18173 DeclOrVector& Entry = Iter->second; 18174 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 18175 // Ensure constants are different. 18176 if (D == ECD) 18177 continue; 18178 18179 // Create new vector and push values onto it. 18180 auto Vec = std::make_unique<ECDVector>(); 18181 Vec->push_back(D); 18182 Vec->push_back(ECD); 18183 18184 // Update entry to point to the duplicates vector. 18185 Entry = Vec.get(); 18186 18187 // Store the vector somewhere we can consult later for quick emission of 18188 // diagnostics. 18189 DupVector.emplace_back(std::move(Vec)); 18190 continue; 18191 } 18192 18193 ECDVector *Vec = Entry.get<ECDVector*>(); 18194 // Make sure constants are not added more than once. 18195 if (*Vec->begin() == ECD) 18196 continue; 18197 18198 Vec->push_back(ECD); 18199 } 18200 18201 // Emit diagnostics. 18202 for (const auto &Vec : DupVector) { 18203 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 18204 18205 // Emit warning for one enum constant. 18206 auto *FirstECD = Vec->front(); 18207 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 18208 << FirstECD << toString(FirstECD->getInitVal(), 10) 18209 << FirstECD->getSourceRange(); 18210 18211 // Emit one note for each of the remaining enum constants with 18212 // the same value. 18213 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 18214 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 18215 << ECD << toString(ECD->getInitVal(), 10) 18216 << ECD->getSourceRange(); 18217 } 18218 } 18219 18220 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 18221 bool AllowMask) const { 18222 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 18223 assert(ED->isCompleteDefinition() && "expected enum definition"); 18224 18225 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 18226 llvm::APInt &FlagBits = R.first->second; 18227 18228 if (R.second) { 18229 for (auto *E : ED->enumerators()) { 18230 const auto &EVal = E->getInitVal(); 18231 // Only single-bit enumerators introduce new flag values. 18232 if (EVal.isPowerOf2()) 18233 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 18234 } 18235 } 18236 18237 // A value is in a flag enum if either its bits are a subset of the enum's 18238 // flag bits (the first condition) or we are allowing masks and the same is 18239 // true of its complement (the second condition). When masks are allowed, we 18240 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 18241 // 18242 // While it's true that any value could be used as a mask, the assumption is 18243 // that a mask will have all of the insignificant bits set. Anything else is 18244 // likely a logic error. 18245 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18246 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18247 } 18248 18249 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18250 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18251 const ParsedAttributesView &Attrs) { 18252 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18253 QualType EnumType = Context.getTypeDeclType(Enum); 18254 18255 ProcessDeclAttributeList(S, Enum, Attrs); 18256 18257 if (Enum->isDependentType()) { 18258 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18259 EnumConstantDecl *ECD = 18260 cast_or_null<EnumConstantDecl>(Elements[i]); 18261 if (!ECD) continue; 18262 18263 ECD->setType(EnumType); 18264 } 18265 18266 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18267 return; 18268 } 18269 18270 // TODO: If the result value doesn't fit in an int, it must be a long or long 18271 // long value. ISO C does not support this, but GCC does as an extension, 18272 // emit a warning. 18273 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18274 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18275 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18276 18277 // Verify that all the values are okay, compute the size of the values, and 18278 // reverse the list. 18279 unsigned NumNegativeBits = 0; 18280 unsigned NumPositiveBits = 0; 18281 18282 // Keep track of whether all elements have type int. 18283 bool AllElementsInt = true; 18284 18285 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18286 EnumConstantDecl *ECD = 18287 cast_or_null<EnumConstantDecl>(Elements[i]); 18288 if (!ECD) continue; // Already issued a diagnostic. 18289 18290 const llvm::APSInt &InitVal = ECD->getInitVal(); 18291 18292 // Keep track of the size of positive and negative values. 18293 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18294 NumPositiveBits = std::max(NumPositiveBits, 18295 (unsigned)InitVal.getActiveBits()); 18296 else 18297 NumNegativeBits = std::max(NumNegativeBits, 18298 (unsigned)InitVal.getMinSignedBits()); 18299 18300 // Keep track of whether every enum element has type int (very common). 18301 if (AllElementsInt) 18302 AllElementsInt = ECD->getType() == Context.IntTy; 18303 } 18304 18305 // Figure out the type that should be used for this enum. 18306 QualType BestType; 18307 unsigned BestWidth; 18308 18309 // C++0x N3000 [conv.prom]p3: 18310 // An rvalue of an unscoped enumeration type whose underlying 18311 // type is not fixed can be converted to an rvalue of the first 18312 // of the following types that can represent all the values of 18313 // the enumeration: int, unsigned int, long int, unsigned long 18314 // int, long long int, or unsigned long long int. 18315 // C99 6.4.4.3p2: 18316 // An identifier declared as an enumeration constant has type int. 18317 // The C99 rule is modified by a gcc extension 18318 QualType BestPromotionType; 18319 18320 bool Packed = Enum->hasAttr<PackedAttr>(); 18321 // -fshort-enums is the equivalent to specifying the packed attribute on all 18322 // enum definitions. 18323 if (LangOpts.ShortEnums) 18324 Packed = true; 18325 18326 // If the enum already has a type because it is fixed or dictated by the 18327 // target, promote that type instead of analyzing the enumerators. 18328 if (Enum->isComplete()) { 18329 BestType = Enum->getIntegerType(); 18330 if (BestType->isPromotableIntegerType()) 18331 BestPromotionType = Context.getPromotedIntegerType(BestType); 18332 else 18333 BestPromotionType = BestType; 18334 18335 BestWidth = Context.getIntWidth(BestType); 18336 } 18337 else if (NumNegativeBits) { 18338 // If there is a negative value, figure out the smallest integer type (of 18339 // int/long/longlong) that fits. 18340 // If it's packed, check also if it fits a char or a short. 18341 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18342 BestType = Context.SignedCharTy; 18343 BestWidth = CharWidth; 18344 } else if (Packed && NumNegativeBits <= ShortWidth && 18345 NumPositiveBits < ShortWidth) { 18346 BestType = Context.ShortTy; 18347 BestWidth = ShortWidth; 18348 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18349 BestType = Context.IntTy; 18350 BestWidth = IntWidth; 18351 } else { 18352 BestWidth = Context.getTargetInfo().getLongWidth(); 18353 18354 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18355 BestType = Context.LongTy; 18356 } else { 18357 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18358 18359 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18360 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18361 BestType = Context.LongLongTy; 18362 } 18363 } 18364 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18365 } else { 18366 // If there is no negative value, figure out the smallest type that fits 18367 // all of the enumerator values. 18368 // If it's packed, check also if it fits a char or a short. 18369 if (Packed && NumPositiveBits <= CharWidth) { 18370 BestType = Context.UnsignedCharTy; 18371 BestPromotionType = Context.IntTy; 18372 BestWidth = CharWidth; 18373 } else if (Packed && NumPositiveBits <= ShortWidth) { 18374 BestType = Context.UnsignedShortTy; 18375 BestPromotionType = Context.IntTy; 18376 BestWidth = ShortWidth; 18377 } else if (NumPositiveBits <= IntWidth) { 18378 BestType = Context.UnsignedIntTy; 18379 BestWidth = IntWidth; 18380 BestPromotionType 18381 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18382 ? Context.UnsignedIntTy : Context.IntTy; 18383 } else if (NumPositiveBits <= 18384 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18385 BestType = Context.UnsignedLongTy; 18386 BestPromotionType 18387 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18388 ? Context.UnsignedLongTy : Context.LongTy; 18389 } else { 18390 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18391 assert(NumPositiveBits <= BestWidth && 18392 "How could an initializer get larger than ULL?"); 18393 BestType = Context.UnsignedLongLongTy; 18394 BestPromotionType 18395 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18396 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18397 } 18398 } 18399 18400 // Loop over all of the enumerator constants, changing their types to match 18401 // the type of the enum if needed. 18402 for (auto *D : Elements) { 18403 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18404 if (!ECD) continue; // Already issued a diagnostic. 18405 18406 // Standard C says the enumerators have int type, but we allow, as an 18407 // extension, the enumerators to be larger than int size. If each 18408 // enumerator value fits in an int, type it as an int, otherwise type it the 18409 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18410 // that X has type 'int', not 'unsigned'. 18411 18412 // Determine whether the value fits into an int. 18413 llvm::APSInt InitVal = ECD->getInitVal(); 18414 18415 // If it fits into an integer type, force it. Otherwise force it to match 18416 // the enum decl type. 18417 QualType NewTy; 18418 unsigned NewWidth; 18419 bool NewSign; 18420 if (!getLangOpts().CPlusPlus && 18421 !Enum->isFixed() && 18422 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18423 NewTy = Context.IntTy; 18424 NewWidth = IntWidth; 18425 NewSign = true; 18426 } else if (ECD->getType() == BestType) { 18427 // Already the right type! 18428 if (getLangOpts().CPlusPlus) 18429 // C++ [dcl.enum]p4: Following the closing brace of an 18430 // enum-specifier, each enumerator has the type of its 18431 // enumeration. 18432 ECD->setType(EnumType); 18433 continue; 18434 } else { 18435 NewTy = BestType; 18436 NewWidth = BestWidth; 18437 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18438 } 18439 18440 // Adjust the APSInt value. 18441 InitVal = InitVal.extOrTrunc(NewWidth); 18442 InitVal.setIsSigned(NewSign); 18443 ECD->setInitVal(InitVal); 18444 18445 // Adjust the Expr initializer and type. 18446 if (ECD->getInitExpr() && 18447 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18448 ECD->setInitExpr(ImplicitCastExpr::Create( 18449 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18450 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride())); 18451 if (getLangOpts().CPlusPlus) 18452 // C++ [dcl.enum]p4: Following the closing brace of an 18453 // enum-specifier, each enumerator has the type of its 18454 // enumeration. 18455 ECD->setType(EnumType); 18456 else 18457 ECD->setType(NewTy); 18458 } 18459 18460 Enum->completeDefinition(BestType, BestPromotionType, 18461 NumPositiveBits, NumNegativeBits); 18462 18463 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18464 18465 if (Enum->isClosedFlag()) { 18466 for (Decl *D : Elements) { 18467 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18468 if (!ECD) continue; // Already issued a diagnostic. 18469 18470 llvm::APSInt InitVal = ECD->getInitVal(); 18471 if (InitVal != 0 && !InitVal.isPowerOf2() && 18472 !IsValueInFlagEnum(Enum, InitVal, true)) 18473 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18474 << ECD << Enum; 18475 } 18476 } 18477 18478 // Now that the enum type is defined, ensure it's not been underaligned. 18479 if (Enum->hasAttrs()) 18480 CheckAlignasUnderalignment(Enum); 18481 } 18482 18483 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18484 SourceLocation StartLoc, 18485 SourceLocation EndLoc) { 18486 StringLiteral *AsmString = cast<StringLiteral>(expr); 18487 18488 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18489 AsmString, StartLoc, 18490 EndLoc); 18491 CurContext->addDecl(New); 18492 return New; 18493 } 18494 18495 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18496 IdentifierInfo* AliasName, 18497 SourceLocation PragmaLoc, 18498 SourceLocation NameLoc, 18499 SourceLocation AliasNameLoc) { 18500 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18501 LookupOrdinaryName); 18502 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18503 AttributeCommonInfo::AS_Pragma); 18504 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18505 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18506 18507 // If a declaration that: 18508 // 1) declares a function or a variable 18509 // 2) has external linkage 18510 // already exists, add a label attribute to it. 18511 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18512 if (isDeclExternC(PrevDecl)) 18513 PrevDecl->addAttr(Attr); 18514 else 18515 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18516 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18517 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18518 } else 18519 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18520 } 18521 18522 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18523 SourceLocation PragmaLoc, 18524 SourceLocation NameLoc) { 18525 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18526 18527 if (PrevDecl) { 18528 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18529 } else { 18530 (void)WeakUndeclaredIdentifiers.insert( 18531 std::pair<IdentifierInfo*,WeakInfo> 18532 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18533 } 18534 } 18535 18536 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18537 IdentifierInfo* AliasName, 18538 SourceLocation PragmaLoc, 18539 SourceLocation NameLoc, 18540 SourceLocation AliasNameLoc) { 18541 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18542 LookupOrdinaryName); 18543 WeakInfo W = WeakInfo(Name, NameLoc); 18544 18545 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18546 if (!PrevDecl->hasAttr<AliasAttr>()) 18547 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18548 DeclApplyPragmaWeak(TUScope, ND, W); 18549 } else { 18550 (void)WeakUndeclaredIdentifiers.insert( 18551 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18552 } 18553 } 18554 18555 Decl *Sema::getObjCDeclContext() const { 18556 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18557 } 18558 18559 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18560 bool Final) { 18561 assert(FD && "Expected non-null FunctionDecl"); 18562 18563 // SYCL functions can be template, so we check if they have appropriate 18564 // attribute prior to checking if it is a template. 18565 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18566 return FunctionEmissionStatus::Emitted; 18567 18568 // Templates are emitted when they're instantiated. 18569 if (FD->isDependentContext()) 18570 return FunctionEmissionStatus::TemplateDiscarded; 18571 18572 // Check whether this function is an externally visible definition. 18573 auto IsEmittedForExternalSymbol = [this, FD]() { 18574 // We have to check the GVA linkage of the function's *definition* -- if we 18575 // only have a declaration, we don't know whether or not the function will 18576 // be emitted, because (say) the definition could include "inline". 18577 FunctionDecl *Def = FD->getDefinition(); 18578 18579 return Def && !isDiscardableGVALinkage( 18580 getASTContext().GetGVALinkageForFunction(Def)); 18581 }; 18582 18583 if (LangOpts.OpenMPIsDevice) { 18584 // In OpenMP device mode we will not emit host only functions, or functions 18585 // we don't need due to their linkage. 18586 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18587 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18588 // DevTy may be changed later by 18589 // #pragma omp declare target to(*) device_type(*). 18590 // Therefore DevTy having no value does not imply host. The emission status 18591 // will be checked again at the end of compilation unit with Final = true. 18592 if (DevTy.hasValue()) 18593 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18594 return FunctionEmissionStatus::OMPDiscarded; 18595 // If we have an explicit value for the device type, or we are in a target 18596 // declare context, we need to emit all extern and used symbols. 18597 if (isInOpenMPDeclareTargetContext() || DevTy.hasValue()) 18598 if (IsEmittedForExternalSymbol()) 18599 return FunctionEmissionStatus::Emitted; 18600 // Device mode only emits what it must, if it wasn't tagged yet and needed, 18601 // we'll omit it. 18602 if (Final) 18603 return FunctionEmissionStatus::OMPDiscarded; 18604 } else if (LangOpts.OpenMP > 45) { 18605 // In OpenMP host compilation prior to 5.0 everything was an emitted host 18606 // function. In 5.0, no_host was introduced which might cause a function to 18607 // be ommitted. 18608 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18609 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18610 if (DevTy.hasValue()) 18611 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 18612 return FunctionEmissionStatus::OMPDiscarded; 18613 } 18614 18615 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 18616 return FunctionEmissionStatus::Emitted; 18617 18618 if (LangOpts.CUDA) { 18619 // When compiling for device, host functions are never emitted. Similarly, 18620 // when compiling for host, device and global functions are never emitted. 18621 // (Technically, we do emit a host-side stub for global functions, but this 18622 // doesn't count for our purposes here.) 18623 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18624 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18625 return FunctionEmissionStatus::CUDADiscarded; 18626 if (!LangOpts.CUDAIsDevice && 18627 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18628 return FunctionEmissionStatus::CUDADiscarded; 18629 18630 if (IsEmittedForExternalSymbol()) 18631 return FunctionEmissionStatus::Emitted; 18632 } 18633 18634 // Otherwise, the function is known-emitted if it's in our set of 18635 // known-emitted functions. 18636 return FunctionEmissionStatus::Unknown; 18637 } 18638 18639 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18640 // Host-side references to a __global__ function refer to the stub, so the 18641 // function itself is never emitted and therefore should not be marked. 18642 // If we have host fn calls kernel fn calls host+device, the HD function 18643 // does not get instantiated on the host. We model this by omitting at the 18644 // call to the kernel from the callgraph. This ensures that, when compiling 18645 // for host, only HD functions actually called from the host get marked as 18646 // known-emitted. 18647 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18648 IdentifyCUDATarget(Callee) == CFT_Global; 18649 } 18650