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_wchar_t: 145 case tok::kw_bool: 146 case tok::kw___underlying_type: 147 case tok::kw___auto_type: 148 return true; 149 150 case tok::annot_typename: 151 case tok::kw_char16_t: 152 case tok::kw_char32_t: 153 case tok::kw_typeof: 154 case tok::annot_decltype: 155 case tok::kw_decltype: 156 return getLangOpts().CPlusPlus; 157 158 case tok::kw_char8_t: 159 return getLangOpts().Char8; 160 161 default: 162 break; 163 } 164 165 return false; 166 } 167 168 namespace { 169 enum class UnqualifiedTypeNameLookupResult { 170 NotFound, 171 FoundNonType, 172 FoundType 173 }; 174 } // end anonymous namespace 175 176 /// Tries to perform unqualified lookup of the type decls in bases for 177 /// dependent class. 178 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 179 /// type decl, \a FoundType if only type decls are found. 180 static UnqualifiedTypeNameLookupResult 181 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 182 SourceLocation NameLoc, 183 const CXXRecordDecl *RD) { 184 if (!RD->hasDefinition()) 185 return UnqualifiedTypeNameLookupResult::NotFound; 186 // Look for type decls in base classes. 187 UnqualifiedTypeNameLookupResult FoundTypeDecl = 188 UnqualifiedTypeNameLookupResult::NotFound; 189 for (const auto &Base : RD->bases()) { 190 const CXXRecordDecl *BaseRD = nullptr; 191 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 192 BaseRD = BaseTT->getAsCXXRecordDecl(); 193 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 194 // Look for type decls in dependent base classes that have known primary 195 // templates. 196 if (!TST || !TST->isDependentType()) 197 continue; 198 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 199 if (!TD) 200 continue; 201 if (auto *BasePrimaryTemplate = 202 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 204 BaseRD = BasePrimaryTemplate; 205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 206 if (const ClassTemplatePartialSpecializationDecl *PS = 207 CTD->findPartialSpecialization(Base.getType())) 208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 209 BaseRD = PS; 210 } 211 } 212 } 213 if (BaseRD) { 214 for (NamedDecl *ND : BaseRD->lookup(&II)) { 215 if (!isa<TypeDecl>(ND)) 216 return UnqualifiedTypeNameLookupResult::FoundNonType; 217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 218 } 219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 221 case UnqualifiedTypeNameLookupResult::FoundNonType: 222 return UnqualifiedTypeNameLookupResult::FoundNonType; 223 case UnqualifiedTypeNameLookupResult::FoundType: 224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 225 break; 226 case UnqualifiedTypeNameLookupResult::NotFound: 227 break; 228 } 229 } 230 } 231 } 232 233 return FoundTypeDecl; 234 } 235 236 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 237 const IdentifierInfo &II, 238 SourceLocation NameLoc) { 239 // Lookup in the parent class template context, if any. 240 const CXXRecordDecl *RD = nullptr; 241 UnqualifiedTypeNameLookupResult FoundTypeDecl = 242 UnqualifiedTypeNameLookupResult::NotFound; 243 for (DeclContext *DC = S.CurContext; 244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 245 DC = DC->getParent()) { 246 // Look for type decls in dependent base classes that have known primary 247 // templates. 248 RD = dyn_cast<CXXRecordDecl>(DC); 249 if (RD && RD->getDescribedClassTemplate()) 250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 251 } 252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 253 return nullptr; 254 255 // We found some types in dependent base classes. Recover as if the user 256 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 257 // lookup during template instantiation. 258 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II; 259 260 ASTContext &Context = S.Context; 261 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 262 cast<Type>(Context.getRecordType(RD))); 263 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 264 265 CXXScopeSpec SS; 266 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 267 268 TypeLocBuilder Builder; 269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 270 DepTL.setNameLoc(NameLoc); 271 DepTL.setElaboratedKeywordLoc(SourceLocation()); 272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 273 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 274 } 275 276 /// If the identifier refers to a type name within this scope, 277 /// return the declaration of that type. 278 /// 279 /// This routine performs ordinary name lookup of the identifier II 280 /// within the given scope, with optional C++ scope specifier SS, to 281 /// determine whether the name refers to a type. If so, returns an 282 /// opaque pointer (actually a QualType) corresponding to that 283 /// type. Otherwise, returns NULL. 284 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 285 Scope *S, CXXScopeSpec *SS, 286 bool isClassName, bool HasTrailingDot, 287 ParsedType ObjectTypePtr, 288 bool IsCtorOrDtorName, 289 bool WantNontrivialTypeSourceInfo, 290 bool IsClassTemplateDeductionContext, 291 IdentifierInfo **CorrectedII) { 292 // FIXME: Consider allowing this outside C++1z mode as an extension. 293 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 294 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 295 !isClassName && !HasTrailingDot; 296 297 // Determine where we will perform name lookup. 298 DeclContext *LookupCtx = nullptr; 299 if (ObjectTypePtr) { 300 QualType ObjectType = ObjectTypePtr.get(); 301 if (ObjectType->isRecordType()) 302 LookupCtx = computeDeclContext(ObjectType); 303 } else if (SS && SS->isNotEmpty()) { 304 LookupCtx = computeDeclContext(*SS, false); 305 306 if (!LookupCtx) { 307 if (isDependentScopeSpecifier(*SS)) { 308 // C++ [temp.res]p3: 309 // A qualified-id that refers to a type and in which the 310 // nested-name-specifier depends on a template-parameter (14.6.2) 311 // shall be prefixed by the keyword typename to indicate that the 312 // qualified-id denotes a type, forming an 313 // elaborated-type-specifier (7.1.5.3). 314 // 315 // We therefore do not perform any name lookup if the result would 316 // refer to a member of an unknown specialization. 317 if (!isClassName && !IsCtorOrDtorName) 318 return nullptr; 319 320 // We know from the grammar that this name refers to a type, 321 // so build a dependent node to describe the type. 322 if (WantNontrivialTypeSourceInfo) 323 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 324 325 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 326 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 327 II, NameLoc); 328 return ParsedType::make(T); 329 } 330 331 return nullptr; 332 } 333 334 if (!LookupCtx->isDependentContext() && 335 RequireCompleteDeclContext(*SS, LookupCtx)) 336 return nullptr; 337 } 338 339 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 340 // lookup for class-names. 341 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 342 LookupOrdinaryName; 343 LookupResult Result(*this, &II, NameLoc, Kind); 344 if (LookupCtx) { 345 // Perform "qualified" name lookup into the declaration context we 346 // computed, which is either the type of the base of a member access 347 // expression or the declaration context associated with a prior 348 // nested-name-specifier. 349 LookupQualifiedName(Result, LookupCtx); 350 351 if (ObjectTypePtr && Result.empty()) { 352 // C++ [basic.lookup.classref]p3: 353 // If the unqualified-id is ~type-name, the type-name is looked up 354 // in the context of the entire postfix-expression. If the type T of 355 // the object expression is of a class type C, the type-name is also 356 // looked up in the scope of class C. At least one of the lookups shall 357 // find a name that refers to (possibly cv-qualified) T. 358 LookupName(Result, S); 359 } 360 } else { 361 // Perform unqualified name lookup. 362 LookupName(Result, S); 363 364 // For unqualified lookup in a class template in MSVC mode, look into 365 // dependent base classes where the primary class template is known. 366 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 367 if (ParsedType TypeInBase = 368 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 369 return TypeInBase; 370 } 371 } 372 373 NamedDecl *IIDecl = nullptr; 374 switch (Result.getResultKind()) { 375 case LookupResult::NotFound: 376 case LookupResult::NotFoundInCurrentInstantiation: 377 if (CorrectedII) { 378 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 379 AllowDeducedTemplate); 380 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 381 S, SS, CCC, CTK_ErrorRecovery); 382 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 383 TemplateTy Template; 384 bool MemberOfUnknownSpecialization; 385 UnqualifiedId TemplateName; 386 TemplateName.setIdentifier(NewII, NameLoc); 387 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 388 CXXScopeSpec NewSS, *NewSSPtr = SS; 389 if (SS && NNS) { 390 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 391 NewSSPtr = &NewSS; 392 } 393 if (Correction && (NNS || NewII != &II) && 394 // Ignore a correction to a template type as the to-be-corrected 395 // identifier is not a template (typo correction for template names 396 // is handled elsewhere). 397 !(getLangOpts().CPlusPlus && NewSSPtr && 398 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 399 Template, MemberOfUnknownSpecialization))) { 400 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 401 isClassName, HasTrailingDot, ObjectTypePtr, 402 IsCtorOrDtorName, 403 WantNontrivialTypeSourceInfo, 404 IsClassTemplateDeductionContext); 405 if (Ty) { 406 diagnoseTypo(Correction, 407 PDiag(diag::err_unknown_type_or_class_name_suggest) 408 << Result.getLookupName() << isClassName); 409 if (SS && NNS) 410 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 411 *CorrectedII = NewII; 412 return Ty; 413 } 414 } 415 } 416 // If typo correction failed or was not performed, fall through 417 LLVM_FALLTHROUGH; 418 case LookupResult::FoundOverloaded: 419 case LookupResult::FoundUnresolvedValue: 420 Result.suppressDiagnostics(); 421 return nullptr; 422 423 case LookupResult::Ambiguous: 424 // Recover from type-hiding ambiguities by hiding the type. We'll 425 // do the lookup again when looking for an object, and we can 426 // diagnose the error then. If we don't do this, then the error 427 // about hiding the type will be immediately followed by an error 428 // that only makes sense if the identifier was treated like a type. 429 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 430 Result.suppressDiagnostics(); 431 return nullptr; 432 } 433 434 // Look to see if we have a type anywhere in the list of results. 435 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 436 Res != ResEnd; ++Res) { 437 NamedDecl *RealRes = (*Res)->getUnderlyingDecl(); 438 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>( 439 RealRes) || 440 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) { 441 if (!IIDecl || 442 // Make the selection of the recovery decl deterministic. 443 RealRes->getLocation() < IIDecl->getLocation()) 444 IIDecl = RealRes; 445 } 446 } 447 448 if (!IIDecl) { 449 // None of the entities we found is a type, so there is no way 450 // to even assume that the result is a type. In this case, don't 451 // complain about the ambiguity. The parser will either try to 452 // perform this lookup again (e.g., as an object name), which 453 // will produce the ambiguity, or will complain that it expected 454 // a type name. 455 Result.suppressDiagnostics(); 456 return nullptr; 457 } 458 459 // We found a type within the ambiguous lookup; diagnose the 460 // ambiguity and then return that type. This might be the right 461 // answer, or it might not be, but it suppresses any attempt to 462 // perform the name lookup again. 463 break; 464 465 case LookupResult::Found: 466 IIDecl = Result.getFoundDecl(); 467 break; 468 } 469 470 assert(IIDecl && "Didn't find decl"); 471 472 QualType T; 473 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 474 // C++ [class.qual]p2: A lookup that would find the injected-class-name 475 // instead names the constructors of the class, except when naming a class. 476 // This is ill-formed when we're not actually forming a ctor or dtor name. 477 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 478 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 479 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 480 FoundRD->isInjectedClassName() && 481 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 482 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 483 << &II << /*Type*/1; 484 485 DiagnoseUseOfDecl(IIDecl, NameLoc); 486 487 T = Context.getTypeDeclType(TD); 488 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 489 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 490 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 491 if (!HasTrailingDot) 492 T = Context.getObjCInterfaceType(IDecl); 493 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) { 494 (void)DiagnoseUseOfDecl(UD, NameLoc); 495 // Recover with 'int' 496 T = Context.IntTy; 497 } else if (AllowDeducedTemplate) { 498 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 499 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 500 QualType(), false); 501 } 502 503 if (T.isNull()) { 504 // If it's not plausibly a type, suppress diagnostics. 505 Result.suppressDiagnostics(); 506 return nullptr; 507 } 508 509 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 510 // constructor or destructor name (in such a case, the scope specifier 511 // will be attached to the enclosing Expr or Decl node). 512 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 513 !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) { 514 if (WantNontrivialTypeSourceInfo) { 515 // Construct a type with type-source information. 516 TypeLocBuilder Builder; 517 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 518 519 T = getElaboratedType(ETK_None, *SS, T); 520 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 521 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 522 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 523 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 524 } else { 525 T = getElaboratedType(ETK_None, *SS, T); 526 } 527 } 528 529 return ParsedType::make(T); 530 } 531 532 // Builds a fake NNS for the given decl context. 533 static NestedNameSpecifier * 534 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 535 for (;; DC = DC->getLookupParent()) { 536 DC = DC->getPrimaryContext(); 537 auto *ND = dyn_cast<NamespaceDecl>(DC); 538 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 539 return NestedNameSpecifier::Create(Context, nullptr, ND); 540 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 541 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 542 RD->getTypeForDecl()); 543 else if (isa<TranslationUnitDecl>(DC)) 544 return NestedNameSpecifier::GlobalSpecifier(Context); 545 } 546 llvm_unreachable("something isn't in TU scope?"); 547 } 548 549 /// Find the parent class with dependent bases of the innermost enclosing method 550 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 551 /// up allowing unqualified dependent type names at class-level, which MSVC 552 /// correctly rejects. 553 static const CXXRecordDecl * 554 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 555 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 556 DC = DC->getPrimaryContext(); 557 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 558 if (MD->getParent()->hasAnyDependentBases()) 559 return MD->getParent(); 560 } 561 return nullptr; 562 } 563 564 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 565 SourceLocation NameLoc, 566 bool IsTemplateTypeArg) { 567 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 568 569 NestedNameSpecifier *NNS = nullptr; 570 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 571 // If we weren't able to parse a default template argument, delay lookup 572 // until instantiation time by making a non-dependent DependentTypeName. We 573 // pretend we saw a NestedNameSpecifier referring to the current scope, and 574 // lookup is retried. 575 // FIXME: This hurts our diagnostic quality, since we get errors like "no 576 // type named 'Foo' in 'current_namespace'" when the user didn't write any 577 // name specifiers. 578 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 579 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 580 } else if (const CXXRecordDecl *RD = 581 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 582 // Build a DependentNameType that will perform lookup into RD at 583 // instantiation time. 584 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 585 RD->getTypeForDecl()); 586 587 // Diagnose that this identifier was undeclared, and retry the lookup during 588 // template instantiation. 589 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 590 << RD; 591 } else { 592 // This is not a situation that we should recover from. 593 return ParsedType(); 594 } 595 596 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 597 598 // Build type location information. We synthesized the qualifier, so we have 599 // to build a fake NestedNameSpecifierLoc. 600 NestedNameSpecifierLocBuilder NNSLocBuilder; 601 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 602 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 603 604 TypeLocBuilder Builder; 605 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 606 DepTL.setNameLoc(NameLoc); 607 DepTL.setElaboratedKeywordLoc(SourceLocation()); 608 DepTL.setQualifierLoc(QualifierLoc); 609 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 610 } 611 612 /// isTagName() - This method is called *for error recovery purposes only* 613 /// to determine if the specified name is a valid tag name ("struct foo"). If 614 /// so, this returns the TST for the tag corresponding to it (TST_enum, 615 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 616 /// cases in C where the user forgot to specify the tag. 617 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 618 // Do a tag name lookup in this scope. 619 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 620 LookupName(R, S, false); 621 R.suppressDiagnostics(); 622 if (R.getResultKind() == LookupResult::Found) 623 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 624 switch (TD->getTagKind()) { 625 case TTK_Struct: return DeclSpec::TST_struct; 626 case TTK_Interface: return DeclSpec::TST_interface; 627 case TTK_Union: return DeclSpec::TST_union; 628 case TTK_Class: return DeclSpec::TST_class; 629 case TTK_Enum: return DeclSpec::TST_enum; 630 } 631 } 632 633 return DeclSpec::TST_unspecified; 634 } 635 636 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 637 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 638 /// then downgrade the missing typename error to a warning. 639 /// This is needed for MSVC compatibility; Example: 640 /// @code 641 /// template<class T> class A { 642 /// public: 643 /// typedef int TYPE; 644 /// }; 645 /// template<class T> class B : public A<T> { 646 /// public: 647 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 648 /// }; 649 /// @endcode 650 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 651 if (CurContext->isRecord()) { 652 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 653 return true; 654 655 const Type *Ty = SS->getScopeRep()->getAsType(); 656 657 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 658 for (const auto &Base : RD->bases()) 659 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 660 return true; 661 return S->isFunctionPrototypeScope(); 662 } 663 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 664 } 665 666 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 667 SourceLocation IILoc, 668 Scope *S, 669 CXXScopeSpec *SS, 670 ParsedType &SuggestedType, 671 bool IsTemplateName) { 672 // Don't report typename errors for editor placeholders. 673 if (II->isEditorPlaceholder()) 674 return; 675 // We don't have anything to suggest (yet). 676 SuggestedType = nullptr; 677 678 // There may have been a typo in the name of the type. Look up typo 679 // results, in case we have something that we can suggest. 680 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 681 /*AllowTemplates=*/IsTemplateName, 682 /*AllowNonTemplates=*/!IsTemplateName); 683 if (TypoCorrection Corrected = 684 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 685 CCC, CTK_ErrorRecovery)) { 686 // FIXME: Support error recovery for the template-name case. 687 bool CanRecover = !IsTemplateName; 688 if (Corrected.isKeyword()) { 689 // We corrected to a keyword. 690 diagnoseTypo(Corrected, 691 PDiag(IsTemplateName ? diag::err_no_template_suggest 692 : diag::err_unknown_typename_suggest) 693 << II); 694 II = Corrected.getCorrectionAsIdentifierInfo(); 695 } else { 696 // We found a similarly-named type or interface; suggest that. 697 if (!SS || !SS->isSet()) { 698 diagnoseTypo(Corrected, 699 PDiag(IsTemplateName ? diag::err_no_template_suggest 700 : diag::err_unknown_typename_suggest) 701 << II, CanRecover); 702 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 703 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 704 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 705 II->getName().equals(CorrectedStr); 706 diagnoseTypo(Corrected, 707 PDiag(IsTemplateName 708 ? diag::err_no_member_template_suggest 709 : diag::err_unknown_nested_typename_suggest) 710 << II << DC << DroppedSpecifier << SS->getRange(), 711 CanRecover); 712 } else { 713 llvm_unreachable("could not have corrected a typo here"); 714 } 715 716 if (!CanRecover) 717 return; 718 719 CXXScopeSpec tmpSS; 720 if (Corrected.getCorrectionSpecifier()) 721 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 722 SourceRange(IILoc)); 723 // FIXME: Support class template argument deduction here. 724 SuggestedType = 725 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 726 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 727 /*IsCtorOrDtorName=*/false, 728 /*WantNontrivialTypeSourceInfo=*/true); 729 } 730 return; 731 } 732 733 if (getLangOpts().CPlusPlus && !IsTemplateName) { 734 // See if II is a class template that the user forgot to pass arguments to. 735 UnqualifiedId Name; 736 Name.setIdentifier(II, IILoc); 737 CXXScopeSpec EmptySS; 738 TemplateTy TemplateResult; 739 bool MemberOfUnknownSpecialization; 740 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 741 Name, nullptr, true, TemplateResult, 742 MemberOfUnknownSpecialization) == TNK_Type_template) { 743 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 744 return; 745 } 746 } 747 748 // FIXME: Should we move the logic that tries to recover from a missing tag 749 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 750 751 if (!SS || (!SS->isSet() && !SS->isInvalid())) 752 Diag(IILoc, IsTemplateName ? diag::err_no_template 753 : diag::err_unknown_typename) 754 << II; 755 else if (DeclContext *DC = computeDeclContext(*SS, false)) 756 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 757 : diag::err_typename_nested_not_found) 758 << II << DC << SS->getRange(); 759 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { 760 SuggestedType = 761 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); 762 } else if (isDependentScopeSpecifier(*SS)) { 763 unsigned DiagID = diag::err_typename_missing; 764 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 765 DiagID = diag::ext_typename_missing; 766 767 Diag(SS->getRange().getBegin(), DiagID) 768 << SS->getScopeRep() << II->getName() 769 << SourceRange(SS->getRange().getBegin(), IILoc) 770 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 771 SuggestedType = ActOnTypenameType(S, SourceLocation(), 772 *SS, *II, IILoc).get(); 773 } else { 774 assert(SS && SS->isInvalid() && 775 "Invalid scope specifier has already been diagnosed"); 776 } 777 } 778 779 /// Determine whether the given result set contains either a type name 780 /// or 781 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 782 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 783 NextToken.is(tok::less); 784 785 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 786 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 787 return true; 788 789 if (CheckTemplate && isa<TemplateDecl>(*I)) 790 return true; 791 } 792 793 return false; 794 } 795 796 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 797 Scope *S, CXXScopeSpec &SS, 798 IdentifierInfo *&Name, 799 SourceLocation NameLoc) { 800 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 801 SemaRef.LookupParsedName(R, S, &SS); 802 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 803 StringRef FixItTagName; 804 switch (Tag->getTagKind()) { 805 case TTK_Class: 806 FixItTagName = "class "; 807 break; 808 809 case TTK_Enum: 810 FixItTagName = "enum "; 811 break; 812 813 case TTK_Struct: 814 FixItTagName = "struct "; 815 break; 816 817 case TTK_Interface: 818 FixItTagName = "__interface "; 819 break; 820 821 case TTK_Union: 822 FixItTagName = "union "; 823 break; 824 } 825 826 StringRef TagName = FixItTagName.drop_back(); 827 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 828 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 829 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 830 831 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 832 I != IEnd; ++I) 833 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 834 << Name << TagName; 835 836 // Replace lookup results with just the tag decl. 837 Result.clear(Sema::LookupTagName); 838 SemaRef.LookupParsedName(Result, S, &SS); 839 return true; 840 } 841 842 return false; 843 } 844 845 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 846 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 847 QualType T, SourceLocation NameLoc) { 848 ASTContext &Context = S.Context; 849 850 TypeLocBuilder Builder; 851 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 852 853 T = S.getElaboratedType(ETK_None, SS, T); 854 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 855 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 856 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 857 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 858 } 859 860 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 861 IdentifierInfo *&Name, 862 SourceLocation NameLoc, 863 const Token &NextToken, 864 CorrectionCandidateCallback *CCC) { 865 DeclarationNameInfo NameInfo(Name, NameLoc); 866 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 867 868 assert(NextToken.isNot(tok::coloncolon) && 869 "parse nested name specifiers before calling ClassifyName"); 870 if (getLangOpts().CPlusPlus && SS.isSet() && 871 isCurrentClassName(*Name, S, &SS)) { 872 // Per [class.qual]p2, this names the constructors of SS, not the 873 // injected-class-name. We don't have a classification for that. 874 // There's not much point caching this result, since the parser 875 // will reject it later. 876 return NameClassification::Unknown(); 877 } 878 879 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 880 LookupParsedName(Result, S, &SS, !CurMethod); 881 882 if (SS.isInvalid()) 883 return NameClassification::Error(); 884 885 // For unqualified lookup in a class template in MSVC mode, look into 886 // dependent base classes where the primary class template is known. 887 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 888 if (ParsedType TypeInBase = 889 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 890 return TypeInBase; 891 } 892 893 // Perform lookup for Objective-C instance variables (including automatically 894 // synthesized instance variables), if we're in an Objective-C method. 895 // FIXME: This lookup really, really needs to be folded in to the normal 896 // unqualified lookup mechanism. 897 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 898 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 899 if (Ivar.isInvalid()) 900 return NameClassification::Error(); 901 if (Ivar.isUsable()) 902 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 903 904 // We defer builtin creation until after ivar lookup inside ObjC methods. 905 if (Result.empty()) 906 LookupBuiltin(Result); 907 } 908 909 bool SecondTry = false; 910 bool IsFilteredTemplateName = false; 911 912 Corrected: 913 switch (Result.getResultKind()) { 914 case LookupResult::NotFound: 915 // If an unqualified-id is followed by a '(', then we have a function 916 // call. 917 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 918 // In C++, this is an ADL-only call. 919 // FIXME: Reference? 920 if (getLangOpts().CPlusPlus) 921 return NameClassification::UndeclaredNonType(); 922 923 // C90 6.3.2.2: 924 // If the expression that precedes the parenthesized argument list in a 925 // function call consists solely of an identifier, and if no 926 // declaration is visible for this identifier, the identifier is 927 // implicitly declared exactly as if, in the innermost block containing 928 // the function call, the declaration 929 // 930 // extern int identifier (); 931 // 932 // appeared. 933 // 934 // We also allow this in C99 as an extension. 935 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 936 return NameClassification::NonType(D); 937 } 938 939 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 940 // In C++20 onwards, this could be an ADL-only call to a function 941 // template, and we're required to assume that this is a template name. 942 // 943 // FIXME: Find a way to still do typo correction in this case. 944 TemplateName Template = 945 Context.getAssumedTemplateName(NameInfo.getName()); 946 return NameClassification::UndeclaredTemplate(Template); 947 } 948 949 // In C, we first see whether there is a tag type by the same name, in 950 // which case it's likely that the user just forgot to write "enum", 951 // "struct", or "union". 952 if (!getLangOpts().CPlusPlus && !SecondTry && 953 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 954 break; 955 } 956 957 // Perform typo correction to determine if there is another name that is 958 // close to this name. 959 if (!SecondTry && CCC) { 960 SecondTry = true; 961 if (TypoCorrection Corrected = 962 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 963 &SS, *CCC, CTK_ErrorRecovery)) { 964 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 965 unsigned QualifiedDiag = diag::err_no_member_suggest; 966 967 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 968 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 969 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 970 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 971 UnqualifiedDiag = diag::err_no_template_suggest; 972 QualifiedDiag = diag::err_no_member_template_suggest; 973 } else if (UnderlyingFirstDecl && 974 (isa<TypeDecl>(UnderlyingFirstDecl) || 975 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 976 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 977 UnqualifiedDiag = diag::err_unknown_typename_suggest; 978 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 979 } 980 981 if (SS.isEmpty()) { 982 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 983 } else {// FIXME: is this even reachable? Test it. 984 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 985 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 986 Name->getName().equals(CorrectedStr); 987 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 988 << Name << computeDeclContext(SS, false) 989 << DroppedSpecifier << SS.getRange()); 990 } 991 992 // Update the name, so that the caller has the new name. 993 Name = Corrected.getCorrectionAsIdentifierInfo(); 994 995 // Typo correction corrected to a keyword. 996 if (Corrected.isKeyword()) 997 return Name; 998 999 // Also update the LookupResult... 1000 // FIXME: This should probably go away at some point 1001 Result.clear(); 1002 Result.setLookupName(Corrected.getCorrection()); 1003 if (FirstDecl) 1004 Result.addDecl(FirstDecl); 1005 1006 // If we found an Objective-C instance variable, let 1007 // LookupInObjCMethod build the appropriate expression to 1008 // reference the ivar. 1009 // FIXME: This is a gross hack. 1010 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1011 DeclResult R = 1012 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1013 if (R.isInvalid()) 1014 return NameClassification::Error(); 1015 if (R.isUsable()) 1016 return NameClassification::NonType(Ivar); 1017 } 1018 1019 goto Corrected; 1020 } 1021 } 1022 1023 // We failed to correct; just fall through and let the parser deal with it. 1024 Result.suppressDiagnostics(); 1025 return NameClassification::Unknown(); 1026 1027 case LookupResult::NotFoundInCurrentInstantiation: { 1028 // We performed name lookup into the current instantiation, and there were 1029 // dependent bases, so we treat this result the same way as any other 1030 // dependent nested-name-specifier. 1031 1032 // C++ [temp.res]p2: 1033 // A name used in a template declaration or definition and that is 1034 // dependent on a template-parameter is assumed not to name a type 1035 // unless the applicable name lookup finds a type name or the name is 1036 // qualified by the keyword typename. 1037 // 1038 // FIXME: If the next token is '<', we might want to ask the parser to 1039 // perform some heroics to see if we actually have a 1040 // template-argument-list, which would indicate a missing 'template' 1041 // keyword here. 1042 return NameClassification::DependentNonType(); 1043 } 1044 1045 case LookupResult::Found: 1046 case LookupResult::FoundOverloaded: 1047 case LookupResult::FoundUnresolvedValue: 1048 break; 1049 1050 case LookupResult::Ambiguous: 1051 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1052 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1053 /*AllowDependent=*/false)) { 1054 // C++ [temp.local]p3: 1055 // A lookup that finds an injected-class-name (10.2) can result in an 1056 // ambiguity in certain cases (for example, if it is found in more than 1057 // one base class). If all of the injected-class-names that are found 1058 // refer to specializations of the same class template, and if the name 1059 // is followed by a template-argument-list, the reference refers to the 1060 // class template itself and not a specialization thereof, and is not 1061 // ambiguous. 1062 // 1063 // This filtering can make an ambiguous result into an unambiguous one, 1064 // so try again after filtering out template names. 1065 FilterAcceptableTemplateNames(Result); 1066 if (!Result.isAmbiguous()) { 1067 IsFilteredTemplateName = true; 1068 break; 1069 } 1070 } 1071 1072 // Diagnose the ambiguity and return an error. 1073 return NameClassification::Error(); 1074 } 1075 1076 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1077 (IsFilteredTemplateName || 1078 hasAnyAcceptableTemplateNames( 1079 Result, /*AllowFunctionTemplates=*/true, 1080 /*AllowDependent=*/false, 1081 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1082 getLangOpts().CPlusPlus20))) { 1083 // C++ [temp.names]p3: 1084 // After name lookup (3.4) finds that a name is a template-name or that 1085 // an operator-function-id or a literal- operator-id refers to a set of 1086 // overloaded functions any member of which is a function template if 1087 // this is followed by a <, the < is always taken as the delimiter of a 1088 // template-argument-list and never as the less-than operator. 1089 // C++2a [temp.names]p2: 1090 // A name is also considered to refer to a template if it is an 1091 // unqualified-id followed by a < and name lookup finds either one 1092 // or more functions or finds nothing. 1093 if (!IsFilteredTemplateName) 1094 FilterAcceptableTemplateNames(Result); 1095 1096 bool IsFunctionTemplate; 1097 bool IsVarTemplate; 1098 TemplateName Template; 1099 if (Result.end() - Result.begin() > 1) { 1100 IsFunctionTemplate = true; 1101 Template = Context.getOverloadedTemplateName(Result.begin(), 1102 Result.end()); 1103 } else if (!Result.empty()) { 1104 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1105 *Result.begin(), /*AllowFunctionTemplates=*/true, 1106 /*AllowDependent=*/false)); 1107 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1108 IsVarTemplate = isa<VarTemplateDecl>(TD); 1109 1110 if (SS.isNotEmpty()) 1111 Template = 1112 Context.getQualifiedTemplateName(SS.getScopeRep(), 1113 /*TemplateKeyword=*/false, TD); 1114 else 1115 Template = TemplateName(TD); 1116 } else { 1117 // All results were non-template functions. This is a function template 1118 // name. 1119 IsFunctionTemplate = true; 1120 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1121 } 1122 1123 if (IsFunctionTemplate) { 1124 // Function templates always go through overload resolution, at which 1125 // point we'll perform the various checks (e.g., accessibility) we need 1126 // to based on which function we selected. 1127 Result.suppressDiagnostics(); 1128 1129 return NameClassification::FunctionTemplate(Template); 1130 } 1131 1132 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1133 : NameClassification::TypeTemplate(Template); 1134 } 1135 1136 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1137 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1138 DiagnoseUseOfDecl(Type, NameLoc); 1139 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1140 QualType T = Context.getTypeDeclType(Type); 1141 if (SS.isNotEmpty()) 1142 return buildNestedType(*this, SS, T, NameLoc); 1143 return ParsedType::make(T); 1144 } 1145 1146 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1147 if (!Class) { 1148 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1149 if (ObjCCompatibleAliasDecl *Alias = 1150 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1151 Class = Alias->getClassInterface(); 1152 } 1153 1154 if (Class) { 1155 DiagnoseUseOfDecl(Class, NameLoc); 1156 1157 if (NextToken.is(tok::period)) { 1158 // Interface. <something> is parsed as a property reference expression. 1159 // Just return "unknown" as a fall-through for now. 1160 Result.suppressDiagnostics(); 1161 return NameClassification::Unknown(); 1162 } 1163 1164 QualType T = Context.getObjCInterfaceType(Class); 1165 return ParsedType::make(T); 1166 } 1167 1168 if (isa<ConceptDecl>(FirstDecl)) 1169 return NameClassification::Concept( 1170 TemplateName(cast<TemplateDecl>(FirstDecl))); 1171 1172 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) { 1173 (void)DiagnoseUseOfDecl(EmptyD, NameLoc); 1174 return NameClassification::Error(); 1175 } 1176 1177 // We can have a type template here if we're classifying a template argument. 1178 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1179 !isa<VarTemplateDecl>(FirstDecl)) 1180 return NameClassification::TypeTemplate( 1181 TemplateName(cast<TemplateDecl>(FirstDecl))); 1182 1183 // Check for a tag type hidden by a non-type decl in a few cases where it 1184 // seems likely a type is wanted instead of the non-type that was found. 1185 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1186 if ((NextToken.is(tok::identifier) || 1187 (NextIsOp && 1188 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1189 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1190 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1191 DiagnoseUseOfDecl(Type, NameLoc); 1192 QualType T = Context.getTypeDeclType(Type); 1193 if (SS.isNotEmpty()) 1194 return buildNestedType(*this, SS, T, NameLoc); 1195 return ParsedType::make(T); 1196 } 1197 1198 // If we already know which single declaration is referenced, just annotate 1199 // that declaration directly. Defer resolving even non-overloaded class 1200 // member accesses, as we need to defer certain access checks until we know 1201 // the context. 1202 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1203 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember()) 1204 return NameClassification::NonType(Result.getRepresentativeDecl()); 1205 1206 // Otherwise, this is an overload set that we will need to resolve later. 1207 Result.suppressDiagnostics(); 1208 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( 1209 Context, Result.getNamingClass(), SS.getWithLocInContext(Context), 1210 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), 1211 Result.begin(), Result.end())); 1212 } 1213 1214 ExprResult 1215 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1216 SourceLocation NameLoc) { 1217 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1218 CXXScopeSpec SS; 1219 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1220 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1221 } 1222 1223 ExprResult 1224 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1225 IdentifierInfo *Name, 1226 SourceLocation NameLoc, 1227 bool IsAddressOfOperand) { 1228 DeclarationNameInfo NameInfo(Name, NameLoc); 1229 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1230 NameInfo, IsAddressOfOperand, 1231 /*TemplateArgs=*/nullptr); 1232 } 1233 1234 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1235 NamedDecl *Found, 1236 SourceLocation NameLoc, 1237 const Token &NextToken) { 1238 if (getCurMethodDecl() && SS.isEmpty()) 1239 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1240 return BuildIvarRefExpr(S, NameLoc, Ivar); 1241 1242 // Reconstruct the lookup result. 1243 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1244 Result.addDecl(Found); 1245 Result.resolveKind(); 1246 1247 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1248 return BuildDeclarationNameExpr(SS, Result, ADL); 1249 } 1250 1251 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { 1252 // For an implicit class member access, transform the result into a member 1253 // access expression if necessary. 1254 auto *ULE = cast<UnresolvedLookupExpr>(E); 1255 if ((*ULE->decls_begin())->isCXXClassMember()) { 1256 CXXScopeSpec SS; 1257 SS.Adopt(ULE->getQualifierLoc()); 1258 1259 // Reconstruct the lookup result. 1260 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), 1261 LookupOrdinaryName); 1262 Result.setNamingClass(ULE->getNamingClass()); 1263 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) 1264 Result.addDecl(*I, I.getAccess()); 1265 Result.resolveKind(); 1266 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1267 nullptr, S); 1268 } 1269 1270 // Otherwise, this is already in the form we needed, and no further checks 1271 // are necessary. 1272 return ULE; 1273 } 1274 1275 Sema::TemplateNameKindForDiagnostics 1276 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1277 auto *TD = Name.getAsTemplateDecl(); 1278 if (!TD) 1279 return TemplateNameKindForDiagnostics::DependentTemplate; 1280 if (isa<ClassTemplateDecl>(TD)) 1281 return TemplateNameKindForDiagnostics::ClassTemplate; 1282 if (isa<FunctionTemplateDecl>(TD)) 1283 return TemplateNameKindForDiagnostics::FunctionTemplate; 1284 if (isa<VarTemplateDecl>(TD)) 1285 return TemplateNameKindForDiagnostics::VarTemplate; 1286 if (isa<TypeAliasTemplateDecl>(TD)) 1287 return TemplateNameKindForDiagnostics::AliasTemplate; 1288 if (isa<TemplateTemplateParmDecl>(TD)) 1289 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1290 if (isa<ConceptDecl>(TD)) 1291 return TemplateNameKindForDiagnostics::Concept; 1292 return TemplateNameKindForDiagnostics::DependentTemplate; 1293 } 1294 1295 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1296 assert(DC->getLexicalParent() == CurContext && 1297 "The next DeclContext should be lexically contained in the current one."); 1298 CurContext = DC; 1299 S->setEntity(DC); 1300 } 1301 1302 void Sema::PopDeclContext() { 1303 assert(CurContext && "DeclContext imbalance!"); 1304 1305 CurContext = CurContext->getLexicalParent(); 1306 assert(CurContext && "Popped translation unit!"); 1307 } 1308 1309 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1310 Decl *D) { 1311 // Unlike PushDeclContext, the context to which we return is not necessarily 1312 // the containing DC of TD, because the new context will be some pre-existing 1313 // TagDecl definition instead of a fresh one. 1314 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1315 CurContext = cast<TagDecl>(D)->getDefinition(); 1316 assert(CurContext && "skipping definition of undefined tag"); 1317 // Start lookups from the parent of the current context; we don't want to look 1318 // into the pre-existing complete definition. 1319 S->setEntity(CurContext->getLookupParent()); 1320 return Result; 1321 } 1322 1323 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1324 CurContext = static_cast<decltype(CurContext)>(Context); 1325 } 1326 1327 /// EnterDeclaratorContext - Used when we must lookup names in the context 1328 /// of a declarator's nested name specifier. 1329 /// 1330 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1331 // C++0x [basic.lookup.unqual]p13: 1332 // A name used in the definition of a static data member of class 1333 // X (after the qualified-id of the static member) is looked up as 1334 // if the name was used in a member function of X. 1335 // C++0x [basic.lookup.unqual]p14: 1336 // If a variable member of a namespace is defined outside of the 1337 // scope of its namespace then any name used in the definition of 1338 // the variable member (after the declarator-id) is looked up as 1339 // if the definition of the variable member occurred in its 1340 // namespace. 1341 // Both of these imply that we should push a scope whose context 1342 // is the semantic context of the declaration. We can't use 1343 // PushDeclContext here because that context is not necessarily 1344 // lexically contained in the current context. Fortunately, 1345 // the containing scope should have the appropriate information. 1346 1347 assert(!S->getEntity() && "scope already has entity"); 1348 1349 #ifndef NDEBUG 1350 Scope *Ancestor = S->getParent(); 1351 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1352 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1353 #endif 1354 1355 CurContext = DC; 1356 S->setEntity(DC); 1357 1358 if (S->getParent()->isTemplateParamScope()) { 1359 // Also set the corresponding entities for all immediately-enclosing 1360 // template parameter scopes. 1361 EnterTemplatedContext(S->getParent(), DC); 1362 } 1363 } 1364 1365 void Sema::ExitDeclaratorContext(Scope *S) { 1366 assert(S->getEntity() == CurContext && "Context imbalance!"); 1367 1368 // Switch back to the lexical context. The safety of this is 1369 // enforced by an assert in EnterDeclaratorContext. 1370 Scope *Ancestor = S->getParent(); 1371 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1372 CurContext = Ancestor->getEntity(); 1373 1374 // We don't need to do anything with the scope, which is going to 1375 // disappear. 1376 } 1377 1378 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1379 assert(S->isTemplateParamScope() && 1380 "expected to be initializing a template parameter scope"); 1381 1382 // C++20 [temp.local]p7: 1383 // In the definition of a member of a class template that appears outside 1384 // of the class template definition, the name of a member of the class 1385 // template hides the name of a template-parameter of any enclosing class 1386 // templates (but not a template-parameter of the member if the member is a 1387 // class or function template). 1388 // C++20 [temp.local]p9: 1389 // In the definition of a class template or in the definition of a member 1390 // of such a template that appears outside of the template definition, for 1391 // each non-dependent base class (13.8.2.1), if the name of the base class 1392 // or the name of a member of the base class is the same as the name of a 1393 // template-parameter, the base class name or member name hides the 1394 // template-parameter name (6.4.10). 1395 // 1396 // This means that a template parameter scope should be searched immediately 1397 // after searching the DeclContext for which it is a template parameter 1398 // scope. For example, for 1399 // template<typename T> template<typename U> template<typename V> 1400 // void N::A<T>::B<U>::f(...) 1401 // we search V then B<U> (and base classes) then U then A<T> (and base 1402 // classes) then T then N then ::. 1403 unsigned ScopeDepth = getTemplateDepth(S); 1404 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1405 DeclContext *SearchDCAfterScope = DC; 1406 for (; DC; DC = DC->getLookupParent()) { 1407 if (const TemplateParameterList *TPL = 1408 cast<Decl>(DC)->getDescribedTemplateParams()) { 1409 unsigned DCDepth = TPL->getDepth() + 1; 1410 if (DCDepth > ScopeDepth) 1411 continue; 1412 if (ScopeDepth == DCDepth) 1413 SearchDCAfterScope = DC = DC->getLookupParent(); 1414 break; 1415 } 1416 } 1417 S->setLookupEntity(SearchDCAfterScope); 1418 } 1419 } 1420 1421 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1422 // We assume that the caller has already called 1423 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1424 FunctionDecl *FD = D->getAsFunction(); 1425 if (!FD) 1426 return; 1427 1428 // Same implementation as PushDeclContext, but enters the context 1429 // from the lexical parent, rather than the top-level class. 1430 assert(CurContext == FD->getLexicalParent() && 1431 "The next DeclContext should be lexically contained in the current one."); 1432 CurContext = FD; 1433 S->setEntity(CurContext); 1434 1435 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1436 ParmVarDecl *Param = FD->getParamDecl(P); 1437 // If the parameter has an identifier, then add it to the scope 1438 if (Param->getIdentifier()) { 1439 S->AddDecl(Param); 1440 IdResolver.AddDecl(Param); 1441 } 1442 } 1443 } 1444 1445 void Sema::ActOnExitFunctionContext() { 1446 // Same implementation as PopDeclContext, but returns to the lexical parent, 1447 // rather than the top-level class. 1448 assert(CurContext && "DeclContext imbalance!"); 1449 CurContext = CurContext->getLexicalParent(); 1450 assert(CurContext && "Popped translation unit!"); 1451 } 1452 1453 /// Determine whether we allow overloading of the function 1454 /// PrevDecl with another declaration. 1455 /// 1456 /// This routine determines whether overloading is possible, not 1457 /// whether some new function is actually an overload. It will return 1458 /// true in C++ (where we can always provide overloads) or, as an 1459 /// extension, in C when the previous function is already an 1460 /// overloaded function declaration or has the "overloadable" 1461 /// attribute. 1462 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1463 ASTContext &Context, 1464 const FunctionDecl *New) { 1465 if (Context.getLangOpts().CPlusPlus) 1466 return true; 1467 1468 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1469 return true; 1470 1471 return Previous.getResultKind() == LookupResult::Found && 1472 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1473 New->hasAttr<OverloadableAttr>()); 1474 } 1475 1476 /// Add this decl to the scope shadowed decl chains. 1477 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1478 // Move up the scope chain until we find the nearest enclosing 1479 // non-transparent context. The declaration will be introduced into this 1480 // scope. 1481 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1482 S = S->getParent(); 1483 1484 // Add scoped declarations into their context, so that they can be 1485 // found later. Declarations without a context won't be inserted 1486 // into any context. 1487 if (AddToContext) 1488 CurContext->addDecl(D); 1489 1490 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1491 // are function-local declarations. 1492 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) 1493 return; 1494 1495 // Template instantiations should also not be pushed into scope. 1496 if (isa<FunctionDecl>(D) && 1497 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1498 return; 1499 1500 // If this replaces anything in the current scope, 1501 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1502 IEnd = IdResolver.end(); 1503 for (; I != IEnd; ++I) { 1504 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1505 S->RemoveDecl(*I); 1506 IdResolver.RemoveDecl(*I); 1507 1508 // Should only need to replace one decl. 1509 break; 1510 } 1511 } 1512 1513 S->AddDecl(D); 1514 1515 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1516 // Implicitly-generated labels may end up getting generated in an order that 1517 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1518 // the label at the appropriate place in the identifier chain. 1519 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1520 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1521 if (IDC == CurContext) { 1522 if (!S->isDeclScope(*I)) 1523 continue; 1524 } else if (IDC->Encloses(CurContext)) 1525 break; 1526 } 1527 1528 IdResolver.InsertDeclAfter(I, D); 1529 } else { 1530 IdResolver.AddDecl(D); 1531 } 1532 warnOnReservedIdentifier(D); 1533 } 1534 1535 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1536 bool AllowInlineNamespace) { 1537 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1538 } 1539 1540 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1541 DeclContext *TargetDC = DC->getPrimaryContext(); 1542 do { 1543 if (DeclContext *ScopeDC = S->getEntity()) 1544 if (ScopeDC->getPrimaryContext() == TargetDC) 1545 return S; 1546 } while ((S = S->getParent())); 1547 1548 return nullptr; 1549 } 1550 1551 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1552 DeclContext*, 1553 ASTContext&); 1554 1555 /// Filters out lookup results that don't fall within the given scope 1556 /// as determined by isDeclInScope. 1557 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1558 bool ConsiderLinkage, 1559 bool AllowInlineNamespace) { 1560 LookupResult::Filter F = R.makeFilter(); 1561 while (F.hasNext()) { 1562 NamedDecl *D = F.next(); 1563 1564 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1565 continue; 1566 1567 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1568 continue; 1569 1570 F.erase(); 1571 } 1572 1573 F.done(); 1574 } 1575 1576 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1577 /// have compatible owning modules. 1578 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1579 // FIXME: The Modules TS is not clear about how friend declarations are 1580 // to be treated. It's not meaningful to have different owning modules for 1581 // linkage in redeclarations of the same entity, so for now allow the 1582 // redeclaration and change the owning modules to match. 1583 if (New->getFriendObjectKind() && 1584 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1585 New->setLocalOwningModule(Old->getOwningModule()); 1586 makeMergedDefinitionVisible(New); 1587 return false; 1588 } 1589 1590 Module *NewM = New->getOwningModule(); 1591 Module *OldM = Old->getOwningModule(); 1592 1593 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1594 NewM = NewM->Parent; 1595 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1596 OldM = OldM->Parent; 1597 1598 if (NewM == OldM) 1599 return false; 1600 1601 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1602 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1603 if (NewIsModuleInterface || OldIsModuleInterface) { 1604 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1605 // if a declaration of D [...] appears in the purview of a module, all 1606 // other such declarations shall appear in the purview of the same module 1607 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1608 << New 1609 << NewIsModuleInterface 1610 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1611 << OldIsModuleInterface 1612 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1613 Diag(Old->getLocation(), diag::note_previous_declaration); 1614 New->setInvalidDecl(); 1615 return true; 1616 } 1617 1618 return false; 1619 } 1620 1621 static bool isUsingDecl(NamedDecl *D) { 1622 return isa<UsingShadowDecl>(D) || 1623 isa<UnresolvedUsingTypenameDecl>(D) || 1624 isa<UnresolvedUsingValueDecl>(D); 1625 } 1626 1627 /// Removes using shadow declarations from the lookup results. 1628 static void RemoveUsingDecls(LookupResult &R) { 1629 LookupResult::Filter F = R.makeFilter(); 1630 while (F.hasNext()) 1631 if (isUsingDecl(F.next())) 1632 F.erase(); 1633 1634 F.done(); 1635 } 1636 1637 /// Check for this common pattern: 1638 /// @code 1639 /// class S { 1640 /// S(const S&); // DO NOT IMPLEMENT 1641 /// void operator=(const S&); // DO NOT IMPLEMENT 1642 /// }; 1643 /// @endcode 1644 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1645 // FIXME: Should check for private access too but access is set after we get 1646 // the decl here. 1647 if (D->doesThisDeclarationHaveABody()) 1648 return false; 1649 1650 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1651 return CD->isCopyConstructor(); 1652 return D->isCopyAssignmentOperator(); 1653 } 1654 1655 // We need this to handle 1656 // 1657 // typedef struct { 1658 // void *foo() { return 0; } 1659 // } A; 1660 // 1661 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1662 // for example. If 'A', foo will have external linkage. If we have '*A', 1663 // foo will have no linkage. Since we can't know until we get to the end 1664 // of the typedef, this function finds out if D might have non-external linkage. 1665 // Callers should verify at the end of the TU if it D has external linkage or 1666 // not. 1667 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1668 const DeclContext *DC = D->getDeclContext(); 1669 while (!DC->isTranslationUnit()) { 1670 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1671 if (!RD->hasNameForLinkage()) 1672 return true; 1673 } 1674 DC = DC->getParent(); 1675 } 1676 1677 return !D->isExternallyVisible(); 1678 } 1679 1680 // FIXME: This needs to be refactored; some other isInMainFile users want 1681 // these semantics. 1682 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1683 if (S.TUKind != TU_Complete) 1684 return false; 1685 return S.SourceMgr.isInMainFile(Loc); 1686 } 1687 1688 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1689 assert(D); 1690 1691 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1692 return false; 1693 1694 // Ignore all entities declared within templates, and out-of-line definitions 1695 // of members of class templates. 1696 if (D->getDeclContext()->isDependentContext() || 1697 D->getLexicalDeclContext()->isDependentContext()) 1698 return false; 1699 1700 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1701 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1702 return false; 1703 // A non-out-of-line declaration of a member specialization was implicitly 1704 // instantiated; it's the out-of-line declaration that we're interested in. 1705 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1706 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1707 return false; 1708 1709 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1710 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1711 return false; 1712 } else { 1713 // 'static inline' functions are defined in headers; don't warn. 1714 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1715 return false; 1716 } 1717 1718 if (FD->doesThisDeclarationHaveABody() && 1719 Context.DeclMustBeEmitted(FD)) 1720 return false; 1721 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1722 // Constants and utility variables are defined in headers with internal 1723 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1724 // like "inline".) 1725 if (!isMainFileLoc(*this, VD->getLocation())) 1726 return false; 1727 1728 if (Context.DeclMustBeEmitted(VD)) 1729 return false; 1730 1731 if (VD->isStaticDataMember() && 1732 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1733 return false; 1734 if (VD->isStaticDataMember() && 1735 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1736 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1737 return false; 1738 1739 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1740 return false; 1741 } else { 1742 return false; 1743 } 1744 1745 // Only warn for unused decls internal to the translation unit. 1746 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1747 // for inline functions defined in the main source file, for instance. 1748 return mightHaveNonExternalLinkage(D); 1749 } 1750 1751 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1752 if (!D) 1753 return; 1754 1755 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1756 const FunctionDecl *First = FD->getFirstDecl(); 1757 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1758 return; // First should already be in the vector. 1759 } 1760 1761 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1762 const VarDecl *First = VD->getFirstDecl(); 1763 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1764 return; // First should already be in the vector. 1765 } 1766 1767 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1768 UnusedFileScopedDecls.push_back(D); 1769 } 1770 1771 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1772 if (D->isInvalidDecl()) 1773 return false; 1774 1775 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1776 // For a decomposition declaration, warn if none of the bindings are 1777 // referenced, instead of if the variable itself is referenced (which 1778 // it is, by the bindings' expressions). 1779 for (auto *BD : DD->bindings()) 1780 if (BD->isReferenced()) 1781 return false; 1782 } else if (!D->getDeclName()) { 1783 return false; 1784 } else if (D->isReferenced() || D->isUsed()) { 1785 return false; 1786 } 1787 1788 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) 1789 return false; 1790 1791 if (isa<LabelDecl>(D)) 1792 return true; 1793 1794 // Except for labels, we only care about unused decls that are local to 1795 // functions. 1796 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1797 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1798 // For dependent types, the diagnostic is deferred. 1799 WithinFunction = 1800 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1801 if (!WithinFunction) 1802 return false; 1803 1804 if (isa<TypedefNameDecl>(D)) 1805 return true; 1806 1807 // White-list anything that isn't a local variable. 1808 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1809 return false; 1810 1811 // Types of valid local variables should be complete, so this should succeed. 1812 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1813 1814 // White-list anything with an __attribute__((unused)) type. 1815 const auto *Ty = VD->getType().getTypePtr(); 1816 1817 // Only look at the outermost level of typedef. 1818 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1819 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1820 return false; 1821 } 1822 1823 // If we failed to complete the type for some reason, or if the type is 1824 // dependent, don't diagnose the variable. 1825 if (Ty->isIncompleteType() || Ty->isDependentType()) 1826 return false; 1827 1828 // Look at the element type to ensure that the warning behaviour is 1829 // consistent for both scalars and arrays. 1830 Ty = Ty->getBaseElementTypeUnsafe(); 1831 1832 if (const TagType *TT = Ty->getAs<TagType>()) { 1833 const TagDecl *Tag = TT->getDecl(); 1834 if (Tag->hasAttr<UnusedAttr>()) 1835 return false; 1836 1837 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1838 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1839 return false; 1840 1841 if (const Expr *Init = VD->getInit()) { 1842 if (const ExprWithCleanups *Cleanups = 1843 dyn_cast<ExprWithCleanups>(Init)) 1844 Init = Cleanups->getSubExpr(); 1845 const CXXConstructExpr *Construct = 1846 dyn_cast<CXXConstructExpr>(Init); 1847 if (Construct && !Construct->isElidable()) { 1848 CXXConstructorDecl *CD = Construct->getConstructor(); 1849 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1850 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1851 return false; 1852 } 1853 1854 // Suppress the warning if we don't know how this is constructed, and 1855 // it could possibly be non-trivial constructor. 1856 if (Init->isTypeDependent()) 1857 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1858 if (!Ctor->isTrivial()) 1859 return false; 1860 } 1861 } 1862 } 1863 1864 // TODO: __attribute__((unused)) templates? 1865 } 1866 1867 return true; 1868 } 1869 1870 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1871 FixItHint &Hint) { 1872 if (isa<LabelDecl>(D)) { 1873 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1874 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1875 true); 1876 if (AfterColon.isInvalid()) 1877 return; 1878 Hint = FixItHint::CreateRemoval( 1879 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1880 } 1881 } 1882 1883 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1884 if (D->getTypeForDecl()->isDependentType()) 1885 return; 1886 1887 for (auto *TmpD : D->decls()) { 1888 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1889 DiagnoseUnusedDecl(T); 1890 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1891 DiagnoseUnusedNestedTypedefs(R); 1892 } 1893 } 1894 1895 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1896 /// unless they are marked attr(unused). 1897 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1898 if (!ShouldDiagnoseUnusedDecl(D)) 1899 return; 1900 1901 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1902 // typedefs can be referenced later on, so the diagnostics are emitted 1903 // at end-of-translation-unit. 1904 UnusedLocalTypedefNameCandidates.insert(TD); 1905 return; 1906 } 1907 1908 FixItHint Hint; 1909 GenerateFixForUnusedDecl(D, Context, Hint); 1910 1911 unsigned DiagID; 1912 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1913 DiagID = diag::warn_unused_exception_param; 1914 else if (isa<LabelDecl>(D)) 1915 DiagID = diag::warn_unused_label; 1916 else 1917 DiagID = diag::warn_unused_variable; 1918 1919 Diag(D->getLocation(), DiagID) << D << Hint; 1920 } 1921 1922 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) { 1923 // If it's not referenced, it can't be set. 1924 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>()) 1925 return; 1926 1927 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe(); 1928 1929 if (Ty->isReferenceType() || Ty->isDependentType()) 1930 return; 1931 1932 if (const TagType *TT = Ty->getAs<TagType>()) { 1933 const TagDecl *Tag = TT->getDecl(); 1934 if (Tag->hasAttr<UnusedAttr>()) 1935 return; 1936 // In C++, don't warn for record types that don't have WarnUnusedAttr, to 1937 // mimic gcc's behavior. 1938 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1939 if (!RD->hasAttr<WarnUnusedAttr>()) 1940 return; 1941 } 1942 } 1943 1944 auto iter = RefsMinusAssignments.find(VD); 1945 if (iter == RefsMinusAssignments.end()) 1946 return; 1947 1948 assert(iter->getSecond() >= 0 && 1949 "Found a negative number of references to a VarDecl"); 1950 if (iter->getSecond() != 0) 1951 return; 1952 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter 1953 : diag::warn_unused_but_set_variable; 1954 Diag(VD->getLocation(), DiagID) << VD; 1955 } 1956 1957 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1958 // Verify that we have no forward references left. If so, there was a goto 1959 // or address of a label taken, but no definition of it. Label fwd 1960 // definitions are indicated with a null substmt which is also not a resolved 1961 // MS inline assembly label name. 1962 bool Diagnose = false; 1963 if (L->isMSAsmLabel()) 1964 Diagnose = !L->isResolvedMSAsmLabel(); 1965 else 1966 Diagnose = L->getStmt() == nullptr; 1967 if (Diagnose) 1968 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; 1969 } 1970 1971 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1972 S->mergeNRVOIntoParent(); 1973 1974 if (S->decl_empty()) return; 1975 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1976 "Scope shouldn't contain decls!"); 1977 1978 for (auto *TmpD : S->decls()) { 1979 assert(TmpD && "This decl didn't get pushed??"); 1980 1981 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1982 NamedDecl *D = cast<NamedDecl>(TmpD); 1983 1984 // Diagnose unused variables in this scope. 1985 if (!S->hasUnrecoverableErrorOccurred()) { 1986 DiagnoseUnusedDecl(D); 1987 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1988 DiagnoseUnusedNestedTypedefs(RD); 1989 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1990 DiagnoseUnusedButSetDecl(VD); 1991 RefsMinusAssignments.erase(VD); 1992 } 1993 } 1994 1995 if (!D->getDeclName()) continue; 1996 1997 // If this was a forward reference to a label, verify it was defined. 1998 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1999 CheckPoppedLabel(LD, *this); 2000 2001 // Remove this name from our lexical scope, and warn on it if we haven't 2002 // already. 2003 IdResolver.RemoveDecl(D); 2004 auto ShadowI = ShadowingDecls.find(D); 2005 if (ShadowI != ShadowingDecls.end()) { 2006 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 2007 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 2008 << D << FD << FD->getParent(); 2009 Diag(FD->getLocation(), diag::note_previous_declaration); 2010 } 2011 ShadowingDecls.erase(ShadowI); 2012 } 2013 } 2014 } 2015 2016 /// Look for an Objective-C class in the translation unit. 2017 /// 2018 /// \param Id The name of the Objective-C class we're looking for. If 2019 /// typo-correction fixes this name, the Id will be updated 2020 /// to the fixed name. 2021 /// 2022 /// \param IdLoc The location of the name in the translation unit. 2023 /// 2024 /// \param DoTypoCorrection If true, this routine will attempt typo correction 2025 /// if there is no class with the given name. 2026 /// 2027 /// \returns The declaration of the named Objective-C class, or NULL if the 2028 /// class could not be found. 2029 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 2030 SourceLocation IdLoc, 2031 bool DoTypoCorrection) { 2032 // The third "scope" argument is 0 since we aren't enabling lazy built-in 2033 // creation from this context. 2034 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 2035 2036 if (!IDecl && DoTypoCorrection) { 2037 // Perform typo correction at the given location, but only if we 2038 // find an Objective-C class name. 2039 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 2040 if (TypoCorrection C = 2041 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 2042 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 2043 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 2044 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 2045 Id = IDecl->getIdentifier(); 2046 } 2047 } 2048 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 2049 // This routine must always return a class definition, if any. 2050 if (Def && Def->getDefinition()) 2051 Def = Def->getDefinition(); 2052 return Def; 2053 } 2054 2055 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2056 /// from S, where a non-field would be declared. This routine copes 2057 /// with the difference between C and C++ scoping rules in structs and 2058 /// unions. For example, the following code is well-formed in C but 2059 /// ill-formed in C++: 2060 /// @code 2061 /// struct S6 { 2062 /// enum { BAR } e; 2063 /// }; 2064 /// 2065 /// void test_S6() { 2066 /// struct S6 a; 2067 /// a.e = BAR; 2068 /// } 2069 /// @endcode 2070 /// For the declaration of BAR, this routine will return a different 2071 /// scope. The scope S will be the scope of the unnamed enumeration 2072 /// within S6. In C++, this routine will return the scope associated 2073 /// with S6, because the enumeration's scope is a transparent 2074 /// context but structures can contain non-field names. In C, this 2075 /// routine will return the translation unit scope, since the 2076 /// enumeration's scope is a transparent context and structures cannot 2077 /// contain non-field names. 2078 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2079 while (((S->getFlags() & Scope::DeclScope) == 0) || 2080 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2081 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2082 S = S->getParent(); 2083 return S; 2084 } 2085 2086 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2087 ASTContext::GetBuiltinTypeError Error) { 2088 switch (Error) { 2089 case ASTContext::GE_None: 2090 return ""; 2091 case ASTContext::GE_Missing_type: 2092 return BuiltinInfo.getHeaderName(ID); 2093 case ASTContext::GE_Missing_stdio: 2094 return "stdio.h"; 2095 case ASTContext::GE_Missing_setjmp: 2096 return "setjmp.h"; 2097 case ASTContext::GE_Missing_ucontext: 2098 return "ucontext.h"; 2099 } 2100 llvm_unreachable("unhandled error kind"); 2101 } 2102 2103 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2104 unsigned ID, SourceLocation Loc) { 2105 DeclContext *Parent = Context.getTranslationUnitDecl(); 2106 2107 if (getLangOpts().CPlusPlus) { 2108 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2109 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); 2110 CLinkageDecl->setImplicit(); 2111 Parent->addDecl(CLinkageDecl); 2112 Parent = CLinkageDecl; 2113 } 2114 2115 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2116 /*TInfo=*/nullptr, SC_Extern, false, 2117 Type->isFunctionProtoType()); 2118 New->setImplicit(); 2119 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2120 2121 // Create Decl objects for each parameter, adding them to the 2122 // FunctionDecl. 2123 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2124 SmallVector<ParmVarDecl *, 16> Params; 2125 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2126 ParmVarDecl *parm = ParmVarDecl::Create( 2127 Context, New, SourceLocation(), SourceLocation(), nullptr, 2128 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2129 parm->setScopeInfo(0, i); 2130 Params.push_back(parm); 2131 } 2132 New->setParams(Params); 2133 } 2134 2135 AddKnownFunctionAttributes(New); 2136 return New; 2137 } 2138 2139 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2140 /// file scope. lazily create a decl for it. ForRedeclaration is true 2141 /// if we're creating this built-in in anticipation of redeclaring the 2142 /// built-in. 2143 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2144 Scope *S, bool ForRedeclaration, 2145 SourceLocation Loc) { 2146 LookupNecessaryTypesForBuiltin(S, ID); 2147 2148 ASTContext::GetBuiltinTypeError Error; 2149 QualType R = Context.GetBuiltinType(ID, Error); 2150 if (Error) { 2151 if (!ForRedeclaration) 2152 return nullptr; 2153 2154 // If we have a builtin without an associated type we should not emit a 2155 // warning when we were not able to find a type for it. 2156 if (Error == ASTContext::GE_Missing_type || 2157 Context.BuiltinInfo.allowTypeMismatch(ID)) 2158 return nullptr; 2159 2160 // If we could not find a type for setjmp it is because the jmp_buf type was 2161 // not defined prior to the setjmp declaration. 2162 if (Error == ASTContext::GE_Missing_setjmp) { 2163 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2164 << Context.BuiltinInfo.getName(ID); 2165 return nullptr; 2166 } 2167 2168 // Generally, we emit a warning that the declaration requires the 2169 // appropriate header. 2170 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2171 << getHeaderName(Context.BuiltinInfo, ID, Error) 2172 << Context.BuiltinInfo.getName(ID); 2173 return nullptr; 2174 } 2175 2176 if (!ForRedeclaration && 2177 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2178 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2179 Diag(Loc, diag::ext_implicit_lib_function_decl) 2180 << Context.BuiltinInfo.getName(ID) << R; 2181 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2182 Diag(Loc, diag::note_include_header_or_declare) 2183 << Header << Context.BuiltinInfo.getName(ID); 2184 } 2185 2186 if (R.isNull()) 2187 return nullptr; 2188 2189 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2190 RegisterLocallyScopedExternCDecl(New, S); 2191 2192 // TUScope is the translation-unit scope to insert this function into. 2193 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2194 // relate Scopes to DeclContexts, and probably eliminate CurContext 2195 // entirely, but we're not there yet. 2196 DeclContext *SavedContext = CurContext; 2197 CurContext = New->getDeclContext(); 2198 PushOnScopeChains(New, TUScope); 2199 CurContext = SavedContext; 2200 return New; 2201 } 2202 2203 /// Typedef declarations don't have linkage, but they still denote the same 2204 /// entity if their types are the same. 2205 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2206 /// isSameEntity. 2207 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2208 TypedefNameDecl *Decl, 2209 LookupResult &Previous) { 2210 // This is only interesting when modules are enabled. 2211 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2212 return; 2213 2214 // Empty sets are uninteresting. 2215 if (Previous.empty()) 2216 return; 2217 2218 LookupResult::Filter Filter = Previous.makeFilter(); 2219 while (Filter.hasNext()) { 2220 NamedDecl *Old = Filter.next(); 2221 2222 // Non-hidden declarations are never ignored. 2223 if (S.isVisible(Old)) 2224 continue; 2225 2226 // Declarations of the same entity are not ignored, even if they have 2227 // different linkages. 2228 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2229 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2230 Decl->getUnderlyingType())) 2231 continue; 2232 2233 // If both declarations give a tag declaration a typedef name for linkage 2234 // purposes, then they declare the same entity. 2235 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2236 Decl->getAnonDeclWithTypedefName()) 2237 continue; 2238 } 2239 2240 Filter.erase(); 2241 } 2242 2243 Filter.done(); 2244 } 2245 2246 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2247 QualType OldType; 2248 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2249 OldType = OldTypedef->getUnderlyingType(); 2250 else 2251 OldType = Context.getTypeDeclType(Old); 2252 QualType NewType = New->getUnderlyingType(); 2253 2254 if (NewType->isVariablyModifiedType()) { 2255 // Must not redefine a typedef with a variably-modified type. 2256 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2257 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2258 << Kind << NewType; 2259 if (Old->getLocation().isValid()) 2260 notePreviousDefinition(Old, New->getLocation()); 2261 New->setInvalidDecl(); 2262 return true; 2263 } 2264 2265 if (OldType != NewType && 2266 !OldType->isDependentType() && 2267 !NewType->isDependentType() && 2268 !Context.hasSameType(OldType, NewType)) { 2269 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2270 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2271 << Kind << NewType << OldType; 2272 if (Old->getLocation().isValid()) 2273 notePreviousDefinition(Old, New->getLocation()); 2274 New->setInvalidDecl(); 2275 return true; 2276 } 2277 return false; 2278 } 2279 2280 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2281 /// same name and scope as a previous declaration 'Old'. Figure out 2282 /// how to resolve this situation, merging decls or emitting 2283 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2284 /// 2285 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2286 LookupResult &OldDecls) { 2287 // If the new decl is known invalid already, don't bother doing any 2288 // merging checks. 2289 if (New->isInvalidDecl()) return; 2290 2291 // Allow multiple definitions for ObjC built-in typedefs. 2292 // FIXME: Verify the underlying types are equivalent! 2293 if (getLangOpts().ObjC) { 2294 const IdentifierInfo *TypeID = New->getIdentifier(); 2295 switch (TypeID->getLength()) { 2296 default: break; 2297 case 2: 2298 { 2299 if (!TypeID->isStr("id")) 2300 break; 2301 QualType T = New->getUnderlyingType(); 2302 if (!T->isPointerType()) 2303 break; 2304 if (!T->isVoidPointerType()) { 2305 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2306 if (!PT->isStructureType()) 2307 break; 2308 } 2309 Context.setObjCIdRedefinitionType(T); 2310 // Install the built-in type for 'id', ignoring the current definition. 2311 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2312 return; 2313 } 2314 case 5: 2315 if (!TypeID->isStr("Class")) 2316 break; 2317 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2318 // Install the built-in type for 'Class', ignoring the current definition. 2319 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2320 return; 2321 case 3: 2322 if (!TypeID->isStr("SEL")) 2323 break; 2324 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2325 // Install the built-in type for 'SEL', ignoring the current definition. 2326 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2327 return; 2328 } 2329 // Fall through - the typedef name was not a builtin type. 2330 } 2331 2332 // Verify the old decl was also a type. 2333 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2334 if (!Old) { 2335 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2336 << New->getDeclName(); 2337 2338 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2339 if (OldD->getLocation().isValid()) 2340 notePreviousDefinition(OldD, New->getLocation()); 2341 2342 return New->setInvalidDecl(); 2343 } 2344 2345 // If the old declaration is invalid, just give up here. 2346 if (Old->isInvalidDecl()) 2347 return New->setInvalidDecl(); 2348 2349 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2350 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2351 auto *NewTag = New->getAnonDeclWithTypedefName(); 2352 NamedDecl *Hidden = nullptr; 2353 if (OldTag && NewTag && 2354 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2355 !hasVisibleDefinition(OldTag, &Hidden)) { 2356 // There is a definition of this tag, but it is not visible. Use it 2357 // instead of our tag. 2358 New->setTypeForDecl(OldTD->getTypeForDecl()); 2359 if (OldTD->isModed()) 2360 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2361 OldTD->getUnderlyingType()); 2362 else 2363 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2364 2365 // Make the old tag definition visible. 2366 makeMergedDefinitionVisible(Hidden); 2367 2368 // If this was an unscoped enumeration, yank all of its enumerators 2369 // out of the scope. 2370 if (isa<EnumDecl>(NewTag)) { 2371 Scope *EnumScope = getNonFieldDeclScope(S); 2372 for (auto *D : NewTag->decls()) { 2373 auto *ED = cast<EnumConstantDecl>(D); 2374 assert(EnumScope->isDeclScope(ED)); 2375 EnumScope->RemoveDecl(ED); 2376 IdResolver.RemoveDecl(ED); 2377 ED->getLexicalDeclContext()->removeDecl(ED); 2378 } 2379 } 2380 } 2381 } 2382 2383 // If the typedef types are not identical, reject them in all languages and 2384 // with any extensions enabled. 2385 if (isIncompatibleTypedef(Old, New)) 2386 return; 2387 2388 // The types match. Link up the redeclaration chain and merge attributes if 2389 // the old declaration was a typedef. 2390 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2391 New->setPreviousDecl(Typedef); 2392 mergeDeclAttributes(New, Old); 2393 } 2394 2395 if (getLangOpts().MicrosoftExt) 2396 return; 2397 2398 if (getLangOpts().CPlusPlus) { 2399 // C++ [dcl.typedef]p2: 2400 // In a given non-class scope, a typedef specifier can be used to 2401 // redefine the name of any type declared in that scope to refer 2402 // to the type to which it already refers. 2403 if (!isa<CXXRecordDecl>(CurContext)) 2404 return; 2405 2406 // C++0x [dcl.typedef]p4: 2407 // In a given class scope, a typedef specifier can be used to redefine 2408 // any class-name declared in that scope that is not also a typedef-name 2409 // to refer to the type to which it already refers. 2410 // 2411 // This wording came in via DR424, which was a correction to the 2412 // wording in DR56, which accidentally banned code like: 2413 // 2414 // struct S { 2415 // typedef struct A { } A; 2416 // }; 2417 // 2418 // in the C++03 standard. We implement the C++0x semantics, which 2419 // allow the above but disallow 2420 // 2421 // struct S { 2422 // typedef int I; 2423 // typedef int I; 2424 // }; 2425 // 2426 // since that was the intent of DR56. 2427 if (!isa<TypedefNameDecl>(Old)) 2428 return; 2429 2430 Diag(New->getLocation(), diag::err_redefinition) 2431 << New->getDeclName(); 2432 notePreviousDefinition(Old, New->getLocation()); 2433 return New->setInvalidDecl(); 2434 } 2435 2436 // Modules always permit redefinition of typedefs, as does C11. 2437 if (getLangOpts().Modules || getLangOpts().C11) 2438 return; 2439 2440 // If we have a redefinition of a typedef in C, emit a warning. This warning 2441 // is normally mapped to an error, but can be controlled with 2442 // -Wtypedef-redefinition. If either the original or the redefinition is 2443 // in a system header, don't emit this for compatibility with GCC. 2444 if (getDiagnostics().getSuppressSystemWarnings() && 2445 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2446 (Old->isImplicit() || 2447 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2448 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2449 return; 2450 2451 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2452 << New->getDeclName(); 2453 notePreviousDefinition(Old, New->getLocation()); 2454 } 2455 2456 /// DeclhasAttr - returns true if decl Declaration already has the target 2457 /// attribute. 2458 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2459 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2460 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2461 for (const auto *i : D->attrs()) 2462 if (i->getKind() == A->getKind()) { 2463 if (Ann) { 2464 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2465 return true; 2466 continue; 2467 } 2468 // FIXME: Don't hardcode this check 2469 if (OA && isa<OwnershipAttr>(i)) 2470 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2471 return true; 2472 } 2473 2474 return false; 2475 } 2476 2477 static bool isAttributeTargetADefinition(Decl *D) { 2478 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2479 return VD->isThisDeclarationADefinition(); 2480 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2481 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2482 return true; 2483 } 2484 2485 /// Merge alignment attributes from \p Old to \p New, taking into account the 2486 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2487 /// 2488 /// \return \c true if any attributes were added to \p New. 2489 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2490 // Look for alignas attributes on Old, and pick out whichever attribute 2491 // specifies the strictest alignment requirement. 2492 AlignedAttr *OldAlignasAttr = nullptr; 2493 AlignedAttr *OldStrictestAlignAttr = nullptr; 2494 unsigned OldAlign = 0; 2495 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2496 // FIXME: We have no way of representing inherited dependent alignments 2497 // in a case like: 2498 // template<int A, int B> struct alignas(A) X; 2499 // template<int A, int B> struct alignas(B) X {}; 2500 // For now, we just ignore any alignas attributes which are not on the 2501 // definition in such a case. 2502 if (I->isAlignmentDependent()) 2503 return false; 2504 2505 if (I->isAlignas()) 2506 OldAlignasAttr = I; 2507 2508 unsigned Align = I->getAlignment(S.Context); 2509 if (Align > OldAlign) { 2510 OldAlign = Align; 2511 OldStrictestAlignAttr = I; 2512 } 2513 } 2514 2515 // Look for alignas attributes on New. 2516 AlignedAttr *NewAlignasAttr = nullptr; 2517 unsigned NewAlign = 0; 2518 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2519 if (I->isAlignmentDependent()) 2520 return false; 2521 2522 if (I->isAlignas()) 2523 NewAlignasAttr = I; 2524 2525 unsigned Align = I->getAlignment(S.Context); 2526 if (Align > NewAlign) 2527 NewAlign = Align; 2528 } 2529 2530 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2531 // Both declarations have 'alignas' attributes. We require them to match. 2532 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2533 // fall short. (If two declarations both have alignas, they must both match 2534 // every definition, and so must match each other if there is a definition.) 2535 2536 // If either declaration only contains 'alignas(0)' specifiers, then it 2537 // specifies the natural alignment for the type. 2538 if (OldAlign == 0 || NewAlign == 0) { 2539 QualType Ty; 2540 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2541 Ty = VD->getType(); 2542 else 2543 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2544 2545 if (OldAlign == 0) 2546 OldAlign = S.Context.getTypeAlign(Ty); 2547 if (NewAlign == 0) 2548 NewAlign = S.Context.getTypeAlign(Ty); 2549 } 2550 2551 if (OldAlign != NewAlign) { 2552 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2553 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2554 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2555 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2556 } 2557 } 2558 2559 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2560 // C++11 [dcl.align]p6: 2561 // if any declaration of an entity has an alignment-specifier, 2562 // every defining declaration of that entity shall specify an 2563 // equivalent alignment. 2564 // C11 6.7.5/7: 2565 // If the definition of an object does not have an alignment 2566 // specifier, any other declaration of that object shall also 2567 // have no alignment specifier. 2568 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2569 << OldAlignasAttr; 2570 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2571 << OldAlignasAttr; 2572 } 2573 2574 bool AnyAdded = false; 2575 2576 // Ensure we have an attribute representing the strictest alignment. 2577 if (OldAlign > NewAlign) { 2578 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2579 Clone->setInherited(true); 2580 New->addAttr(Clone); 2581 AnyAdded = true; 2582 } 2583 2584 // Ensure we have an alignas attribute if the old declaration had one. 2585 if (OldAlignasAttr && !NewAlignasAttr && 2586 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2587 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2588 Clone->setInherited(true); 2589 New->addAttr(Clone); 2590 AnyAdded = true; 2591 } 2592 2593 return AnyAdded; 2594 } 2595 2596 #define WANT_DECL_MERGE_LOGIC 2597 #include "clang/Sema/AttrParsedAttrImpl.inc" 2598 #undef WANT_DECL_MERGE_LOGIC 2599 2600 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2601 const InheritableAttr *Attr, 2602 Sema::AvailabilityMergeKind AMK) { 2603 // Diagnose any mutual exclusions between the attribute that we want to add 2604 // and attributes that already exist on the declaration. 2605 if (!DiagnoseMutualExclusions(S, D, Attr)) 2606 return false; 2607 2608 // This function copies an attribute Attr from a previous declaration to the 2609 // new declaration D if the new declaration doesn't itself have that attribute 2610 // yet or if that attribute allows duplicates. 2611 // If you're adding a new attribute that requires logic different from 2612 // "use explicit attribute on decl if present, else use attribute from 2613 // previous decl", for example if the attribute needs to be consistent 2614 // between redeclarations, you need to call a custom merge function here. 2615 InheritableAttr *NewAttr = nullptr; 2616 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2617 NewAttr = S.mergeAvailabilityAttr( 2618 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2619 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2620 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2621 AA->getPriority()); 2622 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2623 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2624 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2625 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2626 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2627 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2628 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2629 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2630 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2631 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2632 FA->getFirstArg()); 2633 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2634 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2635 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2636 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2637 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2638 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2639 IA->getInheritanceModel()); 2640 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2641 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2642 &S.Context.Idents.get(AA->getSpelling())); 2643 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2644 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2645 isa<CUDAGlobalAttr>(Attr))) { 2646 // CUDA target attributes are part of function signature for 2647 // overloading purposes and must not be merged. 2648 return false; 2649 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2650 NewAttr = S.mergeMinSizeAttr(D, *MA); 2651 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2652 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2653 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2654 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2655 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2656 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2657 else if (isa<AlignedAttr>(Attr)) 2658 // AlignedAttrs are handled separately, because we need to handle all 2659 // such attributes on a declaration at the same time. 2660 NewAttr = nullptr; 2661 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2662 (AMK == Sema::AMK_Override || 2663 AMK == Sema::AMK_ProtocolImplementation || 2664 AMK == Sema::AMK_OptionalProtocolImplementation)) 2665 NewAttr = nullptr; 2666 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2667 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2668 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2669 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2670 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2671 NewAttr = S.mergeImportNameAttr(D, *INA); 2672 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 2673 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 2674 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 2675 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 2676 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2677 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2678 2679 if (NewAttr) { 2680 NewAttr->setInherited(true); 2681 D->addAttr(NewAttr); 2682 if (isa<MSInheritanceAttr>(NewAttr)) 2683 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2684 return true; 2685 } 2686 2687 return false; 2688 } 2689 2690 static const NamedDecl *getDefinition(const Decl *D) { 2691 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2692 return TD->getDefinition(); 2693 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2694 const VarDecl *Def = VD->getDefinition(); 2695 if (Def) 2696 return Def; 2697 return VD->getActingDefinition(); 2698 } 2699 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2700 const FunctionDecl *Def = nullptr; 2701 if (FD->isDefined(Def, true)) 2702 return Def; 2703 } 2704 return nullptr; 2705 } 2706 2707 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2708 for (const auto *Attribute : D->attrs()) 2709 if (Attribute->getKind() == Kind) 2710 return true; 2711 return false; 2712 } 2713 2714 /// checkNewAttributesAfterDef - If we already have a definition, check that 2715 /// there are no new attributes in this declaration. 2716 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2717 if (!New->hasAttrs()) 2718 return; 2719 2720 const NamedDecl *Def = getDefinition(Old); 2721 if (!Def || Def == New) 2722 return; 2723 2724 AttrVec &NewAttributes = New->getAttrs(); 2725 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2726 const Attr *NewAttribute = NewAttributes[I]; 2727 2728 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2729 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2730 Sema::SkipBodyInfo SkipBody; 2731 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2732 2733 // If we're skipping this definition, drop the "alias" attribute. 2734 if (SkipBody.ShouldSkip) { 2735 NewAttributes.erase(NewAttributes.begin() + I); 2736 --E; 2737 continue; 2738 } 2739 } else { 2740 VarDecl *VD = cast<VarDecl>(New); 2741 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2742 VarDecl::TentativeDefinition 2743 ? diag::err_alias_after_tentative 2744 : diag::err_redefinition; 2745 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2746 if (Diag == diag::err_redefinition) 2747 S.notePreviousDefinition(Def, VD->getLocation()); 2748 else 2749 S.Diag(Def->getLocation(), diag::note_previous_definition); 2750 VD->setInvalidDecl(); 2751 } 2752 ++I; 2753 continue; 2754 } 2755 2756 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2757 // Tentative definitions are only interesting for the alias check above. 2758 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2759 ++I; 2760 continue; 2761 } 2762 } 2763 2764 if (hasAttribute(Def, NewAttribute->getKind())) { 2765 ++I; 2766 continue; // regular attr merging will take care of validating this. 2767 } 2768 2769 if (isa<C11NoReturnAttr>(NewAttribute)) { 2770 // C's _Noreturn is allowed to be added to a function after it is defined. 2771 ++I; 2772 continue; 2773 } else if (isa<UuidAttr>(NewAttribute)) { 2774 // msvc will allow a subsequent definition to add an uuid to a class 2775 ++I; 2776 continue; 2777 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2778 if (AA->isAlignas()) { 2779 // C++11 [dcl.align]p6: 2780 // if any declaration of an entity has an alignment-specifier, 2781 // every defining declaration of that entity shall specify an 2782 // equivalent alignment. 2783 // C11 6.7.5/7: 2784 // If the definition of an object does not have an alignment 2785 // specifier, any other declaration of that object shall also 2786 // have no alignment specifier. 2787 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2788 << AA; 2789 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2790 << AA; 2791 NewAttributes.erase(NewAttributes.begin() + I); 2792 --E; 2793 continue; 2794 } 2795 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2796 // If there is a C definition followed by a redeclaration with this 2797 // attribute then there are two different definitions. In C++, prefer the 2798 // standard diagnostics. 2799 if (!S.getLangOpts().CPlusPlus) { 2800 S.Diag(NewAttribute->getLocation(), 2801 diag::err_loader_uninitialized_redeclaration); 2802 S.Diag(Def->getLocation(), diag::note_previous_definition); 2803 NewAttributes.erase(NewAttributes.begin() + I); 2804 --E; 2805 continue; 2806 } 2807 } else if (isa<SelectAnyAttr>(NewAttribute) && 2808 cast<VarDecl>(New)->isInline() && 2809 !cast<VarDecl>(New)->isInlineSpecified()) { 2810 // Don't warn about applying selectany to implicitly inline variables. 2811 // Older compilers and language modes would require the use of selectany 2812 // to make such variables inline, and it would have no effect if we 2813 // honored it. 2814 ++I; 2815 continue; 2816 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2817 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2818 // declarations after defintions. 2819 ++I; 2820 continue; 2821 } 2822 2823 S.Diag(NewAttribute->getLocation(), 2824 diag::warn_attribute_precede_definition); 2825 S.Diag(Def->getLocation(), diag::note_previous_definition); 2826 NewAttributes.erase(NewAttributes.begin() + I); 2827 --E; 2828 } 2829 } 2830 2831 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2832 const ConstInitAttr *CIAttr, 2833 bool AttrBeforeInit) { 2834 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2835 2836 // Figure out a good way to write this specifier on the old declaration. 2837 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2838 // enough of the attribute list spelling information to extract that without 2839 // heroics. 2840 std::string SuitableSpelling; 2841 if (S.getLangOpts().CPlusPlus20) 2842 SuitableSpelling = std::string( 2843 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2844 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2845 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2846 InsertLoc, {tok::l_square, tok::l_square, 2847 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2848 S.PP.getIdentifierInfo("require_constant_initialization"), 2849 tok::r_square, tok::r_square})); 2850 if (SuitableSpelling.empty()) 2851 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2852 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2853 S.PP.getIdentifierInfo("require_constant_initialization"), 2854 tok::r_paren, tok::r_paren})); 2855 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2856 SuitableSpelling = "constinit"; 2857 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2858 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2859 if (SuitableSpelling.empty()) 2860 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2861 SuitableSpelling += " "; 2862 2863 if (AttrBeforeInit) { 2864 // extern constinit int a; 2865 // int a = 0; // error (missing 'constinit'), accepted as extension 2866 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2867 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2868 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2869 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2870 } else { 2871 // int a = 0; 2872 // constinit extern int a; // error (missing 'constinit') 2873 S.Diag(CIAttr->getLocation(), 2874 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2875 : diag::warn_require_const_init_added_too_late) 2876 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2877 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2878 << CIAttr->isConstinit() 2879 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2880 } 2881 } 2882 2883 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2884 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2885 AvailabilityMergeKind AMK) { 2886 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2887 UsedAttr *NewAttr = OldAttr->clone(Context); 2888 NewAttr->setInherited(true); 2889 New->addAttr(NewAttr); 2890 } 2891 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { 2892 RetainAttr *NewAttr = OldAttr->clone(Context); 2893 NewAttr->setInherited(true); 2894 New->addAttr(NewAttr); 2895 } 2896 2897 if (!Old->hasAttrs() && !New->hasAttrs()) 2898 return; 2899 2900 // [dcl.constinit]p1: 2901 // If the [constinit] specifier is applied to any declaration of a 2902 // variable, it shall be applied to the initializing declaration. 2903 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2904 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2905 if (bool(OldConstInit) != bool(NewConstInit)) { 2906 const auto *OldVD = cast<VarDecl>(Old); 2907 auto *NewVD = cast<VarDecl>(New); 2908 2909 // Find the initializing declaration. Note that we might not have linked 2910 // the new declaration into the redeclaration chain yet. 2911 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2912 if (!InitDecl && 2913 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2914 InitDecl = NewVD; 2915 2916 if (InitDecl == NewVD) { 2917 // This is the initializing declaration. If it would inherit 'constinit', 2918 // that's ill-formed. (Note that we do not apply this to the attribute 2919 // form). 2920 if (OldConstInit && OldConstInit->isConstinit()) 2921 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2922 /*AttrBeforeInit=*/true); 2923 } else if (NewConstInit) { 2924 // This is the first time we've been told that this declaration should 2925 // have a constant initializer. If we already saw the initializing 2926 // declaration, this is too late. 2927 if (InitDecl && InitDecl != NewVD) { 2928 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2929 /*AttrBeforeInit=*/false); 2930 NewVD->dropAttr<ConstInitAttr>(); 2931 } 2932 } 2933 } 2934 2935 // Attributes declared post-definition are currently ignored. 2936 checkNewAttributesAfterDef(*this, New, Old); 2937 2938 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2939 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2940 if (!OldA->isEquivalent(NewA)) { 2941 // This redeclaration changes __asm__ label. 2942 Diag(New->getLocation(), diag::err_different_asm_label); 2943 Diag(OldA->getLocation(), diag::note_previous_declaration); 2944 } 2945 } else if (Old->isUsed()) { 2946 // This redeclaration adds an __asm__ label to a declaration that has 2947 // already been ODR-used. 2948 Diag(New->getLocation(), diag::err_late_asm_label_name) 2949 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2950 } 2951 } 2952 2953 // Re-declaration cannot add abi_tag's. 2954 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2955 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2956 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2957 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2958 NewTag) == OldAbiTagAttr->tags_end()) { 2959 Diag(NewAbiTagAttr->getLocation(), 2960 diag::err_new_abi_tag_on_redeclaration) 2961 << NewTag; 2962 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2963 } 2964 } 2965 } else { 2966 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2967 Diag(Old->getLocation(), diag::note_previous_declaration); 2968 } 2969 } 2970 2971 // This redeclaration adds a section attribute. 2972 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2973 if (auto *VD = dyn_cast<VarDecl>(New)) { 2974 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2975 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2976 Diag(Old->getLocation(), diag::note_previous_declaration); 2977 } 2978 } 2979 } 2980 2981 // Redeclaration adds code-seg attribute. 2982 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2983 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2984 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2985 Diag(New->getLocation(), diag::warn_mismatched_section) 2986 << 0 /*codeseg*/; 2987 Diag(Old->getLocation(), diag::note_previous_declaration); 2988 } 2989 2990 if (!Old->hasAttrs()) 2991 return; 2992 2993 bool foundAny = New->hasAttrs(); 2994 2995 // Ensure that any moving of objects within the allocated map is done before 2996 // we process them. 2997 if (!foundAny) New->setAttrs(AttrVec()); 2998 2999 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 3000 // Ignore deprecated/unavailable/availability attributes if requested. 3001 AvailabilityMergeKind LocalAMK = AMK_None; 3002 if (isa<DeprecatedAttr>(I) || 3003 isa<UnavailableAttr>(I) || 3004 isa<AvailabilityAttr>(I)) { 3005 switch (AMK) { 3006 case AMK_None: 3007 continue; 3008 3009 case AMK_Redeclaration: 3010 case AMK_Override: 3011 case AMK_ProtocolImplementation: 3012 case AMK_OptionalProtocolImplementation: 3013 LocalAMK = AMK; 3014 break; 3015 } 3016 } 3017 3018 // Already handled. 3019 if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) 3020 continue; 3021 3022 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 3023 foundAny = true; 3024 } 3025 3026 if (mergeAlignedAttrs(*this, New, Old)) 3027 foundAny = true; 3028 3029 if (!foundAny) New->dropAttrs(); 3030 } 3031 3032 /// mergeParamDeclAttributes - Copy attributes from the old parameter 3033 /// to the new one. 3034 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 3035 const ParmVarDecl *oldDecl, 3036 Sema &S) { 3037 // C++11 [dcl.attr.depend]p2: 3038 // The first declaration of a function shall specify the 3039 // carries_dependency attribute for its declarator-id if any declaration 3040 // of the function specifies the carries_dependency attribute. 3041 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 3042 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 3043 S.Diag(CDA->getLocation(), 3044 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 3045 // Find the first declaration of the parameter. 3046 // FIXME: Should we build redeclaration chains for function parameters? 3047 const FunctionDecl *FirstFD = 3048 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 3049 const ParmVarDecl *FirstVD = 3050 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 3051 S.Diag(FirstVD->getLocation(), 3052 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 3053 } 3054 3055 if (!oldDecl->hasAttrs()) 3056 return; 3057 3058 bool foundAny = newDecl->hasAttrs(); 3059 3060 // Ensure that any moving of objects within the allocated map is 3061 // done before we process them. 3062 if (!foundAny) newDecl->setAttrs(AttrVec()); 3063 3064 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3065 if (!DeclHasAttr(newDecl, I)) { 3066 InheritableAttr *newAttr = 3067 cast<InheritableParamAttr>(I->clone(S.Context)); 3068 newAttr->setInherited(true); 3069 newDecl->addAttr(newAttr); 3070 foundAny = true; 3071 } 3072 } 3073 3074 if (!foundAny) newDecl->dropAttrs(); 3075 } 3076 3077 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3078 const ParmVarDecl *OldParam, 3079 Sema &S) { 3080 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3081 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3082 if (*Oldnullability != *Newnullability) { 3083 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3084 << DiagNullabilityKind( 3085 *Newnullability, 3086 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3087 != 0)) 3088 << DiagNullabilityKind( 3089 *Oldnullability, 3090 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3091 != 0)); 3092 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3093 } 3094 } else { 3095 QualType NewT = NewParam->getType(); 3096 NewT = S.Context.getAttributedType( 3097 AttributedType::getNullabilityAttrKind(*Oldnullability), 3098 NewT, NewT); 3099 NewParam->setType(NewT); 3100 } 3101 } 3102 } 3103 3104 namespace { 3105 3106 /// Used in MergeFunctionDecl to keep track of function parameters in 3107 /// C. 3108 struct GNUCompatibleParamWarning { 3109 ParmVarDecl *OldParm; 3110 ParmVarDecl *NewParm; 3111 QualType PromotedType; 3112 }; 3113 3114 } // end anonymous namespace 3115 3116 // Determine whether the previous declaration was a definition, implicit 3117 // declaration, or a declaration. 3118 template <typename T> 3119 static std::pair<diag::kind, SourceLocation> 3120 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3121 diag::kind PrevDiag; 3122 SourceLocation OldLocation = Old->getLocation(); 3123 if (Old->isThisDeclarationADefinition()) 3124 PrevDiag = diag::note_previous_definition; 3125 else if (Old->isImplicit()) { 3126 PrevDiag = diag::note_previous_implicit_declaration; 3127 if (OldLocation.isInvalid()) 3128 OldLocation = New->getLocation(); 3129 } else 3130 PrevDiag = diag::note_previous_declaration; 3131 return std::make_pair(PrevDiag, OldLocation); 3132 } 3133 3134 /// canRedefineFunction - checks if a function can be redefined. Currently, 3135 /// only extern inline functions can be redefined, and even then only in 3136 /// GNU89 mode. 3137 static bool canRedefineFunction(const FunctionDecl *FD, 3138 const LangOptions& LangOpts) { 3139 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3140 !LangOpts.CPlusPlus && 3141 FD->isInlineSpecified() && 3142 FD->getStorageClass() == SC_Extern); 3143 } 3144 3145 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3146 const AttributedType *AT = T->getAs<AttributedType>(); 3147 while (AT && !AT->isCallingConv()) 3148 AT = AT->getModifiedType()->getAs<AttributedType>(); 3149 return AT; 3150 } 3151 3152 template <typename T> 3153 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3154 const DeclContext *DC = Old->getDeclContext(); 3155 if (DC->isRecord()) 3156 return false; 3157 3158 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3159 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3160 return true; 3161 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3162 return true; 3163 return false; 3164 } 3165 3166 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3167 static bool isExternC(VarTemplateDecl *) { return false; } 3168 static bool isExternC(FunctionTemplateDecl *) { return false; } 3169 3170 /// Check whether a redeclaration of an entity introduced by a 3171 /// using-declaration is valid, given that we know it's not an overload 3172 /// (nor a hidden tag declaration). 3173 template<typename ExpectedDecl> 3174 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3175 ExpectedDecl *New) { 3176 // C++11 [basic.scope.declarative]p4: 3177 // Given a set of declarations in a single declarative region, each of 3178 // which specifies the same unqualified name, 3179 // -- they shall all refer to the same entity, or all refer to functions 3180 // and function templates; or 3181 // -- exactly one declaration shall declare a class name or enumeration 3182 // name that is not a typedef name and the other declarations shall all 3183 // refer to the same variable or enumerator, or all refer to functions 3184 // and function templates; in this case the class name or enumeration 3185 // name is hidden (3.3.10). 3186 3187 // C++11 [namespace.udecl]p14: 3188 // If a function declaration in namespace scope or block scope has the 3189 // same name and the same parameter-type-list as a function introduced 3190 // by a using-declaration, and the declarations do not declare the same 3191 // function, the program is ill-formed. 3192 3193 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3194 if (Old && 3195 !Old->getDeclContext()->getRedeclContext()->Equals( 3196 New->getDeclContext()->getRedeclContext()) && 3197 !(isExternC(Old) && isExternC(New))) 3198 Old = nullptr; 3199 3200 if (!Old) { 3201 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3202 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3203 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0; 3204 return true; 3205 } 3206 return false; 3207 } 3208 3209 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3210 const FunctionDecl *B) { 3211 assert(A->getNumParams() == B->getNumParams()); 3212 3213 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3214 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3215 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3216 if (AttrA == AttrB) 3217 return true; 3218 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3219 AttrA->isDynamic() == AttrB->isDynamic(); 3220 }; 3221 3222 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3223 } 3224 3225 /// If necessary, adjust the semantic declaration context for a qualified 3226 /// declaration to name the correct inline namespace within the qualifier. 3227 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3228 DeclaratorDecl *OldD) { 3229 // The only case where we need to update the DeclContext is when 3230 // redeclaration lookup for a qualified name finds a declaration 3231 // in an inline namespace within the context named by the qualifier: 3232 // 3233 // inline namespace N { int f(); } 3234 // int ::f(); // Sema DC needs adjusting from :: to N::. 3235 // 3236 // For unqualified declarations, the semantic context *can* change 3237 // along the redeclaration chain (for local extern declarations, 3238 // extern "C" declarations, and friend declarations in particular). 3239 if (!NewD->getQualifier()) 3240 return; 3241 3242 // NewD is probably already in the right context. 3243 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3244 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3245 if (NamedDC->Equals(SemaDC)) 3246 return; 3247 3248 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3249 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3250 "unexpected context for redeclaration"); 3251 3252 auto *LexDC = NewD->getLexicalDeclContext(); 3253 auto FixSemaDC = [=](NamedDecl *D) { 3254 if (!D) 3255 return; 3256 D->setDeclContext(SemaDC); 3257 D->setLexicalDeclContext(LexDC); 3258 }; 3259 3260 FixSemaDC(NewD); 3261 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3262 FixSemaDC(FD->getDescribedFunctionTemplate()); 3263 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3264 FixSemaDC(VD->getDescribedVarTemplate()); 3265 } 3266 3267 /// MergeFunctionDecl - We just parsed a function 'New' from 3268 /// declarator D which has the same name and scope as a previous 3269 /// declaration 'Old'. Figure out how to resolve this situation, 3270 /// merging decls or emitting diagnostics as appropriate. 3271 /// 3272 /// In C++, New and Old must be declarations that are not 3273 /// overloaded. Use IsOverload to determine whether New and Old are 3274 /// overloaded, and to select the Old declaration that New should be 3275 /// merged with. 3276 /// 3277 /// Returns true if there was an error, false otherwise. 3278 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3279 Scope *S, bool MergeTypeWithOld) { 3280 // Verify the old decl was also a function. 3281 FunctionDecl *Old = OldD->getAsFunction(); 3282 if (!Old) { 3283 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3284 if (New->getFriendObjectKind()) { 3285 Diag(New->getLocation(), diag::err_using_decl_friend); 3286 Diag(Shadow->getTargetDecl()->getLocation(), 3287 diag::note_using_decl_target); 3288 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 3289 << 0; 3290 return true; 3291 } 3292 3293 // Check whether the two declarations might declare the same function or 3294 // function template. 3295 if (FunctionTemplateDecl *NewTemplate = 3296 New->getDescribedFunctionTemplate()) { 3297 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow, 3298 NewTemplate)) 3299 return true; 3300 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl()) 3301 ->getAsFunction(); 3302 } else { 3303 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3304 return true; 3305 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3306 } 3307 } else { 3308 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3309 << New->getDeclName(); 3310 notePreviousDefinition(OldD, New->getLocation()); 3311 return true; 3312 } 3313 } 3314 3315 // If the old declaration was found in an inline namespace and the new 3316 // declaration was qualified, update the DeclContext to match. 3317 adjustDeclContextForDeclaratorDecl(New, Old); 3318 3319 // If the old declaration is invalid, just give up here. 3320 if (Old->isInvalidDecl()) 3321 return true; 3322 3323 // Disallow redeclaration of some builtins. 3324 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3325 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3326 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3327 << Old << Old->getType(); 3328 return true; 3329 } 3330 3331 diag::kind PrevDiag; 3332 SourceLocation OldLocation; 3333 std::tie(PrevDiag, OldLocation) = 3334 getNoteDiagForInvalidRedeclaration(Old, New); 3335 3336 // Don't complain about this if we're in GNU89 mode and the old function 3337 // is an extern inline function. 3338 // Don't complain about specializations. They are not supposed to have 3339 // storage classes. 3340 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3341 New->getStorageClass() == SC_Static && 3342 Old->hasExternalFormalLinkage() && 3343 !New->getTemplateSpecializationInfo() && 3344 !canRedefineFunction(Old, getLangOpts())) { 3345 if (getLangOpts().MicrosoftExt) { 3346 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3347 Diag(OldLocation, PrevDiag); 3348 } else { 3349 Diag(New->getLocation(), diag::err_static_non_static) << New; 3350 Diag(OldLocation, PrevDiag); 3351 return true; 3352 } 3353 } 3354 3355 if (New->hasAttr<InternalLinkageAttr>() && 3356 !Old->hasAttr<InternalLinkageAttr>()) { 3357 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3358 << New->getDeclName(); 3359 notePreviousDefinition(Old, New->getLocation()); 3360 New->dropAttr<InternalLinkageAttr>(); 3361 } 3362 3363 if (CheckRedeclarationModuleOwnership(New, Old)) 3364 return true; 3365 3366 if (!getLangOpts().CPlusPlus) { 3367 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3368 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3369 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3370 << New << OldOvl; 3371 3372 // Try our best to find a decl that actually has the overloadable 3373 // attribute for the note. In most cases (e.g. programs with only one 3374 // broken declaration/definition), this won't matter. 3375 // 3376 // FIXME: We could do this if we juggled some extra state in 3377 // OverloadableAttr, rather than just removing it. 3378 const Decl *DiagOld = Old; 3379 if (OldOvl) { 3380 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3381 const auto *A = D->getAttr<OverloadableAttr>(); 3382 return A && !A->isImplicit(); 3383 }); 3384 // If we've implicitly added *all* of the overloadable attrs to this 3385 // chain, emitting a "previous redecl" note is pointless. 3386 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3387 } 3388 3389 if (DiagOld) 3390 Diag(DiagOld->getLocation(), 3391 diag::note_attribute_overloadable_prev_overload) 3392 << OldOvl; 3393 3394 if (OldOvl) 3395 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3396 else 3397 New->dropAttr<OverloadableAttr>(); 3398 } 3399 } 3400 3401 // If a function is first declared with a calling convention, but is later 3402 // declared or defined without one, all following decls assume the calling 3403 // convention of the first. 3404 // 3405 // It's OK if a function is first declared without a calling convention, 3406 // but is later declared or defined with the default calling convention. 3407 // 3408 // To test if either decl has an explicit calling convention, we look for 3409 // AttributedType sugar nodes on the type as written. If they are missing or 3410 // were canonicalized away, we assume the calling convention was implicit. 3411 // 3412 // Note also that we DO NOT return at this point, because we still have 3413 // other tests to run. 3414 QualType OldQType = Context.getCanonicalType(Old->getType()); 3415 QualType NewQType = Context.getCanonicalType(New->getType()); 3416 const FunctionType *OldType = cast<FunctionType>(OldQType); 3417 const FunctionType *NewType = cast<FunctionType>(NewQType); 3418 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3419 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3420 bool RequiresAdjustment = false; 3421 3422 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3423 FunctionDecl *First = Old->getFirstDecl(); 3424 const FunctionType *FT = 3425 First->getType().getCanonicalType()->castAs<FunctionType>(); 3426 FunctionType::ExtInfo FI = FT->getExtInfo(); 3427 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3428 if (!NewCCExplicit) { 3429 // Inherit the CC from the previous declaration if it was specified 3430 // there but not here. 3431 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3432 RequiresAdjustment = true; 3433 } else if (Old->getBuiltinID()) { 3434 // Builtin attribute isn't propagated to the new one yet at this point, 3435 // so we check if the old one is a builtin. 3436 3437 // Calling Conventions on a Builtin aren't really useful and setting a 3438 // default calling convention and cdecl'ing some builtin redeclarations is 3439 // common, so warn and ignore the calling convention on the redeclaration. 3440 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3441 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3442 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3443 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3444 RequiresAdjustment = true; 3445 } else { 3446 // Calling conventions aren't compatible, so complain. 3447 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3448 Diag(New->getLocation(), diag::err_cconv_change) 3449 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3450 << !FirstCCExplicit 3451 << (!FirstCCExplicit ? "" : 3452 FunctionType::getNameForCallConv(FI.getCC())); 3453 3454 // Put the note on the first decl, since it is the one that matters. 3455 Diag(First->getLocation(), diag::note_previous_declaration); 3456 return true; 3457 } 3458 } 3459 3460 // FIXME: diagnose the other way around? 3461 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3462 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3463 RequiresAdjustment = true; 3464 } 3465 3466 // Merge regparm attribute. 3467 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3468 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3469 if (NewTypeInfo.getHasRegParm()) { 3470 Diag(New->getLocation(), diag::err_regparm_mismatch) 3471 << NewType->getRegParmType() 3472 << OldType->getRegParmType(); 3473 Diag(OldLocation, diag::note_previous_declaration); 3474 return true; 3475 } 3476 3477 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3478 RequiresAdjustment = true; 3479 } 3480 3481 // Merge ns_returns_retained attribute. 3482 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3483 if (NewTypeInfo.getProducesResult()) { 3484 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3485 << "'ns_returns_retained'"; 3486 Diag(OldLocation, diag::note_previous_declaration); 3487 return true; 3488 } 3489 3490 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3491 RequiresAdjustment = true; 3492 } 3493 3494 if (OldTypeInfo.getNoCallerSavedRegs() != 3495 NewTypeInfo.getNoCallerSavedRegs()) { 3496 if (NewTypeInfo.getNoCallerSavedRegs()) { 3497 AnyX86NoCallerSavedRegistersAttr *Attr = 3498 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3499 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3500 Diag(OldLocation, diag::note_previous_declaration); 3501 return true; 3502 } 3503 3504 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3505 RequiresAdjustment = true; 3506 } 3507 3508 if (RequiresAdjustment) { 3509 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3510 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3511 New->setType(QualType(AdjustedType, 0)); 3512 NewQType = Context.getCanonicalType(New->getType()); 3513 } 3514 3515 // If this redeclaration makes the function inline, we may need to add it to 3516 // UndefinedButUsed. 3517 if (!Old->isInlined() && New->isInlined() && 3518 !New->hasAttr<GNUInlineAttr>() && 3519 !getLangOpts().GNUInline && 3520 Old->isUsed(false) && 3521 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3522 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3523 SourceLocation())); 3524 3525 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3526 // about it. 3527 if (New->hasAttr<GNUInlineAttr>() && 3528 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3529 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3530 } 3531 3532 // If pass_object_size params don't match up perfectly, this isn't a valid 3533 // redeclaration. 3534 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3535 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3536 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3537 << New->getDeclName(); 3538 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3539 return true; 3540 } 3541 3542 if (getLangOpts().CPlusPlus) { 3543 // C++1z [over.load]p2 3544 // Certain function declarations cannot be overloaded: 3545 // -- Function declarations that differ only in the return type, 3546 // the exception specification, or both cannot be overloaded. 3547 3548 // Check the exception specifications match. This may recompute the type of 3549 // both Old and New if it resolved exception specifications, so grab the 3550 // types again after this. Because this updates the type, we do this before 3551 // any of the other checks below, which may update the "de facto" NewQType 3552 // but do not necessarily update the type of New. 3553 if (CheckEquivalentExceptionSpec(Old, New)) 3554 return true; 3555 OldQType = Context.getCanonicalType(Old->getType()); 3556 NewQType = Context.getCanonicalType(New->getType()); 3557 3558 // Go back to the type source info to compare the declared return types, 3559 // per C++1y [dcl.type.auto]p13: 3560 // Redeclarations or specializations of a function or function template 3561 // with a declared return type that uses a placeholder type shall also 3562 // use that placeholder, not a deduced type. 3563 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3564 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3565 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3566 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3567 OldDeclaredReturnType)) { 3568 QualType ResQT; 3569 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3570 OldDeclaredReturnType->isObjCObjectPointerType()) 3571 // FIXME: This does the wrong thing for a deduced return type. 3572 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3573 if (ResQT.isNull()) { 3574 if (New->isCXXClassMember() && New->isOutOfLine()) 3575 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3576 << New << New->getReturnTypeSourceRange(); 3577 else 3578 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3579 << New->getReturnTypeSourceRange(); 3580 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3581 << Old->getReturnTypeSourceRange(); 3582 return true; 3583 } 3584 else 3585 NewQType = ResQT; 3586 } 3587 3588 QualType OldReturnType = OldType->getReturnType(); 3589 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3590 if (OldReturnType != NewReturnType) { 3591 // If this function has a deduced return type and has already been 3592 // defined, copy the deduced value from the old declaration. 3593 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3594 if (OldAT && OldAT->isDeduced()) { 3595 New->setType( 3596 SubstAutoType(New->getType(), 3597 OldAT->isDependentType() ? Context.DependentTy 3598 : OldAT->getDeducedType())); 3599 NewQType = Context.getCanonicalType( 3600 SubstAutoType(NewQType, 3601 OldAT->isDependentType() ? Context.DependentTy 3602 : OldAT->getDeducedType())); 3603 } 3604 } 3605 3606 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3607 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3608 if (OldMethod && NewMethod) { 3609 // Preserve triviality. 3610 NewMethod->setTrivial(OldMethod->isTrivial()); 3611 3612 // MSVC allows explicit template specialization at class scope: 3613 // 2 CXXMethodDecls referring to the same function will be injected. 3614 // We don't want a redeclaration error. 3615 bool IsClassScopeExplicitSpecialization = 3616 OldMethod->isFunctionTemplateSpecialization() && 3617 NewMethod->isFunctionTemplateSpecialization(); 3618 bool isFriend = NewMethod->getFriendObjectKind(); 3619 3620 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3621 !IsClassScopeExplicitSpecialization) { 3622 // -- Member function declarations with the same name and the 3623 // same parameter types cannot be overloaded if any of them 3624 // is a static member function declaration. 3625 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3626 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3627 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3628 return true; 3629 } 3630 3631 // C++ [class.mem]p1: 3632 // [...] A member shall not be declared twice in the 3633 // member-specification, except that a nested class or member 3634 // class template can be declared and then later defined. 3635 if (!inTemplateInstantiation()) { 3636 unsigned NewDiag; 3637 if (isa<CXXConstructorDecl>(OldMethod)) 3638 NewDiag = diag::err_constructor_redeclared; 3639 else if (isa<CXXDestructorDecl>(NewMethod)) 3640 NewDiag = diag::err_destructor_redeclared; 3641 else if (isa<CXXConversionDecl>(NewMethod)) 3642 NewDiag = diag::err_conv_function_redeclared; 3643 else 3644 NewDiag = diag::err_member_redeclared; 3645 3646 Diag(New->getLocation(), NewDiag); 3647 } else { 3648 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3649 << New << New->getType(); 3650 } 3651 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3652 return true; 3653 3654 // Complain if this is an explicit declaration of a special 3655 // member that was initially declared implicitly. 3656 // 3657 // As an exception, it's okay to befriend such methods in order 3658 // to permit the implicit constructor/destructor/operator calls. 3659 } else if (OldMethod->isImplicit()) { 3660 if (isFriend) { 3661 NewMethod->setImplicit(); 3662 } else { 3663 Diag(NewMethod->getLocation(), 3664 diag::err_definition_of_implicitly_declared_member) 3665 << New << getSpecialMember(OldMethod); 3666 return true; 3667 } 3668 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3669 Diag(NewMethod->getLocation(), 3670 diag::err_definition_of_explicitly_defaulted_member) 3671 << getSpecialMember(OldMethod); 3672 return true; 3673 } 3674 } 3675 3676 // C++11 [dcl.attr.noreturn]p1: 3677 // The first declaration of a function shall specify the noreturn 3678 // attribute if any declaration of that function specifies the noreturn 3679 // attribute. 3680 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3681 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3682 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3683 Diag(Old->getFirstDecl()->getLocation(), 3684 diag::note_noreturn_missing_first_decl); 3685 } 3686 3687 // C++11 [dcl.attr.depend]p2: 3688 // The first declaration of a function shall specify the 3689 // carries_dependency attribute for its declarator-id if any declaration 3690 // of the function specifies the carries_dependency attribute. 3691 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3692 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3693 Diag(CDA->getLocation(), 3694 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3695 Diag(Old->getFirstDecl()->getLocation(), 3696 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3697 } 3698 3699 // (C++98 8.3.5p3): 3700 // All declarations for a function shall agree exactly in both the 3701 // return type and the parameter-type-list. 3702 // We also want to respect all the extended bits except noreturn. 3703 3704 // noreturn should now match unless the old type info didn't have it. 3705 QualType OldQTypeForComparison = OldQType; 3706 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3707 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3708 const FunctionType *OldTypeForComparison 3709 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3710 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3711 assert(OldQTypeForComparison.isCanonical()); 3712 } 3713 3714 if (haveIncompatibleLanguageLinkages(Old, New)) { 3715 // As a special case, retain the language linkage from previous 3716 // declarations of a friend function as an extension. 3717 // 3718 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3719 // and is useful because there's otherwise no way to specify language 3720 // linkage within class scope. 3721 // 3722 // Check cautiously as the friend object kind isn't yet complete. 3723 if (New->getFriendObjectKind() != Decl::FOK_None) { 3724 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3725 Diag(OldLocation, PrevDiag); 3726 } else { 3727 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3728 Diag(OldLocation, PrevDiag); 3729 return true; 3730 } 3731 } 3732 3733 // If the function types are compatible, merge the declarations. Ignore the 3734 // exception specifier because it was already checked above in 3735 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3736 // about incompatible types under -fms-compatibility. 3737 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3738 NewQType)) 3739 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3740 3741 // If the types are imprecise (due to dependent constructs in friends or 3742 // local extern declarations), it's OK if they differ. We'll check again 3743 // during instantiation. 3744 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3745 return false; 3746 3747 // Fall through for conflicting redeclarations and redefinitions. 3748 } 3749 3750 // C: Function types need to be compatible, not identical. This handles 3751 // duplicate function decls like "void f(int); void f(enum X);" properly. 3752 if (!getLangOpts().CPlusPlus && 3753 Context.typesAreCompatible(OldQType, NewQType)) { 3754 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3755 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3756 const FunctionProtoType *OldProto = nullptr; 3757 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3758 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3759 // The old declaration provided a function prototype, but the 3760 // new declaration does not. Merge in the prototype. 3761 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3762 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3763 NewQType = 3764 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3765 OldProto->getExtProtoInfo()); 3766 New->setType(NewQType); 3767 New->setHasInheritedPrototype(); 3768 3769 // Synthesize parameters with the same types. 3770 SmallVector<ParmVarDecl*, 16> Params; 3771 for (const auto &ParamType : OldProto->param_types()) { 3772 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3773 SourceLocation(), nullptr, 3774 ParamType, /*TInfo=*/nullptr, 3775 SC_None, nullptr); 3776 Param->setScopeInfo(0, Params.size()); 3777 Param->setImplicit(); 3778 Params.push_back(Param); 3779 } 3780 3781 New->setParams(Params); 3782 } 3783 3784 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3785 } 3786 3787 // Check if the function types are compatible when pointer size address 3788 // spaces are ignored. 3789 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3790 return false; 3791 3792 // GNU C permits a K&R definition to follow a prototype declaration 3793 // if the declared types of the parameters in the K&R definition 3794 // match the types in the prototype declaration, even when the 3795 // promoted types of the parameters from the K&R definition differ 3796 // from the types in the prototype. GCC then keeps the types from 3797 // the prototype. 3798 // 3799 // If a variadic prototype is followed by a non-variadic K&R definition, 3800 // the K&R definition becomes variadic. This is sort of an edge case, but 3801 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3802 // C99 6.9.1p8. 3803 if (!getLangOpts().CPlusPlus && 3804 Old->hasPrototype() && !New->hasPrototype() && 3805 New->getType()->getAs<FunctionProtoType>() && 3806 Old->getNumParams() == New->getNumParams()) { 3807 SmallVector<QualType, 16> ArgTypes; 3808 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3809 const FunctionProtoType *OldProto 3810 = Old->getType()->getAs<FunctionProtoType>(); 3811 const FunctionProtoType *NewProto 3812 = New->getType()->getAs<FunctionProtoType>(); 3813 3814 // Determine whether this is the GNU C extension. 3815 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3816 NewProto->getReturnType()); 3817 bool LooseCompatible = !MergedReturn.isNull(); 3818 for (unsigned Idx = 0, End = Old->getNumParams(); 3819 LooseCompatible && Idx != End; ++Idx) { 3820 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3821 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3822 if (Context.typesAreCompatible(OldParm->getType(), 3823 NewProto->getParamType(Idx))) { 3824 ArgTypes.push_back(NewParm->getType()); 3825 } else if (Context.typesAreCompatible(OldParm->getType(), 3826 NewParm->getType(), 3827 /*CompareUnqualified=*/true)) { 3828 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3829 NewProto->getParamType(Idx) }; 3830 Warnings.push_back(Warn); 3831 ArgTypes.push_back(NewParm->getType()); 3832 } else 3833 LooseCompatible = false; 3834 } 3835 3836 if (LooseCompatible) { 3837 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3838 Diag(Warnings[Warn].NewParm->getLocation(), 3839 diag::ext_param_promoted_not_compatible_with_prototype) 3840 << Warnings[Warn].PromotedType 3841 << Warnings[Warn].OldParm->getType(); 3842 if (Warnings[Warn].OldParm->getLocation().isValid()) 3843 Diag(Warnings[Warn].OldParm->getLocation(), 3844 diag::note_previous_declaration); 3845 } 3846 3847 if (MergeTypeWithOld) 3848 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3849 OldProto->getExtProtoInfo())); 3850 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3851 } 3852 3853 // Fall through to diagnose conflicting types. 3854 } 3855 3856 // A function that has already been declared has been redeclared or 3857 // defined with a different type; show an appropriate diagnostic. 3858 3859 // If the previous declaration was an implicitly-generated builtin 3860 // declaration, then at the very least we should use a specialized note. 3861 unsigned BuiltinID; 3862 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3863 // If it's actually a library-defined builtin function like 'malloc' 3864 // or 'printf', just warn about the incompatible redeclaration. 3865 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3866 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3867 Diag(OldLocation, diag::note_previous_builtin_declaration) 3868 << Old << Old->getType(); 3869 return false; 3870 } 3871 3872 PrevDiag = diag::note_previous_builtin_declaration; 3873 } 3874 3875 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3876 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3877 return true; 3878 } 3879 3880 /// Completes the merge of two function declarations that are 3881 /// known to be compatible. 3882 /// 3883 /// This routine handles the merging of attributes and other 3884 /// properties of function declarations from the old declaration to 3885 /// the new declaration, once we know that New is in fact a 3886 /// redeclaration of Old. 3887 /// 3888 /// \returns false 3889 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3890 Scope *S, bool MergeTypeWithOld) { 3891 // Merge the attributes 3892 mergeDeclAttributes(New, Old); 3893 3894 // Merge "pure" flag. 3895 if (Old->isPure()) 3896 New->setPure(); 3897 3898 // Merge "used" flag. 3899 if (Old->getMostRecentDecl()->isUsed(false)) 3900 New->setIsUsed(); 3901 3902 // Merge attributes from the parameters. These can mismatch with K&R 3903 // declarations. 3904 if (New->getNumParams() == Old->getNumParams()) 3905 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3906 ParmVarDecl *NewParam = New->getParamDecl(i); 3907 ParmVarDecl *OldParam = Old->getParamDecl(i); 3908 mergeParamDeclAttributes(NewParam, OldParam, *this); 3909 mergeParamDeclTypes(NewParam, OldParam, *this); 3910 } 3911 3912 if (getLangOpts().CPlusPlus) 3913 return MergeCXXFunctionDecl(New, Old, S); 3914 3915 // Merge the function types so the we get the composite types for the return 3916 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3917 // was visible. 3918 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3919 if (!Merged.isNull() && MergeTypeWithOld) 3920 New->setType(Merged); 3921 3922 return false; 3923 } 3924 3925 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3926 ObjCMethodDecl *oldMethod) { 3927 // Merge the attributes, including deprecated/unavailable 3928 AvailabilityMergeKind MergeKind = 3929 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3930 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation 3931 : AMK_ProtocolImplementation) 3932 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3933 : AMK_Override; 3934 3935 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3936 3937 // Merge attributes from the parameters. 3938 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3939 oe = oldMethod->param_end(); 3940 for (ObjCMethodDecl::param_iterator 3941 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3942 ni != ne && oi != oe; ++ni, ++oi) 3943 mergeParamDeclAttributes(*ni, *oi, *this); 3944 3945 CheckObjCMethodOverride(newMethod, oldMethod); 3946 } 3947 3948 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3949 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3950 3951 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3952 ? diag::err_redefinition_different_type 3953 : diag::err_redeclaration_different_type) 3954 << New->getDeclName() << New->getType() << Old->getType(); 3955 3956 diag::kind PrevDiag; 3957 SourceLocation OldLocation; 3958 std::tie(PrevDiag, OldLocation) 3959 = getNoteDiagForInvalidRedeclaration(Old, New); 3960 S.Diag(OldLocation, PrevDiag); 3961 New->setInvalidDecl(); 3962 } 3963 3964 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3965 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3966 /// emitting diagnostics as appropriate. 3967 /// 3968 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3969 /// to here in AddInitializerToDecl. We can't check them before the initializer 3970 /// is attached. 3971 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3972 bool MergeTypeWithOld) { 3973 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3974 return; 3975 3976 QualType MergedT; 3977 if (getLangOpts().CPlusPlus) { 3978 if (New->getType()->isUndeducedType()) { 3979 // We don't know what the new type is until the initializer is attached. 3980 return; 3981 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3982 // These could still be something that needs exception specs checked. 3983 return MergeVarDeclExceptionSpecs(New, Old); 3984 } 3985 // C++ [basic.link]p10: 3986 // [...] the types specified by all declarations referring to a given 3987 // object or function shall be identical, except that declarations for an 3988 // array object can specify array types that differ by the presence or 3989 // absence of a major array bound (8.3.4). 3990 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3991 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3992 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3993 3994 // We are merging a variable declaration New into Old. If it has an array 3995 // bound, and that bound differs from Old's bound, we should diagnose the 3996 // mismatch. 3997 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3998 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3999 PrevVD = PrevVD->getPreviousDecl()) { 4000 QualType PrevVDTy = PrevVD->getType(); 4001 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 4002 continue; 4003 4004 if (!Context.hasSameType(New->getType(), PrevVDTy)) 4005 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 4006 } 4007 } 4008 4009 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 4010 if (Context.hasSameType(OldArray->getElementType(), 4011 NewArray->getElementType())) 4012 MergedT = New->getType(); 4013 } 4014 // FIXME: Check visibility. New is hidden but has a complete type. If New 4015 // has no array bound, it should not inherit one from Old, if Old is not 4016 // visible. 4017 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 4018 if (Context.hasSameType(OldArray->getElementType(), 4019 NewArray->getElementType())) 4020 MergedT = Old->getType(); 4021 } 4022 } 4023 else if (New->getType()->isObjCObjectPointerType() && 4024 Old->getType()->isObjCObjectPointerType()) { 4025 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 4026 Old->getType()); 4027 } 4028 } else { 4029 // C 6.2.7p2: 4030 // All declarations that refer to the same object or function shall have 4031 // compatible type. 4032 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 4033 } 4034 if (MergedT.isNull()) { 4035 // It's OK if we couldn't merge types if either type is dependent, for a 4036 // block-scope variable. In other cases (static data members of class 4037 // templates, variable templates, ...), we require the types to be 4038 // equivalent. 4039 // FIXME: The C++ standard doesn't say anything about this. 4040 if ((New->getType()->isDependentType() || 4041 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 4042 // If the old type was dependent, we can't merge with it, so the new type 4043 // becomes dependent for now. We'll reproduce the original type when we 4044 // instantiate the TypeSourceInfo for the variable. 4045 if (!New->getType()->isDependentType() && MergeTypeWithOld) 4046 New->setType(Context.DependentTy); 4047 return; 4048 } 4049 return diagnoseVarDeclTypeMismatch(*this, New, Old); 4050 } 4051 4052 // Don't actually update the type on the new declaration if the old 4053 // declaration was an extern declaration in a different scope. 4054 if (MergeTypeWithOld) 4055 New->setType(MergedT); 4056 } 4057 4058 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 4059 LookupResult &Previous) { 4060 // C11 6.2.7p4: 4061 // For an identifier with internal or external linkage declared 4062 // in a scope in which a prior declaration of that identifier is 4063 // visible, if the prior declaration specifies internal or 4064 // external linkage, the type of the identifier at the later 4065 // declaration becomes the composite type. 4066 // 4067 // If the variable isn't visible, we do not merge with its type. 4068 if (Previous.isShadowed()) 4069 return false; 4070 4071 if (S.getLangOpts().CPlusPlus) { 4072 // C++11 [dcl.array]p3: 4073 // If there is a preceding declaration of the entity in the same 4074 // scope in which the bound was specified, an omitted array bound 4075 // is taken to be the same as in that earlier declaration. 4076 return NewVD->isPreviousDeclInSameBlockScope() || 4077 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4078 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4079 } else { 4080 // If the old declaration was function-local, don't merge with its 4081 // type unless we're in the same function. 4082 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4083 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4084 } 4085 } 4086 4087 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4088 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4089 /// situation, merging decls or emitting diagnostics as appropriate. 4090 /// 4091 /// Tentative definition rules (C99 6.9.2p2) are checked by 4092 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4093 /// definitions here, since the initializer hasn't been attached. 4094 /// 4095 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4096 // If the new decl is already invalid, don't do any other checking. 4097 if (New->isInvalidDecl()) 4098 return; 4099 4100 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4101 return; 4102 4103 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4104 4105 // Verify the old decl was also a variable or variable template. 4106 VarDecl *Old = nullptr; 4107 VarTemplateDecl *OldTemplate = nullptr; 4108 if (Previous.isSingleResult()) { 4109 if (NewTemplate) { 4110 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4111 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4112 4113 if (auto *Shadow = 4114 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4115 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4116 return New->setInvalidDecl(); 4117 } else { 4118 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4119 4120 if (auto *Shadow = 4121 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4122 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4123 return New->setInvalidDecl(); 4124 } 4125 } 4126 if (!Old) { 4127 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4128 << New->getDeclName(); 4129 notePreviousDefinition(Previous.getRepresentativeDecl(), 4130 New->getLocation()); 4131 return New->setInvalidDecl(); 4132 } 4133 4134 // If the old declaration was found in an inline namespace and the new 4135 // declaration was qualified, update the DeclContext to match. 4136 adjustDeclContextForDeclaratorDecl(New, Old); 4137 4138 // Ensure the template parameters are compatible. 4139 if (NewTemplate && 4140 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4141 OldTemplate->getTemplateParameters(), 4142 /*Complain=*/true, TPL_TemplateMatch)) 4143 return New->setInvalidDecl(); 4144 4145 // C++ [class.mem]p1: 4146 // A member shall not be declared twice in the member-specification [...] 4147 // 4148 // Here, we need only consider static data members. 4149 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4150 Diag(New->getLocation(), diag::err_duplicate_member) 4151 << New->getIdentifier(); 4152 Diag(Old->getLocation(), diag::note_previous_declaration); 4153 New->setInvalidDecl(); 4154 } 4155 4156 mergeDeclAttributes(New, Old); 4157 // Warn if an already-declared variable is made a weak_import in a subsequent 4158 // declaration 4159 if (New->hasAttr<WeakImportAttr>() && 4160 Old->getStorageClass() == SC_None && 4161 !Old->hasAttr<WeakImportAttr>()) { 4162 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4163 notePreviousDefinition(Old, New->getLocation()); 4164 // Remove weak_import attribute on new declaration. 4165 New->dropAttr<WeakImportAttr>(); 4166 } 4167 4168 if (New->hasAttr<InternalLinkageAttr>() && 4169 !Old->hasAttr<InternalLinkageAttr>()) { 4170 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4171 << New->getDeclName(); 4172 notePreviousDefinition(Old, New->getLocation()); 4173 New->dropAttr<InternalLinkageAttr>(); 4174 } 4175 4176 // Merge the types. 4177 VarDecl *MostRecent = Old->getMostRecentDecl(); 4178 if (MostRecent != Old) { 4179 MergeVarDeclTypes(New, MostRecent, 4180 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4181 if (New->isInvalidDecl()) 4182 return; 4183 } 4184 4185 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4186 if (New->isInvalidDecl()) 4187 return; 4188 4189 diag::kind PrevDiag; 4190 SourceLocation OldLocation; 4191 std::tie(PrevDiag, OldLocation) = 4192 getNoteDiagForInvalidRedeclaration(Old, New); 4193 4194 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4195 if (New->getStorageClass() == SC_Static && 4196 !New->isStaticDataMember() && 4197 Old->hasExternalFormalLinkage()) { 4198 if (getLangOpts().MicrosoftExt) { 4199 Diag(New->getLocation(), diag::ext_static_non_static) 4200 << New->getDeclName(); 4201 Diag(OldLocation, PrevDiag); 4202 } else { 4203 Diag(New->getLocation(), diag::err_static_non_static) 4204 << New->getDeclName(); 4205 Diag(OldLocation, PrevDiag); 4206 return New->setInvalidDecl(); 4207 } 4208 } 4209 // C99 6.2.2p4: 4210 // For an identifier declared with the storage-class specifier 4211 // extern in a scope in which a prior declaration of that 4212 // identifier is visible,23) if the prior declaration specifies 4213 // internal or external linkage, the linkage of the identifier at 4214 // the later declaration is the same as the linkage specified at 4215 // the prior declaration. If no prior declaration is visible, or 4216 // if the prior declaration specifies no linkage, then the 4217 // identifier has external linkage. 4218 if (New->hasExternalStorage() && Old->hasLinkage()) 4219 /* Okay */; 4220 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4221 !New->isStaticDataMember() && 4222 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4223 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4224 Diag(OldLocation, PrevDiag); 4225 return New->setInvalidDecl(); 4226 } 4227 4228 // Check if extern is followed by non-extern and vice-versa. 4229 if (New->hasExternalStorage() && 4230 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4231 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4232 Diag(OldLocation, PrevDiag); 4233 return New->setInvalidDecl(); 4234 } 4235 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4236 !New->hasExternalStorage()) { 4237 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4238 Diag(OldLocation, PrevDiag); 4239 return New->setInvalidDecl(); 4240 } 4241 4242 if (CheckRedeclarationModuleOwnership(New, Old)) 4243 return; 4244 4245 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4246 4247 // FIXME: The test for external storage here seems wrong? We still 4248 // need to check for mismatches. 4249 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4250 // Don't complain about out-of-line definitions of static members. 4251 !(Old->getLexicalDeclContext()->isRecord() && 4252 !New->getLexicalDeclContext()->isRecord())) { 4253 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4254 Diag(OldLocation, PrevDiag); 4255 return New->setInvalidDecl(); 4256 } 4257 4258 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4259 if (VarDecl *Def = Old->getDefinition()) { 4260 // C++1z [dcl.fcn.spec]p4: 4261 // If the definition of a variable appears in a translation unit before 4262 // its first declaration as inline, the program is ill-formed. 4263 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4264 Diag(Def->getLocation(), diag::note_previous_definition); 4265 } 4266 } 4267 4268 // If this redeclaration makes the variable inline, we may need to add it to 4269 // UndefinedButUsed. 4270 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4271 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4272 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4273 SourceLocation())); 4274 4275 if (New->getTLSKind() != Old->getTLSKind()) { 4276 if (!Old->getTLSKind()) { 4277 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4278 Diag(OldLocation, PrevDiag); 4279 } else if (!New->getTLSKind()) { 4280 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4281 Diag(OldLocation, PrevDiag); 4282 } else { 4283 // Do not allow redeclaration to change the variable between requiring 4284 // static and dynamic initialization. 4285 // FIXME: GCC allows this, but uses the TLS keyword on the first 4286 // declaration to determine the kind. Do we need to be compatible here? 4287 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4288 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4289 Diag(OldLocation, PrevDiag); 4290 } 4291 } 4292 4293 // C++ doesn't have tentative definitions, so go right ahead and check here. 4294 if (getLangOpts().CPlusPlus && 4295 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4296 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4297 Old->getCanonicalDecl()->isConstexpr()) { 4298 // This definition won't be a definition any more once it's been merged. 4299 Diag(New->getLocation(), 4300 diag::warn_deprecated_redundant_constexpr_static_def); 4301 } else if (VarDecl *Def = Old->getDefinition()) { 4302 if (checkVarDeclRedefinition(Def, New)) 4303 return; 4304 } 4305 } 4306 4307 if (haveIncompatibleLanguageLinkages(Old, New)) { 4308 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4309 Diag(OldLocation, PrevDiag); 4310 New->setInvalidDecl(); 4311 return; 4312 } 4313 4314 // Merge "used" flag. 4315 if (Old->getMostRecentDecl()->isUsed(false)) 4316 New->setIsUsed(); 4317 4318 // Keep a chain of previous declarations. 4319 New->setPreviousDecl(Old); 4320 if (NewTemplate) 4321 NewTemplate->setPreviousDecl(OldTemplate); 4322 4323 // Inherit access appropriately. 4324 New->setAccess(Old->getAccess()); 4325 if (NewTemplate) 4326 NewTemplate->setAccess(New->getAccess()); 4327 4328 if (Old->isInline()) 4329 New->setImplicitlyInline(); 4330 } 4331 4332 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4333 SourceManager &SrcMgr = getSourceManager(); 4334 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4335 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4336 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4337 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4338 auto &HSI = PP.getHeaderSearchInfo(); 4339 StringRef HdrFilename = 4340 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4341 4342 auto noteFromModuleOrInclude = [&](Module *Mod, 4343 SourceLocation IncLoc) -> bool { 4344 // Redefinition errors with modules are common with non modular mapped 4345 // headers, example: a non-modular header H in module A that also gets 4346 // included directly in a TU. Pointing twice to the same header/definition 4347 // is confusing, try to get better diagnostics when modules is on. 4348 if (IncLoc.isValid()) { 4349 if (Mod) { 4350 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4351 << HdrFilename.str() << Mod->getFullModuleName(); 4352 if (!Mod->DefinitionLoc.isInvalid()) 4353 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4354 << Mod->getFullModuleName(); 4355 } else { 4356 Diag(IncLoc, diag::note_redefinition_include_same_file) 4357 << HdrFilename.str(); 4358 } 4359 return true; 4360 } 4361 4362 return false; 4363 }; 4364 4365 // Is it the same file and same offset? Provide more information on why 4366 // this leads to a redefinition error. 4367 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4368 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4369 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4370 bool EmittedDiag = 4371 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4372 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4373 4374 // If the header has no guards, emit a note suggesting one. 4375 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4376 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4377 4378 if (EmittedDiag) 4379 return; 4380 } 4381 4382 // Redefinition coming from different files or couldn't do better above. 4383 if (Old->getLocation().isValid()) 4384 Diag(Old->getLocation(), diag::note_previous_definition); 4385 } 4386 4387 /// We've just determined that \p Old and \p New both appear to be definitions 4388 /// of the same variable. Either diagnose or fix the problem. 4389 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4390 if (!hasVisibleDefinition(Old) && 4391 (New->getFormalLinkage() == InternalLinkage || 4392 New->isInline() || 4393 New->getDescribedVarTemplate() || 4394 New->getNumTemplateParameterLists() || 4395 New->getDeclContext()->isDependentContext())) { 4396 // The previous definition is hidden, and multiple definitions are 4397 // permitted (in separate TUs). Demote this to a declaration. 4398 New->demoteThisDefinitionToDeclaration(); 4399 4400 // Make the canonical definition visible. 4401 if (auto *OldTD = Old->getDescribedVarTemplate()) 4402 makeMergedDefinitionVisible(OldTD); 4403 makeMergedDefinitionVisible(Old); 4404 return false; 4405 } else { 4406 Diag(New->getLocation(), diag::err_redefinition) << New; 4407 notePreviousDefinition(Old, New->getLocation()); 4408 New->setInvalidDecl(); 4409 return true; 4410 } 4411 } 4412 4413 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4414 /// no declarator (e.g. "struct foo;") is parsed. 4415 Decl * 4416 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4417 RecordDecl *&AnonRecord) { 4418 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4419 AnonRecord); 4420 } 4421 4422 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4423 // disambiguate entities defined in different scopes. 4424 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4425 // compatibility. 4426 // We will pick our mangling number depending on which version of MSVC is being 4427 // targeted. 4428 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4429 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4430 ? S->getMSCurManglingNumber() 4431 : S->getMSLastManglingNumber(); 4432 } 4433 4434 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4435 if (!Context.getLangOpts().CPlusPlus) 4436 return; 4437 4438 if (isa<CXXRecordDecl>(Tag->getParent())) { 4439 // If this tag is the direct child of a class, number it if 4440 // it is anonymous. 4441 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4442 return; 4443 MangleNumberingContext &MCtx = 4444 Context.getManglingNumberContext(Tag->getParent()); 4445 Context.setManglingNumber( 4446 Tag, MCtx.getManglingNumber( 4447 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4448 return; 4449 } 4450 4451 // If this tag isn't a direct child of a class, number it if it is local. 4452 MangleNumberingContext *MCtx; 4453 Decl *ManglingContextDecl; 4454 std::tie(MCtx, ManglingContextDecl) = 4455 getCurrentMangleNumberContext(Tag->getDeclContext()); 4456 if (MCtx) { 4457 Context.setManglingNumber( 4458 Tag, MCtx->getManglingNumber( 4459 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4460 } 4461 } 4462 4463 namespace { 4464 struct NonCLikeKind { 4465 enum { 4466 None, 4467 BaseClass, 4468 DefaultMemberInit, 4469 Lambda, 4470 Friend, 4471 OtherMember, 4472 Invalid, 4473 } Kind = None; 4474 SourceRange Range; 4475 4476 explicit operator bool() { return Kind != None; } 4477 }; 4478 } 4479 4480 /// Determine whether a class is C-like, according to the rules of C++ 4481 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4482 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4483 if (RD->isInvalidDecl()) 4484 return {NonCLikeKind::Invalid, {}}; 4485 4486 // C++ [dcl.typedef]p9: [P1766R1] 4487 // An unnamed class with a typedef name for linkage purposes shall not 4488 // 4489 // -- have any base classes 4490 if (RD->getNumBases()) 4491 return {NonCLikeKind::BaseClass, 4492 SourceRange(RD->bases_begin()->getBeginLoc(), 4493 RD->bases_end()[-1].getEndLoc())}; 4494 bool Invalid = false; 4495 for (Decl *D : RD->decls()) { 4496 // Don't complain about things we already diagnosed. 4497 if (D->isInvalidDecl()) { 4498 Invalid = true; 4499 continue; 4500 } 4501 4502 // -- have any [...] default member initializers 4503 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4504 if (FD->hasInClassInitializer()) { 4505 auto *Init = FD->getInClassInitializer(); 4506 return {NonCLikeKind::DefaultMemberInit, 4507 Init ? Init->getSourceRange() : D->getSourceRange()}; 4508 } 4509 continue; 4510 } 4511 4512 // FIXME: We don't allow friend declarations. This violates the wording of 4513 // P1766, but not the intent. 4514 if (isa<FriendDecl>(D)) 4515 return {NonCLikeKind::Friend, D->getSourceRange()}; 4516 4517 // -- declare any members other than non-static data members, member 4518 // enumerations, or member classes, 4519 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4520 isa<EnumDecl>(D)) 4521 continue; 4522 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4523 if (!MemberRD) { 4524 if (D->isImplicit()) 4525 continue; 4526 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4527 } 4528 4529 // -- contain a lambda-expression, 4530 if (MemberRD->isLambda()) 4531 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4532 4533 // and all member classes shall also satisfy these requirements 4534 // (recursively). 4535 if (MemberRD->isThisDeclarationADefinition()) { 4536 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4537 return Kind; 4538 } 4539 } 4540 4541 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4542 } 4543 4544 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4545 TypedefNameDecl *NewTD) { 4546 if (TagFromDeclSpec->isInvalidDecl()) 4547 return; 4548 4549 // Do nothing if the tag already has a name for linkage purposes. 4550 if (TagFromDeclSpec->hasNameForLinkage()) 4551 return; 4552 4553 // A well-formed anonymous tag must always be a TUK_Definition. 4554 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4555 4556 // The type must match the tag exactly; no qualifiers allowed. 4557 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4558 Context.getTagDeclType(TagFromDeclSpec))) { 4559 if (getLangOpts().CPlusPlus) 4560 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4561 return; 4562 } 4563 4564 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4565 // An unnamed class with a typedef name for linkage purposes shall [be 4566 // C-like]. 4567 // 4568 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4569 // shouldn't happen, but there are constructs that the language rule doesn't 4570 // disallow for which we can't reasonably avoid computing linkage early. 4571 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4572 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4573 : NonCLikeKind(); 4574 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4575 if (NonCLike || ChangesLinkage) { 4576 if (NonCLike.Kind == NonCLikeKind::Invalid) 4577 return; 4578 4579 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4580 if (ChangesLinkage) { 4581 // If the linkage changes, we can't accept this as an extension. 4582 if (NonCLike.Kind == NonCLikeKind::None) 4583 DiagID = diag::err_typedef_changes_linkage; 4584 else 4585 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4586 } 4587 4588 SourceLocation FixitLoc = 4589 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4590 llvm::SmallString<40> TextToInsert; 4591 TextToInsert += ' '; 4592 TextToInsert += NewTD->getIdentifier()->getName(); 4593 4594 Diag(FixitLoc, DiagID) 4595 << isa<TypeAliasDecl>(NewTD) 4596 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4597 if (NonCLike.Kind != NonCLikeKind::None) { 4598 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4599 << NonCLike.Kind - 1 << NonCLike.Range; 4600 } 4601 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4602 << NewTD << isa<TypeAliasDecl>(NewTD); 4603 4604 if (ChangesLinkage) 4605 return; 4606 } 4607 4608 // Otherwise, set this as the anon-decl typedef for the tag. 4609 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4610 } 4611 4612 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4613 switch (T) { 4614 case DeclSpec::TST_class: 4615 return 0; 4616 case DeclSpec::TST_struct: 4617 return 1; 4618 case DeclSpec::TST_interface: 4619 return 2; 4620 case DeclSpec::TST_union: 4621 return 3; 4622 case DeclSpec::TST_enum: 4623 return 4; 4624 default: 4625 llvm_unreachable("unexpected type specifier"); 4626 } 4627 } 4628 4629 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4630 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4631 /// parameters to cope with template friend declarations. 4632 Decl * 4633 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4634 MultiTemplateParamsArg TemplateParams, 4635 bool IsExplicitInstantiation, 4636 RecordDecl *&AnonRecord) { 4637 Decl *TagD = nullptr; 4638 TagDecl *Tag = nullptr; 4639 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4640 DS.getTypeSpecType() == DeclSpec::TST_struct || 4641 DS.getTypeSpecType() == DeclSpec::TST_interface || 4642 DS.getTypeSpecType() == DeclSpec::TST_union || 4643 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4644 TagD = DS.getRepAsDecl(); 4645 4646 if (!TagD) // We probably had an error 4647 return nullptr; 4648 4649 // Note that the above type specs guarantee that the 4650 // type rep is a Decl, whereas in many of the others 4651 // it's a Type. 4652 if (isa<TagDecl>(TagD)) 4653 Tag = cast<TagDecl>(TagD); 4654 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4655 Tag = CTD->getTemplatedDecl(); 4656 } 4657 4658 if (Tag) { 4659 handleTagNumbering(Tag, S); 4660 Tag->setFreeStanding(); 4661 if (Tag->isInvalidDecl()) 4662 return Tag; 4663 } 4664 4665 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4666 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4667 // or incomplete types shall not be restrict-qualified." 4668 if (TypeQuals & DeclSpec::TQ_restrict) 4669 Diag(DS.getRestrictSpecLoc(), 4670 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4671 << DS.getSourceRange(); 4672 } 4673 4674 if (DS.isInlineSpecified()) 4675 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4676 << getLangOpts().CPlusPlus17; 4677 4678 if (DS.hasConstexprSpecifier()) { 4679 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4680 // and definitions of functions and variables. 4681 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4682 // the declaration of a function or function template 4683 if (Tag) 4684 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4685 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4686 << static_cast<int>(DS.getConstexprSpecifier()); 4687 else 4688 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4689 << static_cast<int>(DS.getConstexprSpecifier()); 4690 // Don't emit warnings after this error. 4691 return TagD; 4692 } 4693 4694 DiagnoseFunctionSpecifiers(DS); 4695 4696 if (DS.isFriendSpecified()) { 4697 // If we're dealing with a decl but not a TagDecl, assume that 4698 // whatever routines created it handled the friendship aspect. 4699 if (TagD && !Tag) 4700 return nullptr; 4701 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4702 } 4703 4704 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4705 bool IsExplicitSpecialization = 4706 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4707 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4708 !IsExplicitInstantiation && !IsExplicitSpecialization && 4709 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4710 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4711 // nested-name-specifier unless it is an explicit instantiation 4712 // or an explicit specialization. 4713 // 4714 // FIXME: We allow class template partial specializations here too, per the 4715 // obvious intent of DR1819. 4716 // 4717 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4718 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4719 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4720 return nullptr; 4721 } 4722 4723 // Track whether this decl-specifier declares anything. 4724 bool DeclaresAnything = true; 4725 4726 // Handle anonymous struct definitions. 4727 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4728 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4729 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4730 if (getLangOpts().CPlusPlus || 4731 Record->getDeclContext()->isRecord()) { 4732 // If CurContext is a DeclContext that can contain statements, 4733 // RecursiveASTVisitor won't visit the decls that 4734 // BuildAnonymousStructOrUnion() will put into CurContext. 4735 // Also store them here so that they can be part of the 4736 // DeclStmt that gets created in this case. 4737 // FIXME: Also return the IndirectFieldDecls created by 4738 // BuildAnonymousStructOr union, for the same reason? 4739 if (CurContext->isFunctionOrMethod()) 4740 AnonRecord = Record; 4741 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4742 Context.getPrintingPolicy()); 4743 } 4744 4745 DeclaresAnything = false; 4746 } 4747 } 4748 4749 // C11 6.7.2.1p2: 4750 // A struct-declaration that does not declare an anonymous structure or 4751 // anonymous union shall contain a struct-declarator-list. 4752 // 4753 // This rule also existed in C89 and C99; the grammar for struct-declaration 4754 // did not permit a struct-declaration without a struct-declarator-list. 4755 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4756 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4757 // Check for Microsoft C extension: anonymous struct/union member. 4758 // Handle 2 kinds of anonymous struct/union: 4759 // struct STRUCT; 4760 // union UNION; 4761 // and 4762 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4763 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4764 if ((Tag && Tag->getDeclName()) || 4765 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4766 RecordDecl *Record = nullptr; 4767 if (Tag) 4768 Record = dyn_cast<RecordDecl>(Tag); 4769 else if (const RecordType *RT = 4770 DS.getRepAsType().get()->getAsStructureType()) 4771 Record = RT->getDecl(); 4772 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4773 Record = UT->getDecl(); 4774 4775 if (Record && getLangOpts().MicrosoftExt) { 4776 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4777 << Record->isUnion() << DS.getSourceRange(); 4778 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4779 } 4780 4781 DeclaresAnything = false; 4782 } 4783 } 4784 4785 // Skip all the checks below if we have a type error. 4786 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4787 (TagD && TagD->isInvalidDecl())) 4788 return TagD; 4789 4790 if (getLangOpts().CPlusPlus && 4791 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4792 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4793 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4794 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4795 DeclaresAnything = false; 4796 4797 if (!DS.isMissingDeclaratorOk()) { 4798 // Customize diagnostic for a typedef missing a name. 4799 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4800 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4801 << DS.getSourceRange(); 4802 else 4803 DeclaresAnything = false; 4804 } 4805 4806 if (DS.isModulePrivateSpecified() && 4807 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4808 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4809 << Tag->getTagKind() 4810 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4811 4812 ActOnDocumentableDecl(TagD); 4813 4814 // C 6.7/2: 4815 // A declaration [...] shall declare at least a declarator [...], a tag, 4816 // or the members of an enumeration. 4817 // C++ [dcl.dcl]p3: 4818 // [If there are no declarators], and except for the declaration of an 4819 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4820 // names into the program, or shall redeclare a name introduced by a 4821 // previous declaration. 4822 if (!DeclaresAnything) { 4823 // In C, we allow this as a (popular) extension / bug. Don't bother 4824 // producing further diagnostics for redundant qualifiers after this. 4825 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 4826 ? diag::err_no_declarators 4827 : diag::ext_no_declarators) 4828 << DS.getSourceRange(); 4829 return TagD; 4830 } 4831 4832 // C++ [dcl.stc]p1: 4833 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4834 // init-declarator-list of the declaration shall not be empty. 4835 // C++ [dcl.fct.spec]p1: 4836 // If a cv-qualifier appears in a decl-specifier-seq, the 4837 // init-declarator-list of the declaration shall not be empty. 4838 // 4839 // Spurious qualifiers here appear to be valid in C. 4840 unsigned DiagID = diag::warn_standalone_specifier; 4841 if (getLangOpts().CPlusPlus) 4842 DiagID = diag::ext_standalone_specifier; 4843 4844 // Note that a linkage-specification sets a storage class, but 4845 // 'extern "C" struct foo;' is actually valid and not theoretically 4846 // useless. 4847 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4848 if (SCS == DeclSpec::SCS_mutable) 4849 // Since mutable is not a viable storage class specifier in C, there is 4850 // no reason to treat it as an extension. Instead, diagnose as an error. 4851 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4852 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4853 Diag(DS.getStorageClassSpecLoc(), DiagID) 4854 << DeclSpec::getSpecifierName(SCS); 4855 } 4856 4857 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4858 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4859 << DeclSpec::getSpecifierName(TSCS); 4860 if (DS.getTypeQualifiers()) { 4861 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4862 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4863 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4864 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4865 // Restrict is covered above. 4866 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4867 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4868 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4869 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4870 } 4871 4872 // Warn about ignored type attributes, for example: 4873 // __attribute__((aligned)) struct A; 4874 // Attributes should be placed after tag to apply to type declaration. 4875 if (!DS.getAttributes().empty()) { 4876 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4877 if (TypeSpecType == DeclSpec::TST_class || 4878 TypeSpecType == DeclSpec::TST_struct || 4879 TypeSpecType == DeclSpec::TST_interface || 4880 TypeSpecType == DeclSpec::TST_union || 4881 TypeSpecType == DeclSpec::TST_enum) { 4882 for (const ParsedAttr &AL : DS.getAttributes()) 4883 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4884 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4885 } 4886 } 4887 4888 return TagD; 4889 } 4890 4891 /// We are trying to inject an anonymous member into the given scope; 4892 /// check if there's an existing declaration that can't be overloaded. 4893 /// 4894 /// \return true if this is a forbidden redeclaration 4895 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4896 Scope *S, 4897 DeclContext *Owner, 4898 DeclarationName Name, 4899 SourceLocation NameLoc, 4900 bool IsUnion) { 4901 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4902 Sema::ForVisibleRedeclaration); 4903 if (!SemaRef.LookupName(R, S)) return false; 4904 4905 // Pick a representative declaration. 4906 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4907 assert(PrevDecl && "Expected a non-null Decl"); 4908 4909 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4910 return false; 4911 4912 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4913 << IsUnion << Name; 4914 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4915 4916 return true; 4917 } 4918 4919 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4920 /// anonymous struct or union AnonRecord into the owning context Owner 4921 /// and scope S. This routine will be invoked just after we realize 4922 /// that an unnamed union or struct is actually an anonymous union or 4923 /// struct, e.g., 4924 /// 4925 /// @code 4926 /// union { 4927 /// int i; 4928 /// float f; 4929 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4930 /// // f into the surrounding scope.x 4931 /// @endcode 4932 /// 4933 /// This routine is recursive, injecting the names of nested anonymous 4934 /// structs/unions into the owning context and scope as well. 4935 static bool 4936 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4937 RecordDecl *AnonRecord, AccessSpecifier AS, 4938 SmallVectorImpl<NamedDecl *> &Chaining) { 4939 bool Invalid = false; 4940 4941 // Look every FieldDecl and IndirectFieldDecl with a name. 4942 for (auto *D : AnonRecord->decls()) { 4943 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4944 cast<NamedDecl>(D)->getDeclName()) { 4945 ValueDecl *VD = cast<ValueDecl>(D); 4946 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4947 VD->getLocation(), 4948 AnonRecord->isUnion())) { 4949 // C++ [class.union]p2: 4950 // The names of the members of an anonymous union shall be 4951 // distinct from the names of any other entity in the 4952 // scope in which the anonymous union is declared. 4953 Invalid = true; 4954 } else { 4955 // C++ [class.union]p2: 4956 // For the purpose of name lookup, after the anonymous union 4957 // definition, the members of the anonymous union are 4958 // considered to have been defined in the scope in which the 4959 // anonymous union is declared. 4960 unsigned OldChainingSize = Chaining.size(); 4961 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4962 Chaining.append(IF->chain_begin(), IF->chain_end()); 4963 else 4964 Chaining.push_back(VD); 4965 4966 assert(Chaining.size() >= 2); 4967 NamedDecl **NamedChain = 4968 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4969 for (unsigned i = 0; i < Chaining.size(); i++) 4970 NamedChain[i] = Chaining[i]; 4971 4972 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4973 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4974 VD->getType(), {NamedChain, Chaining.size()}); 4975 4976 for (const auto *Attr : VD->attrs()) 4977 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4978 4979 IndirectField->setAccess(AS); 4980 IndirectField->setImplicit(); 4981 SemaRef.PushOnScopeChains(IndirectField, S); 4982 4983 // That includes picking up the appropriate access specifier. 4984 if (AS != AS_none) IndirectField->setAccess(AS); 4985 4986 Chaining.resize(OldChainingSize); 4987 } 4988 } 4989 } 4990 4991 return Invalid; 4992 } 4993 4994 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4995 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4996 /// illegal input values are mapped to SC_None. 4997 static StorageClass 4998 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4999 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 5000 assert(StorageClassSpec != DeclSpec::SCS_typedef && 5001 "Parser allowed 'typedef' as storage class VarDecl."); 5002 switch (StorageClassSpec) { 5003 case DeclSpec::SCS_unspecified: return SC_None; 5004 case DeclSpec::SCS_extern: 5005 if (DS.isExternInLinkageSpec()) 5006 return SC_None; 5007 return SC_Extern; 5008 case DeclSpec::SCS_static: return SC_Static; 5009 case DeclSpec::SCS_auto: return SC_Auto; 5010 case DeclSpec::SCS_register: return SC_Register; 5011 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5012 // Illegal SCSs map to None: error reporting is up to the caller. 5013 case DeclSpec::SCS_mutable: // Fall through. 5014 case DeclSpec::SCS_typedef: return SC_None; 5015 } 5016 llvm_unreachable("unknown storage class specifier"); 5017 } 5018 5019 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 5020 assert(Record->hasInClassInitializer()); 5021 5022 for (const auto *I : Record->decls()) { 5023 const auto *FD = dyn_cast<FieldDecl>(I); 5024 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 5025 FD = IFD->getAnonField(); 5026 if (FD && FD->hasInClassInitializer()) 5027 return FD->getLocation(); 5028 } 5029 5030 llvm_unreachable("couldn't find in-class initializer"); 5031 } 5032 5033 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5034 SourceLocation DefaultInitLoc) { 5035 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5036 return; 5037 5038 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 5039 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 5040 } 5041 5042 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5043 CXXRecordDecl *AnonUnion) { 5044 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5045 return; 5046 5047 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 5048 } 5049 5050 /// BuildAnonymousStructOrUnion - Handle the declaration of an 5051 /// anonymous structure or union. Anonymous unions are a C++ feature 5052 /// (C++ [class.union]) and a C11 feature; anonymous structures 5053 /// are a C11 feature and GNU C++ extension. 5054 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 5055 AccessSpecifier AS, 5056 RecordDecl *Record, 5057 const PrintingPolicy &Policy) { 5058 DeclContext *Owner = Record->getDeclContext(); 5059 5060 // Diagnose whether this anonymous struct/union is an extension. 5061 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 5062 Diag(Record->getLocation(), diag::ext_anonymous_union); 5063 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 5064 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 5065 else if (!Record->isUnion() && !getLangOpts().C11) 5066 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 5067 5068 // C and C++ require different kinds of checks for anonymous 5069 // structs/unions. 5070 bool Invalid = false; 5071 if (getLangOpts().CPlusPlus) { 5072 const char *PrevSpec = nullptr; 5073 if (Record->isUnion()) { 5074 // C++ [class.union]p6: 5075 // C++17 [class.union.anon]p2: 5076 // Anonymous unions declared in a named namespace or in the 5077 // global namespace shall be declared static. 5078 unsigned DiagID; 5079 DeclContext *OwnerScope = Owner->getRedeclContext(); 5080 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5081 (OwnerScope->isTranslationUnit() || 5082 (OwnerScope->isNamespace() && 5083 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5084 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5085 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5086 5087 // Recover by adding 'static'. 5088 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5089 PrevSpec, DiagID, Policy); 5090 } 5091 // C++ [class.union]p6: 5092 // A storage class is not allowed in a declaration of an 5093 // anonymous union in a class scope. 5094 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5095 isa<RecordDecl>(Owner)) { 5096 Diag(DS.getStorageClassSpecLoc(), 5097 diag::err_anonymous_union_with_storage_spec) 5098 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5099 5100 // Recover by removing the storage specifier. 5101 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5102 SourceLocation(), 5103 PrevSpec, DiagID, Context.getPrintingPolicy()); 5104 } 5105 } 5106 5107 // Ignore const/volatile/restrict qualifiers. 5108 if (DS.getTypeQualifiers()) { 5109 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5110 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5111 << Record->isUnion() << "const" 5112 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5113 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5114 Diag(DS.getVolatileSpecLoc(), 5115 diag::ext_anonymous_struct_union_qualified) 5116 << Record->isUnion() << "volatile" 5117 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5118 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5119 Diag(DS.getRestrictSpecLoc(), 5120 diag::ext_anonymous_struct_union_qualified) 5121 << Record->isUnion() << "restrict" 5122 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5123 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5124 Diag(DS.getAtomicSpecLoc(), 5125 diag::ext_anonymous_struct_union_qualified) 5126 << Record->isUnion() << "_Atomic" 5127 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5128 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5129 Diag(DS.getUnalignedSpecLoc(), 5130 diag::ext_anonymous_struct_union_qualified) 5131 << Record->isUnion() << "__unaligned" 5132 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5133 5134 DS.ClearTypeQualifiers(); 5135 } 5136 5137 // C++ [class.union]p2: 5138 // The member-specification of an anonymous union shall only 5139 // define non-static data members. [Note: nested types and 5140 // functions cannot be declared within an anonymous union. ] 5141 for (auto *Mem : Record->decls()) { 5142 // Ignore invalid declarations; we already diagnosed them. 5143 if (Mem->isInvalidDecl()) 5144 continue; 5145 5146 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5147 // C++ [class.union]p3: 5148 // An anonymous union shall not have private or protected 5149 // members (clause 11). 5150 assert(FD->getAccess() != AS_none); 5151 if (FD->getAccess() != AS_public) { 5152 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5153 << Record->isUnion() << (FD->getAccess() == AS_protected); 5154 Invalid = true; 5155 } 5156 5157 // C++ [class.union]p1 5158 // An object of a class with a non-trivial constructor, a non-trivial 5159 // copy constructor, a non-trivial destructor, or a non-trivial copy 5160 // assignment operator cannot be a member of a union, nor can an 5161 // array of such objects. 5162 if (CheckNontrivialField(FD)) 5163 Invalid = true; 5164 } else if (Mem->isImplicit()) { 5165 // Any implicit members are fine. 5166 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5167 // This is a type that showed up in an 5168 // elaborated-type-specifier inside the anonymous struct or 5169 // union, but which actually declares a type outside of the 5170 // anonymous struct or union. It's okay. 5171 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5172 if (!MemRecord->isAnonymousStructOrUnion() && 5173 MemRecord->getDeclName()) { 5174 // Visual C++ allows type definition in anonymous struct or union. 5175 if (getLangOpts().MicrosoftExt) 5176 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5177 << Record->isUnion(); 5178 else { 5179 // This is a nested type declaration. 5180 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5181 << Record->isUnion(); 5182 Invalid = true; 5183 } 5184 } else { 5185 // This is an anonymous type definition within another anonymous type. 5186 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5187 // not part of standard C++. 5188 Diag(MemRecord->getLocation(), 5189 diag::ext_anonymous_record_with_anonymous_type) 5190 << Record->isUnion(); 5191 } 5192 } else if (isa<AccessSpecDecl>(Mem)) { 5193 // Any access specifier is fine. 5194 } else if (isa<StaticAssertDecl>(Mem)) { 5195 // In C++1z, static_assert declarations are also fine. 5196 } else { 5197 // We have something that isn't a non-static data 5198 // member. Complain about it. 5199 unsigned DK = diag::err_anonymous_record_bad_member; 5200 if (isa<TypeDecl>(Mem)) 5201 DK = diag::err_anonymous_record_with_type; 5202 else if (isa<FunctionDecl>(Mem)) 5203 DK = diag::err_anonymous_record_with_function; 5204 else if (isa<VarDecl>(Mem)) 5205 DK = diag::err_anonymous_record_with_static; 5206 5207 // Visual C++ allows type definition in anonymous struct or union. 5208 if (getLangOpts().MicrosoftExt && 5209 DK == diag::err_anonymous_record_with_type) 5210 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5211 << Record->isUnion(); 5212 else { 5213 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5214 Invalid = true; 5215 } 5216 } 5217 } 5218 5219 // C++11 [class.union]p8 (DR1460): 5220 // At most one variant member of a union may have a 5221 // brace-or-equal-initializer. 5222 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5223 Owner->isRecord()) 5224 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5225 cast<CXXRecordDecl>(Record)); 5226 } 5227 5228 if (!Record->isUnion() && !Owner->isRecord()) { 5229 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5230 << getLangOpts().CPlusPlus; 5231 Invalid = true; 5232 } 5233 5234 // C++ [dcl.dcl]p3: 5235 // [If there are no declarators], and except for the declaration of an 5236 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5237 // names into the program 5238 // C++ [class.mem]p2: 5239 // each such member-declaration shall either declare at least one member 5240 // name of the class or declare at least one unnamed bit-field 5241 // 5242 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5243 if (getLangOpts().CPlusPlus && Record->field_empty()) 5244 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5245 5246 // Mock up a declarator. 5247 Declarator Dc(DS, DeclaratorContext::Member); 5248 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5249 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5250 5251 // Create a declaration for this anonymous struct/union. 5252 NamedDecl *Anon = nullptr; 5253 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5254 Anon = FieldDecl::Create( 5255 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5256 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5257 /*BitWidth=*/nullptr, /*Mutable=*/false, 5258 /*InitStyle=*/ICIS_NoInit); 5259 Anon->setAccess(AS); 5260 ProcessDeclAttributes(S, Anon, Dc); 5261 5262 if (getLangOpts().CPlusPlus) 5263 FieldCollector->Add(cast<FieldDecl>(Anon)); 5264 } else { 5265 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5266 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5267 if (SCSpec == DeclSpec::SCS_mutable) { 5268 // mutable can only appear on non-static class members, so it's always 5269 // an error here 5270 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5271 Invalid = true; 5272 SC = SC_None; 5273 } 5274 5275 assert(DS.getAttributes().empty() && "No attribute expected"); 5276 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5277 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5278 Context.getTypeDeclType(Record), TInfo, SC); 5279 5280 // Default-initialize the implicit variable. This initialization will be 5281 // trivial in almost all cases, except if a union member has an in-class 5282 // initializer: 5283 // union { int n = 0; }; 5284 if (!Invalid) 5285 ActOnUninitializedDecl(Anon); 5286 } 5287 Anon->setImplicit(); 5288 5289 // Mark this as an anonymous struct/union type. 5290 Record->setAnonymousStructOrUnion(true); 5291 5292 // Add the anonymous struct/union object to the current 5293 // context. We'll be referencing this object when we refer to one of 5294 // its members. 5295 Owner->addDecl(Anon); 5296 5297 // Inject the members of the anonymous struct/union into the owning 5298 // context and into the identifier resolver chain for name lookup 5299 // purposes. 5300 SmallVector<NamedDecl*, 2> Chain; 5301 Chain.push_back(Anon); 5302 5303 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5304 Invalid = true; 5305 5306 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5307 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5308 MangleNumberingContext *MCtx; 5309 Decl *ManglingContextDecl; 5310 std::tie(MCtx, ManglingContextDecl) = 5311 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5312 if (MCtx) { 5313 Context.setManglingNumber( 5314 NewVD, MCtx->getManglingNumber( 5315 NewVD, getMSManglingNumber(getLangOpts(), S))); 5316 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5317 } 5318 } 5319 } 5320 5321 if (Invalid) 5322 Anon->setInvalidDecl(); 5323 5324 return Anon; 5325 } 5326 5327 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5328 /// Microsoft C anonymous structure. 5329 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5330 /// Example: 5331 /// 5332 /// struct A { int a; }; 5333 /// struct B { struct A; int b; }; 5334 /// 5335 /// void foo() { 5336 /// B var; 5337 /// var.a = 3; 5338 /// } 5339 /// 5340 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5341 RecordDecl *Record) { 5342 assert(Record && "expected a record!"); 5343 5344 // Mock up a declarator. 5345 Declarator Dc(DS, DeclaratorContext::TypeName); 5346 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5347 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5348 5349 auto *ParentDecl = cast<RecordDecl>(CurContext); 5350 QualType RecTy = Context.getTypeDeclType(Record); 5351 5352 // Create a declaration for this anonymous struct. 5353 NamedDecl *Anon = 5354 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5355 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5356 /*BitWidth=*/nullptr, /*Mutable=*/false, 5357 /*InitStyle=*/ICIS_NoInit); 5358 Anon->setImplicit(); 5359 5360 // Add the anonymous struct object to the current context. 5361 CurContext->addDecl(Anon); 5362 5363 // Inject the members of the anonymous struct into the current 5364 // context and into the identifier resolver chain for name lookup 5365 // purposes. 5366 SmallVector<NamedDecl*, 2> Chain; 5367 Chain.push_back(Anon); 5368 5369 RecordDecl *RecordDef = Record->getDefinition(); 5370 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5371 diag::err_field_incomplete_or_sizeless) || 5372 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5373 AS_none, Chain)) { 5374 Anon->setInvalidDecl(); 5375 ParentDecl->setInvalidDecl(); 5376 } 5377 5378 return Anon; 5379 } 5380 5381 /// GetNameForDeclarator - Determine the full declaration name for the 5382 /// given Declarator. 5383 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5384 return GetNameFromUnqualifiedId(D.getName()); 5385 } 5386 5387 /// Retrieves the declaration name from a parsed unqualified-id. 5388 DeclarationNameInfo 5389 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5390 DeclarationNameInfo NameInfo; 5391 NameInfo.setLoc(Name.StartLocation); 5392 5393 switch (Name.getKind()) { 5394 5395 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5396 case UnqualifiedIdKind::IK_Identifier: 5397 NameInfo.setName(Name.Identifier); 5398 return NameInfo; 5399 5400 case UnqualifiedIdKind::IK_DeductionGuideName: { 5401 // C++ [temp.deduct.guide]p3: 5402 // The simple-template-id shall name a class template specialization. 5403 // The template-name shall be the same identifier as the template-name 5404 // of the simple-template-id. 5405 // These together intend to imply that the template-name shall name a 5406 // class template. 5407 // FIXME: template<typename T> struct X {}; 5408 // template<typename T> using Y = X<T>; 5409 // Y(int) -> Y<int>; 5410 // satisfies these rules but does not name a class template. 5411 TemplateName TN = Name.TemplateName.get().get(); 5412 auto *Template = TN.getAsTemplateDecl(); 5413 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5414 Diag(Name.StartLocation, 5415 diag::err_deduction_guide_name_not_class_template) 5416 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5417 if (Template) 5418 Diag(Template->getLocation(), diag::note_template_decl_here); 5419 return DeclarationNameInfo(); 5420 } 5421 5422 NameInfo.setName( 5423 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5424 return NameInfo; 5425 } 5426 5427 case UnqualifiedIdKind::IK_OperatorFunctionId: 5428 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5429 Name.OperatorFunctionId.Operator)); 5430 NameInfo.setCXXOperatorNameRange(SourceRange( 5431 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5432 return NameInfo; 5433 5434 case UnqualifiedIdKind::IK_LiteralOperatorId: 5435 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5436 Name.Identifier)); 5437 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5438 return NameInfo; 5439 5440 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5441 TypeSourceInfo *TInfo; 5442 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5443 if (Ty.isNull()) 5444 return DeclarationNameInfo(); 5445 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5446 Context.getCanonicalType(Ty))); 5447 NameInfo.setNamedTypeInfo(TInfo); 5448 return NameInfo; 5449 } 5450 5451 case UnqualifiedIdKind::IK_ConstructorName: { 5452 TypeSourceInfo *TInfo; 5453 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5454 if (Ty.isNull()) 5455 return DeclarationNameInfo(); 5456 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5457 Context.getCanonicalType(Ty))); 5458 NameInfo.setNamedTypeInfo(TInfo); 5459 return NameInfo; 5460 } 5461 5462 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5463 // In well-formed code, we can only have a constructor 5464 // template-id that refers to the current context, so go there 5465 // to find the actual type being constructed. 5466 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5467 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5468 return DeclarationNameInfo(); 5469 5470 // Determine the type of the class being constructed. 5471 QualType CurClassType = Context.getTypeDeclType(CurClass); 5472 5473 // FIXME: Check two things: that the template-id names the same type as 5474 // CurClassType, and that the template-id does not occur when the name 5475 // was qualified. 5476 5477 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5478 Context.getCanonicalType(CurClassType))); 5479 // FIXME: should we retrieve TypeSourceInfo? 5480 NameInfo.setNamedTypeInfo(nullptr); 5481 return NameInfo; 5482 } 5483 5484 case UnqualifiedIdKind::IK_DestructorName: { 5485 TypeSourceInfo *TInfo; 5486 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5487 if (Ty.isNull()) 5488 return DeclarationNameInfo(); 5489 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5490 Context.getCanonicalType(Ty))); 5491 NameInfo.setNamedTypeInfo(TInfo); 5492 return NameInfo; 5493 } 5494 5495 case UnqualifiedIdKind::IK_TemplateId: { 5496 TemplateName TName = Name.TemplateId->Template.get(); 5497 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5498 return Context.getNameForTemplate(TName, TNameLoc); 5499 } 5500 5501 } // switch (Name.getKind()) 5502 5503 llvm_unreachable("Unknown name kind"); 5504 } 5505 5506 static QualType getCoreType(QualType Ty) { 5507 do { 5508 if (Ty->isPointerType() || Ty->isReferenceType()) 5509 Ty = Ty->getPointeeType(); 5510 else if (Ty->isArrayType()) 5511 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5512 else 5513 return Ty.withoutLocalFastQualifiers(); 5514 } while (true); 5515 } 5516 5517 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5518 /// and Definition have "nearly" matching parameters. This heuristic is 5519 /// used to improve diagnostics in the case where an out-of-line function 5520 /// definition doesn't match any declaration within the class or namespace. 5521 /// Also sets Params to the list of indices to the parameters that differ 5522 /// between the declaration and the definition. If hasSimilarParameters 5523 /// returns true and Params is empty, then all of the parameters match. 5524 static bool hasSimilarParameters(ASTContext &Context, 5525 FunctionDecl *Declaration, 5526 FunctionDecl *Definition, 5527 SmallVectorImpl<unsigned> &Params) { 5528 Params.clear(); 5529 if (Declaration->param_size() != Definition->param_size()) 5530 return false; 5531 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5532 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5533 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5534 5535 // The parameter types are identical 5536 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5537 continue; 5538 5539 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5540 QualType DefParamBaseTy = getCoreType(DefParamTy); 5541 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5542 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5543 5544 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5545 (DeclTyName && DeclTyName == DefTyName)) 5546 Params.push_back(Idx); 5547 else // The two parameters aren't even close 5548 return false; 5549 } 5550 5551 return true; 5552 } 5553 5554 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5555 /// declarator needs to be rebuilt in the current instantiation. 5556 /// Any bits of declarator which appear before the name are valid for 5557 /// consideration here. That's specifically the type in the decl spec 5558 /// and the base type in any member-pointer chunks. 5559 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5560 DeclarationName Name) { 5561 // The types we specifically need to rebuild are: 5562 // - typenames, typeofs, and decltypes 5563 // - types which will become injected class names 5564 // Of course, we also need to rebuild any type referencing such a 5565 // type. It's safest to just say "dependent", but we call out a 5566 // few cases here. 5567 5568 DeclSpec &DS = D.getMutableDeclSpec(); 5569 switch (DS.getTypeSpecType()) { 5570 case DeclSpec::TST_typename: 5571 case DeclSpec::TST_typeofType: 5572 case DeclSpec::TST_underlyingType: 5573 case DeclSpec::TST_atomic: { 5574 // Grab the type from the parser. 5575 TypeSourceInfo *TSI = nullptr; 5576 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5577 if (T.isNull() || !T->isInstantiationDependentType()) break; 5578 5579 // Make sure there's a type source info. This isn't really much 5580 // of a waste; most dependent types should have type source info 5581 // attached already. 5582 if (!TSI) 5583 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5584 5585 // Rebuild the type in the current instantiation. 5586 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5587 if (!TSI) return true; 5588 5589 // Store the new type back in the decl spec. 5590 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5591 DS.UpdateTypeRep(LocType); 5592 break; 5593 } 5594 5595 case DeclSpec::TST_decltype: 5596 case DeclSpec::TST_typeofExpr: { 5597 Expr *E = DS.getRepAsExpr(); 5598 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5599 if (Result.isInvalid()) return true; 5600 DS.UpdateExprRep(Result.get()); 5601 break; 5602 } 5603 5604 default: 5605 // Nothing to do for these decl specs. 5606 break; 5607 } 5608 5609 // It doesn't matter what order we do this in. 5610 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5611 DeclaratorChunk &Chunk = D.getTypeObject(I); 5612 5613 // The only type information in the declarator which can come 5614 // before the declaration name is the base type of a member 5615 // pointer. 5616 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5617 continue; 5618 5619 // Rebuild the scope specifier in-place. 5620 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5621 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5622 return true; 5623 } 5624 5625 return false; 5626 } 5627 5628 void Sema::warnOnReservedIdentifier(const NamedDecl *D) { 5629 // Avoid warning twice on the same identifier, and don't warn on redeclaration 5630 // of system decl. 5631 if (D->getPreviousDecl() || D->isImplicit()) 5632 return; 5633 ReservedIdentifierStatus Status = D->isReserved(getLangOpts()); 5634 if (Status != ReservedIdentifierStatus::NotReserved && 5635 !Context.getSourceManager().isInSystemHeader(D->getLocation())) 5636 Diag(D->getLocation(), diag::warn_reserved_extern_symbol) 5637 << D << static_cast<int>(Status); 5638 } 5639 5640 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5641 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 5642 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5643 5644 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5645 Dcl && Dcl->getDeclContext()->isFileContext()) 5646 Dcl->setTopLevelDeclInObjCContainer(); 5647 5648 return Dcl; 5649 } 5650 5651 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5652 /// If T is the name of a class, then each of the following shall have a 5653 /// name different from T: 5654 /// - every static data member of class T; 5655 /// - every member function of class T 5656 /// - every member of class T that is itself a type; 5657 /// \returns true if the declaration name violates these rules. 5658 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5659 DeclarationNameInfo NameInfo) { 5660 DeclarationName Name = NameInfo.getName(); 5661 5662 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5663 while (Record && Record->isAnonymousStructOrUnion()) 5664 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5665 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5666 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5667 return true; 5668 } 5669 5670 return false; 5671 } 5672 5673 /// Diagnose a declaration whose declarator-id has the given 5674 /// nested-name-specifier. 5675 /// 5676 /// \param SS The nested-name-specifier of the declarator-id. 5677 /// 5678 /// \param DC The declaration context to which the nested-name-specifier 5679 /// resolves. 5680 /// 5681 /// \param Name The name of the entity being declared. 5682 /// 5683 /// \param Loc The location of the name of the entity being declared. 5684 /// 5685 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5686 /// we're declaring an explicit / partial specialization / instantiation. 5687 /// 5688 /// \returns true if we cannot safely recover from this error, false otherwise. 5689 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5690 DeclarationName Name, 5691 SourceLocation Loc, bool IsTemplateId) { 5692 DeclContext *Cur = CurContext; 5693 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5694 Cur = Cur->getParent(); 5695 5696 // If the user provided a superfluous scope specifier that refers back to the 5697 // class in which the entity is already declared, diagnose and ignore it. 5698 // 5699 // class X { 5700 // void X::f(); 5701 // }; 5702 // 5703 // Note, it was once ill-formed to give redundant qualification in all 5704 // contexts, but that rule was removed by DR482. 5705 if (Cur->Equals(DC)) { 5706 if (Cur->isRecord()) { 5707 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5708 : diag::err_member_extra_qualification) 5709 << Name << FixItHint::CreateRemoval(SS.getRange()); 5710 SS.clear(); 5711 } else { 5712 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5713 } 5714 return false; 5715 } 5716 5717 // Check whether the qualifying scope encloses the scope of the original 5718 // declaration. For a template-id, we perform the checks in 5719 // CheckTemplateSpecializationScope. 5720 if (!Cur->Encloses(DC) && !IsTemplateId) { 5721 if (Cur->isRecord()) 5722 Diag(Loc, diag::err_member_qualification) 5723 << Name << SS.getRange(); 5724 else if (isa<TranslationUnitDecl>(DC)) 5725 Diag(Loc, diag::err_invalid_declarator_global_scope) 5726 << Name << SS.getRange(); 5727 else if (isa<FunctionDecl>(Cur)) 5728 Diag(Loc, diag::err_invalid_declarator_in_function) 5729 << Name << SS.getRange(); 5730 else if (isa<BlockDecl>(Cur)) 5731 Diag(Loc, diag::err_invalid_declarator_in_block) 5732 << Name << SS.getRange(); 5733 else 5734 Diag(Loc, diag::err_invalid_declarator_scope) 5735 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5736 5737 return true; 5738 } 5739 5740 if (Cur->isRecord()) { 5741 // Cannot qualify members within a class. 5742 Diag(Loc, diag::err_member_qualification) 5743 << Name << SS.getRange(); 5744 SS.clear(); 5745 5746 // C++ constructors and destructors with incorrect scopes can break 5747 // our AST invariants by having the wrong underlying types. If 5748 // that's the case, then drop this declaration entirely. 5749 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5750 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5751 !Context.hasSameType(Name.getCXXNameType(), 5752 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5753 return true; 5754 5755 return false; 5756 } 5757 5758 // C++11 [dcl.meaning]p1: 5759 // [...] "The nested-name-specifier of the qualified declarator-id shall 5760 // not begin with a decltype-specifer" 5761 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5762 while (SpecLoc.getPrefix()) 5763 SpecLoc = SpecLoc.getPrefix(); 5764 if (dyn_cast_or_null<DecltypeType>( 5765 SpecLoc.getNestedNameSpecifier()->getAsType())) 5766 Diag(Loc, diag::err_decltype_in_declarator) 5767 << SpecLoc.getTypeLoc().getSourceRange(); 5768 5769 return false; 5770 } 5771 5772 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5773 MultiTemplateParamsArg TemplateParamLists) { 5774 // TODO: consider using NameInfo for diagnostic. 5775 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5776 DeclarationName Name = NameInfo.getName(); 5777 5778 // All of these full declarators require an identifier. If it doesn't have 5779 // one, the ParsedFreeStandingDeclSpec action should be used. 5780 if (D.isDecompositionDeclarator()) { 5781 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5782 } else if (!Name) { 5783 if (!D.isInvalidType()) // Reject this if we think it is valid. 5784 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5785 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5786 return nullptr; 5787 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5788 return nullptr; 5789 5790 // The scope passed in may not be a decl scope. Zip up the scope tree until 5791 // we find one that is. 5792 while ((S->getFlags() & Scope::DeclScope) == 0 || 5793 (S->getFlags() & Scope::TemplateParamScope) != 0) 5794 S = S->getParent(); 5795 5796 DeclContext *DC = CurContext; 5797 if (D.getCXXScopeSpec().isInvalid()) 5798 D.setInvalidType(); 5799 else if (D.getCXXScopeSpec().isSet()) { 5800 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5801 UPPC_DeclarationQualifier)) 5802 return nullptr; 5803 5804 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5805 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5806 if (!DC || isa<EnumDecl>(DC)) { 5807 // If we could not compute the declaration context, it's because the 5808 // declaration context is dependent but does not refer to a class, 5809 // class template, or class template partial specialization. Complain 5810 // and return early, to avoid the coming semantic disaster. 5811 Diag(D.getIdentifierLoc(), 5812 diag::err_template_qualified_declarator_no_match) 5813 << D.getCXXScopeSpec().getScopeRep() 5814 << D.getCXXScopeSpec().getRange(); 5815 return nullptr; 5816 } 5817 bool IsDependentContext = DC->isDependentContext(); 5818 5819 if (!IsDependentContext && 5820 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5821 return nullptr; 5822 5823 // If a class is incomplete, do not parse entities inside it. 5824 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5825 Diag(D.getIdentifierLoc(), 5826 diag::err_member_def_undefined_record) 5827 << Name << DC << D.getCXXScopeSpec().getRange(); 5828 return nullptr; 5829 } 5830 if (!D.getDeclSpec().isFriendSpecified()) { 5831 if (diagnoseQualifiedDeclaration( 5832 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5833 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5834 if (DC->isRecord()) 5835 return nullptr; 5836 5837 D.setInvalidType(); 5838 } 5839 } 5840 5841 // Check whether we need to rebuild the type of the given 5842 // declaration in the current instantiation. 5843 if (EnteringContext && IsDependentContext && 5844 TemplateParamLists.size() != 0) { 5845 ContextRAII SavedContext(*this, DC); 5846 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5847 D.setInvalidType(); 5848 } 5849 } 5850 5851 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5852 QualType R = TInfo->getType(); 5853 5854 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5855 UPPC_DeclarationType)) 5856 D.setInvalidType(); 5857 5858 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5859 forRedeclarationInCurContext()); 5860 5861 // See if this is a redefinition of a variable in the same scope. 5862 if (!D.getCXXScopeSpec().isSet()) { 5863 bool IsLinkageLookup = false; 5864 bool CreateBuiltins = false; 5865 5866 // If the declaration we're planning to build will be a function 5867 // or object with linkage, then look for another declaration with 5868 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5869 // 5870 // If the declaration we're planning to build will be declared with 5871 // external linkage in the translation unit, create any builtin with 5872 // the same name. 5873 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5874 /* Do nothing*/; 5875 else if (CurContext->isFunctionOrMethod() && 5876 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5877 R->isFunctionType())) { 5878 IsLinkageLookup = true; 5879 CreateBuiltins = 5880 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5881 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5882 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5883 CreateBuiltins = true; 5884 5885 if (IsLinkageLookup) { 5886 Previous.clear(LookupRedeclarationWithLinkage); 5887 Previous.setRedeclarationKind(ForExternalRedeclaration); 5888 } 5889 5890 LookupName(Previous, S, CreateBuiltins); 5891 } else { // Something like "int foo::x;" 5892 LookupQualifiedName(Previous, DC); 5893 5894 // C++ [dcl.meaning]p1: 5895 // When the declarator-id is qualified, the declaration shall refer to a 5896 // previously declared member of the class or namespace to which the 5897 // qualifier refers (or, in the case of a namespace, of an element of the 5898 // inline namespace set of that namespace (7.3.1)) or to a specialization 5899 // thereof; [...] 5900 // 5901 // Note that we already checked the context above, and that we do not have 5902 // enough information to make sure that Previous contains the declaration 5903 // we want to match. For example, given: 5904 // 5905 // class X { 5906 // void f(); 5907 // void f(float); 5908 // }; 5909 // 5910 // void X::f(int) { } // ill-formed 5911 // 5912 // In this case, Previous will point to the overload set 5913 // containing the two f's declared in X, but neither of them 5914 // matches. 5915 5916 // C++ [dcl.meaning]p1: 5917 // [...] the member shall not merely have been introduced by a 5918 // using-declaration in the scope of the class or namespace nominated by 5919 // the nested-name-specifier of the declarator-id. 5920 RemoveUsingDecls(Previous); 5921 } 5922 5923 if (Previous.isSingleResult() && 5924 Previous.getFoundDecl()->isTemplateParameter()) { 5925 // Maybe we will complain about the shadowed template parameter. 5926 if (!D.isInvalidType()) 5927 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5928 Previous.getFoundDecl()); 5929 5930 // Just pretend that we didn't see the previous declaration. 5931 Previous.clear(); 5932 } 5933 5934 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5935 // Forget that the previous declaration is the injected-class-name. 5936 Previous.clear(); 5937 5938 // In C++, the previous declaration we find might be a tag type 5939 // (class or enum). In this case, the new declaration will hide the 5940 // tag type. Note that this applies to functions, function templates, and 5941 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5942 if (Previous.isSingleTagDecl() && 5943 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5944 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5945 Previous.clear(); 5946 5947 // Check that there are no default arguments other than in the parameters 5948 // of a function declaration (C++ only). 5949 if (getLangOpts().CPlusPlus) 5950 CheckExtraCXXDefaultArguments(D); 5951 5952 NamedDecl *New; 5953 5954 bool AddToScope = true; 5955 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5956 if (TemplateParamLists.size()) { 5957 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5958 return nullptr; 5959 } 5960 5961 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5962 } else if (R->isFunctionType()) { 5963 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5964 TemplateParamLists, 5965 AddToScope); 5966 } else { 5967 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5968 AddToScope); 5969 } 5970 5971 if (!New) 5972 return nullptr; 5973 5974 // If this has an identifier and is not a function template specialization, 5975 // add it to the scope stack. 5976 if (New->getDeclName() && AddToScope) 5977 PushOnScopeChains(New, S); 5978 5979 if (isInOpenMPDeclareTargetContext()) 5980 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5981 5982 return New; 5983 } 5984 5985 /// Helper method to turn variable array types into constant array 5986 /// types in certain situations which would otherwise be errors (for 5987 /// GCC compatibility). 5988 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5989 ASTContext &Context, 5990 bool &SizeIsNegative, 5991 llvm::APSInt &Oversized) { 5992 // This method tries to turn a variable array into a constant 5993 // array even when the size isn't an ICE. This is necessary 5994 // for compatibility with code that depends on gcc's buggy 5995 // constant expression folding, like struct {char x[(int)(char*)2];} 5996 SizeIsNegative = false; 5997 Oversized = 0; 5998 5999 if (T->isDependentType()) 6000 return QualType(); 6001 6002 QualifierCollector Qs; 6003 const Type *Ty = Qs.strip(T); 6004 6005 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 6006 QualType Pointee = PTy->getPointeeType(); 6007 QualType FixedType = 6008 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 6009 Oversized); 6010 if (FixedType.isNull()) return FixedType; 6011 FixedType = Context.getPointerType(FixedType); 6012 return Qs.apply(Context, FixedType); 6013 } 6014 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 6015 QualType Inner = PTy->getInnerType(); 6016 QualType FixedType = 6017 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 6018 Oversized); 6019 if (FixedType.isNull()) return FixedType; 6020 FixedType = Context.getParenType(FixedType); 6021 return Qs.apply(Context, FixedType); 6022 } 6023 6024 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 6025 if (!VLATy) 6026 return QualType(); 6027 6028 QualType ElemTy = VLATy->getElementType(); 6029 if (ElemTy->isVariablyModifiedType()) { 6030 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 6031 SizeIsNegative, Oversized); 6032 if (ElemTy.isNull()) 6033 return QualType(); 6034 } 6035 6036 Expr::EvalResult Result; 6037 if (!VLATy->getSizeExpr() || 6038 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 6039 return QualType(); 6040 6041 llvm::APSInt Res = Result.Val.getInt(); 6042 6043 // Check whether the array size is negative. 6044 if (Res.isSigned() && Res.isNegative()) { 6045 SizeIsNegative = true; 6046 return QualType(); 6047 } 6048 6049 // Check whether the array is too large to be addressed. 6050 unsigned ActiveSizeBits = 6051 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 6052 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 6053 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 6054 : Res.getActiveBits(); 6055 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 6056 Oversized = Res; 6057 return QualType(); 6058 } 6059 6060 QualType FoldedArrayType = Context.getConstantArrayType( 6061 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 6062 return Qs.apply(Context, FoldedArrayType); 6063 } 6064 6065 static void 6066 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 6067 SrcTL = SrcTL.getUnqualifiedLoc(); 6068 DstTL = DstTL.getUnqualifiedLoc(); 6069 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 6070 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 6071 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 6072 DstPTL.getPointeeLoc()); 6073 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 6074 return; 6075 } 6076 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 6077 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 6078 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 6079 DstPTL.getInnerLoc()); 6080 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 6081 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 6082 return; 6083 } 6084 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6085 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6086 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6087 TypeLoc DstElemTL = DstATL.getElementLoc(); 6088 if (VariableArrayTypeLoc SrcElemATL = 6089 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6090 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6091 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6092 } else { 6093 DstElemTL.initializeFullCopy(SrcElemTL); 6094 } 6095 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6096 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6097 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6098 } 6099 6100 /// Helper method to turn variable array types into constant array 6101 /// types in certain situations which would otherwise be errors (for 6102 /// GCC compatibility). 6103 static TypeSourceInfo* 6104 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6105 ASTContext &Context, 6106 bool &SizeIsNegative, 6107 llvm::APSInt &Oversized) { 6108 QualType FixedTy 6109 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6110 SizeIsNegative, Oversized); 6111 if (FixedTy.isNull()) 6112 return nullptr; 6113 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6114 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6115 FixedTInfo->getTypeLoc()); 6116 return FixedTInfo; 6117 } 6118 6119 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6120 /// true if we were successful. 6121 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, 6122 QualType &T, SourceLocation Loc, 6123 unsigned FailedFoldDiagID) { 6124 bool SizeIsNegative; 6125 llvm::APSInt Oversized; 6126 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6127 TInfo, Context, SizeIsNegative, Oversized); 6128 if (FixedTInfo) { 6129 Diag(Loc, diag::ext_vla_folded_to_constant); 6130 TInfo = FixedTInfo; 6131 T = FixedTInfo->getType(); 6132 return true; 6133 } 6134 6135 if (SizeIsNegative) 6136 Diag(Loc, diag::err_typecheck_negative_array_size); 6137 else if (Oversized.getBoolValue()) 6138 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10); 6139 else if (FailedFoldDiagID) 6140 Diag(Loc, FailedFoldDiagID); 6141 return false; 6142 } 6143 6144 /// Register the given locally-scoped extern "C" declaration so 6145 /// that it can be found later for redeclarations. We include any extern "C" 6146 /// declaration that is not visible in the translation unit here, not just 6147 /// function-scope declarations. 6148 void 6149 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6150 if (!getLangOpts().CPlusPlus && 6151 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6152 // Don't need to track declarations in the TU in C. 6153 return; 6154 6155 // Note that we have a locally-scoped external with this name. 6156 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6157 } 6158 6159 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6160 // FIXME: We can have multiple results via __attribute__((overloadable)). 6161 auto Result = Context.getExternCContextDecl()->lookup(Name); 6162 return Result.empty() ? nullptr : *Result.begin(); 6163 } 6164 6165 /// Diagnose function specifiers on a declaration of an identifier that 6166 /// does not identify a function. 6167 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6168 // FIXME: We should probably indicate the identifier in question to avoid 6169 // confusion for constructs like "virtual int a(), b;" 6170 if (DS.isVirtualSpecified()) 6171 Diag(DS.getVirtualSpecLoc(), 6172 diag::err_virtual_non_function); 6173 6174 if (DS.hasExplicitSpecifier()) 6175 Diag(DS.getExplicitSpecLoc(), 6176 diag::err_explicit_non_function); 6177 6178 if (DS.isNoreturnSpecified()) 6179 Diag(DS.getNoreturnSpecLoc(), 6180 diag::err_noreturn_non_function); 6181 } 6182 6183 NamedDecl* 6184 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6185 TypeSourceInfo *TInfo, LookupResult &Previous) { 6186 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6187 if (D.getCXXScopeSpec().isSet()) { 6188 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6189 << D.getCXXScopeSpec().getRange(); 6190 D.setInvalidType(); 6191 // Pretend we didn't see the scope specifier. 6192 DC = CurContext; 6193 Previous.clear(); 6194 } 6195 6196 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6197 6198 if (D.getDeclSpec().isInlineSpecified()) 6199 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6200 << getLangOpts().CPlusPlus17; 6201 if (D.getDeclSpec().hasConstexprSpecifier()) 6202 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6203 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6204 6205 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6206 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6207 Diag(D.getName().StartLocation, 6208 diag::err_deduction_guide_invalid_specifier) 6209 << "typedef"; 6210 else 6211 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6212 << D.getName().getSourceRange(); 6213 return nullptr; 6214 } 6215 6216 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6217 if (!NewTD) return nullptr; 6218 6219 // Handle attributes prior to checking for duplicates in MergeVarDecl 6220 ProcessDeclAttributes(S, NewTD, D); 6221 6222 CheckTypedefForVariablyModifiedType(S, NewTD); 6223 6224 bool Redeclaration = D.isRedeclaration(); 6225 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6226 D.setRedeclaration(Redeclaration); 6227 return ND; 6228 } 6229 6230 void 6231 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6232 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6233 // then it shall have block scope. 6234 // Note that variably modified types must be fixed before merging the decl so 6235 // that redeclarations will match. 6236 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6237 QualType T = TInfo->getType(); 6238 if (T->isVariablyModifiedType()) { 6239 setFunctionHasBranchProtectedScope(); 6240 6241 if (S->getFnParent() == nullptr) { 6242 bool SizeIsNegative; 6243 llvm::APSInt Oversized; 6244 TypeSourceInfo *FixedTInfo = 6245 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6246 SizeIsNegative, 6247 Oversized); 6248 if (FixedTInfo) { 6249 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6250 NewTD->setTypeSourceInfo(FixedTInfo); 6251 } else { 6252 if (SizeIsNegative) 6253 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6254 else if (T->isVariableArrayType()) 6255 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6256 else if (Oversized.getBoolValue()) 6257 Diag(NewTD->getLocation(), diag::err_array_too_large) 6258 << toString(Oversized, 10); 6259 else 6260 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6261 NewTD->setInvalidDecl(); 6262 } 6263 } 6264 } 6265 } 6266 6267 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6268 /// declares a typedef-name, either using the 'typedef' type specifier or via 6269 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6270 NamedDecl* 6271 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6272 LookupResult &Previous, bool &Redeclaration) { 6273 6274 // Find the shadowed declaration before filtering for scope. 6275 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6276 6277 // Merge the decl with the existing one if appropriate. If the decl is 6278 // in an outer scope, it isn't the same thing. 6279 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6280 /*AllowInlineNamespace*/false); 6281 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6282 if (!Previous.empty()) { 6283 Redeclaration = true; 6284 MergeTypedefNameDecl(S, NewTD, Previous); 6285 } else { 6286 inferGslPointerAttribute(NewTD); 6287 } 6288 6289 if (ShadowedDecl && !Redeclaration) 6290 CheckShadow(NewTD, ShadowedDecl, Previous); 6291 6292 // If this is the C FILE type, notify the AST context. 6293 if (IdentifierInfo *II = NewTD->getIdentifier()) 6294 if (!NewTD->isInvalidDecl() && 6295 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6296 if (II->isStr("FILE")) 6297 Context.setFILEDecl(NewTD); 6298 else if (II->isStr("jmp_buf")) 6299 Context.setjmp_bufDecl(NewTD); 6300 else if (II->isStr("sigjmp_buf")) 6301 Context.setsigjmp_bufDecl(NewTD); 6302 else if (II->isStr("ucontext_t")) 6303 Context.setucontext_tDecl(NewTD); 6304 } 6305 6306 return NewTD; 6307 } 6308 6309 /// Determines whether the given declaration is an out-of-scope 6310 /// previous declaration. 6311 /// 6312 /// This routine should be invoked when name lookup has found a 6313 /// previous declaration (PrevDecl) that is not in the scope where a 6314 /// new declaration by the same name is being introduced. If the new 6315 /// declaration occurs in a local scope, previous declarations with 6316 /// linkage may still be considered previous declarations (C99 6317 /// 6.2.2p4-5, C++ [basic.link]p6). 6318 /// 6319 /// \param PrevDecl the previous declaration found by name 6320 /// lookup 6321 /// 6322 /// \param DC the context in which the new declaration is being 6323 /// declared. 6324 /// 6325 /// \returns true if PrevDecl is an out-of-scope previous declaration 6326 /// for a new delcaration with the same name. 6327 static bool 6328 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6329 ASTContext &Context) { 6330 if (!PrevDecl) 6331 return false; 6332 6333 if (!PrevDecl->hasLinkage()) 6334 return false; 6335 6336 if (Context.getLangOpts().CPlusPlus) { 6337 // C++ [basic.link]p6: 6338 // If there is a visible declaration of an entity with linkage 6339 // having the same name and type, ignoring entities declared 6340 // outside the innermost enclosing namespace scope, the block 6341 // scope declaration declares that same entity and receives the 6342 // linkage of the previous declaration. 6343 DeclContext *OuterContext = DC->getRedeclContext(); 6344 if (!OuterContext->isFunctionOrMethod()) 6345 // This rule only applies to block-scope declarations. 6346 return false; 6347 6348 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6349 if (PrevOuterContext->isRecord()) 6350 // We found a member function: ignore it. 6351 return false; 6352 6353 // Find the innermost enclosing namespace for the new and 6354 // previous declarations. 6355 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6356 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6357 6358 // The previous declaration is in a different namespace, so it 6359 // isn't the same function. 6360 if (!OuterContext->Equals(PrevOuterContext)) 6361 return false; 6362 } 6363 6364 return true; 6365 } 6366 6367 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6368 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6369 if (!SS.isSet()) return; 6370 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6371 } 6372 6373 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6374 QualType type = decl->getType(); 6375 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6376 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6377 // Various kinds of declaration aren't allowed to be __autoreleasing. 6378 unsigned kind = -1U; 6379 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6380 if (var->hasAttr<BlocksAttr>()) 6381 kind = 0; // __block 6382 else if (!var->hasLocalStorage()) 6383 kind = 1; // global 6384 } else if (isa<ObjCIvarDecl>(decl)) { 6385 kind = 3; // ivar 6386 } else if (isa<FieldDecl>(decl)) { 6387 kind = 2; // field 6388 } 6389 6390 if (kind != -1U) { 6391 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6392 << kind; 6393 } 6394 } else if (lifetime == Qualifiers::OCL_None) { 6395 // Try to infer lifetime. 6396 if (!type->isObjCLifetimeType()) 6397 return false; 6398 6399 lifetime = type->getObjCARCImplicitLifetime(); 6400 type = Context.getLifetimeQualifiedType(type, lifetime); 6401 decl->setType(type); 6402 } 6403 6404 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6405 // Thread-local variables cannot have lifetime. 6406 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6407 var->getTLSKind()) { 6408 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6409 << var->getType(); 6410 return true; 6411 } 6412 } 6413 6414 return false; 6415 } 6416 6417 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6418 if (Decl->getType().hasAddressSpace()) 6419 return; 6420 if (Decl->getType()->isDependentType()) 6421 return; 6422 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6423 QualType Type = Var->getType(); 6424 if (Type->isSamplerT() || Type->isVoidType()) 6425 return; 6426 LangAS ImplAS = LangAS::opencl_private; 6427 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the 6428 // __opencl_c_program_scope_global_variables feature, the address space 6429 // for a variable at program scope or a static or extern variable inside 6430 // a function are inferred to be __global. 6431 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) && 6432 Var->hasGlobalStorage()) 6433 ImplAS = LangAS::opencl_global; 6434 // If the original type from a decayed type is an array type and that array 6435 // type has no address space yet, deduce it now. 6436 if (auto DT = dyn_cast<DecayedType>(Type)) { 6437 auto OrigTy = DT->getOriginalType(); 6438 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6439 // Add the address space to the original array type and then propagate 6440 // that to the element type through `getAsArrayType`. 6441 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6442 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6443 // Re-generate the decayed type. 6444 Type = Context.getDecayedType(OrigTy); 6445 } 6446 } 6447 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6448 // Apply any qualifiers (including address space) from the array type to 6449 // the element type. This implements C99 6.7.3p8: "If the specification of 6450 // an array type includes any type qualifiers, the element type is so 6451 // qualified, not the array type." 6452 if (Type->isArrayType()) 6453 Type = QualType(Context.getAsArrayType(Type), 0); 6454 Decl->setType(Type); 6455 } 6456 } 6457 6458 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6459 // Ensure that an auto decl is deduced otherwise the checks below might cache 6460 // the wrong linkage. 6461 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6462 6463 // 'weak' only applies to declarations with external linkage. 6464 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6465 if (!ND.isExternallyVisible()) { 6466 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6467 ND.dropAttr<WeakAttr>(); 6468 } 6469 } 6470 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6471 if (ND.isExternallyVisible()) { 6472 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6473 ND.dropAttr<WeakRefAttr>(); 6474 ND.dropAttr<AliasAttr>(); 6475 } 6476 } 6477 6478 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6479 if (VD->hasInit()) { 6480 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6481 assert(VD->isThisDeclarationADefinition() && 6482 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6483 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6484 VD->dropAttr<AliasAttr>(); 6485 } 6486 } 6487 } 6488 6489 // 'selectany' only applies to externally visible variable declarations. 6490 // It does not apply to functions. 6491 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6492 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6493 S.Diag(Attr->getLocation(), 6494 diag::err_attribute_selectany_non_extern_data); 6495 ND.dropAttr<SelectAnyAttr>(); 6496 } 6497 } 6498 6499 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6500 auto *VD = dyn_cast<VarDecl>(&ND); 6501 bool IsAnonymousNS = false; 6502 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6503 if (VD) { 6504 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6505 while (NS && !IsAnonymousNS) { 6506 IsAnonymousNS = NS->isAnonymousNamespace(); 6507 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6508 } 6509 } 6510 // dll attributes require external linkage. Static locals may have external 6511 // linkage but still cannot be explicitly imported or exported. 6512 // In Microsoft mode, a variable defined in anonymous namespace must have 6513 // external linkage in order to be exported. 6514 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6515 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6516 (!AnonNSInMicrosoftMode && 6517 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6518 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6519 << &ND << Attr; 6520 ND.setInvalidDecl(); 6521 } 6522 } 6523 6524 // Check the attributes on the function type, if any. 6525 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6526 // Don't declare this variable in the second operand of the for-statement; 6527 // GCC miscompiles that by ending its lifetime before evaluating the 6528 // third operand. See gcc.gnu.org/PR86769. 6529 AttributedTypeLoc ATL; 6530 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6531 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6532 TL = ATL.getModifiedLoc()) { 6533 // The [[lifetimebound]] attribute can be applied to the implicit object 6534 // parameter of a non-static member function (other than a ctor or dtor) 6535 // by applying it to the function type. 6536 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6537 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6538 if (!MD || MD->isStatic()) { 6539 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6540 << !MD << A->getRange(); 6541 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6542 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6543 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6544 } 6545 } 6546 } 6547 } 6548 } 6549 6550 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6551 NamedDecl *NewDecl, 6552 bool IsSpecialization, 6553 bool IsDefinition) { 6554 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6555 return; 6556 6557 bool IsTemplate = false; 6558 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6559 OldDecl = OldTD->getTemplatedDecl(); 6560 IsTemplate = true; 6561 if (!IsSpecialization) 6562 IsDefinition = false; 6563 } 6564 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6565 NewDecl = NewTD->getTemplatedDecl(); 6566 IsTemplate = true; 6567 } 6568 6569 if (!OldDecl || !NewDecl) 6570 return; 6571 6572 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6573 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6574 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6575 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6576 6577 // dllimport and dllexport are inheritable attributes so we have to exclude 6578 // inherited attribute instances. 6579 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6580 (NewExportAttr && !NewExportAttr->isInherited()); 6581 6582 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6583 // the only exception being explicit specializations. 6584 // Implicitly generated declarations are also excluded for now because there 6585 // is no other way to switch these to use dllimport or dllexport. 6586 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6587 6588 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6589 // Allow with a warning for free functions and global variables. 6590 bool JustWarn = false; 6591 if (!OldDecl->isCXXClassMember()) { 6592 auto *VD = dyn_cast<VarDecl>(OldDecl); 6593 if (VD && !VD->getDescribedVarTemplate()) 6594 JustWarn = true; 6595 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6596 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6597 JustWarn = true; 6598 } 6599 6600 // We cannot change a declaration that's been used because IR has already 6601 // been emitted. Dllimported functions will still work though (modulo 6602 // address equality) as they can use the thunk. 6603 if (OldDecl->isUsed()) 6604 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6605 JustWarn = false; 6606 6607 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6608 : diag::err_attribute_dll_redeclaration; 6609 S.Diag(NewDecl->getLocation(), DiagID) 6610 << NewDecl 6611 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6612 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6613 if (!JustWarn) { 6614 NewDecl->setInvalidDecl(); 6615 return; 6616 } 6617 } 6618 6619 // A redeclaration is not allowed to drop a dllimport attribute, the only 6620 // exceptions being inline function definitions (except for function 6621 // templates), local extern declarations, qualified friend declarations or 6622 // special MSVC extension: in the last case, the declaration is treated as if 6623 // it were marked dllexport. 6624 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6625 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 6626 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6627 // Ignore static data because out-of-line definitions are diagnosed 6628 // separately. 6629 IsStaticDataMember = VD->isStaticDataMember(); 6630 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6631 VarDecl::DeclarationOnly; 6632 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6633 IsInline = FD->isInlined(); 6634 IsQualifiedFriend = FD->getQualifier() && 6635 FD->getFriendObjectKind() == Decl::FOK_Declared; 6636 } 6637 6638 if (OldImportAttr && !HasNewAttr && 6639 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 6640 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6641 if (IsMicrosoftABI && IsDefinition) { 6642 S.Diag(NewDecl->getLocation(), 6643 diag::warn_redeclaration_without_import_attribute) 6644 << NewDecl; 6645 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6646 NewDecl->dropAttr<DLLImportAttr>(); 6647 NewDecl->addAttr( 6648 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6649 } else { 6650 S.Diag(NewDecl->getLocation(), 6651 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6652 << NewDecl << OldImportAttr; 6653 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6654 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6655 OldDecl->dropAttr<DLLImportAttr>(); 6656 NewDecl->dropAttr<DLLImportAttr>(); 6657 } 6658 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 6659 // In MinGW, seeing a function declared inline drops the dllimport 6660 // attribute. 6661 OldDecl->dropAttr<DLLImportAttr>(); 6662 NewDecl->dropAttr<DLLImportAttr>(); 6663 S.Diag(NewDecl->getLocation(), 6664 diag::warn_dllimport_dropped_from_inline_function) 6665 << NewDecl << OldImportAttr; 6666 } 6667 6668 // A specialization of a class template member function is processed here 6669 // since it's a redeclaration. If the parent class is dllexport, the 6670 // specialization inherits that attribute. This doesn't happen automatically 6671 // since the parent class isn't instantiated until later. 6672 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6673 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6674 !NewImportAttr && !NewExportAttr) { 6675 if (const DLLExportAttr *ParentExportAttr = 6676 MD->getParent()->getAttr<DLLExportAttr>()) { 6677 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6678 NewAttr->setInherited(true); 6679 NewDecl->addAttr(NewAttr); 6680 } 6681 } 6682 } 6683 } 6684 6685 /// Given that we are within the definition of the given function, 6686 /// will that definition behave like C99's 'inline', where the 6687 /// definition is discarded except for optimization purposes? 6688 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6689 // Try to avoid calling GetGVALinkageForFunction. 6690 6691 // All cases of this require the 'inline' keyword. 6692 if (!FD->isInlined()) return false; 6693 6694 // This is only possible in C++ with the gnu_inline attribute. 6695 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6696 return false; 6697 6698 // Okay, go ahead and call the relatively-more-expensive function. 6699 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6700 } 6701 6702 /// Determine whether a variable is extern "C" prior to attaching 6703 /// an initializer. We can't just call isExternC() here, because that 6704 /// will also compute and cache whether the declaration is externally 6705 /// visible, which might change when we attach the initializer. 6706 /// 6707 /// This can only be used if the declaration is known to not be a 6708 /// redeclaration of an internal linkage declaration. 6709 /// 6710 /// For instance: 6711 /// 6712 /// auto x = []{}; 6713 /// 6714 /// Attaching the initializer here makes this declaration not externally 6715 /// visible, because its type has internal linkage. 6716 /// 6717 /// FIXME: This is a hack. 6718 template<typename T> 6719 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6720 if (S.getLangOpts().CPlusPlus) { 6721 // In C++, the overloadable attribute negates the effects of extern "C". 6722 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6723 return false; 6724 6725 // So do CUDA's host/device attributes. 6726 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6727 D->template hasAttr<CUDAHostAttr>())) 6728 return false; 6729 } 6730 return D->isExternC(); 6731 } 6732 6733 static bool shouldConsiderLinkage(const VarDecl *VD) { 6734 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6735 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6736 isa<OMPDeclareMapperDecl>(DC)) 6737 return VD->hasExternalStorage(); 6738 if (DC->isFileContext()) 6739 return true; 6740 if (DC->isRecord()) 6741 return false; 6742 if (isa<RequiresExprBodyDecl>(DC)) 6743 return false; 6744 llvm_unreachable("Unexpected context"); 6745 } 6746 6747 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6748 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6749 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6750 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6751 return true; 6752 if (DC->isRecord()) 6753 return false; 6754 llvm_unreachable("Unexpected context"); 6755 } 6756 6757 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6758 ParsedAttr::Kind Kind) { 6759 // Check decl attributes on the DeclSpec. 6760 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6761 return true; 6762 6763 // Walk the declarator structure, checking decl attributes that were in a type 6764 // position to the decl itself. 6765 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6766 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6767 return true; 6768 } 6769 6770 // Finally, check attributes on the decl itself. 6771 return PD.getAttributes().hasAttribute(Kind); 6772 } 6773 6774 /// Adjust the \c DeclContext for a function or variable that might be a 6775 /// function-local external declaration. 6776 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6777 if (!DC->isFunctionOrMethod()) 6778 return false; 6779 6780 // If this is a local extern function or variable declared within a function 6781 // template, don't add it into the enclosing namespace scope until it is 6782 // instantiated; it might have a dependent type right now. 6783 if (DC->isDependentContext()) 6784 return true; 6785 6786 // C++11 [basic.link]p7: 6787 // When a block scope declaration of an entity with linkage is not found to 6788 // refer to some other declaration, then that entity is a member of the 6789 // innermost enclosing namespace. 6790 // 6791 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6792 // semantically-enclosing namespace, not a lexically-enclosing one. 6793 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6794 DC = DC->getParent(); 6795 return true; 6796 } 6797 6798 /// Returns true if given declaration has external C language linkage. 6799 static bool isDeclExternC(const Decl *D) { 6800 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6801 return FD->isExternC(); 6802 if (const auto *VD = dyn_cast<VarDecl>(D)) 6803 return VD->isExternC(); 6804 6805 llvm_unreachable("Unknown type of decl!"); 6806 } 6807 6808 /// Returns true if there hasn't been any invalid type diagnosed. 6809 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { 6810 DeclContext *DC = NewVD->getDeclContext(); 6811 QualType R = NewVD->getType(); 6812 6813 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6814 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6815 // argument. 6816 if (R->isImageType() || R->isPipeType()) { 6817 Se.Diag(NewVD->getLocation(), 6818 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6819 << R; 6820 NewVD->setInvalidDecl(); 6821 return false; 6822 } 6823 6824 // OpenCL v1.2 s6.9.r: 6825 // The event type cannot be used to declare a program scope variable. 6826 // OpenCL v2.0 s6.9.q: 6827 // The clk_event_t and reserve_id_t types cannot be declared in program 6828 // scope. 6829 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { 6830 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6831 Se.Diag(NewVD->getLocation(), 6832 diag::err_invalid_type_for_program_scope_var) 6833 << R; 6834 NewVD->setInvalidDecl(); 6835 return false; 6836 } 6837 } 6838 6839 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6840 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 6841 Se.getLangOpts())) { 6842 QualType NR = R.getCanonicalType(); 6843 while (NR->isPointerType() || NR->isMemberFunctionPointerType() || 6844 NR->isReferenceType()) { 6845 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || 6846 NR->isFunctionReferenceType()) { 6847 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer) 6848 << NR->isReferenceType(); 6849 NewVD->setInvalidDecl(); 6850 return false; 6851 } 6852 NR = NR->getPointeeType(); 6853 } 6854 } 6855 6856 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 6857 Se.getLangOpts())) { 6858 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6859 // half array type (unless the cl_khr_fp16 extension is enabled). 6860 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6861 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R; 6862 NewVD->setInvalidDecl(); 6863 return false; 6864 } 6865 } 6866 6867 // OpenCL v1.2 s6.9.r: 6868 // The event type cannot be used with the __local, __constant and __global 6869 // address space qualifiers. 6870 if (R->isEventT()) { 6871 if (R.getAddressSpace() != LangAS::opencl_private) { 6872 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual); 6873 NewVD->setInvalidDecl(); 6874 return false; 6875 } 6876 } 6877 6878 if (R->isSamplerT()) { 6879 // OpenCL v1.2 s6.9.b p4: 6880 // The sampler type cannot be used with the __local and __global address 6881 // space qualifiers. 6882 if (R.getAddressSpace() == LangAS::opencl_local || 6883 R.getAddressSpace() == LangAS::opencl_global) { 6884 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace); 6885 NewVD->setInvalidDecl(); 6886 } 6887 6888 // OpenCL v1.2 s6.12.14.1: 6889 // A global sampler must be declared with either the constant address 6890 // space qualifier or with the const qualifier. 6891 if (DC->isTranslationUnit() && 6892 !(R.getAddressSpace() == LangAS::opencl_constant || 6893 R.isConstQualified())) { 6894 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler); 6895 NewVD->setInvalidDecl(); 6896 } 6897 if (NewVD->isInvalidDecl()) 6898 return false; 6899 } 6900 6901 return true; 6902 } 6903 6904 template <typename AttrTy> 6905 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { 6906 const TypedefNameDecl *TND = TT->getDecl(); 6907 if (const auto *Attribute = TND->getAttr<AttrTy>()) { 6908 AttrTy *Clone = Attribute->clone(S.Context); 6909 Clone->setInherited(true); 6910 D->addAttr(Clone); 6911 } 6912 } 6913 6914 NamedDecl *Sema::ActOnVariableDeclarator( 6915 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6916 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6917 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6918 QualType R = TInfo->getType(); 6919 DeclarationName Name = GetNameForDeclarator(D).getName(); 6920 6921 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6922 6923 if (D.isDecompositionDeclarator()) { 6924 // Take the name of the first declarator as our name for diagnostic 6925 // purposes. 6926 auto &Decomp = D.getDecompositionDeclarator(); 6927 if (!Decomp.bindings().empty()) { 6928 II = Decomp.bindings()[0].Name; 6929 Name = II; 6930 } 6931 } else if (!II) { 6932 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6933 return nullptr; 6934 } 6935 6936 6937 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6938 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6939 6940 // dllimport globals without explicit storage class are treated as extern. We 6941 // have to change the storage class this early to get the right DeclContext. 6942 if (SC == SC_None && !DC->isRecord() && 6943 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6944 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6945 SC = SC_Extern; 6946 6947 DeclContext *OriginalDC = DC; 6948 bool IsLocalExternDecl = SC == SC_Extern && 6949 adjustContextForLocalExternDecl(DC); 6950 6951 if (SCSpec == DeclSpec::SCS_mutable) { 6952 // mutable can only appear on non-static class members, so it's always 6953 // an error here 6954 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6955 D.setInvalidType(); 6956 SC = SC_None; 6957 } 6958 6959 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6960 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6961 D.getDeclSpec().getStorageClassSpecLoc())) { 6962 // In C++11, the 'register' storage class specifier is deprecated. 6963 // Suppress the warning in system macros, it's used in macros in some 6964 // popular C system headers, such as in glibc's htonl() macro. 6965 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6966 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6967 : diag::warn_deprecated_register) 6968 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6969 } 6970 6971 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6972 6973 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6974 // C99 6.9p2: The storage-class specifiers auto and register shall not 6975 // appear in the declaration specifiers in an external declaration. 6976 // Global Register+Asm is a GNU extension we support. 6977 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6978 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6979 D.setInvalidType(); 6980 } 6981 } 6982 6983 // If this variable has a VLA type and an initializer, try to 6984 // fold to a constant-sized type. This is otherwise invalid. 6985 if (D.hasInitializer() && R->isVariableArrayType()) 6986 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(), 6987 /*DiagID=*/0); 6988 6989 bool IsMemberSpecialization = false; 6990 bool IsVariableTemplateSpecialization = false; 6991 bool IsPartialSpecialization = false; 6992 bool IsVariableTemplate = false; 6993 VarDecl *NewVD = nullptr; 6994 VarTemplateDecl *NewTemplate = nullptr; 6995 TemplateParameterList *TemplateParams = nullptr; 6996 if (!getLangOpts().CPlusPlus) { 6997 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6998 II, R, TInfo, SC); 6999 7000 if (R->getContainedDeducedType()) 7001 ParsingInitForAutoVars.insert(NewVD); 7002 7003 if (D.isInvalidType()) 7004 NewVD->setInvalidDecl(); 7005 7006 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 7007 NewVD->hasLocalStorage()) 7008 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 7009 NTCUC_AutoVar, NTCUK_Destruct); 7010 } else { 7011 bool Invalid = false; 7012 7013 if (DC->isRecord() && !CurContext->isRecord()) { 7014 // This is an out-of-line definition of a static data member. 7015 switch (SC) { 7016 case SC_None: 7017 break; 7018 case SC_Static: 7019 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7020 diag::err_static_out_of_line) 7021 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7022 break; 7023 case SC_Auto: 7024 case SC_Register: 7025 case SC_Extern: 7026 // [dcl.stc] p2: The auto or register specifiers shall be applied only 7027 // to names of variables declared in a block or to function parameters. 7028 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 7029 // of class members 7030 7031 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7032 diag::err_storage_class_for_static_member) 7033 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7034 break; 7035 case SC_PrivateExtern: 7036 llvm_unreachable("C storage class in c++!"); 7037 } 7038 } 7039 7040 if (SC == SC_Static && CurContext->isRecord()) { 7041 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 7042 // Walk up the enclosing DeclContexts to check for any that are 7043 // incompatible with static data members. 7044 const DeclContext *FunctionOrMethod = nullptr; 7045 const CXXRecordDecl *AnonStruct = nullptr; 7046 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 7047 if (Ctxt->isFunctionOrMethod()) { 7048 FunctionOrMethod = Ctxt; 7049 break; 7050 } 7051 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 7052 if (ParentDecl && !ParentDecl->getDeclName()) { 7053 AnonStruct = ParentDecl; 7054 break; 7055 } 7056 } 7057 if (FunctionOrMethod) { 7058 // C++ [class.static.data]p5: A local class shall not have static data 7059 // members. 7060 Diag(D.getIdentifierLoc(), 7061 diag::err_static_data_member_not_allowed_in_local_class) 7062 << Name << RD->getDeclName() << RD->getTagKind(); 7063 } else if (AnonStruct) { 7064 // C++ [class.static.data]p4: Unnamed classes and classes contained 7065 // directly or indirectly within unnamed classes shall not contain 7066 // static data members. 7067 Diag(D.getIdentifierLoc(), 7068 diag::err_static_data_member_not_allowed_in_anon_struct) 7069 << Name << AnonStruct->getTagKind(); 7070 Invalid = true; 7071 } else if (RD->isUnion()) { 7072 // C++98 [class.union]p1: If a union contains a static data member, 7073 // the program is ill-formed. C++11 drops this restriction. 7074 Diag(D.getIdentifierLoc(), 7075 getLangOpts().CPlusPlus11 7076 ? diag::warn_cxx98_compat_static_data_member_in_union 7077 : diag::ext_static_data_member_in_union) << Name; 7078 } 7079 } 7080 } 7081 7082 // Match up the template parameter lists with the scope specifier, then 7083 // determine whether we have a template or a template specialization. 7084 bool InvalidScope = false; 7085 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7086 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7087 D.getCXXScopeSpec(), 7088 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7089 ? D.getName().TemplateId 7090 : nullptr, 7091 TemplateParamLists, 7092 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7093 Invalid |= InvalidScope; 7094 7095 if (TemplateParams) { 7096 if (!TemplateParams->size() && 7097 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7098 // There is an extraneous 'template<>' for this variable. Complain 7099 // about it, but allow the declaration of the variable. 7100 Diag(TemplateParams->getTemplateLoc(), 7101 diag::err_template_variable_noparams) 7102 << II 7103 << SourceRange(TemplateParams->getTemplateLoc(), 7104 TemplateParams->getRAngleLoc()); 7105 TemplateParams = nullptr; 7106 } else { 7107 // Check that we can declare a template here. 7108 if (CheckTemplateDeclScope(S, TemplateParams)) 7109 return nullptr; 7110 7111 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7112 // This is an explicit specialization or a partial specialization. 7113 IsVariableTemplateSpecialization = true; 7114 IsPartialSpecialization = TemplateParams->size() > 0; 7115 } else { // if (TemplateParams->size() > 0) 7116 // This is a template declaration. 7117 IsVariableTemplate = true; 7118 7119 // Only C++1y supports variable templates (N3651). 7120 Diag(D.getIdentifierLoc(), 7121 getLangOpts().CPlusPlus14 7122 ? diag::warn_cxx11_compat_variable_template 7123 : diag::ext_variable_template); 7124 } 7125 } 7126 } else { 7127 // Check that we can declare a member specialization here. 7128 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7129 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7130 return nullptr; 7131 assert((Invalid || 7132 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7133 "should have a 'template<>' for this decl"); 7134 } 7135 7136 if (IsVariableTemplateSpecialization) { 7137 SourceLocation TemplateKWLoc = 7138 TemplateParamLists.size() > 0 7139 ? TemplateParamLists[0]->getTemplateLoc() 7140 : SourceLocation(); 7141 DeclResult Res = ActOnVarTemplateSpecialization( 7142 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7143 IsPartialSpecialization); 7144 if (Res.isInvalid()) 7145 return nullptr; 7146 NewVD = cast<VarDecl>(Res.get()); 7147 AddToScope = false; 7148 } else if (D.isDecompositionDeclarator()) { 7149 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7150 D.getIdentifierLoc(), R, TInfo, SC, 7151 Bindings); 7152 } else 7153 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7154 D.getIdentifierLoc(), II, R, TInfo, SC); 7155 7156 // If this is supposed to be a variable template, create it as such. 7157 if (IsVariableTemplate) { 7158 NewTemplate = 7159 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7160 TemplateParams, NewVD); 7161 NewVD->setDescribedVarTemplate(NewTemplate); 7162 } 7163 7164 // If this decl has an auto type in need of deduction, make a note of the 7165 // Decl so we can diagnose uses of it in its own initializer. 7166 if (R->getContainedDeducedType()) 7167 ParsingInitForAutoVars.insert(NewVD); 7168 7169 if (D.isInvalidType() || Invalid) { 7170 NewVD->setInvalidDecl(); 7171 if (NewTemplate) 7172 NewTemplate->setInvalidDecl(); 7173 } 7174 7175 SetNestedNameSpecifier(*this, NewVD, D); 7176 7177 // If we have any template parameter lists that don't directly belong to 7178 // the variable (matching the scope specifier), store them. 7179 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7180 if (TemplateParamLists.size() > VDTemplateParamLists) 7181 NewVD->setTemplateParameterListsInfo( 7182 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7183 } 7184 7185 if (D.getDeclSpec().isInlineSpecified()) { 7186 if (!getLangOpts().CPlusPlus) { 7187 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7188 << 0; 7189 } else if (CurContext->isFunctionOrMethod()) { 7190 // 'inline' is not allowed on block scope variable declaration. 7191 Diag(D.getDeclSpec().getInlineSpecLoc(), 7192 diag::err_inline_declaration_block_scope) << Name 7193 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7194 } else { 7195 Diag(D.getDeclSpec().getInlineSpecLoc(), 7196 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7197 : diag::ext_inline_variable); 7198 NewVD->setInlineSpecified(); 7199 } 7200 } 7201 7202 // Set the lexical context. If the declarator has a C++ scope specifier, the 7203 // lexical context will be different from the semantic context. 7204 NewVD->setLexicalDeclContext(CurContext); 7205 if (NewTemplate) 7206 NewTemplate->setLexicalDeclContext(CurContext); 7207 7208 if (IsLocalExternDecl) { 7209 if (D.isDecompositionDeclarator()) 7210 for (auto *B : Bindings) 7211 B->setLocalExternDecl(); 7212 else 7213 NewVD->setLocalExternDecl(); 7214 } 7215 7216 bool EmitTLSUnsupportedError = false; 7217 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7218 // C++11 [dcl.stc]p4: 7219 // When thread_local is applied to a variable of block scope the 7220 // storage-class-specifier static is implied if it does not appear 7221 // explicitly. 7222 // Core issue: 'static' is not implied if the variable is declared 7223 // 'extern'. 7224 if (NewVD->hasLocalStorage() && 7225 (SCSpec != DeclSpec::SCS_unspecified || 7226 TSCS != DeclSpec::TSCS_thread_local || 7227 !DC->isFunctionOrMethod())) 7228 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7229 diag::err_thread_non_global) 7230 << DeclSpec::getSpecifierName(TSCS); 7231 else if (!Context.getTargetInfo().isTLSSupported()) { 7232 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7233 getLangOpts().SYCLIsDevice) { 7234 // Postpone error emission until we've collected attributes required to 7235 // figure out whether it's a host or device variable and whether the 7236 // error should be ignored. 7237 EmitTLSUnsupportedError = true; 7238 // We still need to mark the variable as TLS so it shows up in AST with 7239 // proper storage class for other tools to use even if we're not going 7240 // to emit any code for it. 7241 NewVD->setTSCSpec(TSCS); 7242 } else 7243 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7244 diag::err_thread_unsupported); 7245 } else 7246 NewVD->setTSCSpec(TSCS); 7247 } 7248 7249 switch (D.getDeclSpec().getConstexprSpecifier()) { 7250 case ConstexprSpecKind::Unspecified: 7251 break; 7252 7253 case ConstexprSpecKind::Consteval: 7254 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7255 diag::err_constexpr_wrong_decl_kind) 7256 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7257 LLVM_FALLTHROUGH; 7258 7259 case ConstexprSpecKind::Constexpr: 7260 NewVD->setConstexpr(true); 7261 // C++1z [dcl.spec.constexpr]p1: 7262 // A static data member declared with the constexpr specifier is 7263 // implicitly an inline variable. 7264 if (NewVD->isStaticDataMember() && 7265 (getLangOpts().CPlusPlus17 || 7266 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7267 NewVD->setImplicitlyInline(); 7268 break; 7269 7270 case ConstexprSpecKind::Constinit: 7271 if (!NewVD->hasGlobalStorage()) 7272 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7273 diag::err_constinit_local_variable); 7274 else 7275 NewVD->addAttr(ConstInitAttr::Create( 7276 Context, D.getDeclSpec().getConstexprSpecLoc(), 7277 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7278 break; 7279 } 7280 7281 // C99 6.7.4p3 7282 // An inline definition of a function with external linkage shall 7283 // not contain a definition of a modifiable object with static or 7284 // thread storage duration... 7285 // We only apply this when the function is required to be defined 7286 // elsewhere, i.e. when the function is not 'extern inline'. Note 7287 // that a local variable with thread storage duration still has to 7288 // be marked 'static'. Also note that it's possible to get these 7289 // semantics in C++ using __attribute__((gnu_inline)). 7290 if (SC == SC_Static && S->getFnParent() != nullptr && 7291 !NewVD->getType().isConstQualified()) { 7292 FunctionDecl *CurFD = getCurFunctionDecl(); 7293 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7294 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7295 diag::warn_static_local_in_extern_inline); 7296 MaybeSuggestAddingStaticToDecl(CurFD); 7297 } 7298 } 7299 7300 if (D.getDeclSpec().isModulePrivateSpecified()) { 7301 if (IsVariableTemplateSpecialization) 7302 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7303 << (IsPartialSpecialization ? 1 : 0) 7304 << FixItHint::CreateRemoval( 7305 D.getDeclSpec().getModulePrivateSpecLoc()); 7306 else if (IsMemberSpecialization) 7307 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7308 << 2 7309 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7310 else if (NewVD->hasLocalStorage()) 7311 Diag(NewVD->getLocation(), diag::err_module_private_local) 7312 << 0 << NewVD 7313 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7314 << FixItHint::CreateRemoval( 7315 D.getDeclSpec().getModulePrivateSpecLoc()); 7316 else { 7317 NewVD->setModulePrivate(); 7318 if (NewTemplate) 7319 NewTemplate->setModulePrivate(); 7320 for (auto *B : Bindings) 7321 B->setModulePrivate(); 7322 } 7323 } 7324 7325 if (getLangOpts().OpenCL) { 7326 deduceOpenCLAddressSpace(NewVD); 7327 7328 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 7329 if (TSC != TSCS_unspecified) { 7330 bool IsCXX = getLangOpts().OpenCLCPlusPlus; 7331 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7332 diag::err_opencl_unknown_type_specifier) 7333 << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString() 7334 << DeclSpec::getSpecifierName(TSC) << 1; 7335 NewVD->setInvalidDecl(); 7336 } 7337 } 7338 7339 // Handle attributes prior to checking for duplicates in MergeVarDecl 7340 ProcessDeclAttributes(S, NewVD, D); 7341 7342 // FIXME: This is probably the wrong location to be doing this and we should 7343 // probably be doing this for more attributes (especially for function 7344 // pointer attributes such as format, warn_unused_result, etc.). Ideally 7345 // the code to copy attributes would be generated by TableGen. 7346 if (R->isFunctionPointerType()) 7347 if (const auto *TT = R->getAs<TypedefType>()) 7348 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT); 7349 7350 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7351 getLangOpts().SYCLIsDevice) { 7352 if (EmitTLSUnsupportedError && 7353 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7354 (getLangOpts().OpenMPIsDevice && 7355 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7356 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7357 diag::err_thread_unsupported); 7358 7359 if (EmitTLSUnsupportedError && 7360 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7361 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7362 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7363 // storage [duration]." 7364 if (SC == SC_None && S->getFnParent() != nullptr && 7365 (NewVD->hasAttr<CUDASharedAttr>() || 7366 NewVD->hasAttr<CUDAConstantAttr>())) { 7367 NewVD->setStorageClass(SC_Static); 7368 } 7369 } 7370 7371 // Ensure that dllimport globals without explicit storage class are treated as 7372 // extern. The storage class is set above using parsed attributes. Now we can 7373 // check the VarDecl itself. 7374 assert(!NewVD->hasAttr<DLLImportAttr>() || 7375 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7376 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7377 7378 // In auto-retain/release, infer strong retension for variables of 7379 // retainable type. 7380 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7381 NewVD->setInvalidDecl(); 7382 7383 // Handle GNU asm-label extension (encoded as an attribute). 7384 if (Expr *E = (Expr*)D.getAsmLabel()) { 7385 // The parser guarantees this is a string. 7386 StringLiteral *SE = cast<StringLiteral>(E); 7387 StringRef Label = SE->getString(); 7388 if (S->getFnParent() != nullptr) { 7389 switch (SC) { 7390 case SC_None: 7391 case SC_Auto: 7392 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7393 break; 7394 case SC_Register: 7395 // Local Named register 7396 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7397 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7398 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7399 break; 7400 case SC_Static: 7401 case SC_Extern: 7402 case SC_PrivateExtern: 7403 break; 7404 } 7405 } else if (SC == SC_Register) { 7406 // Global Named register 7407 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7408 const auto &TI = Context.getTargetInfo(); 7409 bool HasSizeMismatch; 7410 7411 if (!TI.isValidGCCRegisterName(Label)) 7412 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7413 else if (!TI.validateGlobalRegisterVariable(Label, 7414 Context.getTypeSize(R), 7415 HasSizeMismatch)) 7416 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7417 else if (HasSizeMismatch) 7418 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7419 } 7420 7421 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7422 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7423 NewVD->setInvalidDecl(true); 7424 } 7425 } 7426 7427 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7428 /*IsLiteralLabel=*/true, 7429 SE->getStrTokenLoc(0))); 7430 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7431 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7432 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7433 if (I != ExtnameUndeclaredIdentifiers.end()) { 7434 if (isDeclExternC(NewVD)) { 7435 NewVD->addAttr(I->second); 7436 ExtnameUndeclaredIdentifiers.erase(I); 7437 } else 7438 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7439 << /*Variable*/1 << NewVD; 7440 } 7441 } 7442 7443 // Find the shadowed declaration before filtering for scope. 7444 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7445 ? getShadowedDeclaration(NewVD, Previous) 7446 : nullptr; 7447 7448 // Don't consider existing declarations that are in a different 7449 // scope and are out-of-semantic-context declarations (if the new 7450 // declaration has linkage). 7451 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7452 D.getCXXScopeSpec().isNotEmpty() || 7453 IsMemberSpecialization || 7454 IsVariableTemplateSpecialization); 7455 7456 // Check whether the previous declaration is in the same block scope. This 7457 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7458 if (getLangOpts().CPlusPlus && 7459 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7460 NewVD->setPreviousDeclInSameBlockScope( 7461 Previous.isSingleResult() && !Previous.isShadowed() && 7462 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7463 7464 if (!getLangOpts().CPlusPlus) { 7465 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7466 } else { 7467 // If this is an explicit specialization of a static data member, check it. 7468 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7469 CheckMemberSpecialization(NewVD, Previous)) 7470 NewVD->setInvalidDecl(); 7471 7472 // Merge the decl with the existing one if appropriate. 7473 if (!Previous.empty()) { 7474 if (Previous.isSingleResult() && 7475 isa<FieldDecl>(Previous.getFoundDecl()) && 7476 D.getCXXScopeSpec().isSet()) { 7477 // The user tried to define a non-static data member 7478 // out-of-line (C++ [dcl.meaning]p1). 7479 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7480 << D.getCXXScopeSpec().getRange(); 7481 Previous.clear(); 7482 NewVD->setInvalidDecl(); 7483 } 7484 } else if (D.getCXXScopeSpec().isSet()) { 7485 // No previous declaration in the qualifying scope. 7486 Diag(D.getIdentifierLoc(), diag::err_no_member) 7487 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7488 << D.getCXXScopeSpec().getRange(); 7489 NewVD->setInvalidDecl(); 7490 } 7491 7492 if (!IsVariableTemplateSpecialization) 7493 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7494 7495 if (NewTemplate) { 7496 VarTemplateDecl *PrevVarTemplate = 7497 NewVD->getPreviousDecl() 7498 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7499 : nullptr; 7500 7501 // Check the template parameter list of this declaration, possibly 7502 // merging in the template parameter list from the previous variable 7503 // template declaration. 7504 if (CheckTemplateParameterList( 7505 TemplateParams, 7506 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7507 : nullptr, 7508 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7509 DC->isDependentContext()) 7510 ? TPC_ClassTemplateMember 7511 : TPC_VarTemplate)) 7512 NewVD->setInvalidDecl(); 7513 7514 // If we are providing an explicit specialization of a static variable 7515 // template, make a note of that. 7516 if (PrevVarTemplate && 7517 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7518 PrevVarTemplate->setMemberSpecialization(); 7519 } 7520 } 7521 7522 // Diagnose shadowed variables iff this isn't a redeclaration. 7523 if (ShadowedDecl && !D.isRedeclaration()) 7524 CheckShadow(NewVD, ShadowedDecl, Previous); 7525 7526 ProcessPragmaWeak(S, NewVD); 7527 7528 // If this is the first declaration of an extern C variable, update 7529 // the map of such variables. 7530 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7531 isIncompleteDeclExternC(*this, NewVD)) 7532 RegisterLocallyScopedExternCDecl(NewVD, S); 7533 7534 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7535 MangleNumberingContext *MCtx; 7536 Decl *ManglingContextDecl; 7537 std::tie(MCtx, ManglingContextDecl) = 7538 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7539 if (MCtx) { 7540 Context.setManglingNumber( 7541 NewVD, MCtx->getManglingNumber( 7542 NewVD, getMSManglingNumber(getLangOpts(), S))); 7543 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7544 } 7545 } 7546 7547 // Special handling of variable named 'main'. 7548 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7549 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7550 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7551 7552 // C++ [basic.start.main]p3 7553 // A program that declares a variable main at global scope is ill-formed. 7554 if (getLangOpts().CPlusPlus) 7555 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7556 7557 // In C, and external-linkage variable named main results in undefined 7558 // behavior. 7559 else if (NewVD->hasExternalFormalLinkage()) 7560 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7561 } 7562 7563 if (D.isRedeclaration() && !Previous.empty()) { 7564 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7565 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7566 D.isFunctionDefinition()); 7567 } 7568 7569 if (NewTemplate) { 7570 if (NewVD->isInvalidDecl()) 7571 NewTemplate->setInvalidDecl(); 7572 ActOnDocumentableDecl(NewTemplate); 7573 return NewTemplate; 7574 } 7575 7576 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7577 CompleteMemberSpecialization(NewVD, Previous); 7578 7579 return NewVD; 7580 } 7581 7582 /// Enum describing the %select options in diag::warn_decl_shadow. 7583 enum ShadowedDeclKind { 7584 SDK_Local, 7585 SDK_Global, 7586 SDK_StaticMember, 7587 SDK_Field, 7588 SDK_Typedef, 7589 SDK_Using, 7590 SDK_StructuredBinding 7591 }; 7592 7593 /// Determine what kind of declaration we're shadowing. 7594 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7595 const DeclContext *OldDC) { 7596 if (isa<TypeAliasDecl>(ShadowedDecl)) 7597 return SDK_Using; 7598 else if (isa<TypedefDecl>(ShadowedDecl)) 7599 return SDK_Typedef; 7600 else if (isa<BindingDecl>(ShadowedDecl)) 7601 return SDK_StructuredBinding; 7602 else if (isa<RecordDecl>(OldDC)) 7603 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7604 7605 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7606 } 7607 7608 /// Return the location of the capture if the given lambda captures the given 7609 /// variable \p VD, or an invalid source location otherwise. 7610 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7611 const VarDecl *VD) { 7612 for (const Capture &Capture : LSI->Captures) { 7613 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7614 return Capture.getLocation(); 7615 } 7616 return SourceLocation(); 7617 } 7618 7619 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7620 const LookupResult &R) { 7621 // Only diagnose if we're shadowing an unambiguous field or variable. 7622 if (R.getResultKind() != LookupResult::Found) 7623 return false; 7624 7625 // Return false if warning is ignored. 7626 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7627 } 7628 7629 /// Return the declaration shadowed by the given variable \p D, or null 7630 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7631 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7632 const LookupResult &R) { 7633 if (!shouldWarnIfShadowedDecl(Diags, R)) 7634 return nullptr; 7635 7636 // Don't diagnose declarations at file scope. 7637 if (D->hasGlobalStorage()) 7638 return nullptr; 7639 7640 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7641 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7642 : nullptr; 7643 } 7644 7645 /// Return the declaration shadowed by the given typedef \p D, or null 7646 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7647 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7648 const LookupResult &R) { 7649 // Don't warn if typedef declaration is part of a class 7650 if (D->getDeclContext()->isRecord()) 7651 return nullptr; 7652 7653 if (!shouldWarnIfShadowedDecl(Diags, R)) 7654 return nullptr; 7655 7656 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7657 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7658 } 7659 7660 /// Return the declaration shadowed by the given variable \p D, or null 7661 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7662 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, 7663 const LookupResult &R) { 7664 if (!shouldWarnIfShadowedDecl(Diags, R)) 7665 return nullptr; 7666 7667 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7668 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7669 : nullptr; 7670 } 7671 7672 /// Diagnose variable or built-in function shadowing. Implements 7673 /// -Wshadow. 7674 /// 7675 /// This method is called whenever a VarDecl is added to a "useful" 7676 /// scope. 7677 /// 7678 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7679 /// \param R the lookup of the name 7680 /// 7681 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7682 const LookupResult &R) { 7683 DeclContext *NewDC = D->getDeclContext(); 7684 7685 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7686 // Fields are not shadowed by variables in C++ static methods. 7687 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7688 if (MD->isStatic()) 7689 return; 7690 7691 // Fields shadowed by constructor parameters are a special case. Usually 7692 // the constructor initializes the field with the parameter. 7693 if (isa<CXXConstructorDecl>(NewDC)) 7694 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7695 // Remember that this was shadowed so we can either warn about its 7696 // modification or its existence depending on warning settings. 7697 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7698 return; 7699 } 7700 } 7701 7702 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7703 if (shadowedVar->isExternC()) { 7704 // For shadowing external vars, make sure that we point to the global 7705 // declaration, not a locally scoped extern declaration. 7706 for (auto I : shadowedVar->redecls()) 7707 if (I->isFileVarDecl()) { 7708 ShadowedDecl = I; 7709 break; 7710 } 7711 } 7712 7713 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7714 7715 unsigned WarningDiag = diag::warn_decl_shadow; 7716 SourceLocation CaptureLoc; 7717 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7718 isa<CXXMethodDecl>(NewDC)) { 7719 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7720 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7721 if (RD->getLambdaCaptureDefault() == LCD_None) { 7722 // Try to avoid warnings for lambdas with an explicit capture list. 7723 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7724 // Warn only when the lambda captures the shadowed decl explicitly. 7725 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7726 if (CaptureLoc.isInvalid()) 7727 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7728 } else { 7729 // Remember that this was shadowed so we can avoid the warning if the 7730 // shadowed decl isn't captured and the warning settings allow it. 7731 cast<LambdaScopeInfo>(getCurFunction()) 7732 ->ShadowingDecls.push_back( 7733 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7734 return; 7735 } 7736 } 7737 7738 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7739 // A variable can't shadow a local variable in an enclosing scope, if 7740 // they are separated by a non-capturing declaration context. 7741 for (DeclContext *ParentDC = NewDC; 7742 ParentDC && !ParentDC->Equals(OldDC); 7743 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7744 // Only block literals, captured statements, and lambda expressions 7745 // can capture; other scopes don't. 7746 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7747 !isLambdaCallOperator(ParentDC)) { 7748 return; 7749 } 7750 } 7751 } 7752 } 7753 } 7754 7755 // Only warn about certain kinds of shadowing for class members. 7756 if (NewDC && NewDC->isRecord()) { 7757 // In particular, don't warn about shadowing non-class members. 7758 if (!OldDC->isRecord()) 7759 return; 7760 7761 // TODO: should we warn about static data members shadowing 7762 // static data members from base classes? 7763 7764 // TODO: don't diagnose for inaccessible shadowed members. 7765 // This is hard to do perfectly because we might friend the 7766 // shadowing context, but that's just a false negative. 7767 } 7768 7769 7770 DeclarationName Name = R.getLookupName(); 7771 7772 // Emit warning and note. 7773 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7774 return; 7775 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7776 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7777 if (!CaptureLoc.isInvalid()) 7778 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7779 << Name << /*explicitly*/ 1; 7780 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7781 } 7782 7783 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7784 /// when these variables are captured by the lambda. 7785 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7786 for (const auto &Shadow : LSI->ShadowingDecls) { 7787 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7788 // Try to avoid the warning when the shadowed decl isn't captured. 7789 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7790 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7791 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7792 ? diag::warn_decl_shadow_uncaptured_local 7793 : diag::warn_decl_shadow) 7794 << Shadow.VD->getDeclName() 7795 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7796 if (!CaptureLoc.isInvalid()) 7797 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7798 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7799 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7800 } 7801 } 7802 7803 /// Check -Wshadow without the advantage of a previous lookup. 7804 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7805 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7806 return; 7807 7808 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7809 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7810 LookupName(R, S); 7811 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7812 CheckShadow(D, ShadowedDecl, R); 7813 } 7814 7815 /// Check if 'E', which is an expression that is about to be modified, refers 7816 /// to a constructor parameter that shadows a field. 7817 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7818 // Quickly ignore expressions that can't be shadowing ctor parameters. 7819 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7820 return; 7821 E = E->IgnoreParenImpCasts(); 7822 auto *DRE = dyn_cast<DeclRefExpr>(E); 7823 if (!DRE) 7824 return; 7825 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7826 auto I = ShadowingDecls.find(D); 7827 if (I == ShadowingDecls.end()) 7828 return; 7829 const NamedDecl *ShadowedDecl = I->second; 7830 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7831 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7832 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7833 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7834 7835 // Avoid issuing multiple warnings about the same decl. 7836 ShadowingDecls.erase(I); 7837 } 7838 7839 /// Check for conflict between this global or extern "C" declaration and 7840 /// previous global or extern "C" declarations. This is only used in C++. 7841 template<typename T> 7842 static bool checkGlobalOrExternCConflict( 7843 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7844 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7845 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7846 7847 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7848 // The common case: this global doesn't conflict with any extern "C" 7849 // declaration. 7850 return false; 7851 } 7852 7853 if (Prev) { 7854 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7855 // Both the old and new declarations have C language linkage. This is a 7856 // redeclaration. 7857 Previous.clear(); 7858 Previous.addDecl(Prev); 7859 return true; 7860 } 7861 7862 // This is a global, non-extern "C" declaration, and there is a previous 7863 // non-global extern "C" declaration. Diagnose if this is a variable 7864 // declaration. 7865 if (!isa<VarDecl>(ND)) 7866 return false; 7867 } else { 7868 // The declaration is extern "C". Check for any declaration in the 7869 // translation unit which might conflict. 7870 if (IsGlobal) { 7871 // We have already performed the lookup into the translation unit. 7872 IsGlobal = false; 7873 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7874 I != E; ++I) { 7875 if (isa<VarDecl>(*I)) { 7876 Prev = *I; 7877 break; 7878 } 7879 } 7880 } else { 7881 DeclContext::lookup_result R = 7882 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7883 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7884 I != E; ++I) { 7885 if (isa<VarDecl>(*I)) { 7886 Prev = *I; 7887 break; 7888 } 7889 // FIXME: If we have any other entity with this name in global scope, 7890 // the declaration is ill-formed, but that is a defect: it breaks the 7891 // 'stat' hack, for instance. Only variables can have mangled name 7892 // clashes with extern "C" declarations, so only they deserve a 7893 // diagnostic. 7894 } 7895 } 7896 7897 if (!Prev) 7898 return false; 7899 } 7900 7901 // Use the first declaration's location to ensure we point at something which 7902 // is lexically inside an extern "C" linkage-spec. 7903 assert(Prev && "should have found a previous declaration to diagnose"); 7904 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7905 Prev = FD->getFirstDecl(); 7906 else 7907 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7908 7909 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7910 << IsGlobal << ND; 7911 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7912 << IsGlobal; 7913 return false; 7914 } 7915 7916 /// Apply special rules for handling extern "C" declarations. Returns \c true 7917 /// if we have found that this is a redeclaration of some prior entity. 7918 /// 7919 /// Per C++ [dcl.link]p6: 7920 /// Two declarations [for a function or variable] with C language linkage 7921 /// with the same name that appear in different scopes refer to the same 7922 /// [entity]. An entity with C language linkage shall not be declared with 7923 /// the same name as an entity in global scope. 7924 template<typename T> 7925 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7926 LookupResult &Previous) { 7927 if (!S.getLangOpts().CPlusPlus) { 7928 // In C, when declaring a global variable, look for a corresponding 'extern' 7929 // variable declared in function scope. We don't need this in C++, because 7930 // we find local extern decls in the surrounding file-scope DeclContext. 7931 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7932 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7933 Previous.clear(); 7934 Previous.addDecl(Prev); 7935 return true; 7936 } 7937 } 7938 return false; 7939 } 7940 7941 // A declaration in the translation unit can conflict with an extern "C" 7942 // declaration. 7943 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7944 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7945 7946 // An extern "C" declaration can conflict with a declaration in the 7947 // translation unit or can be a redeclaration of an extern "C" declaration 7948 // in another scope. 7949 if (isIncompleteDeclExternC(S,ND)) 7950 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7951 7952 // Neither global nor extern "C": nothing to do. 7953 return false; 7954 } 7955 7956 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7957 // If the decl is already known invalid, don't check it. 7958 if (NewVD->isInvalidDecl()) 7959 return; 7960 7961 QualType T = NewVD->getType(); 7962 7963 // Defer checking an 'auto' type until its initializer is attached. 7964 if (T->isUndeducedType()) 7965 return; 7966 7967 if (NewVD->hasAttrs()) 7968 CheckAlignasUnderalignment(NewVD); 7969 7970 if (T->isObjCObjectType()) { 7971 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7972 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7973 T = Context.getObjCObjectPointerType(T); 7974 NewVD->setType(T); 7975 } 7976 7977 // Emit an error if an address space was applied to decl with local storage. 7978 // This includes arrays of objects with address space qualifiers, but not 7979 // automatic variables that point to other address spaces. 7980 // ISO/IEC TR 18037 S5.1.2 7981 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7982 T.getAddressSpace() != LangAS::Default) { 7983 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7984 NewVD->setInvalidDecl(); 7985 return; 7986 } 7987 7988 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7989 // scope. 7990 if (getLangOpts().OpenCLVersion == 120 && 7991 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", 7992 getLangOpts()) && 7993 NewVD->isStaticLocal()) { 7994 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7995 NewVD->setInvalidDecl(); 7996 return; 7997 } 7998 7999 if (getLangOpts().OpenCL) { 8000 if (!diagnoseOpenCLTypes(*this, NewVD)) 8001 return; 8002 8003 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 8004 if (NewVD->hasAttr<BlocksAttr>()) { 8005 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 8006 return; 8007 } 8008 8009 if (T->isBlockPointerType()) { 8010 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 8011 // can't use 'extern' storage class. 8012 if (!T.isConstQualified()) { 8013 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 8014 << 0 /*const*/; 8015 NewVD->setInvalidDecl(); 8016 return; 8017 } 8018 if (NewVD->hasExternalStorage()) { 8019 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 8020 NewVD->setInvalidDecl(); 8021 return; 8022 } 8023 } 8024 8025 // FIXME: Adding local AS in C++ for OpenCL might make sense. 8026 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 8027 NewVD->hasExternalStorage()) { 8028 if (!T->isSamplerT() && !T->isDependentType() && 8029 !(T.getAddressSpace() == LangAS::opencl_constant || 8030 (T.getAddressSpace() == LangAS::opencl_global && 8031 getOpenCLOptions().areProgramScopeVariablesSupported( 8032 getLangOpts())))) { 8033 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 8034 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts())) 8035 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8036 << Scope << "global or constant"; 8037 else 8038 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8039 << Scope << "constant"; 8040 NewVD->setInvalidDecl(); 8041 return; 8042 } 8043 } else { 8044 if (T.getAddressSpace() == LangAS::opencl_global) { 8045 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8046 << 1 /*is any function*/ << "global"; 8047 NewVD->setInvalidDecl(); 8048 return; 8049 } 8050 if (T.getAddressSpace() == LangAS::opencl_constant || 8051 T.getAddressSpace() == LangAS::opencl_local) { 8052 FunctionDecl *FD = getCurFunctionDecl(); 8053 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 8054 // in functions. 8055 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 8056 if (T.getAddressSpace() == LangAS::opencl_constant) 8057 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8058 << 0 /*non-kernel only*/ << "constant"; 8059 else 8060 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8061 << 0 /*non-kernel only*/ << "local"; 8062 NewVD->setInvalidDecl(); 8063 return; 8064 } 8065 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 8066 // in the outermost scope of a kernel function. 8067 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 8068 if (!getCurScope()->isFunctionScope()) { 8069 if (T.getAddressSpace() == LangAS::opencl_constant) 8070 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8071 << "constant"; 8072 else 8073 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8074 << "local"; 8075 NewVD->setInvalidDecl(); 8076 return; 8077 } 8078 } 8079 } else if (T.getAddressSpace() != LangAS::opencl_private && 8080 // If we are parsing a template we didn't deduce an addr 8081 // space yet. 8082 T.getAddressSpace() != LangAS::Default) { 8083 // Do not allow other address spaces on automatic variable. 8084 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 8085 NewVD->setInvalidDecl(); 8086 return; 8087 } 8088 } 8089 } 8090 8091 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 8092 && !NewVD->hasAttr<BlocksAttr>()) { 8093 if (getLangOpts().getGC() != LangOptions::NonGC) 8094 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 8095 else { 8096 assert(!getLangOpts().ObjCAutoRefCount); 8097 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 8098 } 8099 } 8100 8101 bool isVM = T->isVariablyModifiedType(); 8102 if (isVM || NewVD->hasAttr<CleanupAttr>() || 8103 NewVD->hasAttr<BlocksAttr>()) 8104 setFunctionHasBranchProtectedScope(); 8105 8106 if ((isVM && NewVD->hasLinkage()) || 8107 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8108 bool SizeIsNegative; 8109 llvm::APSInt Oversized; 8110 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8111 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8112 QualType FixedT; 8113 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8114 FixedT = FixedTInfo->getType(); 8115 else if (FixedTInfo) { 8116 // Type and type-as-written are canonically different. We need to fix up 8117 // both types separately. 8118 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8119 Oversized); 8120 } 8121 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8122 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8123 // FIXME: This won't give the correct result for 8124 // int a[10][n]; 8125 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8126 8127 if (NewVD->isFileVarDecl()) 8128 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8129 << SizeRange; 8130 else if (NewVD->isStaticLocal()) 8131 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8132 << SizeRange; 8133 else 8134 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8135 << SizeRange; 8136 NewVD->setInvalidDecl(); 8137 return; 8138 } 8139 8140 if (!FixedTInfo) { 8141 if (NewVD->isFileVarDecl()) 8142 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8143 else 8144 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8145 NewVD->setInvalidDecl(); 8146 return; 8147 } 8148 8149 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8150 NewVD->setType(FixedT); 8151 NewVD->setTypeSourceInfo(FixedTInfo); 8152 } 8153 8154 if (T->isVoidType()) { 8155 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8156 // of objects and functions. 8157 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8158 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8159 << T; 8160 NewVD->setInvalidDecl(); 8161 return; 8162 } 8163 } 8164 8165 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8166 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8167 NewVD->setInvalidDecl(); 8168 return; 8169 } 8170 8171 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8172 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8173 NewVD->setInvalidDecl(); 8174 return; 8175 } 8176 8177 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8178 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8179 NewVD->setInvalidDecl(); 8180 return; 8181 } 8182 8183 if (NewVD->isConstexpr() && !T->isDependentType() && 8184 RequireLiteralType(NewVD->getLocation(), T, 8185 diag::err_constexpr_var_non_literal)) { 8186 NewVD->setInvalidDecl(); 8187 return; 8188 } 8189 8190 // PPC MMA non-pointer types are not allowed as non-local variable types. 8191 if (Context.getTargetInfo().getTriple().isPPC64() && 8192 !NewVD->isLocalVarDecl() && 8193 CheckPPCMMAType(T, NewVD->getLocation())) { 8194 NewVD->setInvalidDecl(); 8195 return; 8196 } 8197 } 8198 8199 /// Perform semantic checking on a newly-created variable 8200 /// declaration. 8201 /// 8202 /// This routine performs all of the type-checking required for a 8203 /// variable declaration once it has been built. It is used both to 8204 /// check variables after they have been parsed and their declarators 8205 /// have been translated into a declaration, and to check variables 8206 /// that have been instantiated from a template. 8207 /// 8208 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8209 /// 8210 /// Returns true if the variable declaration is a redeclaration. 8211 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8212 CheckVariableDeclarationType(NewVD); 8213 8214 // If the decl is already known invalid, don't check it. 8215 if (NewVD->isInvalidDecl()) 8216 return false; 8217 8218 // If we did not find anything by this name, look for a non-visible 8219 // extern "C" declaration with the same name. 8220 if (Previous.empty() && 8221 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8222 Previous.setShadowed(); 8223 8224 if (!Previous.empty()) { 8225 MergeVarDecl(NewVD, Previous); 8226 return true; 8227 } 8228 return false; 8229 } 8230 8231 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8232 /// and if so, check that it's a valid override and remember it. 8233 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8234 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8235 8236 // Look for methods in base classes that this method might override. 8237 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8238 /*DetectVirtual=*/false); 8239 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8240 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8241 DeclarationName Name = MD->getDeclName(); 8242 8243 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8244 // We really want to find the base class destructor here. 8245 QualType T = Context.getTypeDeclType(BaseRecord); 8246 CanQualType CT = Context.getCanonicalType(T); 8247 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8248 } 8249 8250 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8251 CXXMethodDecl *BaseMD = 8252 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8253 if (!BaseMD || !BaseMD->isVirtual() || 8254 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8255 /*ConsiderCudaAttrs=*/true, 8256 // C++2a [class.virtual]p2 does not consider requires 8257 // clauses when overriding. 8258 /*ConsiderRequiresClauses=*/false)) 8259 continue; 8260 8261 if (Overridden.insert(BaseMD).second) { 8262 MD->addOverriddenMethod(BaseMD); 8263 CheckOverridingFunctionReturnType(MD, BaseMD); 8264 CheckOverridingFunctionAttributes(MD, BaseMD); 8265 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8266 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8267 } 8268 8269 // A method can only override one function from each base class. We 8270 // don't track indirectly overridden methods from bases of bases. 8271 return true; 8272 } 8273 8274 return false; 8275 }; 8276 8277 DC->lookupInBases(VisitBase, Paths); 8278 return !Overridden.empty(); 8279 } 8280 8281 namespace { 8282 // Struct for holding all of the extra arguments needed by 8283 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8284 struct ActOnFDArgs { 8285 Scope *S; 8286 Declarator &D; 8287 MultiTemplateParamsArg TemplateParamLists; 8288 bool AddToScope; 8289 }; 8290 } // end anonymous namespace 8291 8292 namespace { 8293 8294 // Callback to only accept typo corrections that have a non-zero edit distance. 8295 // Also only accept corrections that have the same parent decl. 8296 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8297 public: 8298 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8299 CXXRecordDecl *Parent) 8300 : Context(Context), OriginalFD(TypoFD), 8301 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8302 8303 bool ValidateCandidate(const TypoCorrection &candidate) override { 8304 if (candidate.getEditDistance() == 0) 8305 return false; 8306 8307 SmallVector<unsigned, 1> MismatchedParams; 8308 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8309 CDeclEnd = candidate.end(); 8310 CDecl != CDeclEnd; ++CDecl) { 8311 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8312 8313 if (FD && !FD->hasBody() && 8314 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8315 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8316 CXXRecordDecl *Parent = MD->getParent(); 8317 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8318 return true; 8319 } else if (!ExpectedParent) { 8320 return true; 8321 } 8322 } 8323 } 8324 8325 return false; 8326 } 8327 8328 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8329 return std::make_unique<DifferentNameValidatorCCC>(*this); 8330 } 8331 8332 private: 8333 ASTContext &Context; 8334 FunctionDecl *OriginalFD; 8335 CXXRecordDecl *ExpectedParent; 8336 }; 8337 8338 } // end anonymous namespace 8339 8340 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8341 TypoCorrectedFunctionDefinitions.insert(F); 8342 } 8343 8344 /// Generate diagnostics for an invalid function redeclaration. 8345 /// 8346 /// This routine handles generating the diagnostic messages for an invalid 8347 /// function redeclaration, including finding possible similar declarations 8348 /// or performing typo correction if there are no previous declarations with 8349 /// the same name. 8350 /// 8351 /// Returns a NamedDecl iff typo correction was performed and substituting in 8352 /// the new declaration name does not cause new errors. 8353 static NamedDecl *DiagnoseInvalidRedeclaration( 8354 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8355 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8356 DeclarationName Name = NewFD->getDeclName(); 8357 DeclContext *NewDC = NewFD->getDeclContext(); 8358 SmallVector<unsigned, 1> MismatchedParams; 8359 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8360 TypoCorrection Correction; 8361 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8362 unsigned DiagMsg = 8363 IsLocalFriend ? diag::err_no_matching_local_friend : 8364 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8365 diag::err_member_decl_does_not_match; 8366 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8367 IsLocalFriend ? Sema::LookupLocalFriendName 8368 : Sema::LookupOrdinaryName, 8369 Sema::ForVisibleRedeclaration); 8370 8371 NewFD->setInvalidDecl(); 8372 if (IsLocalFriend) 8373 SemaRef.LookupName(Prev, S); 8374 else 8375 SemaRef.LookupQualifiedName(Prev, NewDC); 8376 assert(!Prev.isAmbiguous() && 8377 "Cannot have an ambiguity in previous-declaration lookup"); 8378 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8379 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8380 MD ? MD->getParent() : nullptr); 8381 if (!Prev.empty()) { 8382 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8383 Func != FuncEnd; ++Func) { 8384 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8385 if (FD && 8386 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8387 // Add 1 to the index so that 0 can mean the mismatch didn't 8388 // involve a parameter 8389 unsigned ParamNum = 8390 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8391 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8392 } 8393 } 8394 // If the qualified name lookup yielded nothing, try typo correction 8395 } else if ((Correction = SemaRef.CorrectTypo( 8396 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8397 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8398 IsLocalFriend ? nullptr : NewDC))) { 8399 // Set up everything for the call to ActOnFunctionDeclarator 8400 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8401 ExtraArgs.D.getIdentifierLoc()); 8402 Previous.clear(); 8403 Previous.setLookupName(Correction.getCorrection()); 8404 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8405 CDeclEnd = Correction.end(); 8406 CDecl != CDeclEnd; ++CDecl) { 8407 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8408 if (FD && !FD->hasBody() && 8409 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8410 Previous.addDecl(FD); 8411 } 8412 } 8413 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8414 8415 NamedDecl *Result; 8416 // Retry building the function declaration with the new previous 8417 // declarations, and with errors suppressed. 8418 { 8419 // Trap errors. 8420 Sema::SFINAETrap Trap(SemaRef); 8421 8422 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8423 // pieces need to verify the typo-corrected C++ declaration and hopefully 8424 // eliminate the need for the parameter pack ExtraArgs. 8425 Result = SemaRef.ActOnFunctionDeclarator( 8426 ExtraArgs.S, ExtraArgs.D, 8427 Correction.getCorrectionDecl()->getDeclContext(), 8428 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8429 ExtraArgs.AddToScope); 8430 8431 if (Trap.hasErrorOccurred()) 8432 Result = nullptr; 8433 } 8434 8435 if (Result) { 8436 // Determine which correction we picked. 8437 Decl *Canonical = Result->getCanonicalDecl(); 8438 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8439 I != E; ++I) 8440 if ((*I)->getCanonicalDecl() == Canonical) 8441 Correction.setCorrectionDecl(*I); 8442 8443 // Let Sema know about the correction. 8444 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8445 SemaRef.diagnoseTypo( 8446 Correction, 8447 SemaRef.PDiag(IsLocalFriend 8448 ? diag::err_no_matching_local_friend_suggest 8449 : diag::err_member_decl_does_not_match_suggest) 8450 << Name << NewDC << IsDefinition); 8451 return Result; 8452 } 8453 8454 // Pretend the typo correction never occurred 8455 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8456 ExtraArgs.D.getIdentifierLoc()); 8457 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8458 Previous.clear(); 8459 Previous.setLookupName(Name); 8460 } 8461 8462 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8463 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8464 8465 bool NewFDisConst = false; 8466 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8467 NewFDisConst = NewMD->isConst(); 8468 8469 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8470 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8471 NearMatch != NearMatchEnd; ++NearMatch) { 8472 FunctionDecl *FD = NearMatch->first; 8473 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8474 bool FDisConst = MD && MD->isConst(); 8475 bool IsMember = MD || !IsLocalFriend; 8476 8477 // FIXME: These notes are poorly worded for the local friend case. 8478 if (unsigned Idx = NearMatch->second) { 8479 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8480 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8481 if (Loc.isInvalid()) Loc = FD->getLocation(); 8482 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8483 : diag::note_local_decl_close_param_match) 8484 << Idx << FDParam->getType() 8485 << NewFD->getParamDecl(Idx - 1)->getType(); 8486 } else if (FDisConst != NewFDisConst) { 8487 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8488 << NewFDisConst << FD->getSourceRange().getEnd(); 8489 } else 8490 SemaRef.Diag(FD->getLocation(), 8491 IsMember ? diag::note_member_def_close_match 8492 : diag::note_local_decl_close_match); 8493 } 8494 return nullptr; 8495 } 8496 8497 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8498 switch (D.getDeclSpec().getStorageClassSpec()) { 8499 default: llvm_unreachable("Unknown storage class!"); 8500 case DeclSpec::SCS_auto: 8501 case DeclSpec::SCS_register: 8502 case DeclSpec::SCS_mutable: 8503 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8504 diag::err_typecheck_sclass_func); 8505 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8506 D.setInvalidType(); 8507 break; 8508 case DeclSpec::SCS_unspecified: break; 8509 case DeclSpec::SCS_extern: 8510 if (D.getDeclSpec().isExternInLinkageSpec()) 8511 return SC_None; 8512 return SC_Extern; 8513 case DeclSpec::SCS_static: { 8514 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8515 // C99 6.7.1p5: 8516 // The declaration of an identifier for a function that has 8517 // block scope shall have no explicit storage-class specifier 8518 // other than extern 8519 // See also (C++ [dcl.stc]p4). 8520 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8521 diag::err_static_block_func); 8522 break; 8523 } else 8524 return SC_Static; 8525 } 8526 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8527 } 8528 8529 // No explicit storage class has already been returned 8530 return SC_None; 8531 } 8532 8533 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8534 DeclContext *DC, QualType &R, 8535 TypeSourceInfo *TInfo, 8536 StorageClass SC, 8537 bool &IsVirtualOkay) { 8538 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8539 DeclarationName Name = NameInfo.getName(); 8540 8541 FunctionDecl *NewFD = nullptr; 8542 bool isInline = D.getDeclSpec().isInlineSpecified(); 8543 8544 if (!SemaRef.getLangOpts().CPlusPlus) { 8545 // Determine whether the function was written with a 8546 // prototype. This true when: 8547 // - there is a prototype in the declarator, or 8548 // - the type R of the function is some kind of typedef or other non- 8549 // attributed reference to a type name (which eventually refers to a 8550 // function type). 8551 bool HasPrototype = 8552 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8553 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8554 8555 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8556 R, TInfo, SC, isInline, HasPrototype, 8557 ConstexprSpecKind::Unspecified, 8558 /*TrailingRequiresClause=*/nullptr); 8559 if (D.isInvalidType()) 8560 NewFD->setInvalidDecl(); 8561 8562 return NewFD; 8563 } 8564 8565 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8566 8567 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8568 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8569 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8570 diag::err_constexpr_wrong_decl_kind) 8571 << static_cast<int>(ConstexprKind); 8572 ConstexprKind = ConstexprSpecKind::Unspecified; 8573 D.getMutableDeclSpec().ClearConstexprSpec(); 8574 } 8575 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8576 8577 // Check that the return type is not an abstract class type. 8578 // For record types, this is done by the AbstractClassUsageDiagnoser once 8579 // the class has been completely parsed. 8580 if (!DC->isRecord() && 8581 SemaRef.RequireNonAbstractType( 8582 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8583 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8584 D.setInvalidType(); 8585 8586 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8587 // This is a C++ constructor declaration. 8588 assert(DC->isRecord() && 8589 "Constructors can only be declared in a member context"); 8590 8591 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8592 return CXXConstructorDecl::Create( 8593 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8594 TInfo, ExplicitSpecifier, isInline, 8595 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8596 TrailingRequiresClause); 8597 8598 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8599 // This is a C++ destructor declaration. 8600 if (DC->isRecord()) { 8601 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8602 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8603 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8604 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8605 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8606 TrailingRequiresClause); 8607 8608 // If the destructor needs an implicit exception specification, set it 8609 // now. FIXME: It'd be nice to be able to create the right type to start 8610 // with, but the type needs to reference the destructor declaration. 8611 if (SemaRef.getLangOpts().CPlusPlus11) 8612 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8613 8614 IsVirtualOkay = true; 8615 return NewDD; 8616 8617 } else { 8618 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8619 D.setInvalidType(); 8620 8621 // Create a FunctionDecl to satisfy the function definition parsing 8622 // code path. 8623 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8624 D.getIdentifierLoc(), Name, R, TInfo, SC, 8625 isInline, 8626 /*hasPrototype=*/true, ConstexprKind, 8627 TrailingRequiresClause); 8628 } 8629 8630 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8631 if (!DC->isRecord()) { 8632 SemaRef.Diag(D.getIdentifierLoc(), 8633 diag::err_conv_function_not_member); 8634 return nullptr; 8635 } 8636 8637 SemaRef.CheckConversionDeclarator(D, R, SC); 8638 if (D.isInvalidType()) 8639 return nullptr; 8640 8641 IsVirtualOkay = true; 8642 return CXXConversionDecl::Create( 8643 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8644 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8645 TrailingRequiresClause); 8646 8647 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8648 if (TrailingRequiresClause) 8649 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8650 diag::err_trailing_requires_clause_on_deduction_guide) 8651 << TrailingRequiresClause->getSourceRange(); 8652 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8653 8654 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8655 ExplicitSpecifier, NameInfo, R, TInfo, 8656 D.getEndLoc()); 8657 } else if (DC->isRecord()) { 8658 // If the name of the function is the same as the name of the record, 8659 // then this must be an invalid constructor that has a return type. 8660 // (The parser checks for a return type and makes the declarator a 8661 // constructor if it has no return type). 8662 if (Name.getAsIdentifierInfo() && 8663 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8664 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8665 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8666 << SourceRange(D.getIdentifierLoc()); 8667 return nullptr; 8668 } 8669 8670 // This is a C++ method declaration. 8671 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8672 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8673 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8674 TrailingRequiresClause); 8675 IsVirtualOkay = !Ret->isStatic(); 8676 return Ret; 8677 } else { 8678 bool isFriend = 8679 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8680 if (!isFriend && SemaRef.CurContext->isRecord()) 8681 return nullptr; 8682 8683 // Determine whether the function was written with a 8684 // prototype. This true when: 8685 // - we're in C++ (where every function has a prototype), 8686 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8687 R, TInfo, SC, isInline, true /*HasPrototype*/, 8688 ConstexprKind, TrailingRequiresClause); 8689 } 8690 } 8691 8692 enum OpenCLParamType { 8693 ValidKernelParam, 8694 PtrPtrKernelParam, 8695 PtrKernelParam, 8696 InvalidAddrSpacePtrKernelParam, 8697 InvalidKernelParam, 8698 RecordKernelParam 8699 }; 8700 8701 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8702 // Size dependent types are just typedefs to normal integer types 8703 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8704 // integers other than by their names. 8705 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8706 8707 // Remove typedefs one by one until we reach a typedef 8708 // for a size dependent type. 8709 QualType DesugaredTy = Ty; 8710 do { 8711 ArrayRef<StringRef> Names(SizeTypeNames); 8712 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8713 if (Names.end() != Match) 8714 return true; 8715 8716 Ty = DesugaredTy; 8717 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8718 } while (DesugaredTy != Ty); 8719 8720 return false; 8721 } 8722 8723 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8724 if (PT->isDependentType()) 8725 return InvalidKernelParam; 8726 8727 if (PT->isPointerType() || PT->isReferenceType()) { 8728 QualType PointeeType = PT->getPointeeType(); 8729 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8730 PointeeType.getAddressSpace() == LangAS::opencl_private || 8731 PointeeType.getAddressSpace() == LangAS::Default) 8732 return InvalidAddrSpacePtrKernelParam; 8733 8734 if (PointeeType->isPointerType()) { 8735 // This is a pointer to pointer parameter. 8736 // Recursively check inner type. 8737 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 8738 if (ParamKind == InvalidAddrSpacePtrKernelParam || 8739 ParamKind == InvalidKernelParam) 8740 return ParamKind; 8741 8742 return PtrPtrKernelParam; 8743 } 8744 8745 // C++ for OpenCL v1.0 s2.4: 8746 // Moreover the types used in parameters of the kernel functions must be: 8747 // Standard layout types for pointer parameters. The same applies to 8748 // reference if an implementation supports them in kernel parameters. 8749 if (S.getLangOpts().OpenCLCPlusPlus && 8750 !S.getOpenCLOptions().isAvailableOption( 8751 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 8752 !PointeeType->isAtomicType() && !PointeeType->isVoidType() && 8753 !PointeeType->isStandardLayoutType()) 8754 return InvalidKernelParam; 8755 8756 return PtrKernelParam; 8757 } 8758 8759 // OpenCL v1.2 s6.9.k: 8760 // Arguments to kernel functions in a program cannot be declared with the 8761 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8762 // uintptr_t or a struct and/or union that contain fields declared to be one 8763 // of these built-in scalar types. 8764 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8765 return InvalidKernelParam; 8766 8767 if (PT->isImageType()) 8768 return PtrKernelParam; 8769 8770 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8771 return InvalidKernelParam; 8772 8773 // OpenCL extension spec v1.2 s9.5: 8774 // This extension adds support for half scalar and vector types as built-in 8775 // types that can be used for arithmetic operations, conversions etc. 8776 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 8777 PT->isHalfType()) 8778 return InvalidKernelParam; 8779 8780 // Look into an array argument to check if it has a forbidden type. 8781 if (PT->isArrayType()) { 8782 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8783 // Call ourself to check an underlying type of an array. Since the 8784 // getPointeeOrArrayElementType returns an innermost type which is not an 8785 // array, this recursive call only happens once. 8786 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8787 } 8788 8789 // C++ for OpenCL v1.0 s2.4: 8790 // Moreover the types used in parameters of the kernel functions must be: 8791 // Trivial and standard-layout types C++17 [basic.types] (plain old data 8792 // types) for parameters passed by value; 8793 if (S.getLangOpts().OpenCLCPlusPlus && 8794 !S.getOpenCLOptions().isAvailableOption( 8795 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 8796 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context)) 8797 return InvalidKernelParam; 8798 8799 if (PT->isRecordType()) 8800 return RecordKernelParam; 8801 8802 return ValidKernelParam; 8803 } 8804 8805 static void checkIsValidOpenCLKernelParameter( 8806 Sema &S, 8807 Declarator &D, 8808 ParmVarDecl *Param, 8809 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8810 QualType PT = Param->getType(); 8811 8812 // Cache the valid types we encounter to avoid rechecking structs that are 8813 // used again 8814 if (ValidTypes.count(PT.getTypePtr())) 8815 return; 8816 8817 switch (getOpenCLKernelParameterType(S, PT)) { 8818 case PtrPtrKernelParam: 8819 // OpenCL v3.0 s6.11.a: 8820 // A kernel function argument cannot be declared as a pointer to a pointer 8821 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 8822 if (S.getLangOpts().OpenCLVersion <= 120 && 8823 !S.getLangOpts().OpenCLCPlusPlus) { 8824 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8825 D.setInvalidType(); 8826 return; 8827 } 8828 8829 ValidTypes.insert(PT.getTypePtr()); 8830 return; 8831 8832 case InvalidAddrSpacePtrKernelParam: 8833 // OpenCL v1.0 s6.5: 8834 // __kernel function arguments declared to be a pointer of a type can point 8835 // to one of the following address spaces only : __global, __local or 8836 // __constant. 8837 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8838 D.setInvalidType(); 8839 return; 8840 8841 // OpenCL v1.2 s6.9.k: 8842 // Arguments to kernel functions in a program cannot be declared with the 8843 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8844 // uintptr_t or a struct and/or union that contain fields declared to be 8845 // one of these built-in scalar types. 8846 8847 case InvalidKernelParam: 8848 // OpenCL v1.2 s6.8 n: 8849 // A kernel function argument cannot be declared 8850 // of event_t type. 8851 // Do not diagnose half type since it is diagnosed as invalid argument 8852 // type for any function elsewhere. 8853 if (!PT->isHalfType()) { 8854 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8855 8856 // Explain what typedefs are involved. 8857 const TypedefType *Typedef = nullptr; 8858 while ((Typedef = PT->getAs<TypedefType>())) { 8859 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8860 // SourceLocation may be invalid for a built-in type. 8861 if (Loc.isValid()) 8862 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8863 PT = Typedef->desugar(); 8864 } 8865 } 8866 8867 D.setInvalidType(); 8868 return; 8869 8870 case PtrKernelParam: 8871 case ValidKernelParam: 8872 ValidTypes.insert(PT.getTypePtr()); 8873 return; 8874 8875 case RecordKernelParam: 8876 break; 8877 } 8878 8879 // Track nested structs we will inspect 8880 SmallVector<const Decl *, 4> VisitStack; 8881 8882 // Track where we are in the nested structs. Items will migrate from 8883 // VisitStack to HistoryStack as we do the DFS for bad field. 8884 SmallVector<const FieldDecl *, 4> HistoryStack; 8885 HistoryStack.push_back(nullptr); 8886 8887 // At this point we already handled everything except of a RecordType or 8888 // an ArrayType of a RecordType. 8889 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8890 const RecordType *RecTy = 8891 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8892 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8893 8894 VisitStack.push_back(RecTy->getDecl()); 8895 assert(VisitStack.back() && "First decl null?"); 8896 8897 do { 8898 const Decl *Next = VisitStack.pop_back_val(); 8899 if (!Next) { 8900 assert(!HistoryStack.empty()); 8901 // Found a marker, we have gone up a level 8902 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8903 ValidTypes.insert(Hist->getType().getTypePtr()); 8904 8905 continue; 8906 } 8907 8908 // Adds everything except the original parameter declaration (which is not a 8909 // field itself) to the history stack. 8910 const RecordDecl *RD; 8911 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8912 HistoryStack.push_back(Field); 8913 8914 QualType FieldTy = Field->getType(); 8915 // Other field types (known to be valid or invalid) are handled while we 8916 // walk around RecordDecl::fields(). 8917 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8918 "Unexpected type."); 8919 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8920 8921 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8922 } else { 8923 RD = cast<RecordDecl>(Next); 8924 } 8925 8926 // Add a null marker so we know when we've gone back up a level 8927 VisitStack.push_back(nullptr); 8928 8929 for (const auto *FD : RD->fields()) { 8930 QualType QT = FD->getType(); 8931 8932 if (ValidTypes.count(QT.getTypePtr())) 8933 continue; 8934 8935 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8936 if (ParamType == ValidKernelParam) 8937 continue; 8938 8939 if (ParamType == RecordKernelParam) { 8940 VisitStack.push_back(FD); 8941 continue; 8942 } 8943 8944 // OpenCL v1.2 s6.9.p: 8945 // Arguments to kernel functions that are declared to be a struct or union 8946 // do not allow OpenCL objects to be passed as elements of the struct or 8947 // union. 8948 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8949 ParamType == InvalidAddrSpacePtrKernelParam) { 8950 S.Diag(Param->getLocation(), 8951 diag::err_record_with_pointers_kernel_param) 8952 << PT->isUnionType() 8953 << PT; 8954 } else { 8955 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8956 } 8957 8958 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8959 << OrigRecDecl->getDeclName(); 8960 8961 // We have an error, now let's go back up through history and show where 8962 // the offending field came from 8963 for (ArrayRef<const FieldDecl *>::const_iterator 8964 I = HistoryStack.begin() + 1, 8965 E = HistoryStack.end(); 8966 I != E; ++I) { 8967 const FieldDecl *OuterField = *I; 8968 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8969 << OuterField->getType(); 8970 } 8971 8972 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8973 << QT->isPointerType() 8974 << QT; 8975 D.setInvalidType(); 8976 return; 8977 } 8978 } while (!VisitStack.empty()); 8979 } 8980 8981 /// Find the DeclContext in which a tag is implicitly declared if we see an 8982 /// elaborated type specifier in the specified context, and lookup finds 8983 /// nothing. 8984 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8985 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8986 DC = DC->getParent(); 8987 return DC; 8988 } 8989 8990 /// Find the Scope in which a tag is implicitly declared if we see an 8991 /// elaborated type specifier in the specified context, and lookup finds 8992 /// nothing. 8993 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8994 while (S->isClassScope() || 8995 (LangOpts.CPlusPlus && 8996 S->isFunctionPrototypeScope()) || 8997 ((S->getFlags() & Scope::DeclScope) == 0) || 8998 (S->getEntity() && S->getEntity()->isTransparentContext())) 8999 S = S->getParent(); 9000 return S; 9001 } 9002 9003 NamedDecl* 9004 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 9005 TypeSourceInfo *TInfo, LookupResult &Previous, 9006 MultiTemplateParamsArg TemplateParamListsRef, 9007 bool &AddToScope) { 9008 QualType R = TInfo->getType(); 9009 9010 assert(R->isFunctionType()); 9011 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 9012 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 9013 9014 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 9015 for (TemplateParameterList *TPL : TemplateParamListsRef) 9016 TemplateParamLists.push_back(TPL); 9017 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 9018 if (!TemplateParamLists.empty() && 9019 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 9020 TemplateParamLists.back() = Invented; 9021 else 9022 TemplateParamLists.push_back(Invented); 9023 } 9024 9025 // TODO: consider using NameInfo for diagnostic. 9026 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 9027 DeclarationName Name = NameInfo.getName(); 9028 StorageClass SC = getFunctionStorageClass(*this, D); 9029 9030 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 9031 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 9032 diag::err_invalid_thread) 9033 << DeclSpec::getSpecifierName(TSCS); 9034 9035 if (D.isFirstDeclarationOfMember()) 9036 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 9037 D.getIdentifierLoc()); 9038 9039 bool isFriend = false; 9040 FunctionTemplateDecl *FunctionTemplate = nullptr; 9041 bool isMemberSpecialization = false; 9042 bool isFunctionTemplateSpecialization = false; 9043 9044 bool isDependentClassScopeExplicitSpecialization = false; 9045 bool HasExplicitTemplateArgs = false; 9046 TemplateArgumentListInfo TemplateArgs; 9047 9048 bool isVirtualOkay = false; 9049 9050 DeclContext *OriginalDC = DC; 9051 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 9052 9053 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 9054 isVirtualOkay); 9055 if (!NewFD) return nullptr; 9056 9057 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 9058 NewFD->setTopLevelDeclInObjCContainer(); 9059 9060 // Set the lexical context. If this is a function-scope declaration, or has a 9061 // C++ scope specifier, or is the object of a friend declaration, the lexical 9062 // context will be different from the semantic context. 9063 NewFD->setLexicalDeclContext(CurContext); 9064 9065 if (IsLocalExternDecl) 9066 NewFD->setLocalExternDecl(); 9067 9068 if (getLangOpts().CPlusPlus) { 9069 bool isInline = D.getDeclSpec().isInlineSpecified(); 9070 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9071 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 9072 isFriend = D.getDeclSpec().isFriendSpecified(); 9073 if (isFriend && !isInline && D.isFunctionDefinition()) { 9074 // C++ [class.friend]p5 9075 // A function can be defined in a friend declaration of a 9076 // class . . . . Such a function is implicitly inline. 9077 NewFD->setImplicitlyInline(); 9078 } 9079 9080 // If this is a method defined in an __interface, and is not a constructor 9081 // or an overloaded operator, then set the pure flag (isVirtual will already 9082 // return true). 9083 if (const CXXRecordDecl *Parent = 9084 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 9085 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 9086 NewFD->setPure(true); 9087 9088 // C++ [class.union]p2 9089 // A union can have member functions, but not virtual functions. 9090 if (isVirtual && Parent->isUnion()) 9091 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 9092 } 9093 9094 SetNestedNameSpecifier(*this, NewFD, D); 9095 isMemberSpecialization = false; 9096 isFunctionTemplateSpecialization = false; 9097 if (D.isInvalidType()) 9098 NewFD->setInvalidDecl(); 9099 9100 // Match up the template parameter lists with the scope specifier, then 9101 // determine whether we have a template or a template specialization. 9102 bool Invalid = false; 9103 TemplateParameterList *TemplateParams = 9104 MatchTemplateParametersToScopeSpecifier( 9105 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 9106 D.getCXXScopeSpec(), 9107 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 9108 ? D.getName().TemplateId 9109 : nullptr, 9110 TemplateParamLists, isFriend, isMemberSpecialization, 9111 Invalid); 9112 if (TemplateParams) { 9113 // Check that we can declare a template here. 9114 if (CheckTemplateDeclScope(S, TemplateParams)) 9115 NewFD->setInvalidDecl(); 9116 9117 if (TemplateParams->size() > 0) { 9118 // This is a function template 9119 9120 // A destructor cannot be a template. 9121 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9122 Diag(NewFD->getLocation(), diag::err_destructor_template); 9123 NewFD->setInvalidDecl(); 9124 } 9125 9126 // If we're adding a template to a dependent context, we may need to 9127 // rebuilding some of the types used within the template parameter list, 9128 // now that we know what the current instantiation is. 9129 if (DC->isDependentContext()) { 9130 ContextRAII SavedContext(*this, DC); 9131 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9132 Invalid = true; 9133 } 9134 9135 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9136 NewFD->getLocation(), 9137 Name, TemplateParams, 9138 NewFD); 9139 FunctionTemplate->setLexicalDeclContext(CurContext); 9140 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9141 9142 // For source fidelity, store the other template param lists. 9143 if (TemplateParamLists.size() > 1) { 9144 NewFD->setTemplateParameterListsInfo(Context, 9145 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9146 .drop_back(1)); 9147 } 9148 } else { 9149 // This is a function template specialization. 9150 isFunctionTemplateSpecialization = true; 9151 // For source fidelity, store all the template param lists. 9152 if (TemplateParamLists.size() > 0) 9153 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9154 9155 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9156 if (isFriend) { 9157 // We want to remove the "template<>", found here. 9158 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9159 9160 // If we remove the template<> and the name is not a 9161 // template-id, we're actually silently creating a problem: 9162 // the friend declaration will refer to an untemplated decl, 9163 // and clearly the user wants a template specialization. So 9164 // we need to insert '<>' after the name. 9165 SourceLocation InsertLoc; 9166 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9167 InsertLoc = D.getName().getSourceRange().getEnd(); 9168 InsertLoc = getLocForEndOfToken(InsertLoc); 9169 } 9170 9171 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9172 << Name << RemoveRange 9173 << FixItHint::CreateRemoval(RemoveRange) 9174 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9175 } 9176 } 9177 } else { 9178 // Check that we can declare a template here. 9179 if (!TemplateParamLists.empty() && isMemberSpecialization && 9180 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9181 NewFD->setInvalidDecl(); 9182 9183 // All template param lists were matched against the scope specifier: 9184 // this is NOT (an explicit specialization of) a template. 9185 if (TemplateParamLists.size() > 0) 9186 // For source fidelity, store all the template param lists. 9187 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9188 } 9189 9190 if (Invalid) { 9191 NewFD->setInvalidDecl(); 9192 if (FunctionTemplate) 9193 FunctionTemplate->setInvalidDecl(); 9194 } 9195 9196 // C++ [dcl.fct.spec]p5: 9197 // The virtual specifier shall only be used in declarations of 9198 // nonstatic class member functions that appear within a 9199 // member-specification of a class declaration; see 10.3. 9200 // 9201 if (isVirtual && !NewFD->isInvalidDecl()) { 9202 if (!isVirtualOkay) { 9203 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9204 diag::err_virtual_non_function); 9205 } else if (!CurContext->isRecord()) { 9206 // 'virtual' was specified outside of the class. 9207 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9208 diag::err_virtual_out_of_class) 9209 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9210 } else if (NewFD->getDescribedFunctionTemplate()) { 9211 // C++ [temp.mem]p3: 9212 // A member function template shall not be virtual. 9213 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9214 diag::err_virtual_member_function_template) 9215 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9216 } else { 9217 // Okay: Add virtual to the method. 9218 NewFD->setVirtualAsWritten(true); 9219 } 9220 9221 if (getLangOpts().CPlusPlus14 && 9222 NewFD->getReturnType()->isUndeducedType()) 9223 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9224 } 9225 9226 if (getLangOpts().CPlusPlus14 && 9227 (NewFD->isDependentContext() || 9228 (isFriend && CurContext->isDependentContext())) && 9229 NewFD->getReturnType()->isUndeducedType()) { 9230 // If the function template is referenced directly (for instance, as a 9231 // member of the current instantiation), pretend it has a dependent type. 9232 // This is not really justified by the standard, but is the only sane 9233 // thing to do. 9234 // FIXME: For a friend function, we have not marked the function as being 9235 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9236 const FunctionProtoType *FPT = 9237 NewFD->getType()->castAs<FunctionProtoType>(); 9238 QualType Result = 9239 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9240 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9241 FPT->getExtProtoInfo())); 9242 } 9243 9244 // C++ [dcl.fct.spec]p3: 9245 // The inline specifier shall not appear on a block scope function 9246 // declaration. 9247 if (isInline && !NewFD->isInvalidDecl()) { 9248 if (CurContext->isFunctionOrMethod()) { 9249 // 'inline' is not allowed on block scope function declaration. 9250 Diag(D.getDeclSpec().getInlineSpecLoc(), 9251 diag::err_inline_declaration_block_scope) << Name 9252 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9253 } 9254 } 9255 9256 // C++ [dcl.fct.spec]p6: 9257 // The explicit specifier shall be used only in the declaration of a 9258 // constructor or conversion function within its class definition; 9259 // see 12.3.1 and 12.3.2. 9260 if (hasExplicit && !NewFD->isInvalidDecl() && 9261 !isa<CXXDeductionGuideDecl>(NewFD)) { 9262 if (!CurContext->isRecord()) { 9263 // 'explicit' was specified outside of the class. 9264 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9265 diag::err_explicit_out_of_class) 9266 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9267 } else if (!isa<CXXConstructorDecl>(NewFD) && 9268 !isa<CXXConversionDecl>(NewFD)) { 9269 // 'explicit' was specified on a function that wasn't a constructor 9270 // or conversion function. 9271 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9272 diag::err_explicit_non_ctor_or_conv_function) 9273 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9274 } 9275 } 9276 9277 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9278 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9279 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9280 // are implicitly inline. 9281 NewFD->setImplicitlyInline(); 9282 9283 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9284 // be either constructors or to return a literal type. Therefore, 9285 // destructors cannot be declared constexpr. 9286 if (isa<CXXDestructorDecl>(NewFD) && 9287 (!getLangOpts().CPlusPlus20 || 9288 ConstexprKind == ConstexprSpecKind::Consteval)) { 9289 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9290 << static_cast<int>(ConstexprKind); 9291 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9292 ? ConstexprSpecKind::Unspecified 9293 : ConstexprSpecKind::Constexpr); 9294 } 9295 // C++20 [dcl.constexpr]p2: An allocation function, or a 9296 // deallocation function shall not be declared with the consteval 9297 // specifier. 9298 if (ConstexprKind == ConstexprSpecKind::Consteval && 9299 (NewFD->getOverloadedOperator() == OO_New || 9300 NewFD->getOverloadedOperator() == OO_Array_New || 9301 NewFD->getOverloadedOperator() == OO_Delete || 9302 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9303 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9304 diag::err_invalid_consteval_decl_kind) 9305 << NewFD; 9306 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9307 } 9308 } 9309 9310 // If __module_private__ was specified, mark the function accordingly. 9311 if (D.getDeclSpec().isModulePrivateSpecified()) { 9312 if (isFunctionTemplateSpecialization) { 9313 SourceLocation ModulePrivateLoc 9314 = D.getDeclSpec().getModulePrivateSpecLoc(); 9315 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9316 << 0 9317 << FixItHint::CreateRemoval(ModulePrivateLoc); 9318 } else { 9319 NewFD->setModulePrivate(); 9320 if (FunctionTemplate) 9321 FunctionTemplate->setModulePrivate(); 9322 } 9323 } 9324 9325 if (isFriend) { 9326 if (FunctionTemplate) { 9327 FunctionTemplate->setObjectOfFriendDecl(); 9328 FunctionTemplate->setAccess(AS_public); 9329 } 9330 NewFD->setObjectOfFriendDecl(); 9331 NewFD->setAccess(AS_public); 9332 } 9333 9334 // If a function is defined as defaulted or deleted, mark it as such now. 9335 // We'll do the relevant checks on defaulted / deleted functions later. 9336 switch (D.getFunctionDefinitionKind()) { 9337 case FunctionDefinitionKind::Declaration: 9338 case FunctionDefinitionKind::Definition: 9339 break; 9340 9341 case FunctionDefinitionKind::Defaulted: 9342 NewFD->setDefaulted(); 9343 break; 9344 9345 case FunctionDefinitionKind::Deleted: 9346 NewFD->setDeletedAsWritten(); 9347 break; 9348 } 9349 9350 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9351 D.isFunctionDefinition()) { 9352 // C++ [class.mfct]p2: 9353 // A member function may be defined (8.4) in its class definition, in 9354 // which case it is an inline member function (7.1.2) 9355 NewFD->setImplicitlyInline(); 9356 } 9357 9358 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9359 !CurContext->isRecord()) { 9360 // C++ [class.static]p1: 9361 // A data or function member of a class may be declared static 9362 // in a class definition, in which case it is a static member of 9363 // the class. 9364 9365 // Complain about the 'static' specifier if it's on an out-of-line 9366 // member function definition. 9367 9368 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9369 // member function template declaration and class member template 9370 // declaration (MSVC versions before 2015), warn about this. 9371 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9372 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9373 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9374 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9375 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9376 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9377 } 9378 9379 // C++11 [except.spec]p15: 9380 // A deallocation function with no exception-specification is treated 9381 // as if it were specified with noexcept(true). 9382 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9383 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9384 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9385 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9386 NewFD->setType(Context.getFunctionType( 9387 FPT->getReturnType(), FPT->getParamTypes(), 9388 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9389 } 9390 9391 // Filter out previous declarations that don't match the scope. 9392 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9393 D.getCXXScopeSpec().isNotEmpty() || 9394 isMemberSpecialization || 9395 isFunctionTemplateSpecialization); 9396 9397 // Handle GNU asm-label extension (encoded as an attribute). 9398 if (Expr *E = (Expr*) D.getAsmLabel()) { 9399 // The parser guarantees this is a string. 9400 StringLiteral *SE = cast<StringLiteral>(E); 9401 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9402 /*IsLiteralLabel=*/true, 9403 SE->getStrTokenLoc(0))); 9404 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9405 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9406 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9407 if (I != ExtnameUndeclaredIdentifiers.end()) { 9408 if (isDeclExternC(NewFD)) { 9409 NewFD->addAttr(I->second); 9410 ExtnameUndeclaredIdentifiers.erase(I); 9411 } else 9412 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9413 << /*Variable*/0 << NewFD; 9414 } 9415 } 9416 9417 // Copy the parameter declarations from the declarator D to the function 9418 // declaration NewFD, if they are available. First scavenge them into Params. 9419 SmallVector<ParmVarDecl*, 16> Params; 9420 unsigned FTIIdx; 9421 if (D.isFunctionDeclarator(FTIIdx)) { 9422 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9423 9424 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9425 // function that takes no arguments, not a function that takes a 9426 // single void argument. 9427 // We let through "const void" here because Sema::GetTypeForDeclarator 9428 // already checks for that case. 9429 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9430 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9431 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9432 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9433 Param->setDeclContext(NewFD); 9434 Params.push_back(Param); 9435 9436 if (Param->isInvalidDecl()) 9437 NewFD->setInvalidDecl(); 9438 } 9439 } 9440 9441 if (!getLangOpts().CPlusPlus) { 9442 // In C, find all the tag declarations from the prototype and move them 9443 // into the function DeclContext. Remove them from the surrounding tag 9444 // injection context of the function, which is typically but not always 9445 // the TU. 9446 DeclContext *PrototypeTagContext = 9447 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9448 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9449 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9450 9451 // We don't want to reparent enumerators. Look at their parent enum 9452 // instead. 9453 if (!TD) { 9454 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9455 TD = cast<EnumDecl>(ECD->getDeclContext()); 9456 } 9457 if (!TD) 9458 continue; 9459 DeclContext *TagDC = TD->getLexicalDeclContext(); 9460 if (!TagDC->containsDecl(TD)) 9461 continue; 9462 TagDC->removeDecl(TD); 9463 TD->setDeclContext(NewFD); 9464 NewFD->addDecl(TD); 9465 9466 // Preserve the lexical DeclContext if it is not the surrounding tag 9467 // injection context of the FD. In this example, the semantic context of 9468 // E will be f and the lexical context will be S, while both the 9469 // semantic and lexical contexts of S will be f: 9470 // void f(struct S { enum E { a } f; } s); 9471 if (TagDC != PrototypeTagContext) 9472 TD->setLexicalDeclContext(TagDC); 9473 } 9474 } 9475 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9476 // When we're declaring a function with a typedef, typeof, etc as in the 9477 // following example, we'll need to synthesize (unnamed) 9478 // parameters for use in the declaration. 9479 // 9480 // @code 9481 // typedef void fn(int); 9482 // fn f; 9483 // @endcode 9484 9485 // Synthesize a parameter for each argument type. 9486 for (const auto &AI : FT->param_types()) { 9487 ParmVarDecl *Param = 9488 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9489 Param->setScopeInfo(0, Params.size()); 9490 Params.push_back(Param); 9491 } 9492 } else { 9493 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9494 "Should not need args for typedef of non-prototype fn"); 9495 } 9496 9497 // Finally, we know we have the right number of parameters, install them. 9498 NewFD->setParams(Params); 9499 9500 if (D.getDeclSpec().isNoreturnSpecified()) 9501 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9502 D.getDeclSpec().getNoreturnSpecLoc(), 9503 AttributeCommonInfo::AS_Keyword)); 9504 9505 // Functions returning a variably modified type violate C99 6.7.5.2p2 9506 // because all functions have linkage. 9507 if (!NewFD->isInvalidDecl() && 9508 NewFD->getReturnType()->isVariablyModifiedType()) { 9509 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9510 NewFD->setInvalidDecl(); 9511 } 9512 9513 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9514 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9515 !NewFD->hasAttr<SectionAttr>()) 9516 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9517 Context, PragmaClangTextSection.SectionName, 9518 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9519 9520 // Apply an implicit SectionAttr if #pragma code_seg is active. 9521 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9522 !NewFD->hasAttr<SectionAttr>()) { 9523 NewFD->addAttr(SectionAttr::CreateImplicit( 9524 Context, CodeSegStack.CurrentValue->getString(), 9525 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9526 SectionAttr::Declspec_allocate)); 9527 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9528 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9529 ASTContext::PSF_Read, 9530 NewFD)) 9531 NewFD->dropAttr<SectionAttr>(); 9532 } 9533 9534 // Apply an implicit CodeSegAttr from class declspec or 9535 // apply an implicit SectionAttr from #pragma code_seg if active. 9536 if (!NewFD->hasAttr<CodeSegAttr>()) { 9537 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9538 D.isFunctionDefinition())) { 9539 NewFD->addAttr(SAttr); 9540 } 9541 } 9542 9543 // Handle attributes. 9544 ProcessDeclAttributes(S, NewFD, D); 9545 9546 if (getLangOpts().OpenCL) { 9547 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9548 // type declaration will generate a compilation error. 9549 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9550 if (AddressSpace != LangAS::Default) { 9551 Diag(NewFD->getLocation(), 9552 diag::err_opencl_return_value_with_address_space); 9553 NewFD->setInvalidDecl(); 9554 } 9555 } 9556 9557 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) 9558 checkDeviceDecl(NewFD, D.getBeginLoc()); 9559 9560 if (!getLangOpts().CPlusPlus) { 9561 // Perform semantic checking on the function declaration. 9562 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9563 CheckMain(NewFD, D.getDeclSpec()); 9564 9565 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9566 CheckMSVCRTEntryPoint(NewFD); 9567 9568 if (!NewFD->isInvalidDecl()) 9569 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9570 isMemberSpecialization)); 9571 else if (!Previous.empty()) 9572 // Recover gracefully from an invalid redeclaration. 9573 D.setRedeclaration(true); 9574 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9575 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9576 "previous declaration set still overloaded"); 9577 9578 // Diagnose no-prototype function declarations with calling conventions that 9579 // don't support variadic calls. Only do this in C and do it after merging 9580 // possibly prototyped redeclarations. 9581 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9582 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9583 CallingConv CC = FT->getExtInfo().getCC(); 9584 if (!supportsVariadicCall(CC)) { 9585 // Windows system headers sometimes accidentally use stdcall without 9586 // (void) parameters, so we relax this to a warning. 9587 int DiagID = 9588 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9589 Diag(NewFD->getLocation(), DiagID) 9590 << FunctionType::getNameForCallConv(CC); 9591 } 9592 } 9593 9594 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9595 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9596 checkNonTrivialCUnion(NewFD->getReturnType(), 9597 NewFD->getReturnTypeSourceRange().getBegin(), 9598 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9599 } else { 9600 // C++11 [replacement.functions]p3: 9601 // The program's definitions shall not be specified as inline. 9602 // 9603 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9604 // 9605 // Suppress the diagnostic if the function is __attribute__((used)), since 9606 // that forces an external definition to be emitted. 9607 if (D.getDeclSpec().isInlineSpecified() && 9608 NewFD->isReplaceableGlobalAllocationFunction() && 9609 !NewFD->hasAttr<UsedAttr>()) 9610 Diag(D.getDeclSpec().getInlineSpecLoc(), 9611 diag::ext_operator_new_delete_declared_inline) 9612 << NewFD->getDeclName(); 9613 9614 // If the declarator is a template-id, translate the parser's template 9615 // argument list into our AST format. 9616 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9617 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9618 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9619 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9620 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9621 TemplateId->NumArgs); 9622 translateTemplateArguments(TemplateArgsPtr, 9623 TemplateArgs); 9624 9625 HasExplicitTemplateArgs = true; 9626 9627 if (NewFD->isInvalidDecl()) { 9628 HasExplicitTemplateArgs = false; 9629 } else if (FunctionTemplate) { 9630 // Function template with explicit template arguments. 9631 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9632 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9633 9634 HasExplicitTemplateArgs = false; 9635 } else { 9636 assert((isFunctionTemplateSpecialization || 9637 D.getDeclSpec().isFriendSpecified()) && 9638 "should have a 'template<>' for this decl"); 9639 // "friend void foo<>(int);" is an implicit specialization decl. 9640 isFunctionTemplateSpecialization = true; 9641 } 9642 } else if (isFriend && isFunctionTemplateSpecialization) { 9643 // This combination is only possible in a recovery case; the user 9644 // wrote something like: 9645 // template <> friend void foo(int); 9646 // which we're recovering from as if the user had written: 9647 // friend void foo<>(int); 9648 // Go ahead and fake up a template id. 9649 HasExplicitTemplateArgs = true; 9650 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9651 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9652 } 9653 9654 // We do not add HD attributes to specializations here because 9655 // they may have different constexpr-ness compared to their 9656 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9657 // may end up with different effective targets. Instead, a 9658 // specialization inherits its target attributes from its template 9659 // in the CheckFunctionTemplateSpecialization() call below. 9660 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9661 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9662 9663 // If it's a friend (and only if it's a friend), it's possible 9664 // that either the specialized function type or the specialized 9665 // template is dependent, and therefore matching will fail. In 9666 // this case, don't check the specialization yet. 9667 if (isFunctionTemplateSpecialization && isFriend && 9668 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9669 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 9670 TemplateArgs.arguments()))) { 9671 assert(HasExplicitTemplateArgs && 9672 "friend function specialization without template args"); 9673 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9674 Previous)) 9675 NewFD->setInvalidDecl(); 9676 } else if (isFunctionTemplateSpecialization) { 9677 if (CurContext->isDependentContext() && CurContext->isRecord() 9678 && !isFriend) { 9679 isDependentClassScopeExplicitSpecialization = true; 9680 } else if (!NewFD->isInvalidDecl() && 9681 CheckFunctionTemplateSpecialization( 9682 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9683 Previous)) 9684 NewFD->setInvalidDecl(); 9685 9686 // C++ [dcl.stc]p1: 9687 // A storage-class-specifier shall not be specified in an explicit 9688 // specialization (14.7.3) 9689 FunctionTemplateSpecializationInfo *Info = 9690 NewFD->getTemplateSpecializationInfo(); 9691 if (Info && SC != SC_None) { 9692 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9693 Diag(NewFD->getLocation(), 9694 diag::err_explicit_specialization_inconsistent_storage_class) 9695 << SC 9696 << FixItHint::CreateRemoval( 9697 D.getDeclSpec().getStorageClassSpecLoc()); 9698 9699 else 9700 Diag(NewFD->getLocation(), 9701 diag::ext_explicit_specialization_storage_class) 9702 << FixItHint::CreateRemoval( 9703 D.getDeclSpec().getStorageClassSpecLoc()); 9704 } 9705 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9706 if (CheckMemberSpecialization(NewFD, Previous)) 9707 NewFD->setInvalidDecl(); 9708 } 9709 9710 // Perform semantic checking on the function declaration. 9711 if (!isDependentClassScopeExplicitSpecialization) { 9712 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9713 CheckMain(NewFD, D.getDeclSpec()); 9714 9715 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9716 CheckMSVCRTEntryPoint(NewFD); 9717 9718 if (!NewFD->isInvalidDecl()) 9719 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9720 isMemberSpecialization)); 9721 else if (!Previous.empty()) 9722 // Recover gracefully from an invalid redeclaration. 9723 D.setRedeclaration(true); 9724 } 9725 9726 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9727 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9728 "previous declaration set still overloaded"); 9729 9730 NamedDecl *PrincipalDecl = (FunctionTemplate 9731 ? cast<NamedDecl>(FunctionTemplate) 9732 : NewFD); 9733 9734 if (isFriend && NewFD->getPreviousDecl()) { 9735 AccessSpecifier Access = AS_public; 9736 if (!NewFD->isInvalidDecl()) 9737 Access = NewFD->getPreviousDecl()->getAccess(); 9738 9739 NewFD->setAccess(Access); 9740 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9741 } 9742 9743 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9744 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9745 PrincipalDecl->setNonMemberOperator(); 9746 9747 // If we have a function template, check the template parameter 9748 // list. This will check and merge default template arguments. 9749 if (FunctionTemplate) { 9750 FunctionTemplateDecl *PrevTemplate = 9751 FunctionTemplate->getPreviousDecl(); 9752 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9753 PrevTemplate ? PrevTemplate->getTemplateParameters() 9754 : nullptr, 9755 D.getDeclSpec().isFriendSpecified() 9756 ? (D.isFunctionDefinition() 9757 ? TPC_FriendFunctionTemplateDefinition 9758 : TPC_FriendFunctionTemplate) 9759 : (D.getCXXScopeSpec().isSet() && 9760 DC && DC->isRecord() && 9761 DC->isDependentContext()) 9762 ? TPC_ClassTemplateMember 9763 : TPC_FunctionTemplate); 9764 } 9765 9766 if (NewFD->isInvalidDecl()) { 9767 // Ignore all the rest of this. 9768 } else if (!D.isRedeclaration()) { 9769 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9770 AddToScope }; 9771 // Fake up an access specifier if it's supposed to be a class member. 9772 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9773 NewFD->setAccess(AS_public); 9774 9775 // Qualified decls generally require a previous declaration. 9776 if (D.getCXXScopeSpec().isSet()) { 9777 // ...with the major exception of templated-scope or 9778 // dependent-scope friend declarations. 9779 9780 // TODO: we currently also suppress this check in dependent 9781 // contexts because (1) the parameter depth will be off when 9782 // matching friend templates and (2) we might actually be 9783 // selecting a friend based on a dependent factor. But there 9784 // are situations where these conditions don't apply and we 9785 // can actually do this check immediately. 9786 // 9787 // Unless the scope is dependent, it's always an error if qualified 9788 // redeclaration lookup found nothing at all. Diagnose that now; 9789 // nothing will diagnose that error later. 9790 if (isFriend && 9791 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9792 (!Previous.empty() && CurContext->isDependentContext()))) { 9793 // ignore these 9794 } else if (NewFD->isCPUDispatchMultiVersion() || 9795 NewFD->isCPUSpecificMultiVersion()) { 9796 // ignore this, we allow the redeclaration behavior here to create new 9797 // versions of the function. 9798 } else { 9799 // The user tried to provide an out-of-line definition for a 9800 // function that is a member of a class or namespace, but there 9801 // was no such member function declared (C++ [class.mfct]p2, 9802 // C++ [namespace.memdef]p2). For example: 9803 // 9804 // class X { 9805 // void f() const; 9806 // }; 9807 // 9808 // void X::f() { } // ill-formed 9809 // 9810 // Complain about this problem, and attempt to suggest close 9811 // matches (e.g., those that differ only in cv-qualifiers and 9812 // whether the parameter types are references). 9813 9814 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9815 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9816 AddToScope = ExtraArgs.AddToScope; 9817 return Result; 9818 } 9819 } 9820 9821 // Unqualified local friend declarations are required to resolve 9822 // to something. 9823 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9824 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9825 *this, Previous, NewFD, ExtraArgs, true, S)) { 9826 AddToScope = ExtraArgs.AddToScope; 9827 return Result; 9828 } 9829 } 9830 } else if (!D.isFunctionDefinition() && 9831 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9832 !isFriend && !isFunctionTemplateSpecialization && 9833 !isMemberSpecialization) { 9834 // An out-of-line member function declaration must also be a 9835 // definition (C++ [class.mfct]p2). 9836 // Note that this is not the case for explicit specializations of 9837 // function templates or member functions of class templates, per 9838 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9839 // extension for compatibility with old SWIG code which likes to 9840 // generate them. 9841 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9842 << D.getCXXScopeSpec().getRange(); 9843 } 9844 } 9845 9846 // If this is the first declaration of a library builtin function, add 9847 // attributes as appropriate. 9848 if (!D.isRedeclaration() && 9849 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 9850 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 9851 if (unsigned BuiltinID = II->getBuiltinID()) { 9852 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 9853 // Validate the type matches unless this builtin is specified as 9854 // matching regardless of its declared type. 9855 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 9856 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9857 } else { 9858 ASTContext::GetBuiltinTypeError Error; 9859 LookupNecessaryTypesForBuiltin(S, BuiltinID); 9860 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 9861 9862 if (!Error && !BuiltinType.isNull() && 9863 Context.hasSameFunctionTypeIgnoringExceptionSpec( 9864 NewFD->getType(), BuiltinType)) 9865 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9866 } 9867 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 9868 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9869 // FIXME: We should consider this a builtin only in the std namespace. 9870 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9871 } 9872 } 9873 } 9874 } 9875 9876 ProcessPragmaWeak(S, NewFD); 9877 checkAttributesAfterMerging(*this, *NewFD); 9878 9879 AddKnownFunctionAttributes(NewFD); 9880 9881 if (NewFD->hasAttr<OverloadableAttr>() && 9882 !NewFD->getType()->getAs<FunctionProtoType>()) { 9883 Diag(NewFD->getLocation(), 9884 diag::err_attribute_overloadable_no_prototype) 9885 << NewFD; 9886 9887 // Turn this into a variadic function with no parameters. 9888 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9889 FunctionProtoType::ExtProtoInfo EPI( 9890 Context.getDefaultCallingConvention(true, false)); 9891 EPI.Variadic = true; 9892 EPI.ExtInfo = FT->getExtInfo(); 9893 9894 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9895 NewFD->setType(R); 9896 } 9897 9898 // If there's a #pragma GCC visibility in scope, and this isn't a class 9899 // member, set the visibility of this function. 9900 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9901 AddPushedVisibilityAttribute(NewFD); 9902 9903 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9904 // marking the function. 9905 AddCFAuditedAttribute(NewFD); 9906 9907 // If this is a function definition, check if we have to apply optnone due to 9908 // a pragma. 9909 if(D.isFunctionDefinition()) 9910 AddRangeBasedOptnone(NewFD); 9911 9912 // If this is the first declaration of an extern C variable, update 9913 // the map of such variables. 9914 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9915 isIncompleteDeclExternC(*this, NewFD)) 9916 RegisterLocallyScopedExternCDecl(NewFD, S); 9917 9918 // Set this FunctionDecl's range up to the right paren. 9919 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9920 9921 if (D.isRedeclaration() && !Previous.empty()) { 9922 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9923 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9924 isMemberSpecialization || 9925 isFunctionTemplateSpecialization, 9926 D.isFunctionDefinition()); 9927 } 9928 9929 if (getLangOpts().CUDA) { 9930 IdentifierInfo *II = NewFD->getIdentifier(); 9931 if (II && II->isStr(getCudaConfigureFuncName()) && 9932 !NewFD->isInvalidDecl() && 9933 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9934 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) 9935 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9936 << getCudaConfigureFuncName(); 9937 Context.setcudaConfigureCallDecl(NewFD); 9938 } 9939 9940 // Variadic functions, other than a *declaration* of printf, are not allowed 9941 // in device-side CUDA code, unless someone passed 9942 // -fcuda-allow-variadic-functions. 9943 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9944 (NewFD->hasAttr<CUDADeviceAttr>() || 9945 NewFD->hasAttr<CUDAGlobalAttr>()) && 9946 !(II && II->isStr("printf") && NewFD->isExternC() && 9947 !D.isFunctionDefinition())) { 9948 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9949 } 9950 } 9951 9952 MarkUnusedFileScopedDecl(NewFD); 9953 9954 9955 9956 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9957 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9958 if ((getLangOpts().OpenCLVersion >= 120) 9959 && (SC == SC_Static)) { 9960 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9961 D.setInvalidType(); 9962 } 9963 9964 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9965 if (!NewFD->getReturnType()->isVoidType()) { 9966 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9967 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9968 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9969 : FixItHint()); 9970 D.setInvalidType(); 9971 } 9972 9973 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9974 for (auto Param : NewFD->parameters()) 9975 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9976 9977 if (getLangOpts().OpenCLCPlusPlus) { 9978 if (DC->isRecord()) { 9979 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9980 D.setInvalidType(); 9981 } 9982 if (FunctionTemplate) { 9983 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9984 D.setInvalidType(); 9985 } 9986 } 9987 } 9988 9989 if (getLangOpts().CPlusPlus) { 9990 if (FunctionTemplate) { 9991 if (NewFD->isInvalidDecl()) 9992 FunctionTemplate->setInvalidDecl(); 9993 return FunctionTemplate; 9994 } 9995 9996 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9997 CompleteMemberSpecialization(NewFD, Previous); 9998 } 9999 10000 for (const ParmVarDecl *Param : NewFD->parameters()) { 10001 QualType PT = Param->getType(); 10002 10003 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 10004 // types. 10005 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 10006 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 10007 QualType ElemTy = PipeTy->getElementType(); 10008 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 10009 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 10010 D.setInvalidType(); 10011 } 10012 } 10013 } 10014 } 10015 10016 // Here we have an function template explicit specialization at class scope. 10017 // The actual specialization will be postponed to template instatiation 10018 // time via the ClassScopeFunctionSpecializationDecl node. 10019 if (isDependentClassScopeExplicitSpecialization) { 10020 ClassScopeFunctionSpecializationDecl *NewSpec = 10021 ClassScopeFunctionSpecializationDecl::Create( 10022 Context, CurContext, NewFD->getLocation(), 10023 cast<CXXMethodDecl>(NewFD), 10024 HasExplicitTemplateArgs, TemplateArgs); 10025 CurContext->addDecl(NewSpec); 10026 AddToScope = false; 10027 } 10028 10029 // Diagnose availability attributes. Availability cannot be used on functions 10030 // that are run during load/unload. 10031 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 10032 if (NewFD->hasAttr<ConstructorAttr>()) { 10033 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10034 << 1; 10035 NewFD->dropAttr<AvailabilityAttr>(); 10036 } 10037 if (NewFD->hasAttr<DestructorAttr>()) { 10038 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10039 << 2; 10040 NewFD->dropAttr<AvailabilityAttr>(); 10041 } 10042 } 10043 10044 // Diagnose no_builtin attribute on function declaration that are not a 10045 // definition. 10046 // FIXME: We should really be doing this in 10047 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 10048 // the FunctionDecl and at this point of the code 10049 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 10050 // because Sema::ActOnStartOfFunctionDef has not been called yet. 10051 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 10052 switch (D.getFunctionDefinitionKind()) { 10053 case FunctionDefinitionKind::Defaulted: 10054 case FunctionDefinitionKind::Deleted: 10055 Diag(NBA->getLocation(), 10056 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 10057 << NBA->getSpelling(); 10058 break; 10059 case FunctionDefinitionKind::Declaration: 10060 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 10061 << NBA->getSpelling(); 10062 break; 10063 case FunctionDefinitionKind::Definition: 10064 break; 10065 } 10066 10067 return NewFD; 10068 } 10069 10070 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 10071 /// when __declspec(code_seg) "is applied to a class, all member functions of 10072 /// the class and nested classes -- this includes compiler-generated special 10073 /// member functions -- are put in the specified segment." 10074 /// The actual behavior is a little more complicated. The Microsoft compiler 10075 /// won't check outer classes if there is an active value from #pragma code_seg. 10076 /// The CodeSeg is always applied from the direct parent but only from outer 10077 /// classes when the #pragma code_seg stack is empty. See: 10078 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 10079 /// available since MS has removed the page. 10080 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 10081 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 10082 if (!Method) 10083 return nullptr; 10084 const CXXRecordDecl *Parent = Method->getParent(); 10085 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10086 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10087 NewAttr->setImplicit(true); 10088 return NewAttr; 10089 } 10090 10091 // The Microsoft compiler won't check outer classes for the CodeSeg 10092 // when the #pragma code_seg stack is active. 10093 if (S.CodeSegStack.CurrentValue) 10094 return nullptr; 10095 10096 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 10097 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10098 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10099 NewAttr->setImplicit(true); 10100 return NewAttr; 10101 } 10102 } 10103 return nullptr; 10104 } 10105 10106 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 10107 /// containing class. Otherwise it will return implicit SectionAttr if the 10108 /// function is a definition and there is an active value on CodeSegStack 10109 /// (from the current #pragma code-seg value). 10110 /// 10111 /// \param FD Function being declared. 10112 /// \param IsDefinition Whether it is a definition or just a declarartion. 10113 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 10114 /// nullptr if no attribute should be added. 10115 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 10116 bool IsDefinition) { 10117 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 10118 return A; 10119 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 10120 CodeSegStack.CurrentValue) 10121 return SectionAttr::CreateImplicit( 10122 getASTContext(), CodeSegStack.CurrentValue->getString(), 10123 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 10124 SectionAttr::Declspec_allocate); 10125 return nullptr; 10126 } 10127 10128 /// Determines if we can perform a correct type check for \p D as a 10129 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 10130 /// best-effort check. 10131 /// 10132 /// \param NewD The new declaration. 10133 /// \param OldD The old declaration. 10134 /// \param NewT The portion of the type of the new declaration to check. 10135 /// \param OldT The portion of the type of the old declaration to check. 10136 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 10137 QualType NewT, QualType OldT) { 10138 if (!NewD->getLexicalDeclContext()->isDependentContext()) 10139 return true; 10140 10141 // For dependently-typed local extern declarations and friends, we can't 10142 // perform a correct type check in general until instantiation: 10143 // 10144 // int f(); 10145 // template<typename T> void g() { T f(); } 10146 // 10147 // (valid if g() is only instantiated with T = int). 10148 if (NewT->isDependentType() && 10149 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10150 return false; 10151 10152 // Similarly, if the previous declaration was a dependent local extern 10153 // declaration, we don't really know its type yet. 10154 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10155 return false; 10156 10157 return true; 10158 } 10159 10160 /// Checks if the new declaration declared in dependent context must be 10161 /// put in the same redeclaration chain as the specified declaration. 10162 /// 10163 /// \param D Declaration that is checked. 10164 /// \param PrevDecl Previous declaration found with proper lookup method for the 10165 /// same declaration name. 10166 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10167 /// belongs to. 10168 /// 10169 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10170 if (!D->getLexicalDeclContext()->isDependentContext()) 10171 return true; 10172 10173 // Don't chain dependent friend function definitions until instantiation, to 10174 // permit cases like 10175 // 10176 // void func(); 10177 // template<typename T> class C1 { friend void func() {} }; 10178 // template<typename T> class C2 { friend void func() {} }; 10179 // 10180 // ... which is valid if only one of C1 and C2 is ever instantiated. 10181 // 10182 // FIXME: This need only apply to function definitions. For now, we proxy 10183 // this by checking for a file-scope function. We do not want this to apply 10184 // to friend declarations nominating member functions, because that gets in 10185 // the way of access checks. 10186 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10187 return false; 10188 10189 auto *VD = dyn_cast<ValueDecl>(D); 10190 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10191 return !VD || !PrevVD || 10192 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10193 PrevVD->getType()); 10194 } 10195 10196 /// Check the target attribute of the function for MultiVersion 10197 /// validity. 10198 /// 10199 /// Returns true if there was an error, false otherwise. 10200 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10201 const auto *TA = FD->getAttr<TargetAttr>(); 10202 assert(TA && "MultiVersion Candidate requires a target attribute"); 10203 ParsedTargetAttr ParseInfo = TA->parse(); 10204 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10205 enum ErrType { Feature = 0, Architecture = 1 }; 10206 10207 if (!ParseInfo.Architecture.empty() && 10208 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10209 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10210 << Architecture << ParseInfo.Architecture; 10211 return true; 10212 } 10213 10214 for (const auto &Feat : ParseInfo.Features) { 10215 auto BareFeat = StringRef{Feat}.substr(1); 10216 if (Feat[0] == '-') { 10217 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10218 << Feature << ("no-" + BareFeat).str(); 10219 return true; 10220 } 10221 10222 if (!TargetInfo.validateCpuSupports(BareFeat) || 10223 !TargetInfo.isValidFeatureName(BareFeat)) { 10224 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10225 << Feature << BareFeat; 10226 return true; 10227 } 10228 } 10229 return false; 10230 } 10231 10232 // Provide a white-list of attributes that are allowed to be combined with 10233 // multiversion functions. 10234 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10235 MultiVersionKind MVType) { 10236 // Note: this list/diagnosis must match the list in 10237 // checkMultiversionAttributesAllSame. 10238 switch (Kind) { 10239 default: 10240 return false; 10241 case attr::Used: 10242 return MVType == MultiVersionKind::Target; 10243 case attr::NonNull: 10244 case attr::NoThrow: 10245 return true; 10246 } 10247 } 10248 10249 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10250 const FunctionDecl *FD, 10251 const FunctionDecl *CausedFD, 10252 MultiVersionKind MVType) { 10253 bool IsCPUSpecificCPUDispatchMVType = 10254 MVType == MultiVersionKind::CPUDispatch || 10255 MVType == MultiVersionKind::CPUSpecific; 10256 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType]( 10257 Sema &S, const Attr *A) { 10258 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10259 << IsCPUSpecificCPUDispatchMVType << A; 10260 if (CausedFD) 10261 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10262 return true; 10263 }; 10264 10265 for (const Attr *A : FD->attrs()) { 10266 switch (A->getKind()) { 10267 case attr::CPUDispatch: 10268 case attr::CPUSpecific: 10269 if (MVType != MultiVersionKind::CPUDispatch && 10270 MVType != MultiVersionKind::CPUSpecific) 10271 return Diagnose(S, A); 10272 break; 10273 case attr::Target: 10274 if (MVType != MultiVersionKind::Target) 10275 return Diagnose(S, A); 10276 break; 10277 default: 10278 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10279 return Diagnose(S, A); 10280 break; 10281 } 10282 } 10283 return false; 10284 } 10285 10286 bool Sema::areMultiversionVariantFunctionsCompatible( 10287 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10288 const PartialDiagnostic &NoProtoDiagID, 10289 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10290 const PartialDiagnosticAt &NoSupportDiagIDAt, 10291 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10292 bool ConstexprSupported, bool CLinkageMayDiffer) { 10293 enum DoesntSupport { 10294 FuncTemplates = 0, 10295 VirtFuncs = 1, 10296 DeducedReturn = 2, 10297 Constructors = 3, 10298 Destructors = 4, 10299 DeletedFuncs = 5, 10300 DefaultedFuncs = 6, 10301 ConstexprFuncs = 7, 10302 ConstevalFuncs = 8, 10303 }; 10304 enum Different { 10305 CallingConv = 0, 10306 ReturnType = 1, 10307 ConstexprSpec = 2, 10308 InlineSpec = 3, 10309 StorageClass = 4, 10310 Linkage = 5, 10311 }; 10312 10313 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10314 !OldFD->getType()->getAs<FunctionProtoType>()) { 10315 Diag(OldFD->getLocation(), NoProtoDiagID); 10316 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10317 return true; 10318 } 10319 10320 if (NoProtoDiagID.getDiagID() != 0 && 10321 !NewFD->getType()->getAs<FunctionProtoType>()) 10322 return Diag(NewFD->getLocation(), NoProtoDiagID); 10323 10324 if (!TemplatesSupported && 10325 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10326 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10327 << FuncTemplates; 10328 10329 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10330 if (NewCXXFD->isVirtual()) 10331 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10332 << VirtFuncs; 10333 10334 if (isa<CXXConstructorDecl>(NewCXXFD)) 10335 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10336 << Constructors; 10337 10338 if (isa<CXXDestructorDecl>(NewCXXFD)) 10339 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10340 << Destructors; 10341 } 10342 10343 if (NewFD->isDeleted()) 10344 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10345 << DeletedFuncs; 10346 10347 if (NewFD->isDefaulted()) 10348 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10349 << DefaultedFuncs; 10350 10351 if (!ConstexprSupported && NewFD->isConstexpr()) 10352 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10353 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10354 10355 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10356 const auto *NewType = cast<FunctionType>(NewQType); 10357 QualType NewReturnType = NewType->getReturnType(); 10358 10359 if (NewReturnType->isUndeducedType()) 10360 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10361 << DeducedReturn; 10362 10363 // Ensure the return type is identical. 10364 if (OldFD) { 10365 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10366 const auto *OldType = cast<FunctionType>(OldQType); 10367 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10368 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10369 10370 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10371 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10372 10373 QualType OldReturnType = OldType->getReturnType(); 10374 10375 if (OldReturnType != NewReturnType) 10376 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10377 10378 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10379 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10380 10381 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10382 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10383 10384 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10385 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10386 10387 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10388 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10389 10390 if (CheckEquivalentExceptionSpec( 10391 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10392 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10393 return true; 10394 } 10395 return false; 10396 } 10397 10398 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10399 const FunctionDecl *NewFD, 10400 bool CausesMV, 10401 MultiVersionKind MVType) { 10402 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10403 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10404 if (OldFD) 10405 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10406 return true; 10407 } 10408 10409 bool IsCPUSpecificCPUDispatchMVType = 10410 MVType == MultiVersionKind::CPUDispatch || 10411 MVType == MultiVersionKind::CPUSpecific; 10412 10413 if (CausesMV && OldFD && 10414 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType)) 10415 return true; 10416 10417 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType)) 10418 return true; 10419 10420 // Only allow transition to MultiVersion if it hasn't been used. 10421 if (OldFD && CausesMV && OldFD->isUsed(false)) 10422 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10423 10424 return S.areMultiversionVariantFunctionsCompatible( 10425 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10426 PartialDiagnosticAt(NewFD->getLocation(), 10427 S.PDiag(diag::note_multiversioning_caused_here)), 10428 PartialDiagnosticAt(NewFD->getLocation(), 10429 S.PDiag(diag::err_multiversion_doesnt_support) 10430 << IsCPUSpecificCPUDispatchMVType), 10431 PartialDiagnosticAt(NewFD->getLocation(), 10432 S.PDiag(diag::err_multiversion_diff)), 10433 /*TemplatesSupported=*/false, 10434 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10435 /*CLinkageMayDiffer=*/false); 10436 } 10437 10438 /// Check the validity of a multiversion function declaration that is the 10439 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10440 /// 10441 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10442 /// 10443 /// Returns true if there was an error, false otherwise. 10444 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10445 MultiVersionKind MVType, 10446 const TargetAttr *TA) { 10447 assert(MVType != MultiVersionKind::None && 10448 "Function lacks multiversion attribute"); 10449 10450 // Target only causes MV if it is default, otherwise this is a normal 10451 // function. 10452 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10453 return false; 10454 10455 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10456 FD->setInvalidDecl(); 10457 return true; 10458 } 10459 10460 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10461 FD->setInvalidDecl(); 10462 return true; 10463 } 10464 10465 FD->setIsMultiVersion(); 10466 return false; 10467 } 10468 10469 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10470 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10471 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10472 return true; 10473 } 10474 10475 return false; 10476 } 10477 10478 static bool CheckTargetCausesMultiVersioning( 10479 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10480 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10481 LookupResult &Previous) { 10482 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10483 ParsedTargetAttr NewParsed = NewTA->parse(); 10484 // Sort order doesn't matter, it just needs to be consistent. 10485 llvm::sort(NewParsed.Features); 10486 10487 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10488 // to change, this is a simple redeclaration. 10489 if (!NewTA->isDefaultVersion() && 10490 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10491 return false; 10492 10493 // Otherwise, this decl causes MultiVersioning. 10494 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10495 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10496 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10497 NewFD->setInvalidDecl(); 10498 return true; 10499 } 10500 10501 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10502 MultiVersionKind::Target)) { 10503 NewFD->setInvalidDecl(); 10504 return true; 10505 } 10506 10507 if (CheckMultiVersionValue(S, NewFD)) { 10508 NewFD->setInvalidDecl(); 10509 return true; 10510 } 10511 10512 // If this is 'default', permit the forward declaration. 10513 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10514 Redeclaration = true; 10515 OldDecl = OldFD; 10516 OldFD->setIsMultiVersion(); 10517 NewFD->setIsMultiVersion(); 10518 return false; 10519 } 10520 10521 if (CheckMultiVersionValue(S, OldFD)) { 10522 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10523 NewFD->setInvalidDecl(); 10524 return true; 10525 } 10526 10527 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10528 10529 if (OldParsed == NewParsed) { 10530 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10531 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10532 NewFD->setInvalidDecl(); 10533 return true; 10534 } 10535 10536 for (const auto *FD : OldFD->redecls()) { 10537 const auto *CurTA = FD->getAttr<TargetAttr>(); 10538 // We allow forward declarations before ANY multiversioning attributes, but 10539 // nothing after the fact. 10540 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10541 (!CurTA || CurTA->isInherited())) { 10542 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10543 << 0; 10544 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10545 NewFD->setInvalidDecl(); 10546 return true; 10547 } 10548 } 10549 10550 OldFD->setIsMultiVersion(); 10551 NewFD->setIsMultiVersion(); 10552 Redeclaration = false; 10553 MergeTypeWithPrevious = false; 10554 OldDecl = nullptr; 10555 Previous.clear(); 10556 return false; 10557 } 10558 10559 /// Check the validity of a new function declaration being added to an existing 10560 /// multiversioned declaration collection. 10561 static bool CheckMultiVersionAdditionalDecl( 10562 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10563 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10564 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10565 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10566 LookupResult &Previous) { 10567 10568 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10569 // Disallow mixing of multiversioning types. 10570 if ((OldMVType == MultiVersionKind::Target && 10571 NewMVType != MultiVersionKind::Target) || 10572 (NewMVType == MultiVersionKind::Target && 10573 OldMVType != MultiVersionKind::Target)) { 10574 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10575 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10576 NewFD->setInvalidDecl(); 10577 return true; 10578 } 10579 10580 ParsedTargetAttr NewParsed; 10581 if (NewTA) { 10582 NewParsed = NewTA->parse(); 10583 llvm::sort(NewParsed.Features); 10584 } 10585 10586 bool UseMemberUsingDeclRules = 10587 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10588 10589 // Next, check ALL non-overloads to see if this is a redeclaration of a 10590 // previous member of the MultiVersion set. 10591 for (NamedDecl *ND : Previous) { 10592 FunctionDecl *CurFD = ND->getAsFunction(); 10593 if (!CurFD) 10594 continue; 10595 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10596 continue; 10597 10598 if (NewMVType == MultiVersionKind::Target) { 10599 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10600 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10601 NewFD->setIsMultiVersion(); 10602 Redeclaration = true; 10603 OldDecl = ND; 10604 return false; 10605 } 10606 10607 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10608 if (CurParsed == NewParsed) { 10609 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10610 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10611 NewFD->setInvalidDecl(); 10612 return true; 10613 } 10614 } else { 10615 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10616 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10617 // Handle CPUDispatch/CPUSpecific versions. 10618 // Only 1 CPUDispatch function is allowed, this will make it go through 10619 // the redeclaration errors. 10620 if (NewMVType == MultiVersionKind::CPUDispatch && 10621 CurFD->hasAttr<CPUDispatchAttr>()) { 10622 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10623 std::equal( 10624 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10625 NewCPUDisp->cpus_begin(), 10626 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10627 return Cur->getName() == New->getName(); 10628 })) { 10629 NewFD->setIsMultiVersion(); 10630 Redeclaration = true; 10631 OldDecl = ND; 10632 return false; 10633 } 10634 10635 // If the declarations don't match, this is an error condition. 10636 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10637 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10638 NewFD->setInvalidDecl(); 10639 return true; 10640 } 10641 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10642 10643 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10644 std::equal( 10645 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10646 NewCPUSpec->cpus_begin(), 10647 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10648 return Cur->getName() == New->getName(); 10649 })) { 10650 NewFD->setIsMultiVersion(); 10651 Redeclaration = true; 10652 OldDecl = ND; 10653 return false; 10654 } 10655 10656 // Only 1 version of CPUSpecific is allowed for each CPU. 10657 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10658 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10659 if (CurII == NewII) { 10660 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10661 << NewII; 10662 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10663 NewFD->setInvalidDecl(); 10664 return true; 10665 } 10666 } 10667 } 10668 } 10669 // If the two decls aren't the same MVType, there is no possible error 10670 // condition. 10671 } 10672 } 10673 10674 // Else, this is simply a non-redecl case. Checking the 'value' is only 10675 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10676 // handled in the attribute adding step. 10677 if (NewMVType == MultiVersionKind::Target && 10678 CheckMultiVersionValue(S, NewFD)) { 10679 NewFD->setInvalidDecl(); 10680 return true; 10681 } 10682 10683 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10684 !OldFD->isMultiVersion(), NewMVType)) { 10685 NewFD->setInvalidDecl(); 10686 return true; 10687 } 10688 10689 // Permit forward declarations in the case where these two are compatible. 10690 if (!OldFD->isMultiVersion()) { 10691 OldFD->setIsMultiVersion(); 10692 NewFD->setIsMultiVersion(); 10693 Redeclaration = true; 10694 OldDecl = OldFD; 10695 return false; 10696 } 10697 10698 NewFD->setIsMultiVersion(); 10699 Redeclaration = false; 10700 MergeTypeWithPrevious = false; 10701 OldDecl = nullptr; 10702 Previous.clear(); 10703 return false; 10704 } 10705 10706 10707 /// Check the validity of a mulitversion function declaration. 10708 /// Also sets the multiversion'ness' of the function itself. 10709 /// 10710 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10711 /// 10712 /// Returns true if there was an error, false otherwise. 10713 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10714 bool &Redeclaration, NamedDecl *&OldDecl, 10715 bool &MergeTypeWithPrevious, 10716 LookupResult &Previous) { 10717 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10718 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10719 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10720 10721 // Mixing Multiversioning types is prohibited. 10722 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10723 (NewCPUDisp && NewCPUSpec)) { 10724 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10725 NewFD->setInvalidDecl(); 10726 return true; 10727 } 10728 10729 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10730 10731 // Main isn't allowed to become a multiversion function, however it IS 10732 // permitted to have 'main' be marked with the 'target' optimization hint. 10733 if (NewFD->isMain()) { 10734 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10735 MVType == MultiVersionKind::CPUDispatch || 10736 MVType == MultiVersionKind::CPUSpecific) { 10737 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10738 NewFD->setInvalidDecl(); 10739 return true; 10740 } 10741 return false; 10742 } 10743 10744 if (!OldDecl || !OldDecl->getAsFunction() || 10745 OldDecl->getDeclContext()->getRedeclContext() != 10746 NewFD->getDeclContext()->getRedeclContext()) { 10747 // If there's no previous declaration, AND this isn't attempting to cause 10748 // multiversioning, this isn't an error condition. 10749 if (MVType == MultiVersionKind::None) 10750 return false; 10751 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10752 } 10753 10754 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10755 10756 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10757 return false; 10758 10759 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10760 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10761 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10762 NewFD->setInvalidDecl(); 10763 return true; 10764 } 10765 10766 // Handle the target potentially causes multiversioning case. 10767 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10768 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10769 Redeclaration, OldDecl, 10770 MergeTypeWithPrevious, Previous); 10771 10772 // At this point, we have a multiversion function decl (in OldFD) AND an 10773 // appropriate attribute in the current function decl. Resolve that these are 10774 // still compatible with previous declarations. 10775 return CheckMultiVersionAdditionalDecl( 10776 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10777 OldDecl, MergeTypeWithPrevious, Previous); 10778 } 10779 10780 /// Perform semantic checking of a new function declaration. 10781 /// 10782 /// Performs semantic analysis of the new function declaration 10783 /// NewFD. This routine performs all semantic checking that does not 10784 /// require the actual declarator involved in the declaration, and is 10785 /// used both for the declaration of functions as they are parsed 10786 /// (called via ActOnDeclarator) and for the declaration of functions 10787 /// that have been instantiated via C++ template instantiation (called 10788 /// via InstantiateDecl). 10789 /// 10790 /// \param IsMemberSpecialization whether this new function declaration is 10791 /// a member specialization (that replaces any definition provided by the 10792 /// previous declaration). 10793 /// 10794 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10795 /// 10796 /// \returns true if the function declaration is a redeclaration. 10797 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10798 LookupResult &Previous, 10799 bool IsMemberSpecialization) { 10800 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10801 "Variably modified return types are not handled here"); 10802 10803 // Determine whether the type of this function should be merged with 10804 // a previous visible declaration. This never happens for functions in C++, 10805 // and always happens in C if the previous declaration was visible. 10806 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10807 !Previous.isShadowed(); 10808 10809 bool Redeclaration = false; 10810 NamedDecl *OldDecl = nullptr; 10811 bool MayNeedOverloadableChecks = false; 10812 10813 // Merge or overload the declaration with an existing declaration of 10814 // the same name, if appropriate. 10815 if (!Previous.empty()) { 10816 // Determine whether NewFD is an overload of PrevDecl or 10817 // a declaration that requires merging. If it's an overload, 10818 // there's no more work to do here; we'll just add the new 10819 // function to the scope. 10820 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10821 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10822 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10823 Redeclaration = true; 10824 OldDecl = Candidate; 10825 } 10826 } else { 10827 MayNeedOverloadableChecks = true; 10828 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10829 /*NewIsUsingDecl*/ false)) { 10830 case Ovl_Match: 10831 Redeclaration = true; 10832 break; 10833 10834 case Ovl_NonFunction: 10835 Redeclaration = true; 10836 break; 10837 10838 case Ovl_Overload: 10839 Redeclaration = false; 10840 break; 10841 } 10842 } 10843 } 10844 10845 // Check for a previous extern "C" declaration with this name. 10846 if (!Redeclaration && 10847 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10848 if (!Previous.empty()) { 10849 // This is an extern "C" declaration with the same name as a previous 10850 // declaration, and thus redeclares that entity... 10851 Redeclaration = true; 10852 OldDecl = Previous.getFoundDecl(); 10853 MergeTypeWithPrevious = false; 10854 10855 // ... except in the presence of __attribute__((overloadable)). 10856 if (OldDecl->hasAttr<OverloadableAttr>() || 10857 NewFD->hasAttr<OverloadableAttr>()) { 10858 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10859 MayNeedOverloadableChecks = true; 10860 Redeclaration = false; 10861 OldDecl = nullptr; 10862 } 10863 } 10864 } 10865 } 10866 10867 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10868 MergeTypeWithPrevious, Previous)) 10869 return Redeclaration; 10870 10871 // PPC MMA non-pointer types are not allowed as function return types. 10872 if (Context.getTargetInfo().getTriple().isPPC64() && 10873 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 10874 NewFD->setInvalidDecl(); 10875 } 10876 10877 // C++11 [dcl.constexpr]p8: 10878 // A constexpr specifier for a non-static member function that is not 10879 // a constructor declares that member function to be const. 10880 // 10881 // This needs to be delayed until we know whether this is an out-of-line 10882 // definition of a static member function. 10883 // 10884 // This rule is not present in C++1y, so we produce a backwards 10885 // compatibility warning whenever it happens in C++11. 10886 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10887 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10888 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10889 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10890 CXXMethodDecl *OldMD = nullptr; 10891 if (OldDecl) 10892 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10893 if (!OldMD || !OldMD->isStatic()) { 10894 const FunctionProtoType *FPT = 10895 MD->getType()->castAs<FunctionProtoType>(); 10896 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10897 EPI.TypeQuals.addConst(); 10898 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10899 FPT->getParamTypes(), EPI)); 10900 10901 // Warn that we did this, if we're not performing template instantiation. 10902 // In that case, we'll have warned already when the template was defined. 10903 if (!inTemplateInstantiation()) { 10904 SourceLocation AddConstLoc; 10905 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10906 .IgnoreParens().getAs<FunctionTypeLoc>()) 10907 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10908 10909 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10910 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10911 } 10912 } 10913 } 10914 10915 if (Redeclaration) { 10916 // NewFD and OldDecl represent declarations that need to be 10917 // merged. 10918 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10919 NewFD->setInvalidDecl(); 10920 return Redeclaration; 10921 } 10922 10923 Previous.clear(); 10924 Previous.addDecl(OldDecl); 10925 10926 if (FunctionTemplateDecl *OldTemplateDecl = 10927 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10928 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10929 FunctionTemplateDecl *NewTemplateDecl 10930 = NewFD->getDescribedFunctionTemplate(); 10931 assert(NewTemplateDecl && "Template/non-template mismatch"); 10932 10933 // The call to MergeFunctionDecl above may have created some state in 10934 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10935 // can add it as a redeclaration. 10936 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10937 10938 NewFD->setPreviousDeclaration(OldFD); 10939 if (NewFD->isCXXClassMember()) { 10940 NewFD->setAccess(OldTemplateDecl->getAccess()); 10941 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10942 } 10943 10944 // If this is an explicit specialization of a member that is a function 10945 // template, mark it as a member specialization. 10946 if (IsMemberSpecialization && 10947 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10948 NewTemplateDecl->setMemberSpecialization(); 10949 assert(OldTemplateDecl->isMemberSpecialization()); 10950 // Explicit specializations of a member template do not inherit deleted 10951 // status from the parent member template that they are specializing. 10952 if (OldFD->isDeleted()) { 10953 // FIXME: This assert will not hold in the presence of modules. 10954 assert(OldFD->getCanonicalDecl() == OldFD); 10955 // FIXME: We need an update record for this AST mutation. 10956 OldFD->setDeletedAsWritten(false); 10957 } 10958 } 10959 10960 } else { 10961 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10962 auto *OldFD = cast<FunctionDecl>(OldDecl); 10963 // This needs to happen first so that 'inline' propagates. 10964 NewFD->setPreviousDeclaration(OldFD); 10965 if (NewFD->isCXXClassMember()) 10966 NewFD->setAccess(OldFD->getAccess()); 10967 } 10968 } 10969 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10970 !NewFD->getAttr<OverloadableAttr>()) { 10971 assert((Previous.empty() || 10972 llvm::any_of(Previous, 10973 [](const NamedDecl *ND) { 10974 return ND->hasAttr<OverloadableAttr>(); 10975 })) && 10976 "Non-redecls shouldn't happen without overloadable present"); 10977 10978 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10979 const auto *FD = dyn_cast<FunctionDecl>(ND); 10980 return FD && !FD->hasAttr<OverloadableAttr>(); 10981 }); 10982 10983 if (OtherUnmarkedIter != Previous.end()) { 10984 Diag(NewFD->getLocation(), 10985 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10986 Diag((*OtherUnmarkedIter)->getLocation(), 10987 diag::note_attribute_overloadable_prev_overload) 10988 << false; 10989 10990 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10991 } 10992 } 10993 10994 if (LangOpts.OpenMP) 10995 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 10996 10997 // Semantic checking for this function declaration (in isolation). 10998 10999 if (getLangOpts().CPlusPlus) { 11000 // C++-specific checks. 11001 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 11002 CheckConstructor(Constructor); 11003 } else if (CXXDestructorDecl *Destructor = 11004 dyn_cast<CXXDestructorDecl>(NewFD)) { 11005 CXXRecordDecl *Record = Destructor->getParent(); 11006 QualType ClassType = Context.getTypeDeclType(Record); 11007 11008 // FIXME: Shouldn't we be able to perform this check even when the class 11009 // type is dependent? Both gcc and edg can handle that. 11010 if (!ClassType->isDependentType()) { 11011 DeclarationName Name 11012 = Context.DeclarationNames.getCXXDestructorName( 11013 Context.getCanonicalType(ClassType)); 11014 if (NewFD->getDeclName() != Name) { 11015 Diag(NewFD->getLocation(), diag::err_destructor_name); 11016 NewFD->setInvalidDecl(); 11017 return Redeclaration; 11018 } 11019 } 11020 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 11021 if (auto *TD = Guide->getDescribedFunctionTemplate()) 11022 CheckDeductionGuideTemplate(TD); 11023 11024 // A deduction guide is not on the list of entities that can be 11025 // explicitly specialized. 11026 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 11027 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 11028 << /*explicit specialization*/ 1; 11029 } 11030 11031 // Find any virtual functions that this function overrides. 11032 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 11033 if (!Method->isFunctionTemplateSpecialization() && 11034 !Method->getDescribedFunctionTemplate() && 11035 Method->isCanonicalDecl()) { 11036 AddOverriddenMethods(Method->getParent(), Method); 11037 } 11038 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 11039 // C++2a [class.virtual]p6 11040 // A virtual method shall not have a requires-clause. 11041 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 11042 diag::err_constrained_virtual_method); 11043 11044 if (Method->isStatic()) 11045 checkThisInStaticMemberFunctionType(Method); 11046 } 11047 11048 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 11049 ActOnConversionDeclarator(Conversion); 11050 11051 // Extra checking for C++ overloaded operators (C++ [over.oper]). 11052 if (NewFD->isOverloadedOperator() && 11053 CheckOverloadedOperatorDeclaration(NewFD)) { 11054 NewFD->setInvalidDecl(); 11055 return Redeclaration; 11056 } 11057 11058 // Extra checking for C++0x literal operators (C++0x [over.literal]). 11059 if (NewFD->getLiteralIdentifier() && 11060 CheckLiteralOperatorDeclaration(NewFD)) { 11061 NewFD->setInvalidDecl(); 11062 return Redeclaration; 11063 } 11064 11065 // In C++, check default arguments now that we have merged decls. Unless 11066 // the lexical context is the class, because in this case this is done 11067 // during delayed parsing anyway. 11068 if (!CurContext->isRecord()) 11069 CheckCXXDefaultArguments(NewFD); 11070 11071 // If this function is declared as being extern "C", then check to see if 11072 // the function returns a UDT (class, struct, or union type) that is not C 11073 // compatible, and if it does, warn the user. 11074 // But, issue any diagnostic on the first declaration only. 11075 if (Previous.empty() && NewFD->isExternC()) { 11076 QualType R = NewFD->getReturnType(); 11077 if (R->isIncompleteType() && !R->isVoidType()) 11078 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 11079 << NewFD << R; 11080 else if (!R.isPODType(Context) && !R->isVoidType() && 11081 !R->isObjCObjectPointerType()) 11082 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 11083 } 11084 11085 // C++1z [dcl.fct]p6: 11086 // [...] whether the function has a non-throwing exception-specification 11087 // [is] part of the function type 11088 // 11089 // This results in an ABI break between C++14 and C++17 for functions whose 11090 // declared type includes an exception-specification in a parameter or 11091 // return type. (Exception specifications on the function itself are OK in 11092 // most cases, and exception specifications are not permitted in most other 11093 // contexts where they could make it into a mangling.) 11094 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 11095 auto HasNoexcept = [&](QualType T) -> bool { 11096 // Strip off declarator chunks that could be between us and a function 11097 // type. We don't need to look far, exception specifications are very 11098 // restricted prior to C++17. 11099 if (auto *RT = T->getAs<ReferenceType>()) 11100 T = RT->getPointeeType(); 11101 else if (T->isAnyPointerType()) 11102 T = T->getPointeeType(); 11103 else if (auto *MPT = T->getAs<MemberPointerType>()) 11104 T = MPT->getPointeeType(); 11105 if (auto *FPT = T->getAs<FunctionProtoType>()) 11106 if (FPT->isNothrow()) 11107 return true; 11108 return false; 11109 }; 11110 11111 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 11112 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 11113 for (QualType T : FPT->param_types()) 11114 AnyNoexcept |= HasNoexcept(T); 11115 if (AnyNoexcept) 11116 Diag(NewFD->getLocation(), 11117 diag::warn_cxx17_compat_exception_spec_in_signature) 11118 << NewFD; 11119 } 11120 11121 if (!Redeclaration && LangOpts.CUDA) 11122 checkCUDATargetOverload(NewFD, Previous); 11123 } 11124 return Redeclaration; 11125 } 11126 11127 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11128 // C++11 [basic.start.main]p3: 11129 // A program that [...] declares main to be inline, static or 11130 // constexpr is ill-formed. 11131 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11132 // appear in a declaration of main. 11133 // static main is not an error under C99, but we should warn about it. 11134 // We accept _Noreturn main as an extension. 11135 if (FD->getStorageClass() == SC_Static) 11136 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11137 ? diag::err_static_main : diag::warn_static_main) 11138 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11139 if (FD->isInlineSpecified()) 11140 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11141 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11142 if (DS.isNoreturnSpecified()) { 11143 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11144 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11145 Diag(NoreturnLoc, diag::ext_noreturn_main); 11146 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11147 << FixItHint::CreateRemoval(NoreturnRange); 11148 } 11149 if (FD->isConstexpr()) { 11150 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11151 << FD->isConsteval() 11152 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11153 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11154 } 11155 11156 if (getLangOpts().OpenCL) { 11157 Diag(FD->getLocation(), diag::err_opencl_no_main) 11158 << FD->hasAttr<OpenCLKernelAttr>(); 11159 FD->setInvalidDecl(); 11160 return; 11161 } 11162 11163 QualType T = FD->getType(); 11164 assert(T->isFunctionType() && "function decl is not of function type"); 11165 const FunctionType* FT = T->castAs<FunctionType>(); 11166 11167 // Set default calling convention for main() 11168 if (FT->getCallConv() != CC_C) { 11169 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11170 FD->setType(QualType(FT, 0)); 11171 T = Context.getCanonicalType(FD->getType()); 11172 } 11173 11174 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11175 // In C with GNU extensions we allow main() to have non-integer return 11176 // type, but we should warn about the extension, and we disable the 11177 // implicit-return-zero rule. 11178 11179 // GCC in C mode accepts qualified 'int'. 11180 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11181 FD->setHasImplicitReturnZero(true); 11182 else { 11183 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11184 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11185 if (RTRange.isValid()) 11186 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11187 << FixItHint::CreateReplacement(RTRange, "int"); 11188 } 11189 } else { 11190 // In C and C++, main magically returns 0 if you fall off the end; 11191 // set the flag which tells us that. 11192 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11193 11194 // All the standards say that main() should return 'int'. 11195 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11196 FD->setHasImplicitReturnZero(true); 11197 else { 11198 // Otherwise, this is just a flat-out error. 11199 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11200 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11201 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11202 : FixItHint()); 11203 FD->setInvalidDecl(true); 11204 } 11205 } 11206 11207 // Treat protoless main() as nullary. 11208 if (isa<FunctionNoProtoType>(FT)) return; 11209 11210 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11211 unsigned nparams = FTP->getNumParams(); 11212 assert(FD->getNumParams() == nparams); 11213 11214 bool HasExtraParameters = (nparams > 3); 11215 11216 if (FTP->isVariadic()) { 11217 Diag(FD->getLocation(), diag::ext_variadic_main); 11218 // FIXME: if we had information about the location of the ellipsis, we 11219 // could add a FixIt hint to remove it as a parameter. 11220 } 11221 11222 // Darwin passes an undocumented fourth argument of type char**. If 11223 // other platforms start sprouting these, the logic below will start 11224 // getting shifty. 11225 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11226 HasExtraParameters = false; 11227 11228 if (HasExtraParameters) { 11229 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11230 FD->setInvalidDecl(true); 11231 nparams = 3; 11232 } 11233 11234 // FIXME: a lot of the following diagnostics would be improved 11235 // if we had some location information about types. 11236 11237 QualType CharPP = 11238 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11239 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11240 11241 for (unsigned i = 0; i < nparams; ++i) { 11242 QualType AT = FTP->getParamType(i); 11243 11244 bool mismatch = true; 11245 11246 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11247 mismatch = false; 11248 else if (Expected[i] == CharPP) { 11249 // As an extension, the following forms are okay: 11250 // char const ** 11251 // char const * const * 11252 // char * const * 11253 11254 QualifierCollector qs; 11255 const PointerType* PT; 11256 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11257 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11258 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11259 Context.CharTy)) { 11260 qs.removeConst(); 11261 mismatch = !qs.empty(); 11262 } 11263 } 11264 11265 if (mismatch) { 11266 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11267 // TODO: suggest replacing given type with expected type 11268 FD->setInvalidDecl(true); 11269 } 11270 } 11271 11272 if (nparams == 1 && !FD->isInvalidDecl()) { 11273 Diag(FD->getLocation(), diag::warn_main_one_arg); 11274 } 11275 11276 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11277 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11278 FD->setInvalidDecl(); 11279 } 11280 } 11281 11282 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 11283 11284 // Default calling convention for main and wmain is __cdecl 11285 if (FD->getName() == "main" || FD->getName() == "wmain") 11286 return false; 11287 11288 // Default calling convention for MinGW is __cdecl 11289 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 11290 if (T.isWindowsGNUEnvironment()) 11291 return false; 11292 11293 // Default calling convention for WinMain, wWinMain and DllMain 11294 // is __stdcall on 32 bit Windows 11295 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 11296 return true; 11297 11298 return false; 11299 } 11300 11301 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11302 QualType T = FD->getType(); 11303 assert(T->isFunctionType() && "function decl is not of function type"); 11304 const FunctionType *FT = T->castAs<FunctionType>(); 11305 11306 // Set an implicit return of 'zero' if the function can return some integral, 11307 // enumeration, pointer or nullptr type. 11308 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11309 FT->getReturnType()->isAnyPointerType() || 11310 FT->getReturnType()->isNullPtrType()) 11311 // DllMain is exempt because a return value of zero means it failed. 11312 if (FD->getName() != "DllMain") 11313 FD->setHasImplicitReturnZero(true); 11314 11315 // Explicity specified calling conventions are applied to MSVC entry points 11316 if (!hasExplicitCallingConv(T)) { 11317 if (isDefaultStdCall(FD, *this)) { 11318 if (FT->getCallConv() != CC_X86StdCall) { 11319 FT = Context.adjustFunctionType( 11320 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 11321 FD->setType(QualType(FT, 0)); 11322 } 11323 } else if (FT->getCallConv() != CC_C) { 11324 FT = Context.adjustFunctionType(FT, 11325 FT->getExtInfo().withCallingConv(CC_C)); 11326 FD->setType(QualType(FT, 0)); 11327 } 11328 } 11329 11330 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11331 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11332 FD->setInvalidDecl(); 11333 } 11334 } 11335 11336 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11337 // FIXME: Need strict checking. In C89, we need to check for 11338 // any assignment, increment, decrement, function-calls, or 11339 // commas outside of a sizeof. In C99, it's the same list, 11340 // except that the aforementioned are allowed in unevaluated 11341 // expressions. Everything else falls under the 11342 // "may accept other forms of constant expressions" exception. 11343 // 11344 // Regular C++ code will not end up here (exceptions: language extensions, 11345 // OpenCL C++ etc), so the constant expression rules there don't matter. 11346 if (Init->isValueDependent()) { 11347 assert(Init->containsErrors() && 11348 "Dependent code should only occur in error-recovery path."); 11349 return true; 11350 } 11351 const Expr *Culprit; 11352 if (Init->isConstantInitializer(Context, false, &Culprit)) 11353 return false; 11354 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11355 << Culprit->getSourceRange(); 11356 return true; 11357 } 11358 11359 namespace { 11360 // Visits an initialization expression to see if OrigDecl is evaluated in 11361 // its own initialization and throws a warning if it does. 11362 class SelfReferenceChecker 11363 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11364 Sema &S; 11365 Decl *OrigDecl; 11366 bool isRecordType; 11367 bool isPODType; 11368 bool isReferenceType; 11369 11370 bool isInitList; 11371 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11372 11373 public: 11374 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11375 11376 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11377 S(S), OrigDecl(OrigDecl) { 11378 isPODType = false; 11379 isRecordType = false; 11380 isReferenceType = false; 11381 isInitList = false; 11382 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11383 isPODType = VD->getType().isPODType(S.Context); 11384 isRecordType = VD->getType()->isRecordType(); 11385 isReferenceType = VD->getType()->isReferenceType(); 11386 } 11387 } 11388 11389 // For most expressions, just call the visitor. For initializer lists, 11390 // track the index of the field being initialized since fields are 11391 // initialized in order allowing use of previously initialized fields. 11392 void CheckExpr(Expr *E) { 11393 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11394 if (!InitList) { 11395 Visit(E); 11396 return; 11397 } 11398 11399 // Track and increment the index here. 11400 isInitList = true; 11401 InitFieldIndex.push_back(0); 11402 for (auto Child : InitList->children()) { 11403 CheckExpr(cast<Expr>(Child)); 11404 ++InitFieldIndex.back(); 11405 } 11406 InitFieldIndex.pop_back(); 11407 } 11408 11409 // Returns true if MemberExpr is checked and no further checking is needed. 11410 // Returns false if additional checking is required. 11411 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11412 llvm::SmallVector<FieldDecl*, 4> Fields; 11413 Expr *Base = E; 11414 bool ReferenceField = false; 11415 11416 // Get the field members used. 11417 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11418 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11419 if (!FD) 11420 return false; 11421 Fields.push_back(FD); 11422 if (FD->getType()->isReferenceType()) 11423 ReferenceField = true; 11424 Base = ME->getBase()->IgnoreParenImpCasts(); 11425 } 11426 11427 // Keep checking only if the base Decl is the same. 11428 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11429 if (!DRE || DRE->getDecl() != OrigDecl) 11430 return false; 11431 11432 // A reference field can be bound to an unininitialized field. 11433 if (CheckReference && !ReferenceField) 11434 return true; 11435 11436 // Convert FieldDecls to their index number. 11437 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11438 for (const FieldDecl *I : llvm::reverse(Fields)) 11439 UsedFieldIndex.push_back(I->getFieldIndex()); 11440 11441 // See if a warning is needed by checking the first difference in index 11442 // numbers. If field being used has index less than the field being 11443 // initialized, then the use is safe. 11444 for (auto UsedIter = UsedFieldIndex.begin(), 11445 UsedEnd = UsedFieldIndex.end(), 11446 OrigIter = InitFieldIndex.begin(), 11447 OrigEnd = InitFieldIndex.end(); 11448 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11449 if (*UsedIter < *OrigIter) 11450 return true; 11451 if (*UsedIter > *OrigIter) 11452 break; 11453 } 11454 11455 // TODO: Add a different warning which will print the field names. 11456 HandleDeclRefExpr(DRE); 11457 return true; 11458 } 11459 11460 // For most expressions, the cast is directly above the DeclRefExpr. 11461 // For conditional operators, the cast can be outside the conditional 11462 // operator if both expressions are DeclRefExpr's. 11463 void HandleValue(Expr *E) { 11464 E = E->IgnoreParens(); 11465 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11466 HandleDeclRefExpr(DRE); 11467 return; 11468 } 11469 11470 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11471 Visit(CO->getCond()); 11472 HandleValue(CO->getTrueExpr()); 11473 HandleValue(CO->getFalseExpr()); 11474 return; 11475 } 11476 11477 if (BinaryConditionalOperator *BCO = 11478 dyn_cast<BinaryConditionalOperator>(E)) { 11479 Visit(BCO->getCond()); 11480 HandleValue(BCO->getFalseExpr()); 11481 return; 11482 } 11483 11484 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11485 HandleValue(OVE->getSourceExpr()); 11486 return; 11487 } 11488 11489 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11490 if (BO->getOpcode() == BO_Comma) { 11491 Visit(BO->getLHS()); 11492 HandleValue(BO->getRHS()); 11493 return; 11494 } 11495 } 11496 11497 if (isa<MemberExpr>(E)) { 11498 if (isInitList) { 11499 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11500 false /*CheckReference*/)) 11501 return; 11502 } 11503 11504 Expr *Base = E->IgnoreParenImpCasts(); 11505 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11506 // Check for static member variables and don't warn on them. 11507 if (!isa<FieldDecl>(ME->getMemberDecl())) 11508 return; 11509 Base = ME->getBase()->IgnoreParenImpCasts(); 11510 } 11511 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11512 HandleDeclRefExpr(DRE); 11513 return; 11514 } 11515 11516 Visit(E); 11517 } 11518 11519 // Reference types not handled in HandleValue are handled here since all 11520 // uses of references are bad, not just r-value uses. 11521 void VisitDeclRefExpr(DeclRefExpr *E) { 11522 if (isReferenceType) 11523 HandleDeclRefExpr(E); 11524 } 11525 11526 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11527 if (E->getCastKind() == CK_LValueToRValue) { 11528 HandleValue(E->getSubExpr()); 11529 return; 11530 } 11531 11532 Inherited::VisitImplicitCastExpr(E); 11533 } 11534 11535 void VisitMemberExpr(MemberExpr *E) { 11536 if (isInitList) { 11537 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11538 return; 11539 } 11540 11541 // Don't warn on arrays since they can be treated as pointers. 11542 if (E->getType()->canDecayToPointerType()) return; 11543 11544 // Warn when a non-static method call is followed by non-static member 11545 // field accesses, which is followed by a DeclRefExpr. 11546 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11547 bool Warn = (MD && !MD->isStatic()); 11548 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11549 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11550 if (!isa<FieldDecl>(ME->getMemberDecl())) 11551 Warn = false; 11552 Base = ME->getBase()->IgnoreParenImpCasts(); 11553 } 11554 11555 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11556 if (Warn) 11557 HandleDeclRefExpr(DRE); 11558 return; 11559 } 11560 11561 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11562 // Visit that expression. 11563 Visit(Base); 11564 } 11565 11566 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11567 Expr *Callee = E->getCallee(); 11568 11569 if (isa<UnresolvedLookupExpr>(Callee)) 11570 return Inherited::VisitCXXOperatorCallExpr(E); 11571 11572 Visit(Callee); 11573 for (auto Arg: E->arguments()) 11574 HandleValue(Arg->IgnoreParenImpCasts()); 11575 } 11576 11577 void VisitUnaryOperator(UnaryOperator *E) { 11578 // For POD record types, addresses of its own members are well-defined. 11579 if (E->getOpcode() == UO_AddrOf && isRecordType && 11580 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11581 if (!isPODType) 11582 HandleValue(E->getSubExpr()); 11583 return; 11584 } 11585 11586 if (E->isIncrementDecrementOp()) { 11587 HandleValue(E->getSubExpr()); 11588 return; 11589 } 11590 11591 Inherited::VisitUnaryOperator(E); 11592 } 11593 11594 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11595 11596 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11597 if (E->getConstructor()->isCopyConstructor()) { 11598 Expr *ArgExpr = E->getArg(0); 11599 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11600 if (ILE->getNumInits() == 1) 11601 ArgExpr = ILE->getInit(0); 11602 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11603 if (ICE->getCastKind() == CK_NoOp) 11604 ArgExpr = ICE->getSubExpr(); 11605 HandleValue(ArgExpr); 11606 return; 11607 } 11608 Inherited::VisitCXXConstructExpr(E); 11609 } 11610 11611 void VisitCallExpr(CallExpr *E) { 11612 // Treat std::move as a use. 11613 if (E->isCallToStdMove()) { 11614 HandleValue(E->getArg(0)); 11615 return; 11616 } 11617 11618 Inherited::VisitCallExpr(E); 11619 } 11620 11621 void VisitBinaryOperator(BinaryOperator *E) { 11622 if (E->isCompoundAssignmentOp()) { 11623 HandleValue(E->getLHS()); 11624 Visit(E->getRHS()); 11625 return; 11626 } 11627 11628 Inherited::VisitBinaryOperator(E); 11629 } 11630 11631 // A custom visitor for BinaryConditionalOperator is needed because the 11632 // regular visitor would check the condition and true expression separately 11633 // but both point to the same place giving duplicate diagnostics. 11634 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11635 Visit(E->getCond()); 11636 Visit(E->getFalseExpr()); 11637 } 11638 11639 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11640 Decl* ReferenceDecl = DRE->getDecl(); 11641 if (OrigDecl != ReferenceDecl) return; 11642 unsigned diag; 11643 if (isReferenceType) { 11644 diag = diag::warn_uninit_self_reference_in_reference_init; 11645 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11646 diag = diag::warn_static_self_reference_in_init; 11647 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11648 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11649 DRE->getDecl()->getType()->isRecordType()) { 11650 diag = diag::warn_uninit_self_reference_in_init; 11651 } else { 11652 // Local variables will be handled by the CFG analysis. 11653 return; 11654 } 11655 11656 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11657 S.PDiag(diag) 11658 << DRE->getDecl() << OrigDecl->getLocation() 11659 << DRE->getSourceRange()); 11660 } 11661 }; 11662 11663 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11664 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11665 bool DirectInit) { 11666 // Parameters arguments are occassionially constructed with itself, 11667 // for instance, in recursive functions. Skip them. 11668 if (isa<ParmVarDecl>(OrigDecl)) 11669 return; 11670 11671 E = E->IgnoreParens(); 11672 11673 // Skip checking T a = a where T is not a record or reference type. 11674 // Doing so is a way to silence uninitialized warnings. 11675 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11676 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11677 if (ICE->getCastKind() == CK_LValueToRValue) 11678 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11679 if (DRE->getDecl() == OrigDecl) 11680 return; 11681 11682 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11683 } 11684 } // end anonymous namespace 11685 11686 namespace { 11687 // Simple wrapper to add the name of a variable or (if no variable is 11688 // available) a DeclarationName into a diagnostic. 11689 struct VarDeclOrName { 11690 VarDecl *VDecl; 11691 DeclarationName Name; 11692 11693 friend const Sema::SemaDiagnosticBuilder & 11694 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11695 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11696 } 11697 }; 11698 } // end anonymous namespace 11699 11700 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11701 DeclarationName Name, QualType Type, 11702 TypeSourceInfo *TSI, 11703 SourceRange Range, bool DirectInit, 11704 Expr *Init) { 11705 bool IsInitCapture = !VDecl; 11706 assert((!VDecl || !VDecl->isInitCapture()) && 11707 "init captures are expected to be deduced prior to initialization"); 11708 11709 VarDeclOrName VN{VDecl, Name}; 11710 11711 DeducedType *Deduced = Type->getContainedDeducedType(); 11712 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11713 11714 // C++11 [dcl.spec.auto]p3 11715 if (!Init) { 11716 assert(VDecl && "no init for init capture deduction?"); 11717 11718 // Except for class argument deduction, and then for an initializing 11719 // declaration only, i.e. no static at class scope or extern. 11720 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11721 VDecl->hasExternalStorage() || 11722 VDecl->isStaticDataMember()) { 11723 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11724 << VDecl->getDeclName() << Type; 11725 return QualType(); 11726 } 11727 } 11728 11729 ArrayRef<Expr*> DeduceInits; 11730 if (Init) 11731 DeduceInits = Init; 11732 11733 if (DirectInit) { 11734 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11735 DeduceInits = PL->exprs(); 11736 } 11737 11738 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11739 assert(VDecl && "non-auto type for init capture deduction?"); 11740 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11741 InitializationKind Kind = InitializationKind::CreateForInit( 11742 VDecl->getLocation(), DirectInit, Init); 11743 // FIXME: Initialization should not be taking a mutable list of inits. 11744 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11745 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11746 InitsCopy); 11747 } 11748 11749 if (DirectInit) { 11750 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11751 DeduceInits = IL->inits(); 11752 } 11753 11754 // Deduction only works if we have exactly one source expression. 11755 if (DeduceInits.empty()) { 11756 // It isn't possible to write this directly, but it is possible to 11757 // end up in this situation with "auto x(some_pack...);" 11758 Diag(Init->getBeginLoc(), IsInitCapture 11759 ? diag::err_init_capture_no_expression 11760 : diag::err_auto_var_init_no_expression) 11761 << VN << Type << Range; 11762 return QualType(); 11763 } 11764 11765 if (DeduceInits.size() > 1) { 11766 Diag(DeduceInits[1]->getBeginLoc(), 11767 IsInitCapture ? diag::err_init_capture_multiple_expressions 11768 : diag::err_auto_var_init_multiple_expressions) 11769 << VN << Type << Range; 11770 return QualType(); 11771 } 11772 11773 Expr *DeduceInit = DeduceInits[0]; 11774 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11775 Diag(Init->getBeginLoc(), IsInitCapture 11776 ? diag::err_init_capture_paren_braces 11777 : diag::err_auto_var_init_paren_braces) 11778 << isa<InitListExpr>(Init) << VN << Type << Range; 11779 return QualType(); 11780 } 11781 11782 // Expressions default to 'id' when we're in a debugger. 11783 bool DefaultedAnyToId = false; 11784 if (getLangOpts().DebuggerCastResultToId && 11785 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11786 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11787 if (Result.isInvalid()) { 11788 return QualType(); 11789 } 11790 Init = Result.get(); 11791 DefaultedAnyToId = true; 11792 } 11793 11794 // C++ [dcl.decomp]p1: 11795 // If the assignment-expression [...] has array type A and no ref-qualifier 11796 // is present, e has type cv A 11797 if (VDecl && isa<DecompositionDecl>(VDecl) && 11798 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11799 DeduceInit->getType()->isConstantArrayType()) 11800 return Context.getQualifiedType(DeduceInit->getType(), 11801 Type.getQualifiers()); 11802 11803 QualType DeducedType; 11804 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11805 if (!IsInitCapture) 11806 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11807 else if (isa<InitListExpr>(Init)) 11808 Diag(Range.getBegin(), 11809 diag::err_init_capture_deduction_failure_from_init_list) 11810 << VN 11811 << (DeduceInit->getType().isNull() ? TSI->getType() 11812 : DeduceInit->getType()) 11813 << DeduceInit->getSourceRange(); 11814 else 11815 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11816 << VN << TSI->getType() 11817 << (DeduceInit->getType().isNull() ? TSI->getType() 11818 : DeduceInit->getType()) 11819 << DeduceInit->getSourceRange(); 11820 } 11821 11822 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11823 // 'id' instead of a specific object type prevents most of our usual 11824 // checks. 11825 // We only want to warn outside of template instantiations, though: 11826 // inside a template, the 'id' could have come from a parameter. 11827 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11828 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11829 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11830 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11831 } 11832 11833 return DeducedType; 11834 } 11835 11836 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11837 Expr *Init) { 11838 assert(!Init || !Init->containsErrors()); 11839 QualType DeducedType = deduceVarTypeFromInitializer( 11840 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11841 VDecl->getSourceRange(), DirectInit, Init); 11842 if (DeducedType.isNull()) { 11843 VDecl->setInvalidDecl(); 11844 return true; 11845 } 11846 11847 VDecl->setType(DeducedType); 11848 assert(VDecl->isLinkageValid()); 11849 11850 // In ARC, infer lifetime. 11851 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11852 VDecl->setInvalidDecl(); 11853 11854 if (getLangOpts().OpenCL) 11855 deduceOpenCLAddressSpace(VDecl); 11856 11857 // If this is a redeclaration, check that the type we just deduced matches 11858 // the previously declared type. 11859 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11860 // We never need to merge the type, because we cannot form an incomplete 11861 // array of auto, nor deduce such a type. 11862 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11863 } 11864 11865 // Check the deduced type is valid for a variable declaration. 11866 CheckVariableDeclarationType(VDecl); 11867 return VDecl->isInvalidDecl(); 11868 } 11869 11870 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11871 SourceLocation Loc) { 11872 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11873 Init = EWC->getSubExpr(); 11874 11875 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11876 Init = CE->getSubExpr(); 11877 11878 QualType InitType = Init->getType(); 11879 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11880 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11881 "shouldn't be called if type doesn't have a non-trivial C struct"); 11882 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11883 for (auto I : ILE->inits()) { 11884 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11885 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11886 continue; 11887 SourceLocation SL = I->getExprLoc(); 11888 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11889 } 11890 return; 11891 } 11892 11893 if (isa<ImplicitValueInitExpr>(Init)) { 11894 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11895 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11896 NTCUK_Init); 11897 } else { 11898 // Assume all other explicit initializers involving copying some existing 11899 // object. 11900 // TODO: ignore any explicit initializers where we can guarantee 11901 // copy-elision. 11902 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11903 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11904 } 11905 } 11906 11907 namespace { 11908 11909 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11910 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11911 // in the source code or implicitly by the compiler if it is in a union 11912 // defined in a system header and has non-trivial ObjC ownership 11913 // qualifications. We don't want those fields to participate in determining 11914 // whether the containing union is non-trivial. 11915 return FD->hasAttr<UnavailableAttr>(); 11916 } 11917 11918 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11919 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11920 void> { 11921 using Super = 11922 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11923 void>; 11924 11925 DiagNonTrivalCUnionDefaultInitializeVisitor( 11926 QualType OrigTy, SourceLocation OrigLoc, 11927 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11928 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11929 11930 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11931 const FieldDecl *FD, bool InNonTrivialUnion) { 11932 if (const auto *AT = S.Context.getAsArrayType(QT)) 11933 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11934 InNonTrivialUnion); 11935 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11936 } 11937 11938 void visitARCStrong(QualType QT, const FieldDecl *FD, 11939 bool InNonTrivialUnion) { 11940 if (InNonTrivialUnion) 11941 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11942 << 1 << 0 << QT << FD->getName(); 11943 } 11944 11945 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11946 if (InNonTrivialUnion) 11947 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11948 << 1 << 0 << QT << FD->getName(); 11949 } 11950 11951 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11952 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11953 if (RD->isUnion()) { 11954 if (OrigLoc.isValid()) { 11955 bool IsUnion = false; 11956 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11957 IsUnion = OrigRD->isUnion(); 11958 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11959 << 0 << OrigTy << IsUnion << UseContext; 11960 // Reset OrigLoc so that this diagnostic is emitted only once. 11961 OrigLoc = SourceLocation(); 11962 } 11963 InNonTrivialUnion = true; 11964 } 11965 11966 if (InNonTrivialUnion) 11967 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11968 << 0 << 0 << QT.getUnqualifiedType() << ""; 11969 11970 for (const FieldDecl *FD : RD->fields()) 11971 if (!shouldIgnoreForRecordTriviality(FD)) 11972 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11973 } 11974 11975 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11976 11977 // The non-trivial C union type or the struct/union type that contains a 11978 // non-trivial C union. 11979 QualType OrigTy; 11980 SourceLocation OrigLoc; 11981 Sema::NonTrivialCUnionContext UseContext; 11982 Sema &S; 11983 }; 11984 11985 struct DiagNonTrivalCUnionDestructedTypeVisitor 11986 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11987 using Super = 11988 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11989 11990 DiagNonTrivalCUnionDestructedTypeVisitor( 11991 QualType OrigTy, SourceLocation OrigLoc, 11992 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11993 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11994 11995 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11996 const FieldDecl *FD, bool InNonTrivialUnion) { 11997 if (const auto *AT = S.Context.getAsArrayType(QT)) 11998 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11999 InNonTrivialUnion); 12000 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 12001 } 12002 12003 void visitARCStrong(QualType QT, const FieldDecl *FD, 12004 bool InNonTrivialUnion) { 12005 if (InNonTrivialUnion) 12006 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12007 << 1 << 1 << QT << FD->getName(); 12008 } 12009 12010 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12011 if (InNonTrivialUnion) 12012 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12013 << 1 << 1 << QT << FD->getName(); 12014 } 12015 12016 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12017 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12018 if (RD->isUnion()) { 12019 if (OrigLoc.isValid()) { 12020 bool IsUnion = false; 12021 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12022 IsUnion = OrigRD->isUnion(); 12023 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12024 << 1 << OrigTy << IsUnion << UseContext; 12025 // Reset OrigLoc so that this diagnostic is emitted only once. 12026 OrigLoc = SourceLocation(); 12027 } 12028 InNonTrivialUnion = true; 12029 } 12030 12031 if (InNonTrivialUnion) 12032 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12033 << 0 << 1 << QT.getUnqualifiedType() << ""; 12034 12035 for (const FieldDecl *FD : RD->fields()) 12036 if (!shouldIgnoreForRecordTriviality(FD)) 12037 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12038 } 12039 12040 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12041 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 12042 bool InNonTrivialUnion) {} 12043 12044 // The non-trivial C union type or the struct/union type that contains a 12045 // non-trivial C union. 12046 QualType OrigTy; 12047 SourceLocation OrigLoc; 12048 Sema::NonTrivialCUnionContext UseContext; 12049 Sema &S; 12050 }; 12051 12052 struct DiagNonTrivalCUnionCopyVisitor 12053 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 12054 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 12055 12056 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 12057 Sema::NonTrivialCUnionContext UseContext, 12058 Sema &S) 12059 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12060 12061 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 12062 const FieldDecl *FD, bool InNonTrivialUnion) { 12063 if (const auto *AT = S.Context.getAsArrayType(QT)) 12064 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12065 InNonTrivialUnion); 12066 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 12067 } 12068 12069 void visitARCStrong(QualType QT, const FieldDecl *FD, 12070 bool InNonTrivialUnion) { 12071 if (InNonTrivialUnion) 12072 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12073 << 1 << 2 << QT << FD->getName(); 12074 } 12075 12076 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12077 if (InNonTrivialUnion) 12078 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12079 << 1 << 2 << QT << FD->getName(); 12080 } 12081 12082 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12083 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12084 if (RD->isUnion()) { 12085 if (OrigLoc.isValid()) { 12086 bool IsUnion = false; 12087 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12088 IsUnion = OrigRD->isUnion(); 12089 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12090 << 2 << OrigTy << IsUnion << UseContext; 12091 // Reset OrigLoc so that this diagnostic is emitted only once. 12092 OrigLoc = SourceLocation(); 12093 } 12094 InNonTrivialUnion = true; 12095 } 12096 12097 if (InNonTrivialUnion) 12098 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12099 << 0 << 2 << QT.getUnqualifiedType() << ""; 12100 12101 for (const FieldDecl *FD : RD->fields()) 12102 if (!shouldIgnoreForRecordTriviality(FD)) 12103 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12104 } 12105 12106 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 12107 const FieldDecl *FD, bool InNonTrivialUnion) {} 12108 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12109 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 12110 bool InNonTrivialUnion) {} 12111 12112 // The non-trivial C union type or the struct/union type that contains a 12113 // non-trivial C union. 12114 QualType OrigTy; 12115 SourceLocation OrigLoc; 12116 Sema::NonTrivialCUnionContext UseContext; 12117 Sema &S; 12118 }; 12119 12120 } // namespace 12121 12122 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 12123 NonTrivialCUnionContext UseContext, 12124 unsigned NonTrivialKind) { 12125 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12126 QT.hasNonTrivialToPrimitiveDestructCUnion() || 12127 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 12128 "shouldn't be called if type doesn't have a non-trivial C union"); 12129 12130 if ((NonTrivialKind & NTCUK_Init) && 12131 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12132 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 12133 .visit(QT, nullptr, false); 12134 if ((NonTrivialKind & NTCUK_Destruct) && 12135 QT.hasNonTrivialToPrimitiveDestructCUnion()) 12136 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 12137 .visit(QT, nullptr, false); 12138 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 12139 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 12140 .visit(QT, nullptr, false); 12141 } 12142 12143 /// AddInitializerToDecl - Adds the initializer Init to the 12144 /// declaration dcl. If DirectInit is true, this is C++ direct 12145 /// initialization rather than copy initialization. 12146 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 12147 // If there is no declaration, there was an error parsing it. Just ignore 12148 // the initializer. 12149 if (!RealDecl || RealDecl->isInvalidDecl()) { 12150 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 12151 return; 12152 } 12153 12154 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 12155 // Pure-specifiers are handled in ActOnPureSpecifier. 12156 Diag(Method->getLocation(), diag::err_member_function_initialization) 12157 << Method->getDeclName() << Init->getSourceRange(); 12158 Method->setInvalidDecl(); 12159 return; 12160 } 12161 12162 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12163 if (!VDecl) { 12164 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 12165 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12166 RealDecl->setInvalidDecl(); 12167 return; 12168 } 12169 12170 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12171 if (VDecl->getType()->isUndeducedType()) { 12172 // Attempt typo correction early so that the type of the init expression can 12173 // be deduced based on the chosen correction if the original init contains a 12174 // TypoExpr. 12175 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12176 if (!Res.isUsable()) { 12177 // There are unresolved typos in Init, just drop them. 12178 // FIXME: improve the recovery strategy to preserve the Init. 12179 RealDecl->setInvalidDecl(); 12180 return; 12181 } 12182 if (Res.get()->containsErrors()) { 12183 // Invalidate the decl as we don't know the type for recovery-expr yet. 12184 RealDecl->setInvalidDecl(); 12185 VDecl->setInit(Res.get()); 12186 return; 12187 } 12188 Init = Res.get(); 12189 12190 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12191 return; 12192 } 12193 12194 // dllimport cannot be used on variable definitions. 12195 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12196 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12197 VDecl->setInvalidDecl(); 12198 return; 12199 } 12200 12201 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12202 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12203 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12204 VDecl->setInvalidDecl(); 12205 return; 12206 } 12207 12208 if (!VDecl->getType()->isDependentType()) { 12209 // A definition must end up with a complete type, which means it must be 12210 // complete with the restriction that an array type might be completed by 12211 // the initializer; note that later code assumes this restriction. 12212 QualType BaseDeclType = VDecl->getType(); 12213 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12214 BaseDeclType = Array->getElementType(); 12215 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12216 diag::err_typecheck_decl_incomplete_type)) { 12217 RealDecl->setInvalidDecl(); 12218 return; 12219 } 12220 12221 // The variable can not have an abstract class type. 12222 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12223 diag::err_abstract_type_in_decl, 12224 AbstractVariableType)) 12225 VDecl->setInvalidDecl(); 12226 } 12227 12228 // If adding the initializer will turn this declaration into a definition, 12229 // and we already have a definition for this variable, diagnose or otherwise 12230 // handle the situation. 12231 if (VarDecl *Def = VDecl->getDefinition()) 12232 if (Def != VDecl && 12233 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12234 !VDecl->isThisDeclarationADemotedDefinition() && 12235 checkVarDeclRedefinition(Def, VDecl)) 12236 return; 12237 12238 if (getLangOpts().CPlusPlus) { 12239 // C++ [class.static.data]p4 12240 // If a static data member is of const integral or const 12241 // enumeration type, its declaration in the class definition can 12242 // specify a constant-initializer which shall be an integral 12243 // constant expression (5.19). In that case, the member can appear 12244 // in integral constant expressions. The member shall still be 12245 // defined in a namespace scope if it is used in the program and the 12246 // namespace scope definition shall not contain an initializer. 12247 // 12248 // We already performed a redefinition check above, but for static 12249 // data members we also need to check whether there was an in-class 12250 // declaration with an initializer. 12251 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12252 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12253 << VDecl->getDeclName(); 12254 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12255 diag::note_previous_initializer) 12256 << 0; 12257 return; 12258 } 12259 12260 if (VDecl->hasLocalStorage()) 12261 setFunctionHasBranchProtectedScope(); 12262 12263 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12264 VDecl->setInvalidDecl(); 12265 return; 12266 } 12267 } 12268 12269 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12270 // a kernel function cannot be initialized." 12271 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12272 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12273 VDecl->setInvalidDecl(); 12274 return; 12275 } 12276 12277 // The LoaderUninitialized attribute acts as a definition (of undef). 12278 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12279 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12280 VDecl->setInvalidDecl(); 12281 return; 12282 } 12283 12284 // Get the decls type and save a reference for later, since 12285 // CheckInitializerTypes may change it. 12286 QualType DclT = VDecl->getType(), SavT = DclT; 12287 12288 // Expressions default to 'id' when we're in a debugger 12289 // and we are assigning it to a variable of Objective-C pointer type. 12290 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12291 Init->getType() == Context.UnknownAnyTy) { 12292 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12293 if (Result.isInvalid()) { 12294 VDecl->setInvalidDecl(); 12295 return; 12296 } 12297 Init = Result.get(); 12298 } 12299 12300 // Perform the initialization. 12301 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12302 if (!VDecl->isInvalidDecl()) { 12303 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12304 InitializationKind Kind = InitializationKind::CreateForInit( 12305 VDecl->getLocation(), DirectInit, Init); 12306 12307 MultiExprArg Args = Init; 12308 if (CXXDirectInit) 12309 Args = MultiExprArg(CXXDirectInit->getExprs(), 12310 CXXDirectInit->getNumExprs()); 12311 12312 // Try to correct any TypoExprs in the initialization arguments. 12313 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12314 ExprResult Res = CorrectDelayedTyposInExpr( 12315 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12316 [this, Entity, Kind](Expr *E) { 12317 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12318 return Init.Failed() ? ExprError() : E; 12319 }); 12320 if (Res.isInvalid()) { 12321 VDecl->setInvalidDecl(); 12322 } else if (Res.get() != Args[Idx]) { 12323 Args[Idx] = Res.get(); 12324 } 12325 } 12326 if (VDecl->isInvalidDecl()) 12327 return; 12328 12329 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12330 /*TopLevelOfInitList=*/false, 12331 /*TreatUnavailableAsInvalid=*/false); 12332 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12333 if (Result.isInvalid()) { 12334 // If the provied initializer fails to initialize the var decl, 12335 // we attach a recovery expr for better recovery. 12336 auto RecoveryExpr = 12337 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12338 if (RecoveryExpr.get()) 12339 VDecl->setInit(RecoveryExpr.get()); 12340 return; 12341 } 12342 12343 Init = Result.getAs<Expr>(); 12344 } 12345 12346 // Check for self-references within variable initializers. 12347 // Variables declared within a function/method body (except for references) 12348 // are handled by a dataflow analysis. 12349 // This is undefined behavior in C++, but valid in C. 12350 if (getLangOpts().CPlusPlus) 12351 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12352 VDecl->getType()->isReferenceType()) 12353 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12354 12355 // If the type changed, it means we had an incomplete type that was 12356 // completed by the initializer. For example: 12357 // int ary[] = { 1, 3, 5 }; 12358 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12359 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12360 VDecl->setType(DclT); 12361 12362 if (!VDecl->isInvalidDecl()) { 12363 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12364 12365 if (VDecl->hasAttr<BlocksAttr>()) 12366 checkRetainCycles(VDecl, Init); 12367 12368 // It is safe to assign a weak reference into a strong variable. 12369 // Although this code can still have problems: 12370 // id x = self.weakProp; 12371 // id y = self.weakProp; 12372 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12373 // paths through the function. This should be revisited if 12374 // -Wrepeated-use-of-weak is made flow-sensitive. 12375 if (FunctionScopeInfo *FSI = getCurFunction()) 12376 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12377 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12378 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12379 Init->getBeginLoc())) 12380 FSI->markSafeWeakUse(Init); 12381 } 12382 12383 // The initialization is usually a full-expression. 12384 // 12385 // FIXME: If this is a braced initialization of an aggregate, it is not 12386 // an expression, and each individual field initializer is a separate 12387 // full-expression. For instance, in: 12388 // 12389 // struct Temp { ~Temp(); }; 12390 // struct S { S(Temp); }; 12391 // struct T { S a, b; } t = { Temp(), Temp() } 12392 // 12393 // we should destroy the first Temp before constructing the second. 12394 ExprResult Result = 12395 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12396 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12397 if (Result.isInvalid()) { 12398 VDecl->setInvalidDecl(); 12399 return; 12400 } 12401 Init = Result.get(); 12402 12403 // Attach the initializer to the decl. 12404 VDecl->setInit(Init); 12405 12406 if (VDecl->isLocalVarDecl()) { 12407 // Don't check the initializer if the declaration is malformed. 12408 if (VDecl->isInvalidDecl()) { 12409 // do nothing 12410 12411 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12412 // This is true even in C++ for OpenCL. 12413 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12414 CheckForConstantInitializer(Init, DclT); 12415 12416 // Otherwise, C++ does not restrict the initializer. 12417 } else if (getLangOpts().CPlusPlus) { 12418 // do nothing 12419 12420 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12421 // static storage duration shall be constant expressions or string literals. 12422 } else if (VDecl->getStorageClass() == SC_Static) { 12423 CheckForConstantInitializer(Init, DclT); 12424 12425 // C89 is stricter than C99 for aggregate initializers. 12426 // C89 6.5.7p3: All the expressions [...] in an initializer list 12427 // for an object that has aggregate or union type shall be 12428 // constant expressions. 12429 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12430 isa<InitListExpr>(Init)) { 12431 const Expr *Culprit; 12432 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12433 Diag(Culprit->getExprLoc(), 12434 diag::ext_aggregate_init_not_constant) 12435 << Culprit->getSourceRange(); 12436 } 12437 } 12438 12439 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12440 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12441 if (VDecl->hasLocalStorage()) 12442 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12443 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12444 VDecl->getLexicalDeclContext()->isRecord()) { 12445 // This is an in-class initialization for a static data member, e.g., 12446 // 12447 // struct S { 12448 // static const int value = 17; 12449 // }; 12450 12451 // C++ [class.mem]p4: 12452 // A member-declarator can contain a constant-initializer only 12453 // if it declares a static member (9.4) of const integral or 12454 // const enumeration type, see 9.4.2. 12455 // 12456 // C++11 [class.static.data]p3: 12457 // If a non-volatile non-inline const static data member is of integral 12458 // or enumeration type, its declaration in the class definition can 12459 // specify a brace-or-equal-initializer in which every initializer-clause 12460 // that is an assignment-expression is a constant expression. A static 12461 // data member of literal type can be declared in the class definition 12462 // with the constexpr specifier; if so, its declaration shall specify a 12463 // brace-or-equal-initializer in which every initializer-clause that is 12464 // an assignment-expression is a constant expression. 12465 12466 // Do nothing on dependent types. 12467 if (DclT->isDependentType()) { 12468 12469 // Allow any 'static constexpr' members, whether or not they are of literal 12470 // type. We separately check that every constexpr variable is of literal 12471 // type. 12472 } else if (VDecl->isConstexpr()) { 12473 12474 // Require constness. 12475 } else if (!DclT.isConstQualified()) { 12476 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12477 << Init->getSourceRange(); 12478 VDecl->setInvalidDecl(); 12479 12480 // We allow integer constant expressions in all cases. 12481 } else if (DclT->isIntegralOrEnumerationType()) { 12482 // Check whether the expression is a constant expression. 12483 SourceLocation Loc; 12484 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12485 // In C++11, a non-constexpr const static data member with an 12486 // in-class initializer cannot be volatile. 12487 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12488 else if (Init->isValueDependent()) 12489 ; // Nothing to check. 12490 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12491 ; // Ok, it's an ICE! 12492 else if (Init->getType()->isScopedEnumeralType() && 12493 Init->isCXX11ConstantExpr(Context)) 12494 ; // Ok, it is a scoped-enum constant expression. 12495 else if (Init->isEvaluatable(Context)) { 12496 // If we can constant fold the initializer through heroics, accept it, 12497 // but report this as a use of an extension for -pedantic. 12498 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12499 << Init->getSourceRange(); 12500 } else { 12501 // Otherwise, this is some crazy unknown case. Report the issue at the 12502 // location provided by the isIntegerConstantExpr failed check. 12503 Diag(Loc, diag::err_in_class_initializer_non_constant) 12504 << Init->getSourceRange(); 12505 VDecl->setInvalidDecl(); 12506 } 12507 12508 // We allow foldable floating-point constants as an extension. 12509 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12510 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12511 // it anyway and provide a fixit to add the 'constexpr'. 12512 if (getLangOpts().CPlusPlus11) { 12513 Diag(VDecl->getLocation(), 12514 diag::ext_in_class_initializer_float_type_cxx11) 12515 << DclT << Init->getSourceRange(); 12516 Diag(VDecl->getBeginLoc(), 12517 diag::note_in_class_initializer_float_type_cxx11) 12518 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12519 } else { 12520 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12521 << DclT << Init->getSourceRange(); 12522 12523 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12524 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12525 << Init->getSourceRange(); 12526 VDecl->setInvalidDecl(); 12527 } 12528 } 12529 12530 // Suggest adding 'constexpr' in C++11 for literal types. 12531 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12532 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12533 << DclT << Init->getSourceRange() 12534 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12535 VDecl->setConstexpr(true); 12536 12537 } else { 12538 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12539 << DclT << Init->getSourceRange(); 12540 VDecl->setInvalidDecl(); 12541 } 12542 } else if (VDecl->isFileVarDecl()) { 12543 // In C, extern is typically used to avoid tentative definitions when 12544 // declaring variables in headers, but adding an intializer makes it a 12545 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12546 // In C++, extern is often used to give implictly static const variables 12547 // external linkage, so don't warn in that case. If selectany is present, 12548 // this might be header code intended for C and C++ inclusion, so apply the 12549 // C++ rules. 12550 if (VDecl->getStorageClass() == SC_Extern && 12551 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12552 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12553 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12554 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12555 Diag(VDecl->getLocation(), diag::warn_extern_init); 12556 12557 // In Microsoft C++ mode, a const variable defined in namespace scope has 12558 // external linkage by default if the variable is declared with 12559 // __declspec(dllexport). 12560 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12561 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12562 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12563 VDecl->setStorageClass(SC_Extern); 12564 12565 // C99 6.7.8p4. All file scoped initializers need to be constant. 12566 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12567 CheckForConstantInitializer(Init, DclT); 12568 } 12569 12570 QualType InitType = Init->getType(); 12571 if (!InitType.isNull() && 12572 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12573 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12574 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12575 12576 // We will represent direct-initialization similarly to copy-initialization: 12577 // int x(1); -as-> int x = 1; 12578 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12579 // 12580 // Clients that want to distinguish between the two forms, can check for 12581 // direct initializer using VarDecl::getInitStyle(). 12582 // A major benefit is that clients that don't particularly care about which 12583 // exactly form was it (like the CodeGen) can handle both cases without 12584 // special case code. 12585 12586 // C++ 8.5p11: 12587 // The form of initialization (using parentheses or '=') is generally 12588 // insignificant, but does matter when the entity being initialized has a 12589 // class type. 12590 if (CXXDirectInit) { 12591 assert(DirectInit && "Call-style initializer must be direct init."); 12592 VDecl->setInitStyle(VarDecl::CallInit); 12593 } else if (DirectInit) { 12594 // This must be list-initialization. No other way is direct-initialization. 12595 VDecl->setInitStyle(VarDecl::ListInit); 12596 } 12597 12598 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12599 DeclsToCheckForDeferredDiags.insert(VDecl); 12600 CheckCompleteVariableDeclaration(VDecl); 12601 } 12602 12603 /// ActOnInitializerError - Given that there was an error parsing an 12604 /// initializer for the given declaration, try to return to some form 12605 /// of sanity. 12606 void Sema::ActOnInitializerError(Decl *D) { 12607 // Our main concern here is re-establishing invariants like "a 12608 // variable's type is either dependent or complete". 12609 if (!D || D->isInvalidDecl()) return; 12610 12611 VarDecl *VD = dyn_cast<VarDecl>(D); 12612 if (!VD) return; 12613 12614 // Bindings are not usable if we can't make sense of the initializer. 12615 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12616 for (auto *BD : DD->bindings()) 12617 BD->setInvalidDecl(); 12618 12619 // Auto types are meaningless if we can't make sense of the initializer. 12620 if (VD->getType()->isUndeducedType()) { 12621 D->setInvalidDecl(); 12622 return; 12623 } 12624 12625 QualType Ty = VD->getType(); 12626 if (Ty->isDependentType()) return; 12627 12628 // Require a complete type. 12629 if (RequireCompleteType(VD->getLocation(), 12630 Context.getBaseElementType(Ty), 12631 diag::err_typecheck_decl_incomplete_type)) { 12632 VD->setInvalidDecl(); 12633 return; 12634 } 12635 12636 // Require a non-abstract type. 12637 if (RequireNonAbstractType(VD->getLocation(), Ty, 12638 diag::err_abstract_type_in_decl, 12639 AbstractVariableType)) { 12640 VD->setInvalidDecl(); 12641 return; 12642 } 12643 12644 // Don't bother complaining about constructors or destructors, 12645 // though. 12646 } 12647 12648 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12649 // If there is no declaration, there was an error parsing it. Just ignore it. 12650 if (!RealDecl) 12651 return; 12652 12653 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12654 QualType Type = Var->getType(); 12655 12656 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12657 if (isa<DecompositionDecl>(RealDecl)) { 12658 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12659 Var->setInvalidDecl(); 12660 return; 12661 } 12662 12663 if (Type->isUndeducedType() && 12664 DeduceVariableDeclarationType(Var, false, nullptr)) 12665 return; 12666 12667 // C++11 [class.static.data]p3: A static data member can be declared with 12668 // the constexpr specifier; if so, its declaration shall specify 12669 // a brace-or-equal-initializer. 12670 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12671 // the definition of a variable [...] or the declaration of a static data 12672 // member. 12673 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12674 !Var->isThisDeclarationADemotedDefinition()) { 12675 if (Var->isStaticDataMember()) { 12676 // C++1z removes the relevant rule; the in-class declaration is always 12677 // a definition there. 12678 if (!getLangOpts().CPlusPlus17 && 12679 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12680 Diag(Var->getLocation(), 12681 diag::err_constexpr_static_mem_var_requires_init) 12682 << Var; 12683 Var->setInvalidDecl(); 12684 return; 12685 } 12686 } else { 12687 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12688 Var->setInvalidDecl(); 12689 return; 12690 } 12691 } 12692 12693 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12694 // be initialized. 12695 if (!Var->isInvalidDecl() && 12696 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12697 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12698 bool HasConstExprDefaultConstructor = false; 12699 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12700 for (auto *Ctor : RD->ctors()) { 12701 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && 12702 Ctor->getMethodQualifiers().getAddressSpace() == 12703 LangAS::opencl_constant) { 12704 HasConstExprDefaultConstructor = true; 12705 } 12706 } 12707 } 12708 if (!HasConstExprDefaultConstructor) { 12709 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12710 Var->setInvalidDecl(); 12711 return; 12712 } 12713 } 12714 12715 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12716 if (Var->getStorageClass() == SC_Extern) { 12717 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12718 << Var; 12719 Var->setInvalidDecl(); 12720 return; 12721 } 12722 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12723 diag::err_typecheck_decl_incomplete_type)) { 12724 Var->setInvalidDecl(); 12725 return; 12726 } 12727 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12728 if (!RD->hasTrivialDefaultConstructor()) { 12729 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12730 Var->setInvalidDecl(); 12731 return; 12732 } 12733 } 12734 // The declaration is unitialized, no need for further checks. 12735 return; 12736 } 12737 12738 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12739 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12740 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12741 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12742 NTCUC_DefaultInitializedObject, NTCUK_Init); 12743 12744 12745 switch (DefKind) { 12746 case VarDecl::Definition: 12747 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12748 break; 12749 12750 // We have an out-of-line definition of a static data member 12751 // that has an in-class initializer, so we type-check this like 12752 // a declaration. 12753 // 12754 LLVM_FALLTHROUGH; 12755 12756 case VarDecl::DeclarationOnly: 12757 // It's only a declaration. 12758 12759 // Block scope. C99 6.7p7: If an identifier for an object is 12760 // declared with no linkage (C99 6.2.2p6), the type for the 12761 // object shall be complete. 12762 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12763 !Var->hasLinkage() && !Var->isInvalidDecl() && 12764 RequireCompleteType(Var->getLocation(), Type, 12765 diag::err_typecheck_decl_incomplete_type)) 12766 Var->setInvalidDecl(); 12767 12768 // Make sure that the type is not abstract. 12769 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12770 RequireNonAbstractType(Var->getLocation(), Type, 12771 diag::err_abstract_type_in_decl, 12772 AbstractVariableType)) 12773 Var->setInvalidDecl(); 12774 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12775 Var->getStorageClass() == SC_PrivateExtern) { 12776 Diag(Var->getLocation(), diag::warn_private_extern); 12777 Diag(Var->getLocation(), diag::note_private_extern); 12778 } 12779 12780 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 12781 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12782 ExternalDeclarations.push_back(Var); 12783 12784 return; 12785 12786 case VarDecl::TentativeDefinition: 12787 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12788 // object that has file scope without an initializer, and without a 12789 // storage-class specifier or with the storage-class specifier "static", 12790 // constitutes a tentative definition. Note: A tentative definition with 12791 // external linkage is valid (C99 6.2.2p5). 12792 if (!Var->isInvalidDecl()) { 12793 if (const IncompleteArrayType *ArrayT 12794 = Context.getAsIncompleteArrayType(Type)) { 12795 if (RequireCompleteSizedType( 12796 Var->getLocation(), ArrayT->getElementType(), 12797 diag::err_array_incomplete_or_sizeless_type)) 12798 Var->setInvalidDecl(); 12799 } else if (Var->getStorageClass() == SC_Static) { 12800 // C99 6.9.2p3: If the declaration of an identifier for an object is 12801 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12802 // declared type shall not be an incomplete type. 12803 // NOTE: code such as the following 12804 // static struct s; 12805 // struct s { int a; }; 12806 // is accepted by gcc. Hence here we issue a warning instead of 12807 // an error and we do not invalidate the static declaration. 12808 // NOTE: to avoid multiple warnings, only check the first declaration. 12809 if (Var->isFirstDecl()) 12810 RequireCompleteType(Var->getLocation(), Type, 12811 diag::ext_typecheck_decl_incomplete_type); 12812 } 12813 } 12814 12815 // Record the tentative definition; we're done. 12816 if (!Var->isInvalidDecl()) 12817 TentativeDefinitions.push_back(Var); 12818 return; 12819 } 12820 12821 // Provide a specific diagnostic for uninitialized variable 12822 // definitions with incomplete array type. 12823 if (Type->isIncompleteArrayType()) { 12824 Diag(Var->getLocation(), 12825 diag::err_typecheck_incomplete_array_needs_initializer); 12826 Var->setInvalidDecl(); 12827 return; 12828 } 12829 12830 // Provide a specific diagnostic for uninitialized variable 12831 // definitions with reference type. 12832 if (Type->isReferenceType()) { 12833 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12834 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 12835 Var->setInvalidDecl(); 12836 return; 12837 } 12838 12839 // Do not attempt to type-check the default initializer for a 12840 // variable with dependent type. 12841 if (Type->isDependentType()) 12842 return; 12843 12844 if (Var->isInvalidDecl()) 12845 return; 12846 12847 if (!Var->hasAttr<AliasAttr>()) { 12848 if (RequireCompleteType(Var->getLocation(), 12849 Context.getBaseElementType(Type), 12850 diag::err_typecheck_decl_incomplete_type)) { 12851 Var->setInvalidDecl(); 12852 return; 12853 } 12854 } else { 12855 return; 12856 } 12857 12858 // The variable can not have an abstract class type. 12859 if (RequireNonAbstractType(Var->getLocation(), Type, 12860 diag::err_abstract_type_in_decl, 12861 AbstractVariableType)) { 12862 Var->setInvalidDecl(); 12863 return; 12864 } 12865 12866 // Check for jumps past the implicit initializer. C++0x 12867 // clarifies that this applies to a "variable with automatic 12868 // storage duration", not a "local variable". 12869 // C++11 [stmt.dcl]p3 12870 // A program that jumps from a point where a variable with automatic 12871 // storage duration is not in scope to a point where it is in scope is 12872 // ill-formed unless the variable has scalar type, class type with a 12873 // trivial default constructor and a trivial destructor, a cv-qualified 12874 // version of one of these types, or an array of one of the preceding 12875 // types and is declared without an initializer. 12876 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12877 if (const RecordType *Record 12878 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12879 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12880 // Mark the function (if we're in one) for further checking even if the 12881 // looser rules of C++11 do not require such checks, so that we can 12882 // diagnose incompatibilities with C++98. 12883 if (!CXXRecord->isPOD()) 12884 setFunctionHasBranchProtectedScope(); 12885 } 12886 } 12887 // In OpenCL, we can't initialize objects in the __local address space, 12888 // even implicitly, so don't synthesize an implicit initializer. 12889 if (getLangOpts().OpenCL && 12890 Var->getType().getAddressSpace() == LangAS::opencl_local) 12891 return; 12892 // C++03 [dcl.init]p9: 12893 // If no initializer is specified for an object, and the 12894 // object is of (possibly cv-qualified) non-POD class type (or 12895 // array thereof), the object shall be default-initialized; if 12896 // the object is of const-qualified type, the underlying class 12897 // type shall have a user-declared default 12898 // constructor. Otherwise, if no initializer is specified for 12899 // a non- static object, the object and its subobjects, if 12900 // any, have an indeterminate initial value); if the object 12901 // or any of its subobjects are of const-qualified type, the 12902 // program is ill-formed. 12903 // C++0x [dcl.init]p11: 12904 // If no initializer is specified for an object, the object is 12905 // default-initialized; [...]. 12906 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12907 InitializationKind Kind 12908 = InitializationKind::CreateDefault(Var->getLocation()); 12909 12910 InitializationSequence InitSeq(*this, Entity, Kind, None); 12911 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12912 12913 if (Init.get()) { 12914 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12915 // This is important for template substitution. 12916 Var->setInitStyle(VarDecl::CallInit); 12917 } else if (Init.isInvalid()) { 12918 // If default-init fails, attach a recovery-expr initializer to track 12919 // that initialization was attempted and failed. 12920 auto RecoveryExpr = 12921 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12922 if (RecoveryExpr.get()) 12923 Var->setInit(RecoveryExpr.get()); 12924 } 12925 12926 CheckCompleteVariableDeclaration(Var); 12927 } 12928 } 12929 12930 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12931 // If there is no declaration, there was an error parsing it. Ignore it. 12932 if (!D) 12933 return; 12934 12935 VarDecl *VD = dyn_cast<VarDecl>(D); 12936 if (!VD) { 12937 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12938 D->setInvalidDecl(); 12939 return; 12940 } 12941 12942 VD->setCXXForRangeDecl(true); 12943 12944 // for-range-declaration cannot be given a storage class specifier. 12945 int Error = -1; 12946 switch (VD->getStorageClass()) { 12947 case SC_None: 12948 break; 12949 case SC_Extern: 12950 Error = 0; 12951 break; 12952 case SC_Static: 12953 Error = 1; 12954 break; 12955 case SC_PrivateExtern: 12956 Error = 2; 12957 break; 12958 case SC_Auto: 12959 Error = 3; 12960 break; 12961 case SC_Register: 12962 Error = 4; 12963 break; 12964 } 12965 12966 // for-range-declaration cannot be given a storage class specifier con't. 12967 switch (VD->getTSCSpec()) { 12968 case TSCS_thread_local: 12969 Error = 6; 12970 break; 12971 case TSCS___thread: 12972 case TSCS__Thread_local: 12973 case TSCS_unspecified: 12974 break; 12975 } 12976 12977 if (Error != -1) { 12978 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12979 << VD << Error; 12980 D->setInvalidDecl(); 12981 } 12982 } 12983 12984 StmtResult 12985 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12986 IdentifierInfo *Ident, 12987 ParsedAttributes &Attrs, 12988 SourceLocation AttrEnd) { 12989 // C++1y [stmt.iter]p1: 12990 // A range-based for statement of the form 12991 // for ( for-range-identifier : for-range-initializer ) statement 12992 // is equivalent to 12993 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12994 DeclSpec DS(Attrs.getPool().getFactory()); 12995 12996 const char *PrevSpec; 12997 unsigned DiagID; 12998 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12999 getPrintingPolicy()); 13000 13001 Declarator D(DS, DeclaratorContext::ForInit); 13002 D.SetIdentifier(Ident, IdentLoc); 13003 D.takeAttributes(Attrs, AttrEnd); 13004 13005 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 13006 IdentLoc); 13007 Decl *Var = ActOnDeclarator(S, D); 13008 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 13009 FinalizeDeclaration(Var); 13010 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 13011 AttrEnd.isValid() ? AttrEnd : IdentLoc); 13012 } 13013 13014 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 13015 if (var->isInvalidDecl()) return; 13016 13017 MaybeAddCUDAConstantAttr(var); 13018 13019 if (getLangOpts().OpenCL) { 13020 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 13021 // initialiser 13022 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 13023 !var->hasInit()) { 13024 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 13025 << 1 /*Init*/; 13026 var->setInvalidDecl(); 13027 return; 13028 } 13029 } 13030 13031 // In Objective-C, don't allow jumps past the implicit initialization of a 13032 // local retaining variable. 13033 if (getLangOpts().ObjC && 13034 var->hasLocalStorage()) { 13035 switch (var->getType().getObjCLifetime()) { 13036 case Qualifiers::OCL_None: 13037 case Qualifiers::OCL_ExplicitNone: 13038 case Qualifiers::OCL_Autoreleasing: 13039 break; 13040 13041 case Qualifiers::OCL_Weak: 13042 case Qualifiers::OCL_Strong: 13043 setFunctionHasBranchProtectedScope(); 13044 break; 13045 } 13046 } 13047 13048 if (var->hasLocalStorage() && 13049 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 13050 setFunctionHasBranchProtectedScope(); 13051 13052 // Warn about externally-visible variables being defined without a 13053 // prior declaration. We only want to do this for global 13054 // declarations, but we also specifically need to avoid doing it for 13055 // class members because the linkage of an anonymous class can 13056 // change if it's later given a typedef name. 13057 if (var->isThisDeclarationADefinition() && 13058 var->getDeclContext()->getRedeclContext()->isFileContext() && 13059 var->isExternallyVisible() && var->hasLinkage() && 13060 !var->isInline() && !var->getDescribedVarTemplate() && 13061 !isa<VarTemplatePartialSpecializationDecl>(var) && 13062 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 13063 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 13064 var->getLocation())) { 13065 // Find a previous declaration that's not a definition. 13066 VarDecl *prev = var->getPreviousDecl(); 13067 while (prev && prev->isThisDeclarationADefinition()) 13068 prev = prev->getPreviousDecl(); 13069 13070 if (!prev) { 13071 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 13072 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 13073 << /* variable */ 0; 13074 } 13075 } 13076 13077 // Cache the result of checking for constant initialization. 13078 Optional<bool> CacheHasConstInit; 13079 const Expr *CacheCulprit = nullptr; 13080 auto checkConstInit = [&]() mutable { 13081 if (!CacheHasConstInit) 13082 CacheHasConstInit = var->getInit()->isConstantInitializer( 13083 Context, var->getType()->isReferenceType(), &CacheCulprit); 13084 return *CacheHasConstInit; 13085 }; 13086 13087 if (var->getTLSKind() == VarDecl::TLS_Static) { 13088 if (var->getType().isDestructedType()) { 13089 // GNU C++98 edits for __thread, [basic.start.term]p3: 13090 // The type of an object with thread storage duration shall not 13091 // have a non-trivial destructor. 13092 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 13093 if (getLangOpts().CPlusPlus11) 13094 Diag(var->getLocation(), diag::note_use_thread_local); 13095 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 13096 if (!checkConstInit()) { 13097 // GNU C++98 edits for __thread, [basic.start.init]p4: 13098 // An object of thread storage duration shall not require dynamic 13099 // initialization. 13100 // FIXME: Need strict checking here. 13101 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 13102 << CacheCulprit->getSourceRange(); 13103 if (getLangOpts().CPlusPlus11) 13104 Diag(var->getLocation(), diag::note_use_thread_local); 13105 } 13106 } 13107 } 13108 13109 13110 if (!var->getType()->isStructureType() && var->hasInit() && 13111 isa<InitListExpr>(var->getInit())) { 13112 const auto *ILE = cast<InitListExpr>(var->getInit()); 13113 unsigned NumInits = ILE->getNumInits(); 13114 if (NumInits > 2) 13115 for (unsigned I = 0; I < NumInits; ++I) { 13116 const auto *Init = ILE->getInit(I); 13117 if (!Init) 13118 break; 13119 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13120 if (!SL) 13121 break; 13122 13123 unsigned NumConcat = SL->getNumConcatenated(); 13124 // Diagnose missing comma in string array initialization. 13125 // Do not warn when all the elements in the initializer are concatenated 13126 // together. Do not warn for macros too. 13127 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 13128 bool OnlyOneMissingComma = true; 13129 for (unsigned J = I + 1; J < NumInits; ++J) { 13130 const auto *Init = ILE->getInit(J); 13131 if (!Init) 13132 break; 13133 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13134 if (!SLJ || SLJ->getNumConcatenated() > 1) { 13135 OnlyOneMissingComma = false; 13136 break; 13137 } 13138 } 13139 13140 if (OnlyOneMissingComma) { 13141 SmallVector<FixItHint, 1> Hints; 13142 for (unsigned i = 0; i < NumConcat - 1; ++i) 13143 Hints.push_back(FixItHint::CreateInsertion( 13144 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13145 13146 Diag(SL->getStrTokenLoc(1), 13147 diag::warn_concatenated_literal_array_init) 13148 << Hints; 13149 Diag(SL->getBeginLoc(), 13150 diag::note_concatenated_string_literal_silence); 13151 } 13152 // In any case, stop now. 13153 break; 13154 } 13155 } 13156 } 13157 13158 13159 QualType type = var->getType(); 13160 13161 if (var->hasAttr<BlocksAttr>()) 13162 getCurFunction()->addByrefBlockVar(var); 13163 13164 Expr *Init = var->getInit(); 13165 bool GlobalStorage = var->hasGlobalStorage(); 13166 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13167 QualType baseType = Context.getBaseElementType(type); 13168 bool HasConstInit = true; 13169 13170 // Check whether the initializer is sufficiently constant. 13171 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init && 13172 !Init->isValueDependent() && 13173 (GlobalStorage || var->isConstexpr() || 13174 var->mightBeUsableInConstantExpressions(Context))) { 13175 // If this variable might have a constant initializer or might be usable in 13176 // constant expressions, check whether or not it actually is now. We can't 13177 // do this lazily, because the result might depend on things that change 13178 // later, such as which constexpr functions happen to be defined. 13179 SmallVector<PartialDiagnosticAt, 8> Notes; 13180 if (!getLangOpts().CPlusPlus11) { 13181 // Prior to C++11, in contexts where a constant initializer is required, 13182 // the set of valid constant initializers is described by syntactic rules 13183 // in [expr.const]p2-6. 13184 // FIXME: Stricter checking for these rules would be useful for constinit / 13185 // -Wglobal-constructors. 13186 HasConstInit = checkConstInit(); 13187 13188 // Compute and cache the constant value, and remember that we have a 13189 // constant initializer. 13190 if (HasConstInit) { 13191 (void)var->checkForConstantInitialization(Notes); 13192 Notes.clear(); 13193 } else if (CacheCulprit) { 13194 Notes.emplace_back(CacheCulprit->getExprLoc(), 13195 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13196 Notes.back().second << CacheCulprit->getSourceRange(); 13197 } 13198 } else { 13199 // Evaluate the initializer to see if it's a constant initializer. 13200 HasConstInit = var->checkForConstantInitialization(Notes); 13201 } 13202 13203 if (HasConstInit) { 13204 // FIXME: Consider replacing the initializer with a ConstantExpr. 13205 } else if (var->isConstexpr()) { 13206 SourceLocation DiagLoc = var->getLocation(); 13207 // If the note doesn't add any useful information other than a source 13208 // location, fold it into the primary diagnostic. 13209 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13210 diag::note_invalid_subexpr_in_const_expr) { 13211 DiagLoc = Notes[0].first; 13212 Notes.clear(); 13213 } 13214 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13215 << var << Init->getSourceRange(); 13216 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13217 Diag(Notes[I].first, Notes[I].second); 13218 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13219 auto *Attr = var->getAttr<ConstInitAttr>(); 13220 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13221 << Init->getSourceRange(); 13222 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13223 << Attr->getRange() << Attr->isConstinit(); 13224 for (auto &it : Notes) 13225 Diag(it.first, it.second); 13226 } else if (IsGlobal && 13227 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13228 var->getLocation())) { 13229 // Warn about globals which don't have a constant initializer. Don't 13230 // warn about globals with a non-trivial destructor because we already 13231 // warned about them. 13232 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13233 if (!(RD && !RD->hasTrivialDestructor())) { 13234 // checkConstInit() here permits trivial default initialization even in 13235 // C++11 onwards, where such an initializer is not a constant initializer 13236 // but nonetheless doesn't require a global constructor. 13237 if (!checkConstInit()) 13238 Diag(var->getLocation(), diag::warn_global_constructor) 13239 << Init->getSourceRange(); 13240 } 13241 } 13242 } 13243 13244 // Apply section attributes and pragmas to global variables. 13245 if (GlobalStorage && var->isThisDeclarationADefinition() && 13246 !inTemplateInstantiation()) { 13247 PragmaStack<StringLiteral *> *Stack = nullptr; 13248 int SectionFlags = ASTContext::PSF_Read; 13249 if (var->getType().isConstQualified()) { 13250 if (HasConstInit) 13251 Stack = &ConstSegStack; 13252 else { 13253 Stack = &BSSSegStack; 13254 SectionFlags |= ASTContext::PSF_Write; 13255 } 13256 } else if (var->hasInit() && HasConstInit) { 13257 Stack = &DataSegStack; 13258 SectionFlags |= ASTContext::PSF_Write; 13259 } else { 13260 Stack = &BSSSegStack; 13261 SectionFlags |= ASTContext::PSF_Write; 13262 } 13263 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 13264 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 13265 SectionFlags |= ASTContext::PSF_Implicit; 13266 UnifySection(SA->getName(), SectionFlags, var); 13267 } else if (Stack->CurrentValue) { 13268 SectionFlags |= ASTContext::PSF_Implicit; 13269 auto SectionName = Stack->CurrentValue->getString(); 13270 var->addAttr(SectionAttr::CreateImplicit( 13271 Context, SectionName, Stack->CurrentPragmaLocation, 13272 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 13273 if (UnifySection(SectionName, SectionFlags, var)) 13274 var->dropAttr<SectionAttr>(); 13275 } 13276 13277 // Apply the init_seg attribute if this has an initializer. If the 13278 // initializer turns out to not be dynamic, we'll end up ignoring this 13279 // attribute. 13280 if (CurInitSeg && var->getInit()) 13281 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 13282 CurInitSegLoc, 13283 AttributeCommonInfo::AS_Pragma)); 13284 } 13285 13286 // All the following checks are C++ only. 13287 if (!getLangOpts().CPlusPlus) { 13288 // If this variable must be emitted, add it as an initializer for the 13289 // current module. 13290 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13291 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13292 return; 13293 } 13294 13295 // Require the destructor. 13296 if (!type->isDependentType()) 13297 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13298 FinalizeVarWithDestructor(var, recordType); 13299 13300 // If this variable must be emitted, add it as an initializer for the current 13301 // module. 13302 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13303 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13304 13305 // Build the bindings if this is a structured binding declaration. 13306 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13307 CheckCompleteDecompositionDeclaration(DD); 13308 } 13309 13310 /// Check if VD needs to be dllexport/dllimport due to being in a 13311 /// dllexport/import function. 13312 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13313 assert(VD->isStaticLocal()); 13314 13315 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13316 13317 // Find outermost function when VD is in lambda function. 13318 while (FD && !getDLLAttr(FD) && 13319 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13320 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13321 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13322 } 13323 13324 if (!FD) 13325 return; 13326 13327 // Static locals inherit dll attributes from their function. 13328 if (Attr *A = getDLLAttr(FD)) { 13329 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13330 NewAttr->setInherited(true); 13331 VD->addAttr(NewAttr); 13332 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13333 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13334 NewAttr->setInherited(true); 13335 VD->addAttr(NewAttr); 13336 13337 // Export this function to enforce exporting this static variable even 13338 // if it is not used in this compilation unit. 13339 if (!FD->hasAttr<DLLExportAttr>()) 13340 FD->addAttr(NewAttr); 13341 13342 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13343 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13344 NewAttr->setInherited(true); 13345 VD->addAttr(NewAttr); 13346 } 13347 } 13348 13349 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13350 /// any semantic actions necessary after any initializer has been attached. 13351 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13352 // Note that we are no longer parsing the initializer for this declaration. 13353 ParsingInitForAutoVars.erase(ThisDecl); 13354 13355 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13356 if (!VD) 13357 return; 13358 13359 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13360 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13361 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13362 if (PragmaClangBSSSection.Valid) 13363 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13364 Context, PragmaClangBSSSection.SectionName, 13365 PragmaClangBSSSection.PragmaLocation, 13366 AttributeCommonInfo::AS_Pragma)); 13367 if (PragmaClangDataSection.Valid) 13368 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13369 Context, PragmaClangDataSection.SectionName, 13370 PragmaClangDataSection.PragmaLocation, 13371 AttributeCommonInfo::AS_Pragma)); 13372 if (PragmaClangRodataSection.Valid) 13373 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13374 Context, PragmaClangRodataSection.SectionName, 13375 PragmaClangRodataSection.PragmaLocation, 13376 AttributeCommonInfo::AS_Pragma)); 13377 if (PragmaClangRelroSection.Valid) 13378 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13379 Context, PragmaClangRelroSection.SectionName, 13380 PragmaClangRelroSection.PragmaLocation, 13381 AttributeCommonInfo::AS_Pragma)); 13382 } 13383 13384 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13385 for (auto *BD : DD->bindings()) { 13386 FinalizeDeclaration(BD); 13387 } 13388 } 13389 13390 checkAttributesAfterMerging(*this, *VD); 13391 13392 // Perform TLS alignment check here after attributes attached to the variable 13393 // which may affect the alignment have been processed. Only perform the check 13394 // if the target has a maximum TLS alignment (zero means no constraints). 13395 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13396 // Protect the check so that it's not performed on dependent types and 13397 // dependent alignments (we can't determine the alignment in that case). 13398 if (VD->getTLSKind() && !VD->hasDependentAlignment()) { 13399 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13400 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13401 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13402 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13403 << (unsigned)MaxAlignChars.getQuantity(); 13404 } 13405 } 13406 } 13407 13408 if (VD->isStaticLocal()) 13409 CheckStaticLocalForDllExport(VD); 13410 13411 // Perform check for initializers of device-side global variables. 13412 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13413 // 7.5). We must also apply the same checks to all __shared__ 13414 // variables whether they are local or not. CUDA also allows 13415 // constant initializers for __constant__ and __device__ variables. 13416 if (getLangOpts().CUDA) 13417 checkAllowedCUDAInitializer(VD); 13418 13419 // Grab the dllimport or dllexport attribute off of the VarDecl. 13420 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13421 13422 // Imported static data members cannot be defined out-of-line. 13423 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13424 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13425 VD->isThisDeclarationADefinition()) { 13426 // We allow definitions of dllimport class template static data members 13427 // with a warning. 13428 CXXRecordDecl *Context = 13429 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13430 bool IsClassTemplateMember = 13431 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13432 Context->getDescribedClassTemplate(); 13433 13434 Diag(VD->getLocation(), 13435 IsClassTemplateMember 13436 ? diag::warn_attribute_dllimport_static_field_definition 13437 : diag::err_attribute_dllimport_static_field_definition); 13438 Diag(IA->getLocation(), diag::note_attribute); 13439 if (!IsClassTemplateMember) 13440 VD->setInvalidDecl(); 13441 } 13442 } 13443 13444 // dllimport/dllexport variables cannot be thread local, their TLS index 13445 // isn't exported with the variable. 13446 if (DLLAttr && VD->getTLSKind()) { 13447 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13448 if (F && getDLLAttr(F)) { 13449 assert(VD->isStaticLocal()); 13450 // But if this is a static local in a dlimport/dllexport function, the 13451 // function will never be inlined, which means the var would never be 13452 // imported, so having it marked import/export is safe. 13453 } else { 13454 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13455 << DLLAttr; 13456 VD->setInvalidDecl(); 13457 } 13458 } 13459 13460 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13461 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13462 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13463 << Attr; 13464 VD->dropAttr<UsedAttr>(); 13465 } 13466 } 13467 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 13468 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13469 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13470 << Attr; 13471 VD->dropAttr<RetainAttr>(); 13472 } 13473 } 13474 13475 const DeclContext *DC = VD->getDeclContext(); 13476 // If there's a #pragma GCC visibility in scope, and this isn't a class 13477 // member, set the visibility of this variable. 13478 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13479 AddPushedVisibilityAttribute(VD); 13480 13481 // FIXME: Warn on unused var template partial specializations. 13482 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13483 MarkUnusedFileScopedDecl(VD); 13484 13485 // Now we have parsed the initializer and can update the table of magic 13486 // tag values. 13487 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13488 !VD->getType()->isIntegralOrEnumerationType()) 13489 return; 13490 13491 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13492 const Expr *MagicValueExpr = VD->getInit(); 13493 if (!MagicValueExpr) { 13494 continue; 13495 } 13496 Optional<llvm::APSInt> MagicValueInt; 13497 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13498 Diag(I->getRange().getBegin(), 13499 diag::err_type_tag_for_datatype_not_ice) 13500 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13501 continue; 13502 } 13503 if (MagicValueInt->getActiveBits() > 64) { 13504 Diag(I->getRange().getBegin(), 13505 diag::err_type_tag_for_datatype_too_large) 13506 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13507 continue; 13508 } 13509 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13510 RegisterTypeTagForDatatype(I->getArgumentKind(), 13511 MagicValue, 13512 I->getMatchingCType(), 13513 I->getLayoutCompatible(), 13514 I->getMustBeNull()); 13515 } 13516 } 13517 13518 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13519 auto *VD = dyn_cast<VarDecl>(DD); 13520 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13521 } 13522 13523 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13524 ArrayRef<Decl *> Group) { 13525 SmallVector<Decl*, 8> Decls; 13526 13527 if (DS.isTypeSpecOwned()) 13528 Decls.push_back(DS.getRepAsDecl()); 13529 13530 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13531 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13532 bool DiagnosedMultipleDecomps = false; 13533 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13534 bool DiagnosedNonDeducedAuto = false; 13535 13536 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13537 if (Decl *D = Group[i]) { 13538 // For declarators, there are some additional syntactic-ish checks we need 13539 // to perform. 13540 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13541 if (!FirstDeclaratorInGroup) 13542 FirstDeclaratorInGroup = DD; 13543 if (!FirstDecompDeclaratorInGroup) 13544 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13545 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13546 !hasDeducedAuto(DD)) 13547 FirstNonDeducedAutoInGroup = DD; 13548 13549 if (FirstDeclaratorInGroup != DD) { 13550 // A decomposition declaration cannot be combined with any other 13551 // declaration in the same group. 13552 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13553 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13554 diag::err_decomp_decl_not_alone) 13555 << FirstDeclaratorInGroup->getSourceRange() 13556 << DD->getSourceRange(); 13557 DiagnosedMultipleDecomps = true; 13558 } 13559 13560 // A declarator that uses 'auto' in any way other than to declare a 13561 // variable with a deduced type cannot be combined with any other 13562 // declarator in the same group. 13563 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13564 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13565 diag::err_auto_non_deduced_not_alone) 13566 << FirstNonDeducedAutoInGroup->getType() 13567 ->hasAutoForTrailingReturnType() 13568 << FirstDeclaratorInGroup->getSourceRange() 13569 << DD->getSourceRange(); 13570 DiagnosedNonDeducedAuto = true; 13571 } 13572 } 13573 } 13574 13575 Decls.push_back(D); 13576 } 13577 } 13578 13579 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13580 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13581 handleTagNumbering(Tag, S); 13582 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13583 getLangOpts().CPlusPlus) 13584 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13585 } 13586 } 13587 13588 return BuildDeclaratorGroup(Decls); 13589 } 13590 13591 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13592 /// group, performing any necessary semantic checking. 13593 Sema::DeclGroupPtrTy 13594 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13595 // C++14 [dcl.spec.auto]p7: (DR1347) 13596 // If the type that replaces the placeholder type is not the same in each 13597 // deduction, the program is ill-formed. 13598 if (Group.size() > 1) { 13599 QualType Deduced; 13600 VarDecl *DeducedDecl = nullptr; 13601 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13602 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13603 if (!D || D->isInvalidDecl()) 13604 break; 13605 DeducedType *DT = D->getType()->getContainedDeducedType(); 13606 if (!DT || DT->getDeducedType().isNull()) 13607 continue; 13608 if (Deduced.isNull()) { 13609 Deduced = DT->getDeducedType(); 13610 DeducedDecl = D; 13611 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13612 auto *AT = dyn_cast<AutoType>(DT); 13613 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13614 diag::err_auto_different_deductions) 13615 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13616 << DeducedDecl->getDeclName() << DT->getDeducedType() 13617 << D->getDeclName(); 13618 if (DeducedDecl->hasInit()) 13619 Dia << DeducedDecl->getInit()->getSourceRange(); 13620 if (D->getInit()) 13621 Dia << D->getInit()->getSourceRange(); 13622 D->setInvalidDecl(); 13623 break; 13624 } 13625 } 13626 } 13627 13628 ActOnDocumentableDecls(Group); 13629 13630 return DeclGroupPtrTy::make( 13631 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13632 } 13633 13634 void Sema::ActOnDocumentableDecl(Decl *D) { 13635 ActOnDocumentableDecls(D); 13636 } 13637 13638 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13639 // Don't parse the comment if Doxygen diagnostics are ignored. 13640 if (Group.empty() || !Group[0]) 13641 return; 13642 13643 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13644 Group[0]->getLocation()) && 13645 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13646 Group[0]->getLocation())) 13647 return; 13648 13649 if (Group.size() >= 2) { 13650 // This is a decl group. Normally it will contain only declarations 13651 // produced from declarator list. But in case we have any definitions or 13652 // additional declaration references: 13653 // 'typedef struct S {} S;' 13654 // 'typedef struct S *S;' 13655 // 'struct S *pS;' 13656 // FinalizeDeclaratorGroup adds these as separate declarations. 13657 Decl *MaybeTagDecl = Group[0]; 13658 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13659 Group = Group.slice(1); 13660 } 13661 } 13662 13663 // FIMXE: We assume every Decl in the group is in the same file. 13664 // This is false when preprocessor constructs the group from decls in 13665 // different files (e. g. macros or #include). 13666 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13667 } 13668 13669 /// Common checks for a parameter-declaration that should apply to both function 13670 /// parameters and non-type template parameters. 13671 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13672 // Check that there are no default arguments inside the type of this 13673 // parameter. 13674 if (getLangOpts().CPlusPlus) 13675 CheckExtraCXXDefaultArguments(D); 13676 13677 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13678 if (D.getCXXScopeSpec().isSet()) { 13679 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13680 << D.getCXXScopeSpec().getRange(); 13681 } 13682 13683 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13684 // simple identifier except [...irrelevant cases...]. 13685 switch (D.getName().getKind()) { 13686 case UnqualifiedIdKind::IK_Identifier: 13687 break; 13688 13689 case UnqualifiedIdKind::IK_OperatorFunctionId: 13690 case UnqualifiedIdKind::IK_ConversionFunctionId: 13691 case UnqualifiedIdKind::IK_LiteralOperatorId: 13692 case UnqualifiedIdKind::IK_ConstructorName: 13693 case UnqualifiedIdKind::IK_DestructorName: 13694 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13695 case UnqualifiedIdKind::IK_DeductionGuideName: 13696 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13697 << GetNameForDeclarator(D).getName(); 13698 break; 13699 13700 case UnqualifiedIdKind::IK_TemplateId: 13701 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13702 // GetNameForDeclarator would not produce a useful name in this case. 13703 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13704 break; 13705 } 13706 } 13707 13708 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13709 /// to introduce parameters into function prototype scope. 13710 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13711 const DeclSpec &DS = D.getDeclSpec(); 13712 13713 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13714 13715 // C++03 [dcl.stc]p2 also permits 'auto'. 13716 StorageClass SC = SC_None; 13717 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13718 SC = SC_Register; 13719 // In C++11, the 'register' storage class specifier is deprecated. 13720 // In C++17, it is not allowed, but we tolerate it as an extension. 13721 if (getLangOpts().CPlusPlus11) { 13722 Diag(DS.getStorageClassSpecLoc(), 13723 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13724 : diag::warn_deprecated_register) 13725 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13726 } 13727 } else if (getLangOpts().CPlusPlus && 13728 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13729 SC = SC_Auto; 13730 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13731 Diag(DS.getStorageClassSpecLoc(), 13732 diag::err_invalid_storage_class_in_func_decl); 13733 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13734 } 13735 13736 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13737 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13738 << DeclSpec::getSpecifierName(TSCS); 13739 if (DS.isInlineSpecified()) 13740 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13741 << getLangOpts().CPlusPlus17; 13742 if (DS.hasConstexprSpecifier()) 13743 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13744 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 13745 13746 DiagnoseFunctionSpecifiers(DS); 13747 13748 CheckFunctionOrTemplateParamDeclarator(S, D); 13749 13750 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13751 QualType parmDeclType = TInfo->getType(); 13752 13753 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13754 IdentifierInfo *II = D.getIdentifier(); 13755 if (II) { 13756 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13757 ForVisibleRedeclaration); 13758 LookupName(R, S); 13759 if (R.isSingleResult()) { 13760 NamedDecl *PrevDecl = R.getFoundDecl(); 13761 if (PrevDecl->isTemplateParameter()) { 13762 // Maybe we will complain about the shadowed template parameter. 13763 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13764 // Just pretend that we didn't see the previous declaration. 13765 PrevDecl = nullptr; 13766 } else if (S->isDeclScope(PrevDecl)) { 13767 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13768 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13769 13770 // Recover by removing the name 13771 II = nullptr; 13772 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13773 D.setInvalidType(true); 13774 } 13775 } 13776 } 13777 13778 // Temporarily put parameter variables in the translation unit, not 13779 // the enclosing context. This prevents them from accidentally 13780 // looking like class members in C++. 13781 ParmVarDecl *New = 13782 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13783 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13784 13785 if (D.isInvalidType()) 13786 New->setInvalidDecl(); 13787 13788 assert(S->isFunctionPrototypeScope()); 13789 assert(S->getFunctionPrototypeDepth() >= 1); 13790 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13791 S->getNextFunctionPrototypeIndex()); 13792 13793 // Add the parameter declaration into this scope. 13794 S->AddDecl(New); 13795 if (II) 13796 IdResolver.AddDecl(New); 13797 13798 ProcessDeclAttributes(S, New, D); 13799 13800 if (D.getDeclSpec().isModulePrivateSpecified()) 13801 Diag(New->getLocation(), diag::err_module_private_local) 13802 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13803 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13804 13805 if (New->hasAttr<BlocksAttr>()) { 13806 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13807 } 13808 13809 if (getLangOpts().OpenCL) 13810 deduceOpenCLAddressSpace(New); 13811 13812 return New; 13813 } 13814 13815 /// Synthesizes a variable for a parameter arising from a 13816 /// typedef. 13817 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13818 SourceLocation Loc, 13819 QualType T) { 13820 /* FIXME: setting StartLoc == Loc. 13821 Would it be worth to modify callers so as to provide proper source 13822 location for the unnamed parameters, embedding the parameter's type? */ 13823 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13824 T, Context.getTrivialTypeSourceInfo(T, Loc), 13825 SC_None, nullptr); 13826 Param->setImplicit(); 13827 return Param; 13828 } 13829 13830 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13831 // Don't diagnose unused-parameter errors in template instantiations; we 13832 // will already have done so in the template itself. 13833 if (inTemplateInstantiation()) 13834 return; 13835 13836 for (const ParmVarDecl *Parameter : Parameters) { 13837 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13838 !Parameter->hasAttr<UnusedAttr>()) { 13839 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13840 << Parameter->getDeclName(); 13841 } 13842 } 13843 } 13844 13845 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13846 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13847 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13848 return; 13849 13850 // Warn if the return value is pass-by-value and larger than the specified 13851 // threshold. 13852 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13853 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13854 if (Size > LangOpts.NumLargeByValueCopy) 13855 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 13856 } 13857 13858 // Warn if any parameter is pass-by-value and larger than the specified 13859 // threshold. 13860 for (const ParmVarDecl *Parameter : Parameters) { 13861 QualType T = Parameter->getType(); 13862 if (T->isDependentType() || !T.isPODType(Context)) 13863 continue; 13864 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13865 if (Size > LangOpts.NumLargeByValueCopy) 13866 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13867 << Parameter << Size; 13868 } 13869 } 13870 13871 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13872 SourceLocation NameLoc, IdentifierInfo *Name, 13873 QualType T, TypeSourceInfo *TSInfo, 13874 StorageClass SC) { 13875 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13876 if (getLangOpts().ObjCAutoRefCount && 13877 T.getObjCLifetime() == Qualifiers::OCL_None && 13878 T->isObjCLifetimeType()) { 13879 13880 Qualifiers::ObjCLifetime lifetime; 13881 13882 // Special cases for arrays: 13883 // - if it's const, use __unsafe_unretained 13884 // - otherwise, it's an error 13885 if (T->isArrayType()) { 13886 if (!T.isConstQualified()) { 13887 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13888 DelayedDiagnostics.add( 13889 sema::DelayedDiagnostic::makeForbiddenType( 13890 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13891 else 13892 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13893 << TSInfo->getTypeLoc().getSourceRange(); 13894 } 13895 lifetime = Qualifiers::OCL_ExplicitNone; 13896 } else { 13897 lifetime = T->getObjCARCImplicitLifetime(); 13898 } 13899 T = Context.getLifetimeQualifiedType(T, lifetime); 13900 } 13901 13902 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13903 Context.getAdjustedParameterType(T), 13904 TSInfo, SC, nullptr); 13905 13906 // Make a note if we created a new pack in the scope of a lambda, so that 13907 // we know that references to that pack must also be expanded within the 13908 // lambda scope. 13909 if (New->isParameterPack()) 13910 if (auto *LSI = getEnclosingLambda()) 13911 LSI->LocalPacks.push_back(New); 13912 13913 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13914 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13915 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13916 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13917 13918 // Parameters can not be abstract class types. 13919 // For record types, this is done by the AbstractClassUsageDiagnoser once 13920 // the class has been completely parsed. 13921 if (!CurContext->isRecord() && 13922 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13923 AbstractParamType)) 13924 New->setInvalidDecl(); 13925 13926 // Parameter declarators cannot be interface types. All ObjC objects are 13927 // passed by reference. 13928 if (T->isObjCObjectType()) { 13929 SourceLocation TypeEndLoc = 13930 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13931 Diag(NameLoc, 13932 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13933 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13934 T = Context.getObjCObjectPointerType(T); 13935 New->setType(T); 13936 } 13937 13938 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13939 // duration shall not be qualified by an address-space qualifier." 13940 // Since all parameters have automatic store duration, they can not have 13941 // an address space. 13942 if (T.getAddressSpace() != LangAS::Default && 13943 // OpenCL allows function arguments declared to be an array of a type 13944 // to be qualified with an address space. 13945 !(getLangOpts().OpenCL && 13946 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13947 Diag(NameLoc, diag::err_arg_with_address_space); 13948 New->setInvalidDecl(); 13949 } 13950 13951 // PPC MMA non-pointer types are not allowed as function argument types. 13952 if (Context.getTargetInfo().getTriple().isPPC64() && 13953 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 13954 New->setInvalidDecl(); 13955 } 13956 13957 return New; 13958 } 13959 13960 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13961 SourceLocation LocAfterDecls) { 13962 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13963 13964 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13965 // for a K&R function. 13966 if (!FTI.hasPrototype) { 13967 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13968 --i; 13969 if (FTI.Params[i].Param == nullptr) { 13970 SmallString<256> Code; 13971 llvm::raw_svector_ostream(Code) 13972 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13973 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13974 << FTI.Params[i].Ident 13975 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13976 13977 // Implicitly declare the argument as type 'int' for lack of a better 13978 // type. 13979 AttributeFactory attrs; 13980 DeclSpec DS(attrs); 13981 const char* PrevSpec; // unused 13982 unsigned DiagID; // unused 13983 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13984 DiagID, Context.getPrintingPolicy()); 13985 // Use the identifier location for the type source range. 13986 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13987 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13988 Declarator ParamD(DS, DeclaratorContext::KNRTypeList); 13989 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13990 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13991 } 13992 } 13993 } 13994 } 13995 13996 Decl * 13997 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13998 MultiTemplateParamsArg TemplateParameterLists, 13999 SkipBodyInfo *SkipBody) { 14000 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 14001 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 14002 Scope *ParentScope = FnBodyScope->getParent(); 14003 14004 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 14005 // we define a non-templated function definition, we will create a declaration 14006 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 14007 // The base function declaration will have the equivalent of an `omp declare 14008 // variant` annotation which specifies the mangled definition as a 14009 // specialization function under the OpenMP context defined as part of the 14010 // `omp begin declare variant`. 14011 SmallVector<FunctionDecl *, 4> Bases; 14012 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 14013 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 14014 ParentScope, D, TemplateParameterLists, Bases); 14015 14016 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 14017 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 14018 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 14019 14020 if (!Bases.empty()) 14021 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 14022 14023 return Dcl; 14024 } 14025 14026 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 14027 Consumer.HandleInlineFunctionDefinition(D); 14028 } 14029 14030 static bool 14031 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 14032 const FunctionDecl *&PossiblePrototype) { 14033 // Don't warn about invalid declarations. 14034 if (FD->isInvalidDecl()) 14035 return false; 14036 14037 // Or declarations that aren't global. 14038 if (!FD->isGlobal()) 14039 return false; 14040 14041 // Don't warn about C++ member functions. 14042 if (isa<CXXMethodDecl>(FD)) 14043 return false; 14044 14045 // Don't warn about 'main'. 14046 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 14047 if (IdentifierInfo *II = FD->getIdentifier()) 14048 if (II->isStr("main") || II->isStr("efi_main")) 14049 return false; 14050 14051 // Don't warn about inline functions. 14052 if (FD->isInlined()) 14053 return false; 14054 14055 // Don't warn about function templates. 14056 if (FD->getDescribedFunctionTemplate()) 14057 return false; 14058 14059 // Don't warn about function template specializations. 14060 if (FD->isFunctionTemplateSpecialization()) 14061 return false; 14062 14063 // Don't warn for OpenCL kernels. 14064 if (FD->hasAttr<OpenCLKernelAttr>()) 14065 return false; 14066 14067 // Don't warn on explicitly deleted functions. 14068 if (FD->isDeleted()) 14069 return false; 14070 14071 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 14072 Prev; Prev = Prev->getPreviousDecl()) { 14073 // Ignore any declarations that occur in function or method 14074 // scope, because they aren't visible from the header. 14075 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 14076 continue; 14077 14078 PossiblePrototype = Prev; 14079 return Prev->getType()->isFunctionNoProtoType(); 14080 } 14081 14082 return true; 14083 } 14084 14085 void 14086 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 14087 const FunctionDecl *EffectiveDefinition, 14088 SkipBodyInfo *SkipBody) { 14089 const FunctionDecl *Definition = EffectiveDefinition; 14090 if (!Definition && 14091 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 14092 return; 14093 14094 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 14095 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 14096 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 14097 // A merged copy of the same function, instantiated as a member of 14098 // the same class, is OK. 14099 if (declaresSameEntity(OrigFD, OrigDef) && 14100 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 14101 cast<Decl>(FD->getLexicalDeclContext()))) 14102 return; 14103 } 14104 } 14105 } 14106 14107 if (canRedefineFunction(Definition, getLangOpts())) 14108 return; 14109 14110 // Don't emit an error when this is redefinition of a typo-corrected 14111 // definition. 14112 if (TypoCorrectedFunctionDefinitions.count(Definition)) 14113 return; 14114 14115 // If we don't have a visible definition of the function, and it's inline or 14116 // a template, skip the new definition. 14117 if (SkipBody && !hasVisibleDefinition(Definition) && 14118 (Definition->getFormalLinkage() == InternalLinkage || 14119 Definition->isInlined() || 14120 Definition->getDescribedFunctionTemplate() || 14121 Definition->getNumTemplateParameterLists())) { 14122 SkipBody->ShouldSkip = true; 14123 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 14124 if (auto *TD = Definition->getDescribedFunctionTemplate()) 14125 makeMergedDefinitionVisible(TD); 14126 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 14127 return; 14128 } 14129 14130 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 14131 Definition->getStorageClass() == SC_Extern) 14132 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 14133 << FD << getLangOpts().CPlusPlus; 14134 else 14135 Diag(FD->getLocation(), diag::err_redefinition) << FD; 14136 14137 Diag(Definition->getLocation(), diag::note_previous_definition); 14138 FD->setInvalidDecl(); 14139 } 14140 14141 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 14142 Sema &S) { 14143 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 14144 14145 LambdaScopeInfo *LSI = S.PushLambdaScope(); 14146 LSI->CallOperator = CallOperator; 14147 LSI->Lambda = LambdaClass; 14148 LSI->ReturnType = CallOperator->getReturnType(); 14149 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 14150 14151 if (LCD == LCD_None) 14152 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 14153 else if (LCD == LCD_ByCopy) 14154 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 14155 else if (LCD == LCD_ByRef) 14156 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 14157 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 14158 14159 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 14160 LSI->Mutable = !CallOperator->isConst(); 14161 14162 // Add the captures to the LSI so they can be noted as already 14163 // captured within tryCaptureVar. 14164 auto I = LambdaClass->field_begin(); 14165 for (const auto &C : LambdaClass->captures()) { 14166 if (C.capturesVariable()) { 14167 VarDecl *VD = C.getCapturedVar(); 14168 if (VD->isInitCapture()) 14169 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 14170 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 14171 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 14172 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 14173 /*EllipsisLoc*/C.isPackExpansion() 14174 ? C.getEllipsisLoc() : SourceLocation(), 14175 I->getType(), /*Invalid*/false); 14176 14177 } else if (C.capturesThis()) { 14178 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 14179 C.getCaptureKind() == LCK_StarThis); 14180 } else { 14181 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14182 I->getType()); 14183 } 14184 ++I; 14185 } 14186 } 14187 14188 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14189 SkipBodyInfo *SkipBody) { 14190 if (!D) { 14191 // Parsing the function declaration failed in some way. Push on a fake scope 14192 // anyway so we can try to parse the function body. 14193 PushFunctionScope(); 14194 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14195 return D; 14196 } 14197 14198 FunctionDecl *FD = nullptr; 14199 14200 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14201 FD = FunTmpl->getTemplatedDecl(); 14202 else 14203 FD = cast<FunctionDecl>(D); 14204 14205 // Do not push if it is a lambda because one is already pushed when building 14206 // the lambda in ActOnStartOfLambdaDefinition(). 14207 if (!isLambdaCallOperator(FD)) 14208 PushExpressionEvaluationContext( 14209 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14210 : ExprEvalContexts.back().Context); 14211 14212 // Check for defining attributes before the check for redefinition. 14213 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14214 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14215 FD->dropAttr<AliasAttr>(); 14216 FD->setInvalidDecl(); 14217 } 14218 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14219 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14220 FD->dropAttr<IFuncAttr>(); 14221 FD->setInvalidDecl(); 14222 } 14223 14224 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14225 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14226 Ctor->isDefaultConstructor() && 14227 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14228 // If this is an MS ABI dllexport default constructor, instantiate any 14229 // default arguments. 14230 InstantiateDefaultCtorDefaultArgs(Ctor); 14231 } 14232 } 14233 14234 // See if this is a redefinition. If 'will have body' (or similar) is already 14235 // set, then these checks were already performed when it was set. 14236 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14237 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14238 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14239 14240 // If we're skipping the body, we're done. Don't enter the scope. 14241 if (SkipBody && SkipBody->ShouldSkip) 14242 return D; 14243 } 14244 14245 // Mark this function as "will have a body eventually". This lets users to 14246 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14247 // this function. 14248 FD->setWillHaveBody(); 14249 14250 // If we are instantiating a generic lambda call operator, push 14251 // a LambdaScopeInfo onto the function stack. But use the information 14252 // that's already been calculated (ActOnLambdaExpr) to prime the current 14253 // LambdaScopeInfo. 14254 // When the template operator is being specialized, the LambdaScopeInfo, 14255 // has to be properly restored so that tryCaptureVariable doesn't try 14256 // and capture any new variables. In addition when calculating potential 14257 // captures during transformation of nested lambdas, it is necessary to 14258 // have the LSI properly restored. 14259 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14260 assert(inTemplateInstantiation() && 14261 "There should be an active template instantiation on the stack " 14262 "when instantiating a generic lambda!"); 14263 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14264 } else { 14265 // Enter a new function scope 14266 PushFunctionScope(); 14267 } 14268 14269 // Builtin functions cannot be defined. 14270 if (unsigned BuiltinID = FD->getBuiltinID()) { 14271 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14272 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14273 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14274 FD->setInvalidDecl(); 14275 } 14276 } 14277 14278 // The return type of a function definition must be complete 14279 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14280 QualType ResultType = FD->getReturnType(); 14281 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14282 !FD->isInvalidDecl() && 14283 RequireCompleteType(FD->getLocation(), ResultType, 14284 diag::err_func_def_incomplete_result)) 14285 FD->setInvalidDecl(); 14286 14287 if (FnBodyScope) 14288 PushDeclContext(FnBodyScope, FD); 14289 14290 // Check the validity of our function parameters 14291 CheckParmsForFunctionDef(FD->parameters(), 14292 /*CheckParameterNames=*/true); 14293 14294 // Add non-parameter declarations already in the function to the current 14295 // scope. 14296 if (FnBodyScope) { 14297 for (Decl *NPD : FD->decls()) { 14298 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14299 if (!NonParmDecl) 14300 continue; 14301 assert(!isa<ParmVarDecl>(NonParmDecl) && 14302 "parameters should not be in newly created FD yet"); 14303 14304 // If the decl has a name, make it accessible in the current scope. 14305 if (NonParmDecl->getDeclName()) 14306 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14307 14308 // Similarly, dive into enums and fish their constants out, making them 14309 // accessible in this scope. 14310 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14311 for (auto *EI : ED->enumerators()) 14312 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14313 } 14314 } 14315 } 14316 14317 // Introduce our parameters into the function scope 14318 for (auto Param : FD->parameters()) { 14319 Param->setOwningFunction(FD); 14320 14321 // If this has an identifier, add it to the scope stack. 14322 if (Param->getIdentifier() && FnBodyScope) { 14323 CheckShadow(FnBodyScope, Param); 14324 14325 PushOnScopeChains(Param, FnBodyScope); 14326 } 14327 } 14328 14329 // Ensure that the function's exception specification is instantiated. 14330 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14331 ResolveExceptionSpec(D->getLocation(), FPT); 14332 14333 // dllimport cannot be applied to non-inline function definitions. 14334 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14335 !FD->isTemplateInstantiation()) { 14336 assert(!FD->hasAttr<DLLExportAttr>()); 14337 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14338 FD->setInvalidDecl(); 14339 return D; 14340 } 14341 // We want to attach documentation to original Decl (which might be 14342 // a function template). 14343 ActOnDocumentableDecl(D); 14344 if (getCurLexicalContext()->isObjCContainer() && 14345 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14346 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14347 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14348 14349 return D; 14350 } 14351 14352 /// Given the set of return statements within a function body, 14353 /// compute the variables that are subject to the named return value 14354 /// optimization. 14355 /// 14356 /// Each of the variables that is subject to the named return value 14357 /// optimization will be marked as NRVO variables in the AST, and any 14358 /// return statement that has a marked NRVO variable as its NRVO candidate can 14359 /// use the named return value optimization. 14360 /// 14361 /// This function applies a very simplistic algorithm for NRVO: if every return 14362 /// statement in the scope of a variable has the same NRVO candidate, that 14363 /// candidate is an NRVO variable. 14364 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14365 ReturnStmt **Returns = Scope->Returns.data(); 14366 14367 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14368 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14369 if (!NRVOCandidate->isNRVOVariable()) 14370 Returns[I]->setNRVOCandidate(nullptr); 14371 } 14372 } 14373 } 14374 14375 bool Sema::canDelayFunctionBody(const Declarator &D) { 14376 // We can't delay parsing the body of a constexpr function template (yet). 14377 if (D.getDeclSpec().hasConstexprSpecifier()) 14378 return false; 14379 14380 // We can't delay parsing the body of a function template with a deduced 14381 // return type (yet). 14382 if (D.getDeclSpec().hasAutoTypeSpec()) { 14383 // If the placeholder introduces a non-deduced trailing return type, 14384 // we can still delay parsing it. 14385 if (D.getNumTypeObjects()) { 14386 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14387 if (Outer.Kind == DeclaratorChunk::Function && 14388 Outer.Fun.hasTrailingReturnType()) { 14389 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14390 return Ty.isNull() || !Ty->isUndeducedType(); 14391 } 14392 } 14393 return false; 14394 } 14395 14396 return true; 14397 } 14398 14399 bool Sema::canSkipFunctionBody(Decl *D) { 14400 // We cannot skip the body of a function (or function template) which is 14401 // constexpr, since we may need to evaluate its body in order to parse the 14402 // rest of the file. 14403 // We cannot skip the body of a function with an undeduced return type, 14404 // because any callers of that function need to know the type. 14405 if (const FunctionDecl *FD = D->getAsFunction()) { 14406 if (FD->isConstexpr()) 14407 return false; 14408 // We can't simply call Type::isUndeducedType here, because inside template 14409 // auto can be deduced to a dependent type, which is not considered 14410 // "undeduced". 14411 if (FD->getReturnType()->getContainedDeducedType()) 14412 return false; 14413 } 14414 return Consumer.shouldSkipFunctionBody(D); 14415 } 14416 14417 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14418 if (!Decl) 14419 return nullptr; 14420 if (FunctionDecl *FD = Decl->getAsFunction()) 14421 FD->setHasSkippedBody(); 14422 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14423 MD->setHasSkippedBody(); 14424 return Decl; 14425 } 14426 14427 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14428 return ActOnFinishFunctionBody(D, BodyArg, false); 14429 } 14430 14431 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14432 /// body. 14433 class ExitFunctionBodyRAII { 14434 public: 14435 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14436 ~ExitFunctionBodyRAII() { 14437 if (!IsLambda) 14438 S.PopExpressionEvaluationContext(); 14439 } 14440 14441 private: 14442 Sema &S; 14443 bool IsLambda = false; 14444 }; 14445 14446 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14447 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14448 14449 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14450 if (EscapeInfo.count(BD)) 14451 return EscapeInfo[BD]; 14452 14453 bool R = false; 14454 const BlockDecl *CurBD = BD; 14455 14456 do { 14457 R = !CurBD->doesNotEscape(); 14458 if (R) 14459 break; 14460 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14461 } while (CurBD); 14462 14463 return EscapeInfo[BD] = R; 14464 }; 14465 14466 // If the location where 'self' is implicitly retained is inside a escaping 14467 // block, emit a diagnostic. 14468 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14469 S.ImplicitlyRetainedSelfLocs) 14470 if (IsOrNestedInEscapingBlock(P.second)) 14471 S.Diag(P.first, diag::warn_implicitly_retains_self) 14472 << FixItHint::CreateInsertion(P.first, "self->"); 14473 } 14474 14475 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14476 bool IsInstantiation) { 14477 FunctionScopeInfo *FSI = getCurFunction(); 14478 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14479 14480 if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>()) 14481 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14482 14483 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14484 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14485 14486 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14487 CheckCompletedCoroutineBody(FD, Body); 14488 14489 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14490 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14491 // meant to pop the context added in ActOnStartOfFunctionDef(). 14492 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14493 14494 if (FD) { 14495 FD->setBody(Body); 14496 FD->setWillHaveBody(false); 14497 14498 if (getLangOpts().CPlusPlus14) { 14499 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14500 FD->getReturnType()->isUndeducedType()) { 14501 // If the function has a deduced result type but contains no 'return' 14502 // statements, the result type as written must be exactly 'auto', and 14503 // the deduced result type is 'void'. 14504 if (!FD->getReturnType()->getAs<AutoType>()) { 14505 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14506 << FD->getReturnType(); 14507 FD->setInvalidDecl(); 14508 } else { 14509 // Substitute 'void' for the 'auto' in the type. 14510 TypeLoc ResultType = getReturnTypeLoc(FD); 14511 Context.adjustDeducedFunctionResultType( 14512 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14513 } 14514 } 14515 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14516 // In C++11, we don't use 'auto' deduction rules for lambda call 14517 // operators because we don't support return type deduction. 14518 auto *LSI = getCurLambda(); 14519 if (LSI->HasImplicitReturnType) { 14520 deduceClosureReturnType(*LSI); 14521 14522 // C++11 [expr.prim.lambda]p4: 14523 // [...] if there are no return statements in the compound-statement 14524 // [the deduced type is] the type void 14525 QualType RetType = 14526 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14527 14528 // Update the return type to the deduced type. 14529 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14530 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14531 Proto->getExtProtoInfo())); 14532 } 14533 } 14534 14535 // If the function implicitly returns zero (like 'main') or is naked, 14536 // don't complain about missing return statements. 14537 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14538 WP.disableCheckFallThrough(); 14539 14540 // MSVC permits the use of pure specifier (=0) on function definition, 14541 // defined at class scope, warn about this non-standard construct. 14542 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14543 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14544 14545 if (!FD->isInvalidDecl()) { 14546 // Don't diagnose unused parameters of defaulted or deleted functions. 14547 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14548 DiagnoseUnusedParameters(FD->parameters()); 14549 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14550 FD->getReturnType(), FD); 14551 14552 // If this is a structor, we need a vtable. 14553 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14554 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14555 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14556 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14557 14558 // Try to apply the named return value optimization. We have to check 14559 // if we can do this here because lambdas keep return statements around 14560 // to deduce an implicit return type. 14561 if (FD->getReturnType()->isRecordType() && 14562 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14563 computeNRVO(Body, FSI); 14564 } 14565 14566 // GNU warning -Wmissing-prototypes: 14567 // Warn if a global function is defined without a previous 14568 // prototype declaration. This warning is issued even if the 14569 // definition itself provides a prototype. The aim is to detect 14570 // global functions that fail to be declared in header files. 14571 const FunctionDecl *PossiblePrototype = nullptr; 14572 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14573 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14574 14575 if (PossiblePrototype) { 14576 // We found a declaration that is not a prototype, 14577 // but that could be a zero-parameter prototype 14578 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14579 TypeLoc TL = TI->getTypeLoc(); 14580 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14581 Diag(PossiblePrototype->getLocation(), 14582 diag::note_declaration_not_a_prototype) 14583 << (FD->getNumParams() != 0) 14584 << (FD->getNumParams() == 0 14585 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14586 : FixItHint{}); 14587 } 14588 } else { 14589 // Returns true if the token beginning at this Loc is `const`. 14590 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14591 const LangOptions &LangOpts) { 14592 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14593 if (LocInfo.first.isInvalid()) 14594 return false; 14595 14596 bool Invalid = false; 14597 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14598 if (Invalid) 14599 return false; 14600 14601 if (LocInfo.second > Buffer.size()) 14602 return false; 14603 14604 const char *LexStart = Buffer.data() + LocInfo.second; 14605 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14606 14607 return StartTok.consume_front("const") && 14608 (StartTok.empty() || isWhitespace(StartTok[0]) || 14609 StartTok.startswith("/*") || StartTok.startswith("//")); 14610 }; 14611 14612 auto findBeginLoc = [&]() { 14613 // If the return type has `const` qualifier, we want to insert 14614 // `static` before `const` (and not before the typename). 14615 if ((FD->getReturnType()->isAnyPointerType() && 14616 FD->getReturnType()->getPointeeType().isConstQualified()) || 14617 FD->getReturnType().isConstQualified()) { 14618 // But only do this if we can determine where the `const` is. 14619 14620 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14621 getLangOpts())) 14622 14623 return FD->getBeginLoc(); 14624 } 14625 return FD->getTypeSpecStartLoc(); 14626 }; 14627 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14628 << /* function */ 1 14629 << (FD->getStorageClass() == SC_None 14630 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14631 : FixItHint{}); 14632 } 14633 14634 // GNU warning -Wstrict-prototypes 14635 // Warn if K&R function is defined without a previous declaration. 14636 // This warning is issued only if the definition itself does not provide 14637 // a prototype. Only K&R definitions do not provide a prototype. 14638 if (!FD->hasWrittenPrototype()) { 14639 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14640 TypeLoc TL = TI->getTypeLoc(); 14641 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14642 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14643 } 14644 } 14645 14646 // Warn on CPUDispatch with an actual body. 14647 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14648 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14649 if (!CmpndBody->body_empty()) 14650 Diag(CmpndBody->body_front()->getBeginLoc(), 14651 diag::warn_dispatch_body_ignored); 14652 14653 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14654 const CXXMethodDecl *KeyFunction; 14655 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14656 MD->isVirtual() && 14657 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14658 MD == KeyFunction->getCanonicalDecl()) { 14659 // Update the key-function state if necessary for this ABI. 14660 if (FD->isInlined() && 14661 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14662 Context.setNonKeyFunction(MD); 14663 14664 // If the newly-chosen key function is already defined, then we 14665 // need to mark the vtable as used retroactively. 14666 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14667 const FunctionDecl *Definition; 14668 if (KeyFunction && KeyFunction->isDefined(Definition)) 14669 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14670 } else { 14671 // We just defined they key function; mark the vtable as used. 14672 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14673 } 14674 } 14675 } 14676 14677 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14678 "Function parsing confused"); 14679 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14680 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14681 MD->setBody(Body); 14682 if (!MD->isInvalidDecl()) { 14683 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14684 MD->getReturnType(), MD); 14685 14686 if (Body) 14687 computeNRVO(Body, FSI); 14688 } 14689 if (FSI->ObjCShouldCallSuper) { 14690 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14691 << MD->getSelector().getAsString(); 14692 FSI->ObjCShouldCallSuper = false; 14693 } 14694 if (FSI->ObjCWarnForNoDesignatedInitChain) { 14695 const ObjCMethodDecl *InitMethod = nullptr; 14696 bool isDesignated = 14697 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14698 assert(isDesignated && InitMethod); 14699 (void)isDesignated; 14700 14701 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14702 auto IFace = MD->getClassInterface(); 14703 if (!IFace) 14704 return false; 14705 auto SuperD = IFace->getSuperClass(); 14706 if (!SuperD) 14707 return false; 14708 return SuperD->getIdentifier() == 14709 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14710 }; 14711 // Don't issue this warning for unavailable inits or direct subclasses 14712 // of NSObject. 14713 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14714 Diag(MD->getLocation(), 14715 diag::warn_objc_designated_init_missing_super_call); 14716 Diag(InitMethod->getLocation(), 14717 diag::note_objc_designated_init_marked_here); 14718 } 14719 FSI->ObjCWarnForNoDesignatedInitChain = false; 14720 } 14721 if (FSI->ObjCWarnForNoInitDelegation) { 14722 // Don't issue this warning for unavaialable inits. 14723 if (!MD->isUnavailable()) 14724 Diag(MD->getLocation(), 14725 diag::warn_objc_secondary_init_missing_init_call); 14726 FSI->ObjCWarnForNoInitDelegation = false; 14727 } 14728 14729 diagnoseImplicitlyRetainedSelf(*this); 14730 } else { 14731 // Parsing the function declaration failed in some way. Pop the fake scope 14732 // we pushed on. 14733 PopFunctionScopeInfo(ActivePolicy, dcl); 14734 return nullptr; 14735 } 14736 14737 if (Body && FSI->HasPotentialAvailabilityViolations) 14738 DiagnoseUnguardedAvailabilityViolations(dcl); 14739 14740 assert(!FSI->ObjCShouldCallSuper && 14741 "This should only be set for ObjC methods, which should have been " 14742 "handled in the block above."); 14743 14744 // Verify and clean out per-function state. 14745 if (Body && (!FD || !FD->isDefaulted())) { 14746 // C++ constructors that have function-try-blocks can't have return 14747 // statements in the handlers of that block. (C++ [except.handle]p14) 14748 // Verify this. 14749 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14750 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14751 14752 // Verify that gotos and switch cases don't jump into scopes illegally. 14753 if (FSI->NeedsScopeChecking() && 14754 !PP.isCodeCompletionEnabled()) 14755 DiagnoseInvalidJumps(Body); 14756 14757 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14758 if (!Destructor->getParent()->isDependentType()) 14759 CheckDestructor(Destructor); 14760 14761 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14762 Destructor->getParent()); 14763 } 14764 14765 // If any errors have occurred, clear out any temporaries that may have 14766 // been leftover. This ensures that these temporaries won't be picked up for 14767 // deletion in some later function. 14768 if (hasUncompilableErrorOccurred() || 14769 getDiagnostics().getSuppressAllDiagnostics()) { 14770 DiscardCleanupsInEvaluationContext(); 14771 } 14772 if (!hasUncompilableErrorOccurred() && 14773 !isa<FunctionTemplateDecl>(dcl)) { 14774 // Since the body is valid, issue any analysis-based warnings that are 14775 // enabled. 14776 ActivePolicy = &WP; 14777 } 14778 14779 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14780 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14781 FD->setInvalidDecl(); 14782 14783 if (FD && FD->hasAttr<NakedAttr>()) { 14784 for (const Stmt *S : Body->children()) { 14785 // Allow local register variables without initializer as they don't 14786 // require prologue. 14787 bool RegisterVariables = false; 14788 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14789 for (const auto *Decl : DS->decls()) { 14790 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14791 RegisterVariables = 14792 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14793 if (!RegisterVariables) 14794 break; 14795 } 14796 } 14797 } 14798 if (RegisterVariables) 14799 continue; 14800 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14801 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14802 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14803 FD->setInvalidDecl(); 14804 break; 14805 } 14806 } 14807 } 14808 14809 assert(ExprCleanupObjects.size() == 14810 ExprEvalContexts.back().NumCleanupObjects && 14811 "Leftover temporaries in function"); 14812 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14813 assert(MaybeODRUseExprs.empty() && 14814 "Leftover expressions for odr-use checking"); 14815 } 14816 14817 if (!IsInstantiation) 14818 PopDeclContext(); 14819 14820 PopFunctionScopeInfo(ActivePolicy, dcl); 14821 // If any errors have occurred, clear out any temporaries that may have 14822 // been leftover. This ensures that these temporaries won't be picked up for 14823 // deletion in some later function. 14824 if (hasUncompilableErrorOccurred()) { 14825 DiscardCleanupsInEvaluationContext(); 14826 } 14827 14828 if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 14829 auto ES = getEmissionStatus(FD); 14830 if (ES == Sema::FunctionEmissionStatus::Emitted || 14831 ES == Sema::FunctionEmissionStatus::Unknown) 14832 DeclsToCheckForDeferredDiags.insert(FD); 14833 } 14834 14835 return dcl; 14836 } 14837 14838 /// When we finish delayed parsing of an attribute, we must attach it to the 14839 /// relevant Decl. 14840 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14841 ParsedAttributes &Attrs) { 14842 // Always attach attributes to the underlying decl. 14843 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14844 D = TD->getTemplatedDecl(); 14845 ProcessDeclAttributeList(S, D, Attrs); 14846 14847 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14848 if (Method->isStatic()) 14849 checkThisInStaticMemberFunctionAttributes(Method); 14850 } 14851 14852 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14853 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14854 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14855 IdentifierInfo &II, Scope *S) { 14856 // Find the scope in which the identifier is injected and the corresponding 14857 // DeclContext. 14858 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14859 // In that case, we inject the declaration into the translation unit scope 14860 // instead. 14861 Scope *BlockScope = S; 14862 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14863 BlockScope = BlockScope->getParent(); 14864 14865 Scope *ContextScope = BlockScope; 14866 while (!ContextScope->getEntity()) 14867 ContextScope = ContextScope->getParent(); 14868 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14869 14870 // Before we produce a declaration for an implicitly defined 14871 // function, see whether there was a locally-scoped declaration of 14872 // this name as a function or variable. If so, use that 14873 // (non-visible) declaration, and complain about it. 14874 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14875 if (ExternCPrev) { 14876 // We still need to inject the function into the enclosing block scope so 14877 // that later (non-call) uses can see it. 14878 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14879 14880 // C89 footnote 38: 14881 // If in fact it is not defined as having type "function returning int", 14882 // the behavior is undefined. 14883 if (!isa<FunctionDecl>(ExternCPrev) || 14884 !Context.typesAreCompatible( 14885 cast<FunctionDecl>(ExternCPrev)->getType(), 14886 Context.getFunctionNoProtoType(Context.IntTy))) { 14887 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14888 << ExternCPrev << !getLangOpts().C99; 14889 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14890 return ExternCPrev; 14891 } 14892 } 14893 14894 // Extension in C99. Legal in C90, but warn about it. 14895 unsigned diag_id; 14896 if (II.getName().startswith("__builtin_")) 14897 diag_id = diag::warn_builtin_unknown; 14898 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14899 else if (getLangOpts().OpenCL) 14900 diag_id = diag::err_opencl_implicit_function_decl; 14901 else if (getLangOpts().C99) 14902 diag_id = diag::ext_implicit_function_decl; 14903 else 14904 diag_id = diag::warn_implicit_function_decl; 14905 Diag(Loc, diag_id) << &II; 14906 14907 // If we found a prior declaration of this function, don't bother building 14908 // another one. We've already pushed that one into scope, so there's nothing 14909 // more to do. 14910 if (ExternCPrev) 14911 return ExternCPrev; 14912 14913 // Because typo correction is expensive, only do it if the implicit 14914 // function declaration is going to be treated as an error. 14915 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14916 TypoCorrection Corrected; 14917 DeclFilterCCC<FunctionDecl> CCC{}; 14918 if (S && (Corrected = 14919 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14920 S, nullptr, CCC, CTK_NonError))) 14921 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14922 /*ErrorRecovery*/false); 14923 } 14924 14925 // Set a Declarator for the implicit definition: int foo(); 14926 const char *Dummy; 14927 AttributeFactory attrFactory; 14928 DeclSpec DS(attrFactory); 14929 unsigned DiagID; 14930 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14931 Context.getPrintingPolicy()); 14932 (void)Error; // Silence warning. 14933 assert(!Error && "Error setting up implicit decl!"); 14934 SourceLocation NoLoc; 14935 Declarator D(DS, DeclaratorContext::Block); 14936 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14937 /*IsAmbiguous=*/false, 14938 /*LParenLoc=*/NoLoc, 14939 /*Params=*/nullptr, 14940 /*NumParams=*/0, 14941 /*EllipsisLoc=*/NoLoc, 14942 /*RParenLoc=*/NoLoc, 14943 /*RefQualifierIsLvalueRef=*/true, 14944 /*RefQualifierLoc=*/NoLoc, 14945 /*MutableLoc=*/NoLoc, EST_None, 14946 /*ESpecRange=*/SourceRange(), 14947 /*Exceptions=*/nullptr, 14948 /*ExceptionRanges=*/nullptr, 14949 /*NumExceptions=*/0, 14950 /*NoexceptExpr=*/nullptr, 14951 /*ExceptionSpecTokens=*/nullptr, 14952 /*DeclsInPrototype=*/None, Loc, 14953 Loc, D), 14954 std::move(DS.getAttributes()), SourceLocation()); 14955 D.SetIdentifier(&II, Loc); 14956 14957 // Insert this function into the enclosing block scope. 14958 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14959 FD->setImplicit(); 14960 14961 AddKnownFunctionAttributes(FD); 14962 14963 return FD; 14964 } 14965 14966 /// If this function is a C++ replaceable global allocation function 14967 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14968 /// adds any function attributes that we know a priori based on the standard. 14969 /// 14970 /// We need to check for duplicate attributes both here and where user-written 14971 /// attributes are applied to declarations. 14972 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14973 FunctionDecl *FD) { 14974 if (FD->isInvalidDecl()) 14975 return; 14976 14977 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14978 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14979 return; 14980 14981 Optional<unsigned> AlignmentParam; 14982 bool IsNothrow = false; 14983 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14984 return; 14985 14986 // C++2a [basic.stc.dynamic.allocation]p4: 14987 // An allocation function that has a non-throwing exception specification 14988 // indicates failure by returning a null pointer value. Any other allocation 14989 // function never returns a null pointer value and indicates failure only by 14990 // throwing an exception [...] 14991 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14992 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14993 14994 // C++2a [basic.stc.dynamic.allocation]p2: 14995 // An allocation function attempts to allocate the requested amount of 14996 // storage. [...] If the request succeeds, the value returned by a 14997 // replaceable allocation function is a [...] pointer value p0 different 14998 // from any previously returned value p1 [...] 14999 // 15000 // However, this particular information is being added in codegen, 15001 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 15002 15003 // C++2a [basic.stc.dynamic.allocation]p2: 15004 // An allocation function attempts to allocate the requested amount of 15005 // storage. If it is successful, it returns the address of the start of a 15006 // block of storage whose length in bytes is at least as large as the 15007 // requested size. 15008 if (!FD->hasAttr<AllocSizeAttr>()) { 15009 FD->addAttr(AllocSizeAttr::CreateImplicit( 15010 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 15011 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 15012 } 15013 15014 // C++2a [basic.stc.dynamic.allocation]p3: 15015 // For an allocation function [...], the pointer returned on a successful 15016 // call shall represent the address of storage that is aligned as follows: 15017 // (3.1) If the allocation function takes an argument of type 15018 // std::align_val_t, the storage will have the alignment 15019 // specified by the value of this argument. 15020 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 15021 FD->addAttr(AllocAlignAttr::CreateImplicit( 15022 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 15023 } 15024 15025 // FIXME: 15026 // C++2a [basic.stc.dynamic.allocation]p3: 15027 // For an allocation function [...], the pointer returned on a successful 15028 // call shall represent the address of storage that is aligned as follows: 15029 // (3.2) Otherwise, if the allocation function is named operator new[], 15030 // the storage is aligned for any object that does not have 15031 // new-extended alignment ([basic.align]) and is no larger than the 15032 // requested size. 15033 // (3.3) Otherwise, the storage is aligned for any object that does not 15034 // have new-extended alignment and is of the requested size. 15035 } 15036 15037 /// Adds any function attributes that we know a priori based on 15038 /// the declaration of this function. 15039 /// 15040 /// These attributes can apply both to implicitly-declared builtins 15041 /// (like __builtin___printf_chk) or to library-declared functions 15042 /// like NSLog or printf. 15043 /// 15044 /// We need to check for duplicate attributes both here and where user-written 15045 /// attributes are applied to declarations. 15046 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 15047 if (FD->isInvalidDecl()) 15048 return; 15049 15050 // If this is a built-in function, map its builtin attributes to 15051 // actual attributes. 15052 if (unsigned BuiltinID = FD->getBuiltinID()) { 15053 // Handle printf-formatting attributes. 15054 unsigned FormatIdx; 15055 bool HasVAListArg; 15056 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 15057 if (!FD->hasAttr<FormatAttr>()) { 15058 const char *fmt = "printf"; 15059 unsigned int NumParams = FD->getNumParams(); 15060 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 15061 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 15062 fmt = "NSString"; 15063 FD->addAttr(FormatAttr::CreateImplicit(Context, 15064 &Context.Idents.get(fmt), 15065 FormatIdx+1, 15066 HasVAListArg ? 0 : FormatIdx+2, 15067 FD->getLocation())); 15068 } 15069 } 15070 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 15071 HasVAListArg)) { 15072 if (!FD->hasAttr<FormatAttr>()) 15073 FD->addAttr(FormatAttr::CreateImplicit(Context, 15074 &Context.Idents.get("scanf"), 15075 FormatIdx+1, 15076 HasVAListArg ? 0 : FormatIdx+2, 15077 FD->getLocation())); 15078 } 15079 15080 // Handle automatically recognized callbacks. 15081 SmallVector<int, 4> Encoding; 15082 if (!FD->hasAttr<CallbackAttr>() && 15083 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 15084 FD->addAttr(CallbackAttr::CreateImplicit( 15085 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 15086 15087 // Mark const if we don't care about errno and that is the only thing 15088 // preventing the function from being const. This allows IRgen to use LLVM 15089 // intrinsics for such functions. 15090 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 15091 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 15092 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15093 15094 // We make "fma" on some platforms const because we know it does not set 15095 // errno in those environments even though it could set errno based on the 15096 // C standard. 15097 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 15098 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 15099 !FD->hasAttr<ConstAttr>()) { 15100 switch (BuiltinID) { 15101 case Builtin::BI__builtin_fma: 15102 case Builtin::BI__builtin_fmaf: 15103 case Builtin::BI__builtin_fmal: 15104 case Builtin::BIfma: 15105 case Builtin::BIfmaf: 15106 case Builtin::BIfmal: 15107 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15108 break; 15109 default: 15110 break; 15111 } 15112 } 15113 15114 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 15115 !FD->hasAttr<ReturnsTwiceAttr>()) 15116 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 15117 FD->getLocation())); 15118 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 15119 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15120 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 15121 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 15122 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 15123 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15124 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 15125 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 15126 // Add the appropriate attribute, depending on the CUDA compilation mode 15127 // and which target the builtin belongs to. For example, during host 15128 // compilation, aux builtins are __device__, while the rest are __host__. 15129 if (getLangOpts().CUDAIsDevice != 15130 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 15131 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 15132 else 15133 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 15134 } 15135 } 15136 15137 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 15138 15139 // If C++ exceptions are enabled but we are told extern "C" functions cannot 15140 // throw, add an implicit nothrow attribute to any extern "C" function we come 15141 // across. 15142 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 15143 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 15144 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 15145 if (!FPT || FPT->getExceptionSpecType() == EST_None) 15146 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15147 } 15148 15149 IdentifierInfo *Name = FD->getIdentifier(); 15150 if (!Name) 15151 return; 15152 if ((!getLangOpts().CPlusPlus && 15153 FD->getDeclContext()->isTranslationUnit()) || 15154 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 15155 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 15156 LinkageSpecDecl::lang_c)) { 15157 // Okay: this could be a libc/libm/Objective-C function we know 15158 // about. 15159 } else 15160 return; 15161 15162 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 15163 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 15164 // target-specific builtins, perhaps? 15165 if (!FD->hasAttr<FormatAttr>()) 15166 FD->addAttr(FormatAttr::CreateImplicit(Context, 15167 &Context.Idents.get("printf"), 2, 15168 Name->isStr("vasprintf") ? 0 : 3, 15169 FD->getLocation())); 15170 } 15171 15172 if (Name->isStr("__CFStringMakeConstantString")) { 15173 // We already have a __builtin___CFStringMakeConstantString, 15174 // but builds that use -fno-constant-cfstrings don't go through that. 15175 if (!FD->hasAttr<FormatArgAttr>()) 15176 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 15177 FD->getLocation())); 15178 } 15179 } 15180 15181 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15182 TypeSourceInfo *TInfo) { 15183 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 15184 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15185 15186 if (!TInfo) { 15187 assert(D.isInvalidType() && "no declarator info for valid type"); 15188 TInfo = Context.getTrivialTypeSourceInfo(T); 15189 } 15190 15191 // Scope manipulation handled by caller. 15192 TypedefDecl *NewTD = 15193 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15194 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15195 15196 // Bail out immediately if we have an invalid declaration. 15197 if (D.isInvalidType()) { 15198 NewTD->setInvalidDecl(); 15199 return NewTD; 15200 } 15201 15202 if (D.getDeclSpec().isModulePrivateSpecified()) { 15203 if (CurContext->isFunctionOrMethod()) 15204 Diag(NewTD->getLocation(), diag::err_module_private_local) 15205 << 2 << NewTD 15206 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15207 << FixItHint::CreateRemoval( 15208 D.getDeclSpec().getModulePrivateSpecLoc()); 15209 else 15210 NewTD->setModulePrivate(); 15211 } 15212 15213 // C++ [dcl.typedef]p8: 15214 // If the typedef declaration defines an unnamed class (or 15215 // enum), the first typedef-name declared by the declaration 15216 // to be that class type (or enum type) is used to denote the 15217 // class type (or enum type) for linkage purposes only. 15218 // We need to check whether the type was declared in the declaration. 15219 switch (D.getDeclSpec().getTypeSpecType()) { 15220 case TST_enum: 15221 case TST_struct: 15222 case TST_interface: 15223 case TST_union: 15224 case TST_class: { 15225 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15226 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15227 break; 15228 } 15229 15230 default: 15231 break; 15232 } 15233 15234 return NewTD; 15235 } 15236 15237 /// Check that this is a valid underlying type for an enum declaration. 15238 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15239 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15240 QualType T = TI->getType(); 15241 15242 if (T->isDependentType()) 15243 return false; 15244 15245 // This doesn't use 'isIntegralType' despite the error message mentioning 15246 // integral type because isIntegralType would also allow enum types in C. 15247 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15248 if (BT->isInteger()) 15249 return false; 15250 15251 if (T->isExtIntType()) 15252 return false; 15253 15254 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15255 } 15256 15257 /// Check whether this is a valid redeclaration of a previous enumeration. 15258 /// \return true if the redeclaration was invalid. 15259 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15260 QualType EnumUnderlyingTy, bool IsFixed, 15261 const EnumDecl *Prev) { 15262 if (IsScoped != Prev->isScoped()) { 15263 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15264 << Prev->isScoped(); 15265 Diag(Prev->getLocation(), diag::note_previous_declaration); 15266 return true; 15267 } 15268 15269 if (IsFixed && Prev->isFixed()) { 15270 if (!EnumUnderlyingTy->isDependentType() && 15271 !Prev->getIntegerType()->isDependentType() && 15272 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15273 Prev->getIntegerType())) { 15274 // TODO: Highlight the underlying type of the redeclaration. 15275 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15276 << EnumUnderlyingTy << Prev->getIntegerType(); 15277 Diag(Prev->getLocation(), diag::note_previous_declaration) 15278 << Prev->getIntegerTypeRange(); 15279 return true; 15280 } 15281 } else if (IsFixed != Prev->isFixed()) { 15282 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15283 << Prev->isFixed(); 15284 Diag(Prev->getLocation(), diag::note_previous_declaration); 15285 return true; 15286 } 15287 15288 return false; 15289 } 15290 15291 /// Get diagnostic %select index for tag kind for 15292 /// redeclaration diagnostic message. 15293 /// WARNING: Indexes apply to particular diagnostics only! 15294 /// 15295 /// \returns diagnostic %select index. 15296 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15297 switch (Tag) { 15298 case TTK_Struct: return 0; 15299 case TTK_Interface: return 1; 15300 case TTK_Class: return 2; 15301 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15302 } 15303 } 15304 15305 /// Determine if tag kind is a class-key compatible with 15306 /// class for redeclaration (class, struct, or __interface). 15307 /// 15308 /// \returns true iff the tag kind is compatible. 15309 static bool isClassCompatTagKind(TagTypeKind Tag) 15310 { 15311 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15312 } 15313 15314 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15315 TagTypeKind TTK) { 15316 if (isa<TypedefDecl>(PrevDecl)) 15317 return NTK_Typedef; 15318 else if (isa<TypeAliasDecl>(PrevDecl)) 15319 return NTK_TypeAlias; 15320 else if (isa<ClassTemplateDecl>(PrevDecl)) 15321 return NTK_Template; 15322 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15323 return NTK_TypeAliasTemplate; 15324 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15325 return NTK_TemplateTemplateArgument; 15326 switch (TTK) { 15327 case TTK_Struct: 15328 case TTK_Interface: 15329 case TTK_Class: 15330 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15331 case TTK_Union: 15332 return NTK_NonUnion; 15333 case TTK_Enum: 15334 return NTK_NonEnum; 15335 } 15336 llvm_unreachable("invalid TTK"); 15337 } 15338 15339 /// Determine whether a tag with a given kind is acceptable 15340 /// as a redeclaration of the given tag declaration. 15341 /// 15342 /// \returns true if the new tag kind is acceptable, false otherwise. 15343 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15344 TagTypeKind NewTag, bool isDefinition, 15345 SourceLocation NewTagLoc, 15346 const IdentifierInfo *Name) { 15347 // C++ [dcl.type.elab]p3: 15348 // The class-key or enum keyword present in the 15349 // elaborated-type-specifier shall agree in kind with the 15350 // declaration to which the name in the elaborated-type-specifier 15351 // refers. This rule also applies to the form of 15352 // elaborated-type-specifier that declares a class-name or 15353 // friend class since it can be construed as referring to the 15354 // definition of the class. Thus, in any 15355 // elaborated-type-specifier, the enum keyword shall be used to 15356 // refer to an enumeration (7.2), the union class-key shall be 15357 // used to refer to a union (clause 9), and either the class or 15358 // struct class-key shall be used to refer to a class (clause 9) 15359 // declared using the class or struct class-key. 15360 TagTypeKind OldTag = Previous->getTagKind(); 15361 if (OldTag != NewTag && 15362 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15363 return false; 15364 15365 // Tags are compatible, but we might still want to warn on mismatched tags. 15366 // Non-class tags can't be mismatched at this point. 15367 if (!isClassCompatTagKind(NewTag)) 15368 return true; 15369 15370 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15371 // by our warning analysis. We don't want to warn about mismatches with (eg) 15372 // declarations in system headers that are designed to be specialized, but if 15373 // a user asks us to warn, we should warn if their code contains mismatched 15374 // declarations. 15375 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15376 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15377 Loc); 15378 }; 15379 if (IsIgnoredLoc(NewTagLoc)) 15380 return true; 15381 15382 auto IsIgnored = [&](const TagDecl *Tag) { 15383 return IsIgnoredLoc(Tag->getLocation()); 15384 }; 15385 while (IsIgnored(Previous)) { 15386 Previous = Previous->getPreviousDecl(); 15387 if (!Previous) 15388 return true; 15389 OldTag = Previous->getTagKind(); 15390 } 15391 15392 bool isTemplate = false; 15393 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15394 isTemplate = Record->getDescribedClassTemplate(); 15395 15396 if (inTemplateInstantiation()) { 15397 if (OldTag != NewTag) { 15398 // In a template instantiation, do not offer fix-its for tag mismatches 15399 // since they usually mess up the template instead of fixing the problem. 15400 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15401 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15402 << getRedeclDiagFromTagKind(OldTag); 15403 // FIXME: Note previous location? 15404 } 15405 return true; 15406 } 15407 15408 if (isDefinition) { 15409 // On definitions, check all previous tags and issue a fix-it for each 15410 // one that doesn't match the current tag. 15411 if (Previous->getDefinition()) { 15412 // Don't suggest fix-its for redefinitions. 15413 return true; 15414 } 15415 15416 bool previousMismatch = false; 15417 for (const TagDecl *I : Previous->redecls()) { 15418 if (I->getTagKind() != NewTag) { 15419 // Ignore previous declarations for which the warning was disabled. 15420 if (IsIgnored(I)) 15421 continue; 15422 15423 if (!previousMismatch) { 15424 previousMismatch = true; 15425 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15426 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15427 << getRedeclDiagFromTagKind(I->getTagKind()); 15428 } 15429 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15430 << getRedeclDiagFromTagKind(NewTag) 15431 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15432 TypeWithKeyword::getTagTypeKindName(NewTag)); 15433 } 15434 } 15435 return true; 15436 } 15437 15438 // Identify the prevailing tag kind: this is the kind of the definition (if 15439 // there is a non-ignored definition), or otherwise the kind of the prior 15440 // (non-ignored) declaration. 15441 const TagDecl *PrevDef = Previous->getDefinition(); 15442 if (PrevDef && IsIgnored(PrevDef)) 15443 PrevDef = nullptr; 15444 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15445 if (Redecl->getTagKind() != NewTag) { 15446 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15447 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15448 << getRedeclDiagFromTagKind(OldTag); 15449 Diag(Redecl->getLocation(), diag::note_previous_use); 15450 15451 // If there is a previous definition, suggest a fix-it. 15452 if (PrevDef) { 15453 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15454 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15455 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15456 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15457 } 15458 } 15459 15460 return true; 15461 } 15462 15463 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15464 /// from an outer enclosing namespace or file scope inside a friend declaration. 15465 /// This should provide the commented out code in the following snippet: 15466 /// namespace N { 15467 /// struct X; 15468 /// namespace M { 15469 /// struct Y { friend struct /*N::*/ X; }; 15470 /// } 15471 /// } 15472 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15473 SourceLocation NameLoc) { 15474 // While the decl is in a namespace, do repeated lookup of that name and see 15475 // if we get the same namespace back. If we do not, continue until 15476 // translation unit scope, at which point we have a fully qualified NNS. 15477 SmallVector<IdentifierInfo *, 4> Namespaces; 15478 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15479 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15480 // This tag should be declared in a namespace, which can only be enclosed by 15481 // other namespaces. Bail if there's an anonymous namespace in the chain. 15482 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15483 if (!Namespace || Namespace->isAnonymousNamespace()) 15484 return FixItHint(); 15485 IdentifierInfo *II = Namespace->getIdentifier(); 15486 Namespaces.push_back(II); 15487 NamedDecl *Lookup = SemaRef.LookupSingleName( 15488 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15489 if (Lookup == Namespace) 15490 break; 15491 } 15492 15493 // Once we have all the namespaces, reverse them to go outermost first, and 15494 // build an NNS. 15495 SmallString<64> Insertion; 15496 llvm::raw_svector_ostream OS(Insertion); 15497 if (DC->isTranslationUnit()) 15498 OS << "::"; 15499 std::reverse(Namespaces.begin(), Namespaces.end()); 15500 for (auto *II : Namespaces) 15501 OS << II->getName() << "::"; 15502 return FixItHint::CreateInsertion(NameLoc, Insertion); 15503 } 15504 15505 /// Determine whether a tag originally declared in context \p OldDC can 15506 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15507 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15508 /// using-declaration). 15509 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15510 DeclContext *NewDC) { 15511 OldDC = OldDC->getRedeclContext(); 15512 NewDC = NewDC->getRedeclContext(); 15513 15514 if (OldDC->Equals(NewDC)) 15515 return true; 15516 15517 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15518 // encloses the other). 15519 if (S.getLangOpts().MSVCCompat && 15520 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15521 return true; 15522 15523 return false; 15524 } 15525 15526 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15527 /// former case, Name will be non-null. In the later case, Name will be null. 15528 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15529 /// reference/declaration/definition of a tag. 15530 /// 15531 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15532 /// trailing-type-specifier) other than one in an alias-declaration. 15533 /// 15534 /// \param SkipBody If non-null, will be set to indicate if the caller should 15535 /// skip the definition of this tag and treat it as if it were a declaration. 15536 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15537 SourceLocation KWLoc, CXXScopeSpec &SS, 15538 IdentifierInfo *Name, SourceLocation NameLoc, 15539 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15540 SourceLocation ModulePrivateLoc, 15541 MultiTemplateParamsArg TemplateParameterLists, 15542 bool &OwnedDecl, bool &IsDependent, 15543 SourceLocation ScopedEnumKWLoc, 15544 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15545 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15546 SkipBodyInfo *SkipBody) { 15547 // If this is not a definition, it must have a name. 15548 IdentifierInfo *OrigName = Name; 15549 assert((Name != nullptr || TUK == TUK_Definition) && 15550 "Nameless record must be a definition!"); 15551 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15552 15553 OwnedDecl = false; 15554 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15555 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15556 15557 // FIXME: Check member specializations more carefully. 15558 bool isMemberSpecialization = false; 15559 bool Invalid = false; 15560 15561 // We only need to do this matching if we have template parameters 15562 // or a scope specifier, which also conveniently avoids this work 15563 // for non-C++ cases. 15564 if (TemplateParameterLists.size() > 0 || 15565 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15566 if (TemplateParameterList *TemplateParams = 15567 MatchTemplateParametersToScopeSpecifier( 15568 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15569 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15570 if (Kind == TTK_Enum) { 15571 Diag(KWLoc, diag::err_enum_template); 15572 return nullptr; 15573 } 15574 15575 if (TemplateParams->size() > 0) { 15576 // This is a declaration or definition of a class template (which may 15577 // be a member of another template). 15578 15579 if (Invalid) 15580 return nullptr; 15581 15582 OwnedDecl = false; 15583 DeclResult Result = CheckClassTemplate( 15584 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15585 AS, ModulePrivateLoc, 15586 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15587 TemplateParameterLists.data(), SkipBody); 15588 return Result.get(); 15589 } else { 15590 // The "template<>" header is extraneous. 15591 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15592 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15593 isMemberSpecialization = true; 15594 } 15595 } 15596 15597 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15598 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15599 return nullptr; 15600 } 15601 15602 // Figure out the underlying type if this a enum declaration. We need to do 15603 // this early, because it's needed to detect if this is an incompatible 15604 // redeclaration. 15605 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15606 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15607 15608 if (Kind == TTK_Enum) { 15609 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15610 // No underlying type explicitly specified, or we failed to parse the 15611 // type, default to int. 15612 EnumUnderlying = Context.IntTy.getTypePtr(); 15613 } else if (UnderlyingType.get()) { 15614 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15615 // integral type; any cv-qualification is ignored. 15616 TypeSourceInfo *TI = nullptr; 15617 GetTypeFromParser(UnderlyingType.get(), &TI); 15618 EnumUnderlying = TI; 15619 15620 if (CheckEnumUnderlyingType(TI)) 15621 // Recover by falling back to int. 15622 EnumUnderlying = Context.IntTy.getTypePtr(); 15623 15624 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15625 UPPC_FixedUnderlyingType)) 15626 EnumUnderlying = Context.IntTy.getTypePtr(); 15627 15628 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15629 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15630 // of 'int'. However, if this is an unfixed forward declaration, don't set 15631 // the underlying type unless the user enables -fms-compatibility. This 15632 // makes unfixed forward declared enums incomplete and is more conforming. 15633 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15634 EnumUnderlying = Context.IntTy.getTypePtr(); 15635 } 15636 } 15637 15638 DeclContext *SearchDC = CurContext; 15639 DeclContext *DC = CurContext; 15640 bool isStdBadAlloc = false; 15641 bool isStdAlignValT = false; 15642 15643 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15644 if (TUK == TUK_Friend || TUK == TUK_Reference) 15645 Redecl = NotForRedeclaration; 15646 15647 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15648 /// implemented asks for structural equivalence checking, the returned decl 15649 /// here is passed back to the parser, allowing the tag body to be parsed. 15650 auto createTagFromNewDecl = [&]() -> TagDecl * { 15651 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15652 // If there is an identifier, use the location of the identifier as the 15653 // location of the decl, otherwise use the location of the struct/union 15654 // keyword. 15655 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15656 TagDecl *New = nullptr; 15657 15658 if (Kind == TTK_Enum) { 15659 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15660 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15661 // If this is an undefined enum, bail. 15662 if (TUK != TUK_Definition && !Invalid) 15663 return nullptr; 15664 if (EnumUnderlying) { 15665 EnumDecl *ED = cast<EnumDecl>(New); 15666 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15667 ED->setIntegerTypeSourceInfo(TI); 15668 else 15669 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15670 ED->setPromotionType(ED->getIntegerType()); 15671 } 15672 } else { // struct/union 15673 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15674 nullptr); 15675 } 15676 15677 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15678 // Add alignment attributes if necessary; these attributes are checked 15679 // when the ASTContext lays out the structure. 15680 // 15681 // It is important for implementing the correct semantics that this 15682 // happen here (in ActOnTag). The #pragma pack stack is 15683 // maintained as a result of parser callbacks which can occur at 15684 // many points during the parsing of a struct declaration (because 15685 // the #pragma tokens are effectively skipped over during the 15686 // parsing of the struct). 15687 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15688 AddAlignmentAttributesForRecord(RD); 15689 AddMsStructLayoutForRecord(RD); 15690 } 15691 } 15692 New->setLexicalDeclContext(CurContext); 15693 return New; 15694 }; 15695 15696 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15697 if (Name && SS.isNotEmpty()) { 15698 // We have a nested-name tag ('struct foo::bar'). 15699 15700 // Check for invalid 'foo::'. 15701 if (SS.isInvalid()) { 15702 Name = nullptr; 15703 goto CreateNewDecl; 15704 } 15705 15706 // If this is a friend or a reference to a class in a dependent 15707 // context, don't try to make a decl for it. 15708 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15709 DC = computeDeclContext(SS, false); 15710 if (!DC) { 15711 IsDependent = true; 15712 return nullptr; 15713 } 15714 } else { 15715 DC = computeDeclContext(SS, true); 15716 if (!DC) { 15717 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15718 << SS.getRange(); 15719 return nullptr; 15720 } 15721 } 15722 15723 if (RequireCompleteDeclContext(SS, DC)) 15724 return nullptr; 15725 15726 SearchDC = DC; 15727 // Look-up name inside 'foo::'. 15728 LookupQualifiedName(Previous, DC); 15729 15730 if (Previous.isAmbiguous()) 15731 return nullptr; 15732 15733 if (Previous.empty()) { 15734 // Name lookup did not find anything. However, if the 15735 // nested-name-specifier refers to the current instantiation, 15736 // and that current instantiation has any dependent base 15737 // classes, we might find something at instantiation time: treat 15738 // this as a dependent elaborated-type-specifier. 15739 // But this only makes any sense for reference-like lookups. 15740 if (Previous.wasNotFoundInCurrentInstantiation() && 15741 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15742 IsDependent = true; 15743 return nullptr; 15744 } 15745 15746 // A tag 'foo::bar' must already exist. 15747 Diag(NameLoc, diag::err_not_tag_in_scope) 15748 << Kind << Name << DC << SS.getRange(); 15749 Name = nullptr; 15750 Invalid = true; 15751 goto CreateNewDecl; 15752 } 15753 } else if (Name) { 15754 // C++14 [class.mem]p14: 15755 // If T is the name of a class, then each of the following shall have a 15756 // name different from T: 15757 // -- every member of class T that is itself a type 15758 if (TUK != TUK_Reference && TUK != TUK_Friend && 15759 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15760 return nullptr; 15761 15762 // If this is a named struct, check to see if there was a previous forward 15763 // declaration or definition. 15764 // FIXME: We're looking into outer scopes here, even when we 15765 // shouldn't be. Doing so can result in ambiguities that we 15766 // shouldn't be diagnosing. 15767 LookupName(Previous, S); 15768 15769 // When declaring or defining a tag, ignore ambiguities introduced 15770 // by types using'ed into this scope. 15771 if (Previous.isAmbiguous() && 15772 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15773 LookupResult::Filter F = Previous.makeFilter(); 15774 while (F.hasNext()) { 15775 NamedDecl *ND = F.next(); 15776 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15777 SearchDC->getRedeclContext())) 15778 F.erase(); 15779 } 15780 F.done(); 15781 } 15782 15783 // C++11 [namespace.memdef]p3: 15784 // If the name in a friend declaration is neither qualified nor 15785 // a template-id and the declaration is a function or an 15786 // elaborated-type-specifier, the lookup to determine whether 15787 // the entity has been previously declared shall not consider 15788 // any scopes outside the innermost enclosing namespace. 15789 // 15790 // MSVC doesn't implement the above rule for types, so a friend tag 15791 // declaration may be a redeclaration of a type declared in an enclosing 15792 // scope. They do implement this rule for friend functions. 15793 // 15794 // Does it matter that this should be by scope instead of by 15795 // semantic context? 15796 if (!Previous.empty() && TUK == TUK_Friend) { 15797 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15798 LookupResult::Filter F = Previous.makeFilter(); 15799 bool FriendSawTagOutsideEnclosingNamespace = false; 15800 while (F.hasNext()) { 15801 NamedDecl *ND = F.next(); 15802 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15803 if (DC->isFileContext() && 15804 !EnclosingNS->Encloses(ND->getDeclContext())) { 15805 if (getLangOpts().MSVCCompat) 15806 FriendSawTagOutsideEnclosingNamespace = true; 15807 else 15808 F.erase(); 15809 } 15810 } 15811 F.done(); 15812 15813 // Diagnose this MSVC extension in the easy case where lookup would have 15814 // unambiguously found something outside the enclosing namespace. 15815 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15816 NamedDecl *ND = Previous.getFoundDecl(); 15817 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15818 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15819 } 15820 } 15821 15822 // Note: there used to be some attempt at recovery here. 15823 if (Previous.isAmbiguous()) 15824 return nullptr; 15825 15826 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15827 // FIXME: This makes sure that we ignore the contexts associated 15828 // with C structs, unions, and enums when looking for a matching 15829 // tag declaration or definition. See the similar lookup tweak 15830 // in Sema::LookupName; is there a better way to deal with this? 15831 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15832 SearchDC = SearchDC->getParent(); 15833 } 15834 } 15835 15836 if (Previous.isSingleResult() && 15837 Previous.getFoundDecl()->isTemplateParameter()) { 15838 // Maybe we will complain about the shadowed template parameter. 15839 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15840 // Just pretend that we didn't see the previous declaration. 15841 Previous.clear(); 15842 } 15843 15844 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15845 DC->Equals(getStdNamespace())) { 15846 if (Name->isStr("bad_alloc")) { 15847 // This is a declaration of or a reference to "std::bad_alloc". 15848 isStdBadAlloc = true; 15849 15850 // If std::bad_alloc has been implicitly declared (but made invisible to 15851 // name lookup), fill in this implicit declaration as the previous 15852 // declaration, so that the declarations get chained appropriately. 15853 if (Previous.empty() && StdBadAlloc) 15854 Previous.addDecl(getStdBadAlloc()); 15855 } else if (Name->isStr("align_val_t")) { 15856 isStdAlignValT = true; 15857 if (Previous.empty() && StdAlignValT) 15858 Previous.addDecl(getStdAlignValT()); 15859 } 15860 } 15861 15862 // If we didn't find a previous declaration, and this is a reference 15863 // (or friend reference), move to the correct scope. In C++, we 15864 // also need to do a redeclaration lookup there, just in case 15865 // there's a shadow friend decl. 15866 if (Name && Previous.empty() && 15867 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15868 if (Invalid) goto CreateNewDecl; 15869 assert(SS.isEmpty()); 15870 15871 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15872 // C++ [basic.scope.pdecl]p5: 15873 // -- for an elaborated-type-specifier of the form 15874 // 15875 // class-key identifier 15876 // 15877 // if the elaborated-type-specifier is used in the 15878 // decl-specifier-seq or parameter-declaration-clause of a 15879 // function defined in namespace scope, the identifier is 15880 // declared as a class-name in the namespace that contains 15881 // the declaration; otherwise, except as a friend 15882 // declaration, the identifier is declared in the smallest 15883 // non-class, non-function-prototype scope that contains the 15884 // declaration. 15885 // 15886 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15887 // C structs and unions. 15888 // 15889 // It is an error in C++ to declare (rather than define) an enum 15890 // type, including via an elaborated type specifier. We'll 15891 // diagnose that later; for now, declare the enum in the same 15892 // scope as we would have picked for any other tag type. 15893 // 15894 // GNU C also supports this behavior as part of its incomplete 15895 // enum types extension, while GNU C++ does not. 15896 // 15897 // Find the context where we'll be declaring the tag. 15898 // FIXME: We would like to maintain the current DeclContext as the 15899 // lexical context, 15900 SearchDC = getTagInjectionContext(SearchDC); 15901 15902 // Find the scope where we'll be declaring the tag. 15903 S = getTagInjectionScope(S, getLangOpts()); 15904 } else { 15905 assert(TUK == TUK_Friend); 15906 // C++ [namespace.memdef]p3: 15907 // If a friend declaration in a non-local class first declares a 15908 // class or function, the friend class or function is a member of 15909 // the innermost enclosing namespace. 15910 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15911 } 15912 15913 // In C++, we need to do a redeclaration lookup to properly 15914 // diagnose some problems. 15915 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15916 // hidden declaration so that we don't get ambiguity errors when using a 15917 // type declared by an elaborated-type-specifier. In C that is not correct 15918 // and we should instead merge compatible types found by lookup. 15919 if (getLangOpts().CPlusPlus) { 15920 // FIXME: This can perform qualified lookups into function contexts, 15921 // which are meaningless. 15922 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15923 LookupQualifiedName(Previous, SearchDC); 15924 } else { 15925 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15926 LookupName(Previous, S); 15927 } 15928 } 15929 15930 // If we have a known previous declaration to use, then use it. 15931 if (Previous.empty() && SkipBody && SkipBody->Previous) 15932 Previous.addDecl(SkipBody->Previous); 15933 15934 if (!Previous.empty()) { 15935 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15936 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15937 15938 // It's okay to have a tag decl in the same scope as a typedef 15939 // which hides a tag decl in the same scope. Finding this 15940 // insanity with a redeclaration lookup can only actually happen 15941 // in C++. 15942 // 15943 // This is also okay for elaborated-type-specifiers, which is 15944 // technically forbidden by the current standard but which is 15945 // okay according to the likely resolution of an open issue; 15946 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15947 if (getLangOpts().CPlusPlus) { 15948 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15949 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15950 TagDecl *Tag = TT->getDecl(); 15951 if (Tag->getDeclName() == Name && 15952 Tag->getDeclContext()->getRedeclContext() 15953 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15954 PrevDecl = Tag; 15955 Previous.clear(); 15956 Previous.addDecl(Tag); 15957 Previous.resolveKind(); 15958 } 15959 } 15960 } 15961 } 15962 15963 // If this is a redeclaration of a using shadow declaration, it must 15964 // declare a tag in the same context. In MSVC mode, we allow a 15965 // redefinition if either context is within the other. 15966 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15967 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15968 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15969 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15970 !(OldTag && isAcceptableTagRedeclContext( 15971 *this, OldTag->getDeclContext(), SearchDC))) { 15972 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15973 Diag(Shadow->getTargetDecl()->getLocation(), 15974 diag::note_using_decl_target); 15975 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 15976 << 0; 15977 // Recover by ignoring the old declaration. 15978 Previous.clear(); 15979 goto CreateNewDecl; 15980 } 15981 } 15982 15983 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15984 // If this is a use of a previous tag, or if the tag is already declared 15985 // in the same scope (so that the definition/declaration completes or 15986 // rementions the tag), reuse the decl. 15987 if (TUK == TUK_Reference || TUK == TUK_Friend || 15988 isDeclInScope(DirectPrevDecl, SearchDC, S, 15989 SS.isNotEmpty() || isMemberSpecialization)) { 15990 // Make sure that this wasn't declared as an enum and now used as a 15991 // struct or something similar. 15992 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15993 TUK == TUK_Definition, KWLoc, 15994 Name)) { 15995 bool SafeToContinue 15996 = (PrevTagDecl->getTagKind() != TTK_Enum && 15997 Kind != TTK_Enum); 15998 if (SafeToContinue) 15999 Diag(KWLoc, diag::err_use_with_wrong_tag) 16000 << Name 16001 << FixItHint::CreateReplacement(SourceRange(KWLoc), 16002 PrevTagDecl->getKindName()); 16003 else 16004 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 16005 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 16006 16007 if (SafeToContinue) 16008 Kind = PrevTagDecl->getTagKind(); 16009 else { 16010 // Recover by making this an anonymous redefinition. 16011 Name = nullptr; 16012 Previous.clear(); 16013 Invalid = true; 16014 } 16015 } 16016 16017 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 16018 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 16019 if (TUK == TUK_Reference || TUK == TUK_Friend) 16020 return PrevTagDecl; 16021 16022 QualType EnumUnderlyingTy; 16023 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16024 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 16025 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 16026 EnumUnderlyingTy = QualType(T, 0); 16027 16028 // All conflicts with previous declarations are recovered by 16029 // returning the previous declaration, unless this is a definition, 16030 // in which case we want the caller to bail out. 16031 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 16032 ScopedEnum, EnumUnderlyingTy, 16033 IsFixed, PrevEnum)) 16034 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 16035 } 16036 16037 // C++11 [class.mem]p1: 16038 // A member shall not be declared twice in the member-specification, 16039 // except that a nested class or member class template can be declared 16040 // and then later defined. 16041 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 16042 S->isDeclScope(PrevDecl)) { 16043 Diag(NameLoc, diag::ext_member_redeclared); 16044 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 16045 } 16046 16047 if (!Invalid) { 16048 // If this is a use, just return the declaration we found, unless 16049 // we have attributes. 16050 if (TUK == TUK_Reference || TUK == TUK_Friend) { 16051 if (!Attrs.empty()) { 16052 // FIXME: Diagnose these attributes. For now, we create a new 16053 // declaration to hold them. 16054 } else if (TUK == TUK_Reference && 16055 (PrevTagDecl->getFriendObjectKind() == 16056 Decl::FOK_Undeclared || 16057 PrevDecl->getOwningModule() != getCurrentModule()) && 16058 SS.isEmpty()) { 16059 // This declaration is a reference to an existing entity, but 16060 // has different visibility from that entity: it either makes 16061 // a friend visible or it makes a type visible in a new module. 16062 // In either case, create a new declaration. We only do this if 16063 // the declaration would have meant the same thing if no prior 16064 // declaration were found, that is, if it was found in the same 16065 // scope where we would have injected a declaration. 16066 if (!getTagInjectionContext(CurContext)->getRedeclContext() 16067 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 16068 return PrevTagDecl; 16069 // This is in the injected scope, create a new declaration in 16070 // that scope. 16071 S = getTagInjectionScope(S, getLangOpts()); 16072 } else { 16073 return PrevTagDecl; 16074 } 16075 } 16076 16077 // Diagnose attempts to redefine a tag. 16078 if (TUK == TUK_Definition) { 16079 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 16080 // If we're defining a specialization and the previous definition 16081 // is from an implicit instantiation, don't emit an error 16082 // here; we'll catch this in the general case below. 16083 bool IsExplicitSpecializationAfterInstantiation = false; 16084 if (isMemberSpecialization) { 16085 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 16086 IsExplicitSpecializationAfterInstantiation = 16087 RD->getTemplateSpecializationKind() != 16088 TSK_ExplicitSpecialization; 16089 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 16090 IsExplicitSpecializationAfterInstantiation = 16091 ED->getTemplateSpecializationKind() != 16092 TSK_ExplicitSpecialization; 16093 } 16094 16095 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 16096 // not keep more that one definition around (merge them). However, 16097 // ensure the decl passes the structural compatibility check in 16098 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 16099 NamedDecl *Hidden = nullptr; 16100 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 16101 // There is a definition of this tag, but it is not visible. We 16102 // explicitly make use of C++'s one definition rule here, and 16103 // assume that this definition is identical to the hidden one 16104 // we already have. Make the existing definition visible and 16105 // use it in place of this one. 16106 if (!getLangOpts().CPlusPlus) { 16107 // Postpone making the old definition visible until after we 16108 // complete parsing the new one and do the structural 16109 // comparison. 16110 SkipBody->CheckSameAsPrevious = true; 16111 SkipBody->New = createTagFromNewDecl(); 16112 SkipBody->Previous = Def; 16113 return Def; 16114 } else { 16115 SkipBody->ShouldSkip = true; 16116 SkipBody->Previous = Def; 16117 makeMergedDefinitionVisible(Hidden); 16118 // Carry on and handle it like a normal definition. We'll 16119 // skip starting the definitiion later. 16120 } 16121 } else if (!IsExplicitSpecializationAfterInstantiation) { 16122 // A redeclaration in function prototype scope in C isn't 16123 // visible elsewhere, so merely issue a warning. 16124 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 16125 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 16126 else 16127 Diag(NameLoc, diag::err_redefinition) << Name; 16128 notePreviousDefinition(Def, 16129 NameLoc.isValid() ? NameLoc : KWLoc); 16130 // If this is a redefinition, recover by making this 16131 // struct be anonymous, which will make any later 16132 // references get the previous definition. 16133 Name = nullptr; 16134 Previous.clear(); 16135 Invalid = true; 16136 } 16137 } else { 16138 // If the type is currently being defined, complain 16139 // about a nested redefinition. 16140 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 16141 if (TD->isBeingDefined()) { 16142 Diag(NameLoc, diag::err_nested_redefinition) << Name; 16143 Diag(PrevTagDecl->getLocation(), 16144 diag::note_previous_definition); 16145 Name = nullptr; 16146 Previous.clear(); 16147 Invalid = true; 16148 } 16149 } 16150 16151 // Okay, this is definition of a previously declared or referenced 16152 // tag. We're going to create a new Decl for it. 16153 } 16154 16155 // Okay, we're going to make a redeclaration. If this is some kind 16156 // of reference, make sure we build the redeclaration in the same DC 16157 // as the original, and ignore the current access specifier. 16158 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16159 SearchDC = PrevTagDecl->getDeclContext(); 16160 AS = AS_none; 16161 } 16162 } 16163 // If we get here we have (another) forward declaration or we 16164 // have a definition. Just create a new decl. 16165 16166 } else { 16167 // If we get here, this is a definition of a new tag type in a nested 16168 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 16169 // new decl/type. We set PrevDecl to NULL so that the entities 16170 // have distinct types. 16171 Previous.clear(); 16172 } 16173 // If we get here, we're going to create a new Decl. If PrevDecl 16174 // is non-NULL, it's a definition of the tag declared by 16175 // PrevDecl. If it's NULL, we have a new definition. 16176 16177 // Otherwise, PrevDecl is not a tag, but was found with tag 16178 // lookup. This is only actually possible in C++, where a few 16179 // things like templates still live in the tag namespace. 16180 } else { 16181 // Use a better diagnostic if an elaborated-type-specifier 16182 // found the wrong kind of type on the first 16183 // (non-redeclaration) lookup. 16184 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16185 !Previous.isForRedeclaration()) { 16186 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16187 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16188 << Kind; 16189 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16190 Invalid = true; 16191 16192 // Otherwise, only diagnose if the declaration is in scope. 16193 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16194 SS.isNotEmpty() || isMemberSpecialization)) { 16195 // do nothing 16196 16197 // Diagnose implicit declarations introduced by elaborated types. 16198 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16199 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16200 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16201 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16202 Invalid = true; 16203 16204 // Otherwise it's a declaration. Call out a particularly common 16205 // case here. 16206 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16207 unsigned Kind = 0; 16208 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16209 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16210 << Name << Kind << TND->getUnderlyingType(); 16211 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16212 Invalid = true; 16213 16214 // Otherwise, diagnose. 16215 } else { 16216 // The tag name clashes with something else in the target scope, 16217 // issue an error and recover by making this tag be anonymous. 16218 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16219 notePreviousDefinition(PrevDecl, NameLoc); 16220 Name = nullptr; 16221 Invalid = true; 16222 } 16223 16224 // The existing declaration isn't relevant to us; we're in a 16225 // new scope, so clear out the previous declaration. 16226 Previous.clear(); 16227 } 16228 } 16229 16230 CreateNewDecl: 16231 16232 TagDecl *PrevDecl = nullptr; 16233 if (Previous.isSingleResult()) 16234 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16235 16236 // If there is an identifier, use the location of the identifier as the 16237 // location of the decl, otherwise use the location of the struct/union 16238 // keyword. 16239 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16240 16241 // Otherwise, create a new declaration. If there is a previous 16242 // declaration of the same entity, the two will be linked via 16243 // PrevDecl. 16244 TagDecl *New; 16245 16246 if (Kind == TTK_Enum) { 16247 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16248 // enum X { A, B, C } D; D should chain to X. 16249 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16250 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16251 ScopedEnumUsesClassTag, IsFixed); 16252 16253 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16254 StdAlignValT = cast<EnumDecl>(New); 16255 16256 // If this is an undefined enum, warn. 16257 if (TUK != TUK_Definition && !Invalid) { 16258 TagDecl *Def; 16259 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16260 // C++0x: 7.2p2: opaque-enum-declaration. 16261 // Conflicts are diagnosed above. Do nothing. 16262 } 16263 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16264 Diag(Loc, diag::ext_forward_ref_enum_def) 16265 << New; 16266 Diag(Def->getLocation(), diag::note_previous_definition); 16267 } else { 16268 unsigned DiagID = diag::ext_forward_ref_enum; 16269 if (getLangOpts().MSVCCompat) 16270 DiagID = diag::ext_ms_forward_ref_enum; 16271 else if (getLangOpts().CPlusPlus) 16272 DiagID = diag::err_forward_ref_enum; 16273 Diag(Loc, DiagID); 16274 } 16275 } 16276 16277 if (EnumUnderlying) { 16278 EnumDecl *ED = cast<EnumDecl>(New); 16279 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16280 ED->setIntegerTypeSourceInfo(TI); 16281 else 16282 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16283 ED->setPromotionType(ED->getIntegerType()); 16284 assert(ED->isComplete() && "enum with type should be complete"); 16285 } 16286 } else { 16287 // struct/union/class 16288 16289 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16290 // struct X { int A; } D; D should chain to X. 16291 if (getLangOpts().CPlusPlus) { 16292 // FIXME: Look for a way to use RecordDecl for simple structs. 16293 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16294 cast_or_null<CXXRecordDecl>(PrevDecl)); 16295 16296 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16297 StdBadAlloc = cast<CXXRecordDecl>(New); 16298 } else 16299 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16300 cast_or_null<RecordDecl>(PrevDecl)); 16301 } 16302 16303 // C++11 [dcl.type]p3: 16304 // A type-specifier-seq shall not define a class or enumeration [...]. 16305 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16306 TUK == TUK_Definition) { 16307 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16308 << Context.getTagDeclType(New); 16309 Invalid = true; 16310 } 16311 16312 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16313 DC->getDeclKind() == Decl::Enum) { 16314 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16315 << Context.getTagDeclType(New); 16316 Invalid = true; 16317 } 16318 16319 // Maybe add qualifier info. 16320 if (SS.isNotEmpty()) { 16321 if (SS.isSet()) { 16322 // If this is either a declaration or a definition, check the 16323 // nested-name-specifier against the current context. 16324 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16325 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16326 isMemberSpecialization)) 16327 Invalid = true; 16328 16329 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16330 if (TemplateParameterLists.size() > 0) { 16331 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16332 } 16333 } 16334 else 16335 Invalid = true; 16336 } 16337 16338 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16339 // Add alignment attributes if necessary; these attributes are checked when 16340 // the ASTContext lays out the structure. 16341 // 16342 // It is important for implementing the correct semantics that this 16343 // happen here (in ActOnTag). The #pragma pack stack is 16344 // maintained as a result of parser callbacks which can occur at 16345 // many points during the parsing of a struct declaration (because 16346 // the #pragma tokens are effectively skipped over during the 16347 // parsing of the struct). 16348 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16349 AddAlignmentAttributesForRecord(RD); 16350 AddMsStructLayoutForRecord(RD); 16351 } 16352 } 16353 16354 if (ModulePrivateLoc.isValid()) { 16355 if (isMemberSpecialization) 16356 Diag(New->getLocation(), diag::err_module_private_specialization) 16357 << 2 16358 << FixItHint::CreateRemoval(ModulePrivateLoc); 16359 // __module_private__ does not apply to local classes. However, we only 16360 // diagnose this as an error when the declaration specifiers are 16361 // freestanding. Here, we just ignore the __module_private__. 16362 else if (!SearchDC->isFunctionOrMethod()) 16363 New->setModulePrivate(); 16364 } 16365 16366 // If this is a specialization of a member class (of a class template), 16367 // check the specialization. 16368 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16369 Invalid = true; 16370 16371 // If we're declaring or defining a tag in function prototype scope in C, 16372 // note that this type can only be used within the function and add it to 16373 // the list of decls to inject into the function definition scope. 16374 if ((Name || Kind == TTK_Enum) && 16375 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16376 if (getLangOpts().CPlusPlus) { 16377 // C++ [dcl.fct]p6: 16378 // Types shall not be defined in return or parameter types. 16379 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16380 Diag(Loc, diag::err_type_defined_in_param_type) 16381 << Name; 16382 Invalid = true; 16383 } 16384 } else if (!PrevDecl) { 16385 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16386 } 16387 } 16388 16389 if (Invalid) 16390 New->setInvalidDecl(); 16391 16392 // Set the lexical context. If the tag has a C++ scope specifier, the 16393 // lexical context will be different from the semantic context. 16394 New->setLexicalDeclContext(CurContext); 16395 16396 // Mark this as a friend decl if applicable. 16397 // In Microsoft mode, a friend declaration also acts as a forward 16398 // declaration so we always pass true to setObjectOfFriendDecl to make 16399 // the tag name visible. 16400 if (TUK == TUK_Friend) 16401 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16402 16403 // Set the access specifier. 16404 if (!Invalid && SearchDC->isRecord()) 16405 SetMemberAccessSpecifier(New, PrevDecl, AS); 16406 16407 if (PrevDecl) 16408 CheckRedeclarationModuleOwnership(New, PrevDecl); 16409 16410 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16411 New->startDefinition(); 16412 16413 ProcessDeclAttributeList(S, New, Attrs); 16414 AddPragmaAttributes(S, New); 16415 16416 // If this has an identifier, add it to the scope stack. 16417 if (TUK == TUK_Friend) { 16418 // We might be replacing an existing declaration in the lookup tables; 16419 // if so, borrow its access specifier. 16420 if (PrevDecl) 16421 New->setAccess(PrevDecl->getAccess()); 16422 16423 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16424 DC->makeDeclVisibleInContext(New); 16425 if (Name) // can be null along some error paths 16426 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16427 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16428 } else if (Name) { 16429 S = getNonFieldDeclScope(S); 16430 PushOnScopeChains(New, S, true); 16431 } else { 16432 CurContext->addDecl(New); 16433 } 16434 16435 // If this is the C FILE type, notify the AST context. 16436 if (IdentifierInfo *II = New->getIdentifier()) 16437 if (!New->isInvalidDecl() && 16438 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16439 II->isStr("FILE")) 16440 Context.setFILEDecl(New); 16441 16442 if (PrevDecl) 16443 mergeDeclAttributes(New, PrevDecl); 16444 16445 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16446 inferGslOwnerPointerAttribute(CXXRD); 16447 16448 // If there's a #pragma GCC visibility in scope, set the visibility of this 16449 // record. 16450 AddPushedVisibilityAttribute(New); 16451 16452 if (isMemberSpecialization && !New->isInvalidDecl()) 16453 CompleteMemberSpecialization(New, Previous); 16454 16455 OwnedDecl = true; 16456 // In C++, don't return an invalid declaration. We can't recover well from 16457 // the cases where we make the type anonymous. 16458 if (Invalid && getLangOpts().CPlusPlus) { 16459 if (New->isBeingDefined()) 16460 if (auto RD = dyn_cast<RecordDecl>(New)) 16461 RD->completeDefinition(); 16462 return nullptr; 16463 } else if (SkipBody && SkipBody->ShouldSkip) { 16464 return SkipBody->Previous; 16465 } else { 16466 return New; 16467 } 16468 } 16469 16470 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16471 AdjustDeclIfTemplate(TagD); 16472 TagDecl *Tag = cast<TagDecl>(TagD); 16473 16474 // Enter the tag context. 16475 PushDeclContext(S, Tag); 16476 16477 ActOnDocumentableDecl(TagD); 16478 16479 // If there's a #pragma GCC visibility in scope, set the visibility of this 16480 // record. 16481 AddPushedVisibilityAttribute(Tag); 16482 } 16483 16484 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16485 SkipBodyInfo &SkipBody) { 16486 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16487 return false; 16488 16489 // Make the previous decl visible. 16490 makeMergedDefinitionVisible(SkipBody.Previous); 16491 return true; 16492 } 16493 16494 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16495 assert(isa<ObjCContainerDecl>(IDecl) && 16496 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16497 DeclContext *OCD = cast<DeclContext>(IDecl); 16498 assert(OCD->getLexicalParent() == CurContext && 16499 "The next DeclContext should be lexically contained in the current one."); 16500 CurContext = OCD; 16501 return IDecl; 16502 } 16503 16504 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16505 SourceLocation FinalLoc, 16506 bool IsFinalSpelledSealed, 16507 bool IsAbstract, 16508 SourceLocation LBraceLoc) { 16509 AdjustDeclIfTemplate(TagD); 16510 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16511 16512 FieldCollector->StartClass(); 16513 16514 if (!Record->getIdentifier()) 16515 return; 16516 16517 if (IsAbstract) 16518 Record->markAbstract(); 16519 16520 if (FinalLoc.isValid()) { 16521 Record->addAttr(FinalAttr::Create( 16522 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16523 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16524 } 16525 // C++ [class]p2: 16526 // [...] The class-name is also inserted into the scope of the 16527 // class itself; this is known as the injected-class-name. For 16528 // purposes of access checking, the injected-class-name is treated 16529 // as if it were a public member name. 16530 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16531 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16532 Record->getLocation(), Record->getIdentifier(), 16533 /*PrevDecl=*/nullptr, 16534 /*DelayTypeCreation=*/true); 16535 Context.getTypeDeclType(InjectedClassName, Record); 16536 InjectedClassName->setImplicit(); 16537 InjectedClassName->setAccess(AS_public); 16538 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16539 InjectedClassName->setDescribedClassTemplate(Template); 16540 PushOnScopeChains(InjectedClassName, S); 16541 assert(InjectedClassName->isInjectedClassName() && 16542 "Broken injected-class-name"); 16543 } 16544 16545 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16546 SourceRange BraceRange) { 16547 AdjustDeclIfTemplate(TagD); 16548 TagDecl *Tag = cast<TagDecl>(TagD); 16549 Tag->setBraceRange(BraceRange); 16550 16551 // Make sure we "complete" the definition even it is invalid. 16552 if (Tag->isBeingDefined()) { 16553 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16554 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16555 RD->completeDefinition(); 16556 } 16557 16558 if (isa<CXXRecordDecl>(Tag)) { 16559 FieldCollector->FinishClass(); 16560 } 16561 16562 // Exit this scope of this tag's definition. 16563 PopDeclContext(); 16564 16565 if (getCurLexicalContext()->isObjCContainer() && 16566 Tag->getDeclContext()->isFileContext()) 16567 Tag->setTopLevelDeclInObjCContainer(); 16568 16569 // Notify the consumer that we've defined a tag. 16570 if (!Tag->isInvalidDecl()) 16571 Consumer.HandleTagDeclDefinition(Tag); 16572 } 16573 16574 void Sema::ActOnObjCContainerFinishDefinition() { 16575 // Exit this scope of this interface definition. 16576 PopDeclContext(); 16577 } 16578 16579 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16580 assert(DC == CurContext && "Mismatch of container contexts"); 16581 OriginalLexicalContext = DC; 16582 ActOnObjCContainerFinishDefinition(); 16583 } 16584 16585 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16586 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16587 OriginalLexicalContext = nullptr; 16588 } 16589 16590 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16591 AdjustDeclIfTemplate(TagD); 16592 TagDecl *Tag = cast<TagDecl>(TagD); 16593 Tag->setInvalidDecl(); 16594 16595 // Make sure we "complete" the definition even it is invalid. 16596 if (Tag->isBeingDefined()) { 16597 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16598 RD->completeDefinition(); 16599 } 16600 16601 // We're undoing ActOnTagStartDefinition here, not 16602 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16603 // the FieldCollector. 16604 16605 PopDeclContext(); 16606 } 16607 16608 // Note that FieldName may be null for anonymous bitfields. 16609 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16610 IdentifierInfo *FieldName, 16611 QualType FieldTy, bool IsMsStruct, 16612 Expr *BitWidth, bool *ZeroWidth) { 16613 assert(BitWidth); 16614 if (BitWidth->containsErrors()) 16615 return ExprError(); 16616 16617 // Default to true; that shouldn't confuse checks for emptiness 16618 if (ZeroWidth) 16619 *ZeroWidth = true; 16620 16621 // C99 6.7.2.1p4 - verify the field type. 16622 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16623 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16624 // Handle incomplete and sizeless types with a specific error. 16625 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16626 diag::err_field_incomplete_or_sizeless)) 16627 return ExprError(); 16628 if (FieldName) 16629 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16630 << FieldName << FieldTy << BitWidth->getSourceRange(); 16631 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16632 << FieldTy << BitWidth->getSourceRange(); 16633 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16634 UPPC_BitFieldWidth)) 16635 return ExprError(); 16636 16637 // If the bit-width is type- or value-dependent, don't try to check 16638 // it now. 16639 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16640 return BitWidth; 16641 16642 llvm::APSInt Value; 16643 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 16644 if (ICE.isInvalid()) 16645 return ICE; 16646 BitWidth = ICE.get(); 16647 16648 if (Value != 0 && ZeroWidth) 16649 *ZeroWidth = false; 16650 16651 // Zero-width bitfield is ok for anonymous field. 16652 if (Value == 0 && FieldName) 16653 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16654 16655 if (Value.isSigned() && Value.isNegative()) { 16656 if (FieldName) 16657 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16658 << FieldName << toString(Value, 10); 16659 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16660 << toString(Value, 10); 16661 } 16662 16663 // The size of the bit-field must not exceed our maximum permitted object 16664 // size. 16665 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 16666 return Diag(FieldLoc, diag::err_bitfield_too_wide) 16667 << !FieldName << FieldName << toString(Value, 10); 16668 } 16669 16670 if (!FieldTy->isDependentType()) { 16671 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16672 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16673 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16674 16675 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16676 // ABI. 16677 bool CStdConstraintViolation = 16678 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16679 bool MSBitfieldViolation = 16680 Value.ugt(TypeStorageSize) && 16681 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16682 if (CStdConstraintViolation || MSBitfieldViolation) { 16683 unsigned DiagWidth = 16684 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16685 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16686 << (bool)FieldName << FieldName << toString(Value, 10) 16687 << !CStdConstraintViolation << DiagWidth; 16688 } 16689 16690 // Warn on types where the user might conceivably expect to get all 16691 // specified bits as value bits: that's all integral types other than 16692 // 'bool'. 16693 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 16694 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16695 << FieldName << toString(Value, 10) 16696 << (unsigned)TypeWidth; 16697 } 16698 } 16699 16700 return BitWidth; 16701 } 16702 16703 /// ActOnField - Each field of a C struct/union is passed into this in order 16704 /// to create a FieldDecl object for it. 16705 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16706 Declarator &D, Expr *BitfieldWidth) { 16707 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16708 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16709 /*InitStyle=*/ICIS_NoInit, AS_public); 16710 return Res; 16711 } 16712 16713 /// HandleField - Analyze a field of a C struct or a C++ data member. 16714 /// 16715 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16716 SourceLocation DeclStart, 16717 Declarator &D, Expr *BitWidth, 16718 InClassInitStyle InitStyle, 16719 AccessSpecifier AS) { 16720 if (D.isDecompositionDeclarator()) { 16721 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16722 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16723 << Decomp.getSourceRange(); 16724 return nullptr; 16725 } 16726 16727 IdentifierInfo *II = D.getIdentifier(); 16728 SourceLocation Loc = DeclStart; 16729 if (II) Loc = D.getIdentifierLoc(); 16730 16731 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16732 QualType T = TInfo->getType(); 16733 if (getLangOpts().CPlusPlus) { 16734 CheckExtraCXXDefaultArguments(D); 16735 16736 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16737 UPPC_DataMemberType)) { 16738 D.setInvalidType(); 16739 T = Context.IntTy; 16740 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16741 } 16742 } 16743 16744 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16745 16746 if (D.getDeclSpec().isInlineSpecified()) 16747 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16748 << getLangOpts().CPlusPlus17; 16749 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16750 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16751 diag::err_invalid_thread) 16752 << DeclSpec::getSpecifierName(TSCS); 16753 16754 // Check to see if this name was declared as a member previously 16755 NamedDecl *PrevDecl = nullptr; 16756 LookupResult Previous(*this, II, Loc, LookupMemberName, 16757 ForVisibleRedeclaration); 16758 LookupName(Previous, S); 16759 switch (Previous.getResultKind()) { 16760 case LookupResult::Found: 16761 case LookupResult::FoundUnresolvedValue: 16762 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16763 break; 16764 16765 case LookupResult::FoundOverloaded: 16766 PrevDecl = Previous.getRepresentativeDecl(); 16767 break; 16768 16769 case LookupResult::NotFound: 16770 case LookupResult::NotFoundInCurrentInstantiation: 16771 case LookupResult::Ambiguous: 16772 break; 16773 } 16774 Previous.suppressDiagnostics(); 16775 16776 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16777 // Maybe we will complain about the shadowed template parameter. 16778 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16779 // Just pretend that we didn't see the previous declaration. 16780 PrevDecl = nullptr; 16781 } 16782 16783 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16784 PrevDecl = nullptr; 16785 16786 bool Mutable 16787 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16788 SourceLocation TSSL = D.getBeginLoc(); 16789 FieldDecl *NewFD 16790 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16791 TSSL, AS, PrevDecl, &D); 16792 16793 if (NewFD->isInvalidDecl()) 16794 Record->setInvalidDecl(); 16795 16796 if (D.getDeclSpec().isModulePrivateSpecified()) 16797 NewFD->setModulePrivate(); 16798 16799 if (NewFD->isInvalidDecl() && PrevDecl) { 16800 // Don't introduce NewFD into scope; there's already something 16801 // with the same name in the same scope. 16802 } else if (II) { 16803 PushOnScopeChains(NewFD, S); 16804 } else 16805 Record->addDecl(NewFD); 16806 16807 return NewFD; 16808 } 16809 16810 /// Build a new FieldDecl and check its well-formedness. 16811 /// 16812 /// This routine builds a new FieldDecl given the fields name, type, 16813 /// record, etc. \p PrevDecl should refer to any previous declaration 16814 /// with the same name and in the same scope as the field to be 16815 /// created. 16816 /// 16817 /// \returns a new FieldDecl. 16818 /// 16819 /// \todo The Declarator argument is a hack. It will be removed once 16820 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16821 TypeSourceInfo *TInfo, 16822 RecordDecl *Record, SourceLocation Loc, 16823 bool Mutable, Expr *BitWidth, 16824 InClassInitStyle InitStyle, 16825 SourceLocation TSSL, 16826 AccessSpecifier AS, NamedDecl *PrevDecl, 16827 Declarator *D) { 16828 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16829 bool InvalidDecl = false; 16830 if (D) InvalidDecl = D->isInvalidType(); 16831 16832 // If we receive a broken type, recover by assuming 'int' and 16833 // marking this declaration as invalid. 16834 if (T.isNull() || T->containsErrors()) { 16835 InvalidDecl = true; 16836 T = Context.IntTy; 16837 } 16838 16839 QualType EltTy = Context.getBaseElementType(T); 16840 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16841 if (RequireCompleteSizedType(Loc, EltTy, 16842 diag::err_field_incomplete_or_sizeless)) { 16843 // Fields of incomplete type force their record to be invalid. 16844 Record->setInvalidDecl(); 16845 InvalidDecl = true; 16846 } else { 16847 NamedDecl *Def; 16848 EltTy->isIncompleteType(&Def); 16849 if (Def && Def->isInvalidDecl()) { 16850 Record->setInvalidDecl(); 16851 InvalidDecl = true; 16852 } 16853 } 16854 } 16855 16856 // TR 18037 does not allow fields to be declared with address space 16857 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16858 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16859 Diag(Loc, diag::err_field_with_address_space); 16860 Record->setInvalidDecl(); 16861 InvalidDecl = true; 16862 } 16863 16864 if (LangOpts.OpenCL) { 16865 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16866 // used as structure or union field: image, sampler, event or block types. 16867 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16868 T->isBlockPointerType()) { 16869 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16870 Record->setInvalidDecl(); 16871 InvalidDecl = true; 16872 } 16873 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension 16874 // is enabled. 16875 if (BitWidth && !getOpenCLOptions().isAvailableOption( 16876 "__cl_clang_bitfields", LangOpts)) { 16877 Diag(Loc, diag::err_opencl_bitfields); 16878 InvalidDecl = true; 16879 } 16880 } 16881 16882 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16883 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16884 T.hasQualifiers()) { 16885 InvalidDecl = true; 16886 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16887 } 16888 16889 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16890 // than a variably modified type. 16891 if (!InvalidDecl && T->isVariablyModifiedType()) { 16892 if (!tryToFixVariablyModifiedVarType( 16893 TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 16894 InvalidDecl = true; 16895 } 16896 16897 // Fields can not have abstract class types 16898 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16899 diag::err_abstract_type_in_decl, 16900 AbstractFieldType)) 16901 InvalidDecl = true; 16902 16903 bool ZeroWidth = false; 16904 if (InvalidDecl) 16905 BitWidth = nullptr; 16906 // If this is declared as a bit-field, check the bit-field. 16907 if (BitWidth) { 16908 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16909 &ZeroWidth).get(); 16910 if (!BitWidth) { 16911 InvalidDecl = true; 16912 BitWidth = nullptr; 16913 ZeroWidth = false; 16914 } 16915 } 16916 16917 // Check that 'mutable' is consistent with the type of the declaration. 16918 if (!InvalidDecl && Mutable) { 16919 unsigned DiagID = 0; 16920 if (T->isReferenceType()) 16921 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16922 : diag::err_mutable_reference; 16923 else if (T.isConstQualified()) 16924 DiagID = diag::err_mutable_const; 16925 16926 if (DiagID) { 16927 SourceLocation ErrLoc = Loc; 16928 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16929 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16930 Diag(ErrLoc, DiagID); 16931 if (DiagID != diag::ext_mutable_reference) { 16932 Mutable = false; 16933 InvalidDecl = true; 16934 } 16935 } 16936 } 16937 16938 // C++11 [class.union]p8 (DR1460): 16939 // At most one variant member of a union may have a 16940 // brace-or-equal-initializer. 16941 if (InitStyle != ICIS_NoInit) 16942 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16943 16944 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16945 BitWidth, Mutable, InitStyle); 16946 if (InvalidDecl) 16947 NewFD->setInvalidDecl(); 16948 16949 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16950 Diag(Loc, diag::err_duplicate_member) << II; 16951 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16952 NewFD->setInvalidDecl(); 16953 } 16954 16955 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16956 if (Record->isUnion()) { 16957 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16958 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16959 if (RDecl->getDefinition()) { 16960 // C++ [class.union]p1: An object of a class with a non-trivial 16961 // constructor, a non-trivial copy constructor, a non-trivial 16962 // destructor, or a non-trivial copy assignment operator 16963 // cannot be a member of a union, nor can an array of such 16964 // objects. 16965 if (CheckNontrivialField(NewFD)) 16966 NewFD->setInvalidDecl(); 16967 } 16968 } 16969 16970 // C++ [class.union]p1: If a union contains a member of reference type, 16971 // the program is ill-formed, except when compiling with MSVC extensions 16972 // enabled. 16973 if (EltTy->isReferenceType()) { 16974 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16975 diag::ext_union_member_of_reference_type : 16976 diag::err_union_member_of_reference_type) 16977 << NewFD->getDeclName() << EltTy; 16978 if (!getLangOpts().MicrosoftExt) 16979 NewFD->setInvalidDecl(); 16980 } 16981 } 16982 } 16983 16984 // FIXME: We need to pass in the attributes given an AST 16985 // representation, not a parser representation. 16986 if (D) { 16987 // FIXME: The current scope is almost... but not entirely... correct here. 16988 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16989 16990 if (NewFD->hasAttrs()) 16991 CheckAlignasUnderalignment(NewFD); 16992 } 16993 16994 // In auto-retain/release, infer strong retension for fields of 16995 // retainable type. 16996 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16997 NewFD->setInvalidDecl(); 16998 16999 if (T.isObjCGCWeak()) 17000 Diag(Loc, diag::warn_attribute_weak_on_field); 17001 17002 // PPC MMA non-pointer types are not allowed as field types. 17003 if (Context.getTargetInfo().getTriple().isPPC64() && 17004 CheckPPCMMAType(T, NewFD->getLocation())) 17005 NewFD->setInvalidDecl(); 17006 17007 NewFD->setAccess(AS); 17008 return NewFD; 17009 } 17010 17011 bool Sema::CheckNontrivialField(FieldDecl *FD) { 17012 assert(FD); 17013 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 17014 17015 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 17016 return false; 17017 17018 QualType EltTy = Context.getBaseElementType(FD->getType()); 17019 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17020 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17021 if (RDecl->getDefinition()) { 17022 // We check for copy constructors before constructors 17023 // because otherwise we'll never get complaints about 17024 // copy constructors. 17025 17026 CXXSpecialMember member = CXXInvalid; 17027 // We're required to check for any non-trivial constructors. Since the 17028 // implicit default constructor is suppressed if there are any 17029 // user-declared constructors, we just need to check that there is a 17030 // trivial default constructor and a trivial copy constructor. (We don't 17031 // worry about move constructors here, since this is a C++98 check.) 17032 if (RDecl->hasNonTrivialCopyConstructor()) 17033 member = CXXCopyConstructor; 17034 else if (!RDecl->hasTrivialDefaultConstructor()) 17035 member = CXXDefaultConstructor; 17036 else if (RDecl->hasNonTrivialCopyAssignment()) 17037 member = CXXCopyAssignment; 17038 else if (RDecl->hasNonTrivialDestructor()) 17039 member = CXXDestructor; 17040 17041 if (member != CXXInvalid) { 17042 if (!getLangOpts().CPlusPlus11 && 17043 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 17044 // Objective-C++ ARC: it is an error to have a non-trivial field of 17045 // a union. However, system headers in Objective-C programs 17046 // occasionally have Objective-C lifetime objects within unions, 17047 // and rather than cause the program to fail, we make those 17048 // members unavailable. 17049 SourceLocation Loc = FD->getLocation(); 17050 if (getSourceManager().isInSystemHeader(Loc)) { 17051 if (!FD->hasAttr<UnavailableAttr>()) 17052 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 17053 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 17054 return false; 17055 } 17056 } 17057 17058 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 17059 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 17060 diag::err_illegal_union_or_anon_struct_member) 17061 << FD->getParent()->isUnion() << FD->getDeclName() << member; 17062 DiagnoseNontrivial(RDecl, member); 17063 return !getLangOpts().CPlusPlus11; 17064 } 17065 } 17066 } 17067 17068 return false; 17069 } 17070 17071 /// TranslateIvarVisibility - Translate visibility from a token ID to an 17072 /// AST enum value. 17073 static ObjCIvarDecl::AccessControl 17074 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 17075 switch (ivarVisibility) { 17076 default: llvm_unreachable("Unknown visitibility kind"); 17077 case tok::objc_private: return ObjCIvarDecl::Private; 17078 case tok::objc_public: return ObjCIvarDecl::Public; 17079 case tok::objc_protected: return ObjCIvarDecl::Protected; 17080 case tok::objc_package: return ObjCIvarDecl::Package; 17081 } 17082 } 17083 17084 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 17085 /// in order to create an IvarDecl object for it. 17086 Decl *Sema::ActOnIvar(Scope *S, 17087 SourceLocation DeclStart, 17088 Declarator &D, Expr *BitfieldWidth, 17089 tok::ObjCKeywordKind Visibility) { 17090 17091 IdentifierInfo *II = D.getIdentifier(); 17092 Expr *BitWidth = (Expr*)BitfieldWidth; 17093 SourceLocation Loc = DeclStart; 17094 if (II) Loc = D.getIdentifierLoc(); 17095 17096 // FIXME: Unnamed fields can be handled in various different ways, for 17097 // example, unnamed unions inject all members into the struct namespace! 17098 17099 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17100 QualType T = TInfo->getType(); 17101 17102 if (BitWidth) { 17103 // 6.7.2.1p3, 6.7.2.1p4 17104 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 17105 if (!BitWidth) 17106 D.setInvalidType(); 17107 } else { 17108 // Not a bitfield. 17109 17110 // validate II. 17111 17112 } 17113 if (T->isReferenceType()) { 17114 Diag(Loc, diag::err_ivar_reference_type); 17115 D.setInvalidType(); 17116 } 17117 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17118 // than a variably modified type. 17119 else if (T->isVariablyModifiedType()) { 17120 if (!tryToFixVariablyModifiedVarType( 17121 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 17122 D.setInvalidType(); 17123 } 17124 17125 // Get the visibility (access control) for this ivar. 17126 ObjCIvarDecl::AccessControl ac = 17127 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 17128 : ObjCIvarDecl::None; 17129 // Must set ivar's DeclContext to its enclosing interface. 17130 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 17131 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 17132 return nullptr; 17133 ObjCContainerDecl *EnclosingContext; 17134 if (ObjCImplementationDecl *IMPDecl = 17135 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17136 if (LangOpts.ObjCRuntime.isFragile()) { 17137 // Case of ivar declared in an implementation. Context is that of its class. 17138 EnclosingContext = IMPDecl->getClassInterface(); 17139 assert(EnclosingContext && "Implementation has no class interface!"); 17140 } 17141 else 17142 EnclosingContext = EnclosingDecl; 17143 } else { 17144 if (ObjCCategoryDecl *CDecl = 17145 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17146 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 17147 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 17148 return nullptr; 17149 } 17150 } 17151 EnclosingContext = EnclosingDecl; 17152 } 17153 17154 // Construct the decl. 17155 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 17156 DeclStart, Loc, II, T, 17157 TInfo, ac, (Expr *)BitfieldWidth); 17158 17159 if (II) { 17160 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 17161 ForVisibleRedeclaration); 17162 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 17163 && !isa<TagDecl>(PrevDecl)) { 17164 Diag(Loc, diag::err_duplicate_member) << II; 17165 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17166 NewID->setInvalidDecl(); 17167 } 17168 } 17169 17170 // Process attributes attached to the ivar. 17171 ProcessDeclAttributes(S, NewID, D); 17172 17173 if (D.isInvalidType()) 17174 NewID->setInvalidDecl(); 17175 17176 // In ARC, infer 'retaining' for ivars of retainable type. 17177 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 17178 NewID->setInvalidDecl(); 17179 17180 if (D.getDeclSpec().isModulePrivateSpecified()) 17181 NewID->setModulePrivate(); 17182 17183 if (II) { 17184 // FIXME: When interfaces are DeclContexts, we'll need to add 17185 // these to the interface. 17186 S->AddDecl(NewID); 17187 IdResolver.AddDecl(NewID); 17188 } 17189 17190 if (LangOpts.ObjCRuntime.isNonFragile() && 17191 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17192 Diag(Loc, diag::warn_ivars_in_interface); 17193 17194 return NewID; 17195 } 17196 17197 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17198 /// class and class extensions. For every class \@interface and class 17199 /// extension \@interface, if the last ivar is a bitfield of any type, 17200 /// then add an implicit `char :0` ivar to the end of that interface. 17201 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17202 SmallVectorImpl<Decl *> &AllIvarDecls) { 17203 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17204 return; 17205 17206 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17207 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17208 17209 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17210 return; 17211 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17212 if (!ID) { 17213 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17214 if (!CD->IsClassExtension()) 17215 return; 17216 } 17217 // No need to add this to end of @implementation. 17218 else 17219 return; 17220 } 17221 // All conditions are met. Add a new bitfield to the tail end of ivars. 17222 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17223 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17224 17225 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17226 DeclLoc, DeclLoc, nullptr, 17227 Context.CharTy, 17228 Context.getTrivialTypeSourceInfo(Context.CharTy, 17229 DeclLoc), 17230 ObjCIvarDecl::Private, BW, 17231 true); 17232 AllIvarDecls.push_back(Ivar); 17233 } 17234 17235 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17236 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17237 SourceLocation RBrac, 17238 const ParsedAttributesView &Attrs) { 17239 assert(EnclosingDecl && "missing record or interface decl"); 17240 17241 // If this is an Objective-C @implementation or category and we have 17242 // new fields here we should reset the layout of the interface since 17243 // it will now change. 17244 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17245 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17246 switch (DC->getKind()) { 17247 default: break; 17248 case Decl::ObjCCategory: 17249 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17250 break; 17251 case Decl::ObjCImplementation: 17252 Context. 17253 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17254 break; 17255 } 17256 } 17257 17258 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17259 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17260 17261 // Start counting up the number of named members; make sure to include 17262 // members of anonymous structs and unions in the total. 17263 unsigned NumNamedMembers = 0; 17264 if (Record) { 17265 for (const auto *I : Record->decls()) { 17266 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17267 if (IFD->getDeclName()) 17268 ++NumNamedMembers; 17269 } 17270 } 17271 17272 // Verify that all the fields are okay. 17273 SmallVector<FieldDecl*, 32> RecFields; 17274 17275 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17276 i != end; ++i) { 17277 FieldDecl *FD = cast<FieldDecl>(*i); 17278 17279 // Get the type for the field. 17280 const Type *FDTy = FD->getType().getTypePtr(); 17281 17282 if (!FD->isAnonymousStructOrUnion()) { 17283 // Remember all fields written by the user. 17284 RecFields.push_back(FD); 17285 } 17286 17287 // If the field is already invalid for some reason, don't emit more 17288 // diagnostics about it. 17289 if (FD->isInvalidDecl()) { 17290 EnclosingDecl->setInvalidDecl(); 17291 continue; 17292 } 17293 17294 // C99 6.7.2.1p2: 17295 // A structure or union shall not contain a member with 17296 // incomplete or function type (hence, a structure shall not 17297 // contain an instance of itself, but may contain a pointer to 17298 // an instance of itself), except that the last member of a 17299 // structure with more than one named member may have incomplete 17300 // array type; such a structure (and any union containing, 17301 // possibly recursively, a member that is such a structure) 17302 // shall not be a member of a structure or an element of an 17303 // array. 17304 bool IsLastField = (i + 1 == Fields.end()); 17305 if (FDTy->isFunctionType()) { 17306 // Field declared as a function. 17307 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17308 << FD->getDeclName(); 17309 FD->setInvalidDecl(); 17310 EnclosingDecl->setInvalidDecl(); 17311 continue; 17312 } else if (FDTy->isIncompleteArrayType() && 17313 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17314 if (Record) { 17315 // Flexible array member. 17316 // Microsoft and g++ is more permissive regarding flexible array. 17317 // It will accept flexible array in union and also 17318 // as the sole element of a struct/class. 17319 unsigned DiagID = 0; 17320 if (!Record->isUnion() && !IsLastField) { 17321 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17322 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17323 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17324 FD->setInvalidDecl(); 17325 EnclosingDecl->setInvalidDecl(); 17326 continue; 17327 } else if (Record->isUnion()) 17328 DiagID = getLangOpts().MicrosoftExt 17329 ? diag::ext_flexible_array_union_ms 17330 : getLangOpts().CPlusPlus 17331 ? diag::ext_flexible_array_union_gnu 17332 : diag::err_flexible_array_union; 17333 else if (NumNamedMembers < 1) 17334 DiagID = getLangOpts().MicrosoftExt 17335 ? diag::ext_flexible_array_empty_aggregate_ms 17336 : getLangOpts().CPlusPlus 17337 ? diag::ext_flexible_array_empty_aggregate_gnu 17338 : diag::err_flexible_array_empty_aggregate; 17339 17340 if (DiagID) 17341 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17342 << Record->getTagKind(); 17343 // While the layout of types that contain virtual bases is not specified 17344 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17345 // virtual bases after the derived members. This would make a flexible 17346 // array member declared at the end of an object not adjacent to the end 17347 // of the type. 17348 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17349 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17350 << FD->getDeclName() << Record->getTagKind(); 17351 if (!getLangOpts().C99) 17352 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17353 << FD->getDeclName() << Record->getTagKind(); 17354 17355 // If the element type has a non-trivial destructor, we would not 17356 // implicitly destroy the elements, so disallow it for now. 17357 // 17358 // FIXME: GCC allows this. We should probably either implicitly delete 17359 // the destructor of the containing class, or just allow this. 17360 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17361 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17362 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17363 << FD->getDeclName() << FD->getType(); 17364 FD->setInvalidDecl(); 17365 EnclosingDecl->setInvalidDecl(); 17366 continue; 17367 } 17368 // Okay, we have a legal flexible array member at the end of the struct. 17369 Record->setHasFlexibleArrayMember(true); 17370 } else { 17371 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17372 // unless they are followed by another ivar. That check is done 17373 // elsewhere, after synthesized ivars are known. 17374 } 17375 } else if (!FDTy->isDependentType() && 17376 RequireCompleteSizedType( 17377 FD->getLocation(), FD->getType(), 17378 diag::err_field_incomplete_or_sizeless)) { 17379 // Incomplete type 17380 FD->setInvalidDecl(); 17381 EnclosingDecl->setInvalidDecl(); 17382 continue; 17383 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17384 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17385 // A type which contains a flexible array member is considered to be a 17386 // flexible array member. 17387 Record->setHasFlexibleArrayMember(true); 17388 if (!Record->isUnion()) { 17389 // If this is a struct/class and this is not the last element, reject 17390 // it. Note that GCC supports variable sized arrays in the middle of 17391 // structures. 17392 if (!IsLastField) 17393 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17394 << FD->getDeclName() << FD->getType(); 17395 else { 17396 // We support flexible arrays at the end of structs in 17397 // other structs as an extension. 17398 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17399 << FD->getDeclName(); 17400 } 17401 } 17402 } 17403 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17404 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17405 diag::err_abstract_type_in_decl, 17406 AbstractIvarType)) { 17407 // Ivars can not have abstract class types 17408 FD->setInvalidDecl(); 17409 } 17410 if (Record && FDTTy->getDecl()->hasObjectMember()) 17411 Record->setHasObjectMember(true); 17412 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17413 Record->setHasVolatileMember(true); 17414 } else if (FDTy->isObjCObjectType()) { 17415 /// A field cannot be an Objective-c object 17416 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17417 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17418 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17419 FD->setType(T); 17420 } else if (Record && Record->isUnion() && 17421 FD->getType().hasNonTrivialObjCLifetime() && 17422 getSourceManager().isInSystemHeader(FD->getLocation()) && 17423 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17424 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17425 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17426 // For backward compatibility, fields of C unions declared in system 17427 // headers that have non-trivial ObjC ownership qualifications are marked 17428 // as unavailable unless the qualifier is explicit and __strong. This can 17429 // break ABI compatibility between programs compiled with ARC and MRR, but 17430 // is a better option than rejecting programs using those unions under 17431 // ARC. 17432 FD->addAttr(UnavailableAttr::CreateImplicit( 17433 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17434 FD->getLocation())); 17435 } else if (getLangOpts().ObjC && 17436 getLangOpts().getGC() != LangOptions::NonGC && Record && 17437 !Record->hasObjectMember()) { 17438 if (FD->getType()->isObjCObjectPointerType() || 17439 FD->getType().isObjCGCStrong()) 17440 Record->setHasObjectMember(true); 17441 else if (Context.getAsArrayType(FD->getType())) { 17442 QualType BaseType = Context.getBaseElementType(FD->getType()); 17443 if (BaseType->isRecordType() && 17444 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17445 Record->setHasObjectMember(true); 17446 else if (BaseType->isObjCObjectPointerType() || 17447 BaseType.isObjCGCStrong()) 17448 Record->setHasObjectMember(true); 17449 } 17450 } 17451 17452 if (Record && !getLangOpts().CPlusPlus && 17453 !shouldIgnoreForRecordTriviality(FD)) { 17454 QualType FT = FD->getType(); 17455 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17456 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17457 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17458 Record->isUnion()) 17459 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17460 } 17461 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17462 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17463 Record->setNonTrivialToPrimitiveCopy(true); 17464 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17465 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17466 } 17467 if (FT.isDestructedType()) { 17468 Record->setNonTrivialToPrimitiveDestroy(true); 17469 Record->setParamDestroyedInCallee(true); 17470 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17471 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17472 } 17473 17474 if (const auto *RT = FT->getAs<RecordType>()) { 17475 if (RT->getDecl()->getArgPassingRestrictions() == 17476 RecordDecl::APK_CanNeverPassInRegs) 17477 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17478 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17479 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17480 } 17481 17482 if (Record && FD->getType().isVolatileQualified()) 17483 Record->setHasVolatileMember(true); 17484 // Keep track of the number of named members. 17485 if (FD->getIdentifier()) 17486 ++NumNamedMembers; 17487 } 17488 17489 // Okay, we successfully defined 'Record'. 17490 if (Record) { 17491 bool Completed = false; 17492 if (CXXRecord) { 17493 if (!CXXRecord->isInvalidDecl()) { 17494 // Set access bits correctly on the directly-declared conversions. 17495 for (CXXRecordDecl::conversion_iterator 17496 I = CXXRecord->conversion_begin(), 17497 E = CXXRecord->conversion_end(); I != E; ++I) 17498 I.setAccess((*I)->getAccess()); 17499 } 17500 17501 // Add any implicitly-declared members to this class. 17502 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17503 17504 if (!CXXRecord->isDependentType()) { 17505 if (!CXXRecord->isInvalidDecl()) { 17506 // If we have virtual base classes, we may end up finding multiple 17507 // final overriders for a given virtual function. Check for this 17508 // problem now. 17509 if (CXXRecord->getNumVBases()) { 17510 CXXFinalOverriderMap FinalOverriders; 17511 CXXRecord->getFinalOverriders(FinalOverriders); 17512 17513 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17514 MEnd = FinalOverriders.end(); 17515 M != MEnd; ++M) { 17516 for (OverridingMethods::iterator SO = M->second.begin(), 17517 SOEnd = M->second.end(); 17518 SO != SOEnd; ++SO) { 17519 assert(SO->second.size() > 0 && 17520 "Virtual function without overriding functions?"); 17521 if (SO->second.size() == 1) 17522 continue; 17523 17524 // C++ [class.virtual]p2: 17525 // In a derived class, if a virtual member function of a base 17526 // class subobject has more than one final overrider the 17527 // program is ill-formed. 17528 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17529 << (const NamedDecl *)M->first << Record; 17530 Diag(M->first->getLocation(), 17531 diag::note_overridden_virtual_function); 17532 for (OverridingMethods::overriding_iterator 17533 OM = SO->second.begin(), 17534 OMEnd = SO->second.end(); 17535 OM != OMEnd; ++OM) 17536 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17537 << (const NamedDecl *)M->first << OM->Method->getParent(); 17538 17539 Record->setInvalidDecl(); 17540 } 17541 } 17542 CXXRecord->completeDefinition(&FinalOverriders); 17543 Completed = true; 17544 } 17545 } 17546 } 17547 } 17548 17549 if (!Completed) 17550 Record->completeDefinition(); 17551 17552 // Handle attributes before checking the layout. 17553 ProcessDeclAttributeList(S, Record, Attrs); 17554 17555 // We may have deferred checking for a deleted destructor. Check now. 17556 if (CXXRecord) { 17557 auto *Dtor = CXXRecord->getDestructor(); 17558 if (Dtor && Dtor->isImplicit() && 17559 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17560 CXXRecord->setImplicitDestructorIsDeleted(); 17561 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17562 } 17563 } 17564 17565 if (Record->hasAttrs()) { 17566 CheckAlignasUnderalignment(Record); 17567 17568 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17569 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17570 IA->getRange(), IA->getBestCase(), 17571 IA->getInheritanceModel()); 17572 } 17573 17574 // Check if the structure/union declaration is a type that can have zero 17575 // size in C. For C this is a language extension, for C++ it may cause 17576 // compatibility problems. 17577 bool CheckForZeroSize; 17578 if (!getLangOpts().CPlusPlus) { 17579 CheckForZeroSize = true; 17580 } else { 17581 // For C++ filter out types that cannot be referenced in C code. 17582 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17583 CheckForZeroSize = 17584 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17585 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 17586 CXXRecord->isCLike(); 17587 } 17588 if (CheckForZeroSize) { 17589 bool ZeroSize = true; 17590 bool IsEmpty = true; 17591 unsigned NonBitFields = 0; 17592 for (RecordDecl::field_iterator I = Record->field_begin(), 17593 E = Record->field_end(); 17594 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17595 IsEmpty = false; 17596 if (I->isUnnamedBitfield()) { 17597 if (!I->isZeroLengthBitField(Context)) 17598 ZeroSize = false; 17599 } else { 17600 ++NonBitFields; 17601 QualType FieldType = I->getType(); 17602 if (FieldType->isIncompleteType() || 17603 !Context.getTypeSizeInChars(FieldType).isZero()) 17604 ZeroSize = false; 17605 } 17606 } 17607 17608 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17609 // allowed in C++, but warn if its declaration is inside 17610 // extern "C" block. 17611 if (ZeroSize) { 17612 Diag(RecLoc, getLangOpts().CPlusPlus ? 17613 diag::warn_zero_size_struct_union_in_extern_c : 17614 diag::warn_zero_size_struct_union_compat) 17615 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17616 } 17617 17618 // Structs without named members are extension in C (C99 6.7.2.1p7), 17619 // but are accepted by GCC. 17620 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17621 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17622 diag::ext_no_named_members_in_struct_union) 17623 << Record->isUnion(); 17624 } 17625 } 17626 } else { 17627 ObjCIvarDecl **ClsFields = 17628 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17629 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17630 ID->setEndOfDefinitionLoc(RBrac); 17631 // Add ivar's to class's DeclContext. 17632 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17633 ClsFields[i]->setLexicalDeclContext(ID); 17634 ID->addDecl(ClsFields[i]); 17635 } 17636 // Must enforce the rule that ivars in the base classes may not be 17637 // duplicates. 17638 if (ID->getSuperClass()) 17639 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17640 } else if (ObjCImplementationDecl *IMPDecl = 17641 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17642 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17643 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17644 // Ivar declared in @implementation never belongs to the implementation. 17645 // Only it is in implementation's lexical context. 17646 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17647 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17648 IMPDecl->setIvarLBraceLoc(LBrac); 17649 IMPDecl->setIvarRBraceLoc(RBrac); 17650 } else if (ObjCCategoryDecl *CDecl = 17651 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17652 // case of ivars in class extension; all other cases have been 17653 // reported as errors elsewhere. 17654 // FIXME. Class extension does not have a LocEnd field. 17655 // CDecl->setLocEnd(RBrac); 17656 // Add ivar's to class extension's DeclContext. 17657 // Diagnose redeclaration of private ivars. 17658 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17659 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17660 if (IDecl) { 17661 if (const ObjCIvarDecl *ClsIvar = 17662 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17663 Diag(ClsFields[i]->getLocation(), 17664 diag::err_duplicate_ivar_declaration); 17665 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17666 continue; 17667 } 17668 for (const auto *Ext : IDecl->known_extensions()) { 17669 if (const ObjCIvarDecl *ClsExtIvar 17670 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17671 Diag(ClsFields[i]->getLocation(), 17672 diag::err_duplicate_ivar_declaration); 17673 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17674 continue; 17675 } 17676 } 17677 } 17678 ClsFields[i]->setLexicalDeclContext(CDecl); 17679 CDecl->addDecl(ClsFields[i]); 17680 } 17681 CDecl->setIvarLBraceLoc(LBrac); 17682 CDecl->setIvarRBraceLoc(RBrac); 17683 } 17684 } 17685 } 17686 17687 /// Determine whether the given integral value is representable within 17688 /// the given type T. 17689 static bool isRepresentableIntegerValue(ASTContext &Context, 17690 llvm::APSInt &Value, 17691 QualType T) { 17692 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17693 "Integral type required!"); 17694 unsigned BitWidth = Context.getIntWidth(T); 17695 17696 if (Value.isUnsigned() || Value.isNonNegative()) { 17697 if (T->isSignedIntegerOrEnumerationType()) 17698 --BitWidth; 17699 return Value.getActiveBits() <= BitWidth; 17700 } 17701 return Value.getMinSignedBits() <= BitWidth; 17702 } 17703 17704 // Given an integral type, return the next larger integral type 17705 // (or a NULL type of no such type exists). 17706 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17707 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17708 // enum checking below. 17709 assert((T->isIntegralType(Context) || 17710 T->isEnumeralType()) && "Integral type required!"); 17711 const unsigned NumTypes = 4; 17712 QualType SignedIntegralTypes[NumTypes] = { 17713 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17714 }; 17715 QualType UnsignedIntegralTypes[NumTypes] = { 17716 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17717 Context.UnsignedLongLongTy 17718 }; 17719 17720 unsigned BitWidth = Context.getTypeSize(T); 17721 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17722 : UnsignedIntegralTypes; 17723 for (unsigned I = 0; I != NumTypes; ++I) 17724 if (Context.getTypeSize(Types[I]) > BitWidth) 17725 return Types[I]; 17726 17727 return QualType(); 17728 } 17729 17730 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17731 EnumConstantDecl *LastEnumConst, 17732 SourceLocation IdLoc, 17733 IdentifierInfo *Id, 17734 Expr *Val) { 17735 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17736 llvm::APSInt EnumVal(IntWidth); 17737 QualType EltTy; 17738 17739 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17740 Val = nullptr; 17741 17742 if (Val) 17743 Val = DefaultLvalueConversion(Val).get(); 17744 17745 if (Val) { 17746 if (Enum->isDependentType() || Val->isTypeDependent()) 17747 EltTy = Context.DependentTy; 17748 else { 17749 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 17750 // underlying type, but do allow it in all other contexts. 17751 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17752 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17753 // constant-expression in the enumerator-definition shall be a converted 17754 // constant expression of the underlying type. 17755 EltTy = Enum->getIntegerType(); 17756 ExprResult Converted = 17757 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17758 CCEK_Enumerator); 17759 if (Converted.isInvalid()) 17760 Val = nullptr; 17761 else 17762 Val = Converted.get(); 17763 } else if (!Val->isValueDependent() && 17764 !(Val = 17765 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 17766 .get())) { 17767 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17768 } else { 17769 if (Enum->isComplete()) { 17770 EltTy = Enum->getIntegerType(); 17771 17772 // In Obj-C and Microsoft mode, require the enumeration value to be 17773 // representable in the underlying type of the enumeration. In C++11, 17774 // we perform a non-narrowing conversion as part of converted constant 17775 // expression checking. 17776 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17777 if (Context.getTargetInfo() 17778 .getTriple() 17779 .isWindowsMSVCEnvironment()) { 17780 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17781 } else { 17782 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17783 } 17784 } 17785 17786 // Cast to the underlying type. 17787 Val = ImpCastExprToType(Val, EltTy, 17788 EltTy->isBooleanType() ? CK_IntegralToBoolean 17789 : CK_IntegralCast) 17790 .get(); 17791 } else if (getLangOpts().CPlusPlus) { 17792 // C++11 [dcl.enum]p5: 17793 // If the underlying type is not fixed, the type of each enumerator 17794 // is the type of its initializing value: 17795 // - If an initializer is specified for an enumerator, the 17796 // initializing value has the same type as the expression. 17797 EltTy = Val->getType(); 17798 } else { 17799 // C99 6.7.2.2p2: 17800 // The expression that defines the value of an enumeration constant 17801 // shall be an integer constant expression that has a value 17802 // representable as an int. 17803 17804 // Complain if the value is not representable in an int. 17805 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17806 Diag(IdLoc, diag::ext_enum_value_not_int) 17807 << toString(EnumVal, 10) << Val->getSourceRange() 17808 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17809 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17810 // Force the type of the expression to 'int'. 17811 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17812 } 17813 EltTy = Val->getType(); 17814 } 17815 } 17816 } 17817 } 17818 17819 if (!Val) { 17820 if (Enum->isDependentType()) 17821 EltTy = Context.DependentTy; 17822 else if (!LastEnumConst) { 17823 // C++0x [dcl.enum]p5: 17824 // If the underlying type is not fixed, the type of each enumerator 17825 // is the type of its initializing value: 17826 // - If no initializer is specified for the first enumerator, the 17827 // initializing value has an unspecified integral type. 17828 // 17829 // GCC uses 'int' for its unspecified integral type, as does 17830 // C99 6.7.2.2p3. 17831 if (Enum->isFixed()) { 17832 EltTy = Enum->getIntegerType(); 17833 } 17834 else { 17835 EltTy = Context.IntTy; 17836 } 17837 } else { 17838 // Assign the last value + 1. 17839 EnumVal = LastEnumConst->getInitVal(); 17840 ++EnumVal; 17841 EltTy = LastEnumConst->getType(); 17842 17843 // Check for overflow on increment. 17844 if (EnumVal < LastEnumConst->getInitVal()) { 17845 // C++0x [dcl.enum]p5: 17846 // If the underlying type is not fixed, the type of each enumerator 17847 // is the type of its initializing value: 17848 // 17849 // - Otherwise the type of the initializing value is the same as 17850 // the type of the initializing value of the preceding enumerator 17851 // unless the incremented value is not representable in that type, 17852 // in which case the type is an unspecified integral type 17853 // sufficient to contain the incremented value. If no such type 17854 // exists, the program is ill-formed. 17855 QualType T = getNextLargerIntegralType(Context, EltTy); 17856 if (T.isNull() || Enum->isFixed()) { 17857 // There is no integral type larger enough to represent this 17858 // value. Complain, then allow the value to wrap around. 17859 EnumVal = LastEnumConst->getInitVal(); 17860 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17861 ++EnumVal; 17862 if (Enum->isFixed()) 17863 // When the underlying type is fixed, this is ill-formed. 17864 Diag(IdLoc, diag::err_enumerator_wrapped) 17865 << toString(EnumVal, 10) 17866 << EltTy; 17867 else 17868 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17869 << toString(EnumVal, 10); 17870 } else { 17871 EltTy = T; 17872 } 17873 17874 // Retrieve the last enumerator's value, extent that type to the 17875 // type that is supposed to be large enough to represent the incremented 17876 // value, then increment. 17877 EnumVal = LastEnumConst->getInitVal(); 17878 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17879 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17880 ++EnumVal; 17881 17882 // If we're not in C++, diagnose the overflow of enumerator values, 17883 // which in C99 means that the enumerator value is not representable in 17884 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17885 // permits enumerator values that are representable in some larger 17886 // integral type. 17887 if (!getLangOpts().CPlusPlus && !T.isNull()) 17888 Diag(IdLoc, diag::warn_enum_value_overflow); 17889 } else if (!getLangOpts().CPlusPlus && 17890 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17891 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17892 Diag(IdLoc, diag::ext_enum_value_not_int) 17893 << toString(EnumVal, 10) << 1; 17894 } 17895 } 17896 } 17897 17898 if (!EltTy->isDependentType()) { 17899 // Make the enumerator value match the signedness and size of the 17900 // enumerator's type. 17901 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17902 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17903 } 17904 17905 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17906 Val, EnumVal); 17907 } 17908 17909 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17910 SourceLocation IILoc) { 17911 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17912 !getLangOpts().CPlusPlus) 17913 return SkipBodyInfo(); 17914 17915 // We have an anonymous enum definition. Look up the first enumerator to 17916 // determine if we should merge the definition with an existing one and 17917 // skip the body. 17918 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17919 forRedeclarationInCurContext()); 17920 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17921 if (!PrevECD) 17922 return SkipBodyInfo(); 17923 17924 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17925 NamedDecl *Hidden; 17926 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17927 SkipBodyInfo Skip; 17928 Skip.Previous = Hidden; 17929 return Skip; 17930 } 17931 17932 return SkipBodyInfo(); 17933 } 17934 17935 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17936 SourceLocation IdLoc, IdentifierInfo *Id, 17937 const ParsedAttributesView &Attrs, 17938 SourceLocation EqualLoc, Expr *Val) { 17939 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17940 EnumConstantDecl *LastEnumConst = 17941 cast_or_null<EnumConstantDecl>(lastEnumConst); 17942 17943 // The scope passed in may not be a decl scope. Zip up the scope tree until 17944 // we find one that is. 17945 S = getNonFieldDeclScope(S); 17946 17947 // Verify that there isn't already something declared with this name in this 17948 // scope. 17949 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17950 LookupName(R, S); 17951 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17952 17953 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17954 // Maybe we will complain about the shadowed template parameter. 17955 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17956 // Just pretend that we didn't see the previous declaration. 17957 PrevDecl = nullptr; 17958 } 17959 17960 // C++ [class.mem]p15: 17961 // If T is the name of a class, then each of the following shall have a name 17962 // different from T: 17963 // - every enumerator of every member of class T that is an unscoped 17964 // enumerated type 17965 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17966 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17967 DeclarationNameInfo(Id, IdLoc)); 17968 17969 EnumConstantDecl *New = 17970 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17971 if (!New) 17972 return nullptr; 17973 17974 if (PrevDecl) { 17975 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17976 // Check for other kinds of shadowing not already handled. 17977 CheckShadow(New, PrevDecl, R); 17978 } 17979 17980 // When in C++, we may get a TagDecl with the same name; in this case the 17981 // enum constant will 'hide' the tag. 17982 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17983 "Received TagDecl when not in C++!"); 17984 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17985 if (isa<EnumConstantDecl>(PrevDecl)) 17986 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17987 else 17988 Diag(IdLoc, diag::err_redefinition) << Id; 17989 notePreviousDefinition(PrevDecl, IdLoc); 17990 return nullptr; 17991 } 17992 } 17993 17994 // Process attributes. 17995 ProcessDeclAttributeList(S, New, Attrs); 17996 AddPragmaAttributes(S, New); 17997 17998 // Register this decl in the current scope stack. 17999 New->setAccess(TheEnumDecl->getAccess()); 18000 PushOnScopeChains(New, S); 18001 18002 ActOnDocumentableDecl(New); 18003 18004 return New; 18005 } 18006 18007 // Returns true when the enum initial expression does not trigger the 18008 // duplicate enum warning. A few common cases are exempted as follows: 18009 // Element2 = Element1 18010 // Element2 = Element1 + 1 18011 // Element2 = Element1 - 1 18012 // Where Element2 and Element1 are from the same enum. 18013 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 18014 Expr *InitExpr = ECD->getInitExpr(); 18015 if (!InitExpr) 18016 return true; 18017 InitExpr = InitExpr->IgnoreImpCasts(); 18018 18019 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 18020 if (!BO->isAdditiveOp()) 18021 return true; 18022 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 18023 if (!IL) 18024 return true; 18025 if (IL->getValue() != 1) 18026 return true; 18027 18028 InitExpr = BO->getLHS(); 18029 } 18030 18031 // This checks if the elements are from the same enum. 18032 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 18033 if (!DRE) 18034 return true; 18035 18036 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 18037 if (!EnumConstant) 18038 return true; 18039 18040 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 18041 Enum) 18042 return true; 18043 18044 return false; 18045 } 18046 18047 // Emits a warning when an element is implicitly set a value that 18048 // a previous element has already been set to. 18049 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 18050 EnumDecl *Enum, QualType EnumType) { 18051 // Avoid anonymous enums 18052 if (!Enum->getIdentifier()) 18053 return; 18054 18055 // Only check for small enums. 18056 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 18057 return; 18058 18059 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 18060 return; 18061 18062 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 18063 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 18064 18065 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 18066 18067 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 18068 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 18069 18070 // Use int64_t as a key to avoid needing special handling for map keys. 18071 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 18072 llvm::APSInt Val = D->getInitVal(); 18073 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 18074 }; 18075 18076 DuplicatesVector DupVector; 18077 ValueToVectorMap EnumMap; 18078 18079 // Populate the EnumMap with all values represented by enum constants without 18080 // an initializer. 18081 for (auto *Element : Elements) { 18082 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 18083 18084 // Null EnumConstantDecl means a previous diagnostic has been emitted for 18085 // this constant. Skip this enum since it may be ill-formed. 18086 if (!ECD) { 18087 return; 18088 } 18089 18090 // Constants with initalizers are handled in the next loop. 18091 if (ECD->getInitExpr()) 18092 continue; 18093 18094 // Duplicate values are handled in the next loop. 18095 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 18096 } 18097 18098 if (EnumMap.size() == 0) 18099 return; 18100 18101 // Create vectors for any values that has duplicates. 18102 for (auto *Element : Elements) { 18103 // The last loop returned if any constant was null. 18104 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 18105 if (!ValidDuplicateEnum(ECD, Enum)) 18106 continue; 18107 18108 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 18109 if (Iter == EnumMap.end()) 18110 continue; 18111 18112 DeclOrVector& Entry = Iter->second; 18113 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 18114 // Ensure constants are different. 18115 if (D == ECD) 18116 continue; 18117 18118 // Create new vector and push values onto it. 18119 auto Vec = std::make_unique<ECDVector>(); 18120 Vec->push_back(D); 18121 Vec->push_back(ECD); 18122 18123 // Update entry to point to the duplicates vector. 18124 Entry = Vec.get(); 18125 18126 // Store the vector somewhere we can consult later for quick emission of 18127 // diagnostics. 18128 DupVector.emplace_back(std::move(Vec)); 18129 continue; 18130 } 18131 18132 ECDVector *Vec = Entry.get<ECDVector*>(); 18133 // Make sure constants are not added more than once. 18134 if (*Vec->begin() == ECD) 18135 continue; 18136 18137 Vec->push_back(ECD); 18138 } 18139 18140 // Emit diagnostics. 18141 for (const auto &Vec : DupVector) { 18142 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 18143 18144 // Emit warning for one enum constant. 18145 auto *FirstECD = Vec->front(); 18146 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 18147 << FirstECD << toString(FirstECD->getInitVal(), 10) 18148 << FirstECD->getSourceRange(); 18149 18150 // Emit one note for each of the remaining enum constants with 18151 // the same value. 18152 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 18153 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 18154 << ECD << toString(ECD->getInitVal(), 10) 18155 << ECD->getSourceRange(); 18156 } 18157 } 18158 18159 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 18160 bool AllowMask) const { 18161 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 18162 assert(ED->isCompleteDefinition() && "expected enum definition"); 18163 18164 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 18165 llvm::APInt &FlagBits = R.first->second; 18166 18167 if (R.second) { 18168 for (auto *E : ED->enumerators()) { 18169 const auto &EVal = E->getInitVal(); 18170 // Only single-bit enumerators introduce new flag values. 18171 if (EVal.isPowerOf2()) 18172 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 18173 } 18174 } 18175 18176 // A value is in a flag enum if either its bits are a subset of the enum's 18177 // flag bits (the first condition) or we are allowing masks and the same is 18178 // true of its complement (the second condition). When masks are allowed, we 18179 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 18180 // 18181 // While it's true that any value could be used as a mask, the assumption is 18182 // that a mask will have all of the insignificant bits set. Anything else is 18183 // likely a logic error. 18184 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18185 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18186 } 18187 18188 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18189 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18190 const ParsedAttributesView &Attrs) { 18191 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18192 QualType EnumType = Context.getTypeDeclType(Enum); 18193 18194 ProcessDeclAttributeList(S, Enum, Attrs); 18195 18196 if (Enum->isDependentType()) { 18197 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18198 EnumConstantDecl *ECD = 18199 cast_or_null<EnumConstantDecl>(Elements[i]); 18200 if (!ECD) continue; 18201 18202 ECD->setType(EnumType); 18203 } 18204 18205 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18206 return; 18207 } 18208 18209 // TODO: If the result value doesn't fit in an int, it must be a long or long 18210 // long value. ISO C does not support this, but GCC does as an extension, 18211 // emit a warning. 18212 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18213 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18214 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18215 18216 // Verify that all the values are okay, compute the size of the values, and 18217 // reverse the list. 18218 unsigned NumNegativeBits = 0; 18219 unsigned NumPositiveBits = 0; 18220 18221 // Keep track of whether all elements have type int. 18222 bool AllElementsInt = true; 18223 18224 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18225 EnumConstantDecl *ECD = 18226 cast_or_null<EnumConstantDecl>(Elements[i]); 18227 if (!ECD) continue; // Already issued a diagnostic. 18228 18229 const llvm::APSInt &InitVal = ECD->getInitVal(); 18230 18231 // Keep track of the size of positive and negative values. 18232 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18233 NumPositiveBits = std::max(NumPositiveBits, 18234 (unsigned)InitVal.getActiveBits()); 18235 else 18236 NumNegativeBits = std::max(NumNegativeBits, 18237 (unsigned)InitVal.getMinSignedBits()); 18238 18239 // Keep track of whether every enum element has type int (very common). 18240 if (AllElementsInt) 18241 AllElementsInt = ECD->getType() == Context.IntTy; 18242 } 18243 18244 // Figure out the type that should be used for this enum. 18245 QualType BestType; 18246 unsigned BestWidth; 18247 18248 // C++0x N3000 [conv.prom]p3: 18249 // An rvalue of an unscoped enumeration type whose underlying 18250 // type is not fixed can be converted to an rvalue of the first 18251 // of the following types that can represent all the values of 18252 // the enumeration: int, unsigned int, long int, unsigned long 18253 // int, long long int, or unsigned long long int. 18254 // C99 6.4.4.3p2: 18255 // An identifier declared as an enumeration constant has type int. 18256 // The C99 rule is modified by a gcc extension 18257 QualType BestPromotionType; 18258 18259 bool Packed = Enum->hasAttr<PackedAttr>(); 18260 // -fshort-enums is the equivalent to specifying the packed attribute on all 18261 // enum definitions. 18262 if (LangOpts.ShortEnums) 18263 Packed = true; 18264 18265 // If the enum already has a type because it is fixed or dictated by the 18266 // target, promote that type instead of analyzing the enumerators. 18267 if (Enum->isComplete()) { 18268 BestType = Enum->getIntegerType(); 18269 if (BestType->isPromotableIntegerType()) 18270 BestPromotionType = Context.getPromotedIntegerType(BestType); 18271 else 18272 BestPromotionType = BestType; 18273 18274 BestWidth = Context.getIntWidth(BestType); 18275 } 18276 else if (NumNegativeBits) { 18277 // If there is a negative value, figure out the smallest integer type (of 18278 // int/long/longlong) that fits. 18279 // If it's packed, check also if it fits a char or a short. 18280 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18281 BestType = Context.SignedCharTy; 18282 BestWidth = CharWidth; 18283 } else if (Packed && NumNegativeBits <= ShortWidth && 18284 NumPositiveBits < ShortWidth) { 18285 BestType = Context.ShortTy; 18286 BestWidth = ShortWidth; 18287 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18288 BestType = Context.IntTy; 18289 BestWidth = IntWidth; 18290 } else { 18291 BestWidth = Context.getTargetInfo().getLongWidth(); 18292 18293 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18294 BestType = Context.LongTy; 18295 } else { 18296 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18297 18298 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18299 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18300 BestType = Context.LongLongTy; 18301 } 18302 } 18303 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18304 } else { 18305 // If there is no negative value, figure out the smallest type that fits 18306 // all of the enumerator values. 18307 // If it's packed, check also if it fits a char or a short. 18308 if (Packed && NumPositiveBits <= CharWidth) { 18309 BestType = Context.UnsignedCharTy; 18310 BestPromotionType = Context.IntTy; 18311 BestWidth = CharWidth; 18312 } else if (Packed && NumPositiveBits <= ShortWidth) { 18313 BestType = Context.UnsignedShortTy; 18314 BestPromotionType = Context.IntTy; 18315 BestWidth = ShortWidth; 18316 } else if (NumPositiveBits <= IntWidth) { 18317 BestType = Context.UnsignedIntTy; 18318 BestWidth = IntWidth; 18319 BestPromotionType 18320 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18321 ? Context.UnsignedIntTy : Context.IntTy; 18322 } else if (NumPositiveBits <= 18323 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18324 BestType = Context.UnsignedLongTy; 18325 BestPromotionType 18326 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18327 ? Context.UnsignedLongTy : Context.LongTy; 18328 } else { 18329 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18330 assert(NumPositiveBits <= BestWidth && 18331 "How could an initializer get larger than ULL?"); 18332 BestType = Context.UnsignedLongLongTy; 18333 BestPromotionType 18334 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18335 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18336 } 18337 } 18338 18339 // Loop over all of the enumerator constants, changing their types to match 18340 // the type of the enum if needed. 18341 for (auto *D : Elements) { 18342 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18343 if (!ECD) continue; // Already issued a diagnostic. 18344 18345 // Standard C says the enumerators have int type, but we allow, as an 18346 // extension, the enumerators to be larger than int size. If each 18347 // enumerator value fits in an int, type it as an int, otherwise type it the 18348 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18349 // that X has type 'int', not 'unsigned'. 18350 18351 // Determine whether the value fits into an int. 18352 llvm::APSInt InitVal = ECD->getInitVal(); 18353 18354 // If it fits into an integer type, force it. Otherwise force it to match 18355 // the enum decl type. 18356 QualType NewTy; 18357 unsigned NewWidth; 18358 bool NewSign; 18359 if (!getLangOpts().CPlusPlus && 18360 !Enum->isFixed() && 18361 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18362 NewTy = Context.IntTy; 18363 NewWidth = IntWidth; 18364 NewSign = true; 18365 } else if (ECD->getType() == BestType) { 18366 // Already the right type! 18367 if (getLangOpts().CPlusPlus) 18368 // C++ [dcl.enum]p4: Following the closing brace of an 18369 // enum-specifier, each enumerator has the type of its 18370 // enumeration. 18371 ECD->setType(EnumType); 18372 continue; 18373 } else { 18374 NewTy = BestType; 18375 NewWidth = BestWidth; 18376 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18377 } 18378 18379 // Adjust the APSInt value. 18380 InitVal = InitVal.extOrTrunc(NewWidth); 18381 InitVal.setIsSigned(NewSign); 18382 ECD->setInitVal(InitVal); 18383 18384 // Adjust the Expr initializer and type. 18385 if (ECD->getInitExpr() && 18386 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18387 ECD->setInitExpr(ImplicitCastExpr::Create( 18388 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18389 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride())); 18390 if (getLangOpts().CPlusPlus) 18391 // C++ [dcl.enum]p4: Following the closing brace of an 18392 // enum-specifier, each enumerator has the type of its 18393 // enumeration. 18394 ECD->setType(EnumType); 18395 else 18396 ECD->setType(NewTy); 18397 } 18398 18399 Enum->completeDefinition(BestType, BestPromotionType, 18400 NumPositiveBits, NumNegativeBits); 18401 18402 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18403 18404 if (Enum->isClosedFlag()) { 18405 for (Decl *D : Elements) { 18406 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18407 if (!ECD) continue; // Already issued a diagnostic. 18408 18409 llvm::APSInt InitVal = ECD->getInitVal(); 18410 if (InitVal != 0 && !InitVal.isPowerOf2() && 18411 !IsValueInFlagEnum(Enum, InitVal, true)) 18412 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18413 << ECD << Enum; 18414 } 18415 } 18416 18417 // Now that the enum type is defined, ensure it's not been underaligned. 18418 if (Enum->hasAttrs()) 18419 CheckAlignasUnderalignment(Enum); 18420 } 18421 18422 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18423 SourceLocation StartLoc, 18424 SourceLocation EndLoc) { 18425 StringLiteral *AsmString = cast<StringLiteral>(expr); 18426 18427 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18428 AsmString, StartLoc, 18429 EndLoc); 18430 CurContext->addDecl(New); 18431 return New; 18432 } 18433 18434 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18435 IdentifierInfo* AliasName, 18436 SourceLocation PragmaLoc, 18437 SourceLocation NameLoc, 18438 SourceLocation AliasNameLoc) { 18439 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18440 LookupOrdinaryName); 18441 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18442 AttributeCommonInfo::AS_Pragma); 18443 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18444 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18445 18446 // If a declaration that: 18447 // 1) declares a function or a variable 18448 // 2) has external linkage 18449 // already exists, add a label attribute to it. 18450 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18451 if (isDeclExternC(PrevDecl)) 18452 PrevDecl->addAttr(Attr); 18453 else 18454 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18455 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18456 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18457 } else 18458 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18459 } 18460 18461 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18462 SourceLocation PragmaLoc, 18463 SourceLocation NameLoc) { 18464 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18465 18466 if (PrevDecl) { 18467 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18468 } else { 18469 (void)WeakUndeclaredIdentifiers.insert( 18470 std::pair<IdentifierInfo*,WeakInfo> 18471 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18472 } 18473 } 18474 18475 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18476 IdentifierInfo* AliasName, 18477 SourceLocation PragmaLoc, 18478 SourceLocation NameLoc, 18479 SourceLocation AliasNameLoc) { 18480 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18481 LookupOrdinaryName); 18482 WeakInfo W = WeakInfo(Name, NameLoc); 18483 18484 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18485 if (!PrevDecl->hasAttr<AliasAttr>()) 18486 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18487 DeclApplyPragmaWeak(TUScope, ND, W); 18488 } else { 18489 (void)WeakUndeclaredIdentifiers.insert( 18490 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18491 } 18492 } 18493 18494 Decl *Sema::getObjCDeclContext() const { 18495 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18496 } 18497 18498 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18499 bool Final) { 18500 assert(FD && "Expected non-null FunctionDecl"); 18501 18502 // SYCL functions can be template, so we check if they have appropriate 18503 // attribute prior to checking if it is a template. 18504 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18505 return FunctionEmissionStatus::Emitted; 18506 18507 // Templates are emitted when they're instantiated. 18508 if (FD->isDependentContext()) 18509 return FunctionEmissionStatus::TemplateDiscarded; 18510 18511 // Check whether this function is an externally visible definition. 18512 auto IsEmittedForExternalSymbol = [this, FD]() { 18513 // We have to check the GVA linkage of the function's *definition* -- if we 18514 // only have a declaration, we don't know whether or not the function will 18515 // be emitted, because (say) the definition could include "inline". 18516 FunctionDecl *Def = FD->getDefinition(); 18517 18518 return Def && !isDiscardableGVALinkage( 18519 getASTContext().GetGVALinkageForFunction(Def)); 18520 }; 18521 18522 if (LangOpts.OpenMPIsDevice) { 18523 // In OpenMP device mode we will not emit host only functions, or functions 18524 // we don't need due to their linkage. 18525 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18526 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18527 // DevTy may be changed later by 18528 // #pragma omp declare target to(*) device_type(*). 18529 // Therefore DevTy having no value does not imply host. The emission status 18530 // will be checked again at the end of compilation unit with Final = true. 18531 if (DevTy.hasValue()) 18532 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18533 return FunctionEmissionStatus::OMPDiscarded; 18534 // If we have an explicit value for the device type, or we are in a target 18535 // declare context, we need to emit all extern and used symbols. 18536 if (isInOpenMPDeclareTargetContext() || DevTy.hasValue()) 18537 if (IsEmittedForExternalSymbol()) 18538 return FunctionEmissionStatus::Emitted; 18539 // Device mode only emits what it must, if it wasn't tagged yet and needed, 18540 // we'll omit it. 18541 if (Final) 18542 return FunctionEmissionStatus::OMPDiscarded; 18543 } else if (LangOpts.OpenMP > 45) { 18544 // In OpenMP host compilation prior to 5.0 everything was an emitted host 18545 // function. In 5.0, no_host was introduced which might cause a function to 18546 // be ommitted. 18547 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18548 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18549 if (DevTy.hasValue()) 18550 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 18551 return FunctionEmissionStatus::OMPDiscarded; 18552 } 18553 18554 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 18555 return FunctionEmissionStatus::Emitted; 18556 18557 if (LangOpts.CUDA) { 18558 // When compiling for device, host functions are never emitted. Similarly, 18559 // when compiling for host, device and global functions are never emitted. 18560 // (Technically, we do emit a host-side stub for global functions, but this 18561 // doesn't count for our purposes here.) 18562 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18563 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18564 return FunctionEmissionStatus::CUDADiscarded; 18565 if (!LangOpts.CUDAIsDevice && 18566 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18567 return FunctionEmissionStatus::CUDADiscarded; 18568 18569 if (IsEmittedForExternalSymbol()) 18570 return FunctionEmissionStatus::Emitted; 18571 } 18572 18573 // Otherwise, the function is known-emitted if it's in our set of 18574 // known-emitted functions. 18575 return FunctionEmissionStatus::Unknown; 18576 } 18577 18578 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18579 // Host-side references to a __global__ function refer to the stub, so the 18580 // function itself is never emitted and therefore should not be marked. 18581 // If we have host fn calls kernel fn calls host+device, the HD function 18582 // does not get instantiated on the host. We model this by omitting at the 18583 // call to the kernel from the callgraph. This ensures that, when compiling 18584 // for host, only HD functions actually called from the host get marked as 18585 // known-emitted. 18586 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18587 IdentifyCUDATarget(Callee) == CFT_Global; 18588 } 18589