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/ExprCXX.h" 25 #include "clang/AST/NonTrivialTypeVisitor.h" 26 #include "clang/AST/StmtCXX.h" 27 #include "clang/Basic/Builtins.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 35 #include "clang/Sema/CXXFieldCollector.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaInternal.h" 44 #include "clang/Sema/Template.h" 45 #include "llvm/ADT/SmallString.h" 46 #include "llvm/ADT/Triple.h" 47 #include <algorithm> 48 #include <cstring> 49 #include <functional> 50 #include <unordered_map> 51 52 using namespace clang; 53 using namespace sema; 54 55 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 56 if (OwnedType) { 57 Decl *Group[2] = { OwnedType, Ptr }; 58 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 59 } 60 61 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 62 } 63 64 namespace { 65 66 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 67 public: 68 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 69 bool AllowTemplates = false, 70 bool AllowNonTemplates = true) 71 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 72 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 73 WantExpressionKeywords = false; 74 WantCXXNamedCasts = false; 75 WantRemainingKeywords = false; 76 } 77 78 bool ValidateCandidate(const TypoCorrection &candidate) override { 79 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 80 if (!AllowInvalidDecl && ND->isInvalidDecl()) 81 return false; 82 83 if (getAsTypeTemplateDecl(ND)) 84 return AllowTemplates; 85 86 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 87 if (!IsType) 88 return false; 89 90 if (AllowNonTemplates) 91 return true; 92 93 // An injected-class-name of a class template (specialization) is valid 94 // as a template or as a non-template. 95 if (AllowTemplates) { 96 auto *RD = dyn_cast<CXXRecordDecl>(ND); 97 if (!RD || !RD->isInjectedClassName()) 98 return false; 99 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 100 return RD->getDescribedClassTemplate() || 101 isa<ClassTemplateSpecializationDecl>(RD); 102 } 103 104 return false; 105 } 106 107 return !WantClassName && candidate.isKeyword(); 108 } 109 110 std::unique_ptr<CorrectionCandidateCallback> clone() override { 111 return std::make_unique<TypeNameValidatorCCC>(*this); 112 } 113 114 private: 115 bool AllowInvalidDecl; 116 bool WantClassName; 117 bool AllowTemplates; 118 bool AllowNonTemplates; 119 }; 120 121 } // end anonymous namespace 122 123 /// Determine whether the token kind starts a simple-type-specifier. 124 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 125 switch (Kind) { 126 // FIXME: Take into account the current language when deciding whether a 127 // token kind is a valid type specifier 128 case tok::kw_short: 129 case tok::kw_long: 130 case tok::kw___int64: 131 case tok::kw___int128: 132 case tok::kw_signed: 133 case tok::kw_unsigned: 134 case tok::kw_void: 135 case tok::kw_char: 136 case tok::kw_int: 137 case tok::kw_half: 138 case tok::kw_float: 139 case tok::kw_double: 140 case tok::kw__Float16: 141 case tok::kw___float128: 142 case tok::kw_wchar_t: 143 case tok::kw_bool: 144 case tok::kw___underlying_type: 145 case tok::kw___auto_type: 146 return true; 147 148 case tok::annot_typename: 149 case tok::kw_char16_t: 150 case tok::kw_char32_t: 151 case tok::kw_typeof: 152 case tok::annot_decltype: 153 case tok::kw_decltype: 154 return getLangOpts().CPlusPlus; 155 156 case tok::kw_char8_t: 157 return getLangOpts().Char8; 158 159 default: 160 break; 161 } 162 163 return false; 164 } 165 166 namespace { 167 enum class UnqualifiedTypeNameLookupResult { 168 NotFound, 169 FoundNonType, 170 FoundType 171 }; 172 } // end anonymous namespace 173 174 /// Tries to perform unqualified lookup of the type decls in bases for 175 /// dependent class. 176 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 177 /// type decl, \a FoundType if only type decls are found. 178 static UnqualifiedTypeNameLookupResult 179 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 180 SourceLocation NameLoc, 181 const CXXRecordDecl *RD) { 182 if (!RD->hasDefinition()) 183 return UnqualifiedTypeNameLookupResult::NotFound; 184 // Look for type decls in base classes. 185 UnqualifiedTypeNameLookupResult FoundTypeDecl = 186 UnqualifiedTypeNameLookupResult::NotFound; 187 for (const auto &Base : RD->bases()) { 188 const CXXRecordDecl *BaseRD = nullptr; 189 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 190 BaseRD = BaseTT->getAsCXXRecordDecl(); 191 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 192 // Look for type decls in dependent base classes that have known primary 193 // templates. 194 if (!TST || !TST->isDependentType()) 195 continue; 196 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 197 if (!TD) 198 continue; 199 if (auto *BasePrimaryTemplate = 200 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 201 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 202 BaseRD = BasePrimaryTemplate; 203 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 204 if (const ClassTemplatePartialSpecializationDecl *PS = 205 CTD->findPartialSpecialization(Base.getType())) 206 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 207 BaseRD = PS; 208 } 209 } 210 } 211 if (BaseRD) { 212 for (NamedDecl *ND : BaseRD->lookup(&II)) { 213 if (!isa<TypeDecl>(ND)) 214 return UnqualifiedTypeNameLookupResult::FoundNonType; 215 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 216 } 217 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 218 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 219 case UnqualifiedTypeNameLookupResult::FoundNonType: 220 return UnqualifiedTypeNameLookupResult::FoundNonType; 221 case UnqualifiedTypeNameLookupResult::FoundType: 222 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 223 break; 224 case UnqualifiedTypeNameLookupResult::NotFound: 225 break; 226 } 227 } 228 } 229 } 230 231 return FoundTypeDecl; 232 } 233 234 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 235 const IdentifierInfo &II, 236 SourceLocation NameLoc) { 237 // Lookup in the parent class template context, if any. 238 const CXXRecordDecl *RD = nullptr; 239 UnqualifiedTypeNameLookupResult FoundTypeDecl = 240 UnqualifiedTypeNameLookupResult::NotFound; 241 for (DeclContext *DC = S.CurContext; 242 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 243 DC = DC->getParent()) { 244 // Look for type decls in dependent base classes that have known primary 245 // templates. 246 RD = dyn_cast<CXXRecordDecl>(DC); 247 if (RD && RD->getDescribedClassTemplate()) 248 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 249 } 250 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 251 return nullptr; 252 253 // We found some types in dependent base classes. Recover as if the user 254 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 255 // lookup during template instantiation. 256 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 257 258 ASTContext &Context = S.Context; 259 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 260 cast<Type>(Context.getRecordType(RD))); 261 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 262 263 CXXScopeSpec SS; 264 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 265 266 TypeLocBuilder Builder; 267 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 268 DepTL.setNameLoc(NameLoc); 269 DepTL.setElaboratedKeywordLoc(SourceLocation()); 270 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 271 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 272 } 273 274 /// If the identifier refers to a type name within this scope, 275 /// return the declaration of that type. 276 /// 277 /// This routine performs ordinary name lookup of the identifier II 278 /// within the given scope, with optional C++ scope specifier SS, to 279 /// determine whether the name refers to a type. If so, returns an 280 /// opaque pointer (actually a QualType) corresponding to that 281 /// type. Otherwise, returns NULL. 282 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 283 Scope *S, CXXScopeSpec *SS, 284 bool isClassName, bool HasTrailingDot, 285 ParsedType ObjectTypePtr, 286 bool IsCtorOrDtorName, 287 bool WantNontrivialTypeSourceInfo, 288 bool IsClassTemplateDeductionContext, 289 IdentifierInfo **CorrectedII) { 290 // FIXME: Consider allowing this outside C++1z mode as an extension. 291 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 292 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 293 !isClassName && !HasTrailingDot; 294 295 // Determine where we will perform name lookup. 296 DeclContext *LookupCtx = nullptr; 297 if (ObjectTypePtr) { 298 QualType ObjectType = ObjectTypePtr.get(); 299 if (ObjectType->isRecordType()) 300 LookupCtx = computeDeclContext(ObjectType); 301 } else if (SS && SS->isNotEmpty()) { 302 LookupCtx = computeDeclContext(*SS, false); 303 304 if (!LookupCtx) { 305 if (isDependentScopeSpecifier(*SS)) { 306 // C++ [temp.res]p3: 307 // A qualified-id that refers to a type and in which the 308 // nested-name-specifier depends on a template-parameter (14.6.2) 309 // shall be prefixed by the keyword typename to indicate that the 310 // qualified-id denotes a type, forming an 311 // elaborated-type-specifier (7.1.5.3). 312 // 313 // We therefore do not perform any name lookup if the result would 314 // refer to a member of an unknown specialization. 315 if (!isClassName && !IsCtorOrDtorName) 316 return nullptr; 317 318 // We know from the grammar that this name refers to a type, 319 // so build a dependent node to describe the type. 320 if (WantNontrivialTypeSourceInfo) 321 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 322 323 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 324 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 325 II, NameLoc); 326 return ParsedType::make(T); 327 } 328 329 return nullptr; 330 } 331 332 if (!LookupCtx->isDependentContext() && 333 RequireCompleteDeclContext(*SS, LookupCtx)) 334 return nullptr; 335 } 336 337 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 338 // lookup for class-names. 339 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 340 LookupOrdinaryName; 341 LookupResult Result(*this, &II, NameLoc, Kind); 342 if (LookupCtx) { 343 // Perform "qualified" name lookup into the declaration context we 344 // computed, which is either the type of the base of a member access 345 // expression or the declaration context associated with a prior 346 // nested-name-specifier. 347 LookupQualifiedName(Result, LookupCtx); 348 349 if (ObjectTypePtr && Result.empty()) { 350 // C++ [basic.lookup.classref]p3: 351 // If the unqualified-id is ~type-name, the type-name is looked up 352 // in the context of the entire postfix-expression. If the type T of 353 // the object expression is of a class type C, the type-name is also 354 // looked up in the scope of class C. At least one of the lookups shall 355 // find a name that refers to (possibly cv-qualified) T. 356 LookupName(Result, S); 357 } 358 } else { 359 // Perform unqualified name lookup. 360 LookupName(Result, S); 361 362 // For unqualified lookup in a class template in MSVC mode, look into 363 // dependent base classes where the primary class template is known. 364 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 365 if (ParsedType TypeInBase = 366 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 367 return TypeInBase; 368 } 369 } 370 371 NamedDecl *IIDecl = nullptr; 372 switch (Result.getResultKind()) { 373 case LookupResult::NotFound: 374 case LookupResult::NotFoundInCurrentInstantiation: 375 if (CorrectedII) { 376 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 377 AllowDeducedTemplate); 378 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 379 S, SS, CCC, CTK_ErrorRecovery); 380 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 381 TemplateTy Template; 382 bool MemberOfUnknownSpecialization; 383 UnqualifiedId TemplateName; 384 TemplateName.setIdentifier(NewII, NameLoc); 385 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 386 CXXScopeSpec NewSS, *NewSSPtr = SS; 387 if (SS && NNS) { 388 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 389 NewSSPtr = &NewSS; 390 } 391 if (Correction && (NNS || NewII != &II) && 392 // Ignore a correction to a template type as the to-be-corrected 393 // identifier is not a template (typo correction for template names 394 // is handled elsewhere). 395 !(getLangOpts().CPlusPlus && NewSSPtr && 396 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 397 Template, MemberOfUnknownSpecialization))) { 398 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 399 isClassName, HasTrailingDot, ObjectTypePtr, 400 IsCtorOrDtorName, 401 WantNontrivialTypeSourceInfo, 402 IsClassTemplateDeductionContext); 403 if (Ty) { 404 diagnoseTypo(Correction, 405 PDiag(diag::err_unknown_type_or_class_name_suggest) 406 << Result.getLookupName() << isClassName); 407 if (SS && NNS) 408 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 409 *CorrectedII = NewII; 410 return Ty; 411 } 412 } 413 } 414 // If typo correction failed or was not performed, fall through 415 LLVM_FALLTHROUGH; 416 case LookupResult::FoundOverloaded: 417 case LookupResult::FoundUnresolvedValue: 418 Result.suppressDiagnostics(); 419 return nullptr; 420 421 case LookupResult::Ambiguous: 422 // Recover from type-hiding ambiguities by hiding the type. We'll 423 // do the lookup again when looking for an object, and we can 424 // diagnose the error then. If we don't do this, then the error 425 // about hiding the type will be immediately followed by an error 426 // that only makes sense if the identifier was treated like a type. 427 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 428 Result.suppressDiagnostics(); 429 return nullptr; 430 } 431 432 // Look to see if we have a type anywhere in the list of results. 433 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 434 Res != ResEnd; ++Res) { 435 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 436 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 437 if (!IIDecl || 438 (*Res)->getLocation().getRawEncoding() < 439 IIDecl->getLocation().getRawEncoding()) 440 IIDecl = *Res; 441 } 442 } 443 444 if (!IIDecl) { 445 // None of the entities we found is a type, so there is no way 446 // to even assume that the result is a type. In this case, don't 447 // complain about the ambiguity. The parser will either try to 448 // perform this lookup again (e.g., as an object name), which 449 // will produce the ambiguity, or will complain that it expected 450 // a type name. 451 Result.suppressDiagnostics(); 452 return nullptr; 453 } 454 455 // We found a type within the ambiguous lookup; diagnose the 456 // ambiguity and then return that type. This might be the right 457 // answer, or it might not be, but it suppresses any attempt to 458 // perform the name lookup again. 459 break; 460 461 case LookupResult::Found: 462 IIDecl = Result.getFoundDecl(); 463 break; 464 } 465 466 assert(IIDecl && "Didn't find decl"); 467 468 QualType T; 469 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 470 // C++ [class.qual]p2: A lookup that would find the injected-class-name 471 // instead names the constructors of the class, except when naming a class. 472 // This is ill-formed when we're not actually forming a ctor or dtor name. 473 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 474 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 475 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 476 FoundRD->isInjectedClassName() && 477 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 478 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 479 << &II << /*Type*/1; 480 481 DiagnoseUseOfDecl(IIDecl, NameLoc); 482 483 T = Context.getTypeDeclType(TD); 484 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 485 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 486 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 487 if (!HasTrailingDot) 488 T = Context.getObjCInterfaceType(IDecl); 489 } else if (AllowDeducedTemplate) { 490 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 491 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 492 QualType(), false); 493 } 494 495 if (T.isNull()) { 496 // If it's not plausibly a type, suppress diagnostics. 497 Result.suppressDiagnostics(); 498 return nullptr; 499 } 500 501 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 502 // constructor or destructor name (in such a case, the scope specifier 503 // will be attached to the enclosing Expr or Decl node). 504 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 505 !isa<ObjCInterfaceDecl>(IIDecl)) { 506 if (WantNontrivialTypeSourceInfo) { 507 // Construct a type with type-source information. 508 TypeLocBuilder Builder; 509 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 510 511 T = getElaboratedType(ETK_None, *SS, T); 512 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 513 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 514 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 515 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 516 } else { 517 T = getElaboratedType(ETK_None, *SS, T); 518 } 519 } 520 521 return ParsedType::make(T); 522 } 523 524 // Builds a fake NNS for the given decl context. 525 static NestedNameSpecifier * 526 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 527 for (;; DC = DC->getLookupParent()) { 528 DC = DC->getPrimaryContext(); 529 auto *ND = dyn_cast<NamespaceDecl>(DC); 530 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 531 return NestedNameSpecifier::Create(Context, nullptr, ND); 532 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 533 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 534 RD->getTypeForDecl()); 535 else if (isa<TranslationUnitDecl>(DC)) 536 return NestedNameSpecifier::GlobalSpecifier(Context); 537 } 538 llvm_unreachable("something isn't in TU scope?"); 539 } 540 541 /// Find the parent class with dependent bases of the innermost enclosing method 542 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 543 /// up allowing unqualified dependent type names at class-level, which MSVC 544 /// correctly rejects. 545 static const CXXRecordDecl * 546 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 547 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 548 DC = DC->getPrimaryContext(); 549 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 550 if (MD->getParent()->hasAnyDependentBases()) 551 return MD->getParent(); 552 } 553 return nullptr; 554 } 555 556 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 557 SourceLocation NameLoc, 558 bool IsTemplateTypeArg) { 559 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 560 561 NestedNameSpecifier *NNS = nullptr; 562 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 563 // If we weren't able to parse a default template argument, delay lookup 564 // until instantiation time by making a non-dependent DependentTypeName. We 565 // pretend we saw a NestedNameSpecifier referring to the current scope, and 566 // lookup is retried. 567 // FIXME: This hurts our diagnostic quality, since we get errors like "no 568 // type named 'Foo' in 'current_namespace'" when the user didn't write any 569 // name specifiers. 570 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 571 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 572 } else if (const CXXRecordDecl *RD = 573 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 574 // Build a DependentNameType that will perform lookup into RD at 575 // instantiation time. 576 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 577 RD->getTypeForDecl()); 578 579 // Diagnose that this identifier was undeclared, and retry the lookup during 580 // template instantiation. 581 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 582 << RD; 583 } else { 584 // This is not a situation that we should recover from. 585 return ParsedType(); 586 } 587 588 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 589 590 // Build type location information. We synthesized the qualifier, so we have 591 // to build a fake NestedNameSpecifierLoc. 592 NestedNameSpecifierLocBuilder NNSLocBuilder; 593 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 594 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 595 596 TypeLocBuilder Builder; 597 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 598 DepTL.setNameLoc(NameLoc); 599 DepTL.setElaboratedKeywordLoc(SourceLocation()); 600 DepTL.setQualifierLoc(QualifierLoc); 601 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 602 } 603 604 /// isTagName() - This method is called *for error recovery purposes only* 605 /// to determine if the specified name is a valid tag name ("struct foo"). If 606 /// so, this returns the TST for the tag corresponding to it (TST_enum, 607 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 608 /// cases in C where the user forgot to specify the tag. 609 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 610 // Do a tag name lookup in this scope. 611 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 612 LookupName(R, S, false); 613 R.suppressDiagnostics(); 614 if (R.getResultKind() == LookupResult::Found) 615 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 616 switch (TD->getTagKind()) { 617 case TTK_Struct: return DeclSpec::TST_struct; 618 case TTK_Interface: return DeclSpec::TST_interface; 619 case TTK_Union: return DeclSpec::TST_union; 620 case TTK_Class: return DeclSpec::TST_class; 621 case TTK_Enum: return DeclSpec::TST_enum; 622 } 623 } 624 625 return DeclSpec::TST_unspecified; 626 } 627 628 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 629 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 630 /// then downgrade the missing typename error to a warning. 631 /// This is needed for MSVC compatibility; Example: 632 /// @code 633 /// template<class T> class A { 634 /// public: 635 /// typedef int TYPE; 636 /// }; 637 /// template<class T> class B : public A<T> { 638 /// public: 639 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 640 /// }; 641 /// @endcode 642 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 643 if (CurContext->isRecord()) { 644 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 645 return true; 646 647 const Type *Ty = SS->getScopeRep()->getAsType(); 648 649 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 650 for (const auto &Base : RD->bases()) 651 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 652 return true; 653 return S->isFunctionPrototypeScope(); 654 } 655 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 656 } 657 658 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 659 SourceLocation IILoc, 660 Scope *S, 661 CXXScopeSpec *SS, 662 ParsedType &SuggestedType, 663 bool IsTemplateName) { 664 // Don't report typename errors for editor placeholders. 665 if (II->isEditorPlaceholder()) 666 return; 667 // We don't have anything to suggest (yet). 668 SuggestedType = nullptr; 669 670 // There may have been a typo in the name of the type. Look up typo 671 // results, in case we have something that we can suggest. 672 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 673 /*AllowTemplates=*/IsTemplateName, 674 /*AllowNonTemplates=*/!IsTemplateName); 675 if (TypoCorrection Corrected = 676 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 677 CCC, CTK_ErrorRecovery)) { 678 // FIXME: Support error recovery for the template-name case. 679 bool CanRecover = !IsTemplateName; 680 if (Corrected.isKeyword()) { 681 // We corrected to a keyword. 682 diagnoseTypo(Corrected, 683 PDiag(IsTemplateName ? diag::err_no_template_suggest 684 : diag::err_unknown_typename_suggest) 685 << II); 686 II = Corrected.getCorrectionAsIdentifierInfo(); 687 } else { 688 // We found a similarly-named type or interface; suggest that. 689 if (!SS || !SS->isSet()) { 690 diagnoseTypo(Corrected, 691 PDiag(IsTemplateName ? diag::err_no_template_suggest 692 : diag::err_unknown_typename_suggest) 693 << II, CanRecover); 694 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 695 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 696 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 697 II->getName().equals(CorrectedStr); 698 diagnoseTypo(Corrected, 699 PDiag(IsTemplateName 700 ? diag::err_no_member_template_suggest 701 : diag::err_unknown_nested_typename_suggest) 702 << II << DC << DroppedSpecifier << SS->getRange(), 703 CanRecover); 704 } else { 705 llvm_unreachable("could not have corrected a typo here"); 706 } 707 708 if (!CanRecover) 709 return; 710 711 CXXScopeSpec tmpSS; 712 if (Corrected.getCorrectionSpecifier()) 713 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 714 SourceRange(IILoc)); 715 // FIXME: Support class template argument deduction here. 716 SuggestedType = 717 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 718 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 719 /*IsCtorOrDtorName=*/false, 720 /*WantNontrivialTypeSourceInfo=*/true); 721 } 722 return; 723 } 724 725 if (getLangOpts().CPlusPlus && !IsTemplateName) { 726 // See if II is a class template that the user forgot to pass arguments to. 727 UnqualifiedId Name; 728 Name.setIdentifier(II, IILoc); 729 CXXScopeSpec EmptySS; 730 TemplateTy TemplateResult; 731 bool MemberOfUnknownSpecialization; 732 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 733 Name, nullptr, true, TemplateResult, 734 MemberOfUnknownSpecialization) == TNK_Type_template) { 735 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 736 return; 737 } 738 } 739 740 // FIXME: Should we move the logic that tries to recover from a missing tag 741 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 742 743 if (!SS || (!SS->isSet() && !SS->isInvalid())) 744 Diag(IILoc, IsTemplateName ? diag::err_no_template 745 : diag::err_unknown_typename) 746 << II; 747 else if (DeclContext *DC = computeDeclContext(*SS, false)) 748 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 749 : diag::err_typename_nested_not_found) 750 << II << DC << SS->getRange(); 751 else if (isDependentScopeSpecifier(*SS)) { 752 unsigned DiagID = diag::err_typename_missing; 753 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 754 DiagID = diag::ext_typename_missing; 755 756 Diag(SS->getRange().getBegin(), DiagID) 757 << SS->getScopeRep() << II->getName() 758 << SourceRange(SS->getRange().getBegin(), IILoc) 759 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 760 SuggestedType = ActOnTypenameType(S, SourceLocation(), 761 *SS, *II, IILoc).get(); 762 } else { 763 assert(SS && SS->isInvalid() && 764 "Invalid scope specifier has already been diagnosed"); 765 } 766 } 767 768 /// Determine whether the given result set contains either a type name 769 /// or 770 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 771 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 772 NextToken.is(tok::less); 773 774 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 775 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 776 return true; 777 778 if (CheckTemplate && isa<TemplateDecl>(*I)) 779 return true; 780 } 781 782 return false; 783 } 784 785 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 786 Scope *S, CXXScopeSpec &SS, 787 IdentifierInfo *&Name, 788 SourceLocation NameLoc) { 789 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 790 SemaRef.LookupParsedName(R, S, &SS); 791 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 792 StringRef FixItTagName; 793 switch (Tag->getTagKind()) { 794 case TTK_Class: 795 FixItTagName = "class "; 796 break; 797 798 case TTK_Enum: 799 FixItTagName = "enum "; 800 break; 801 802 case TTK_Struct: 803 FixItTagName = "struct "; 804 break; 805 806 case TTK_Interface: 807 FixItTagName = "__interface "; 808 break; 809 810 case TTK_Union: 811 FixItTagName = "union "; 812 break; 813 } 814 815 StringRef TagName = FixItTagName.drop_back(); 816 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 817 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 818 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 819 820 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 821 I != IEnd; ++I) 822 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 823 << Name << TagName; 824 825 // Replace lookup results with just the tag decl. 826 Result.clear(Sema::LookupTagName); 827 SemaRef.LookupParsedName(Result, S, &SS); 828 return true; 829 } 830 831 return false; 832 } 833 834 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 835 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 836 QualType T, SourceLocation NameLoc) { 837 ASTContext &Context = S.Context; 838 839 TypeLocBuilder Builder; 840 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 841 842 T = S.getElaboratedType(ETK_None, SS, T); 843 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 844 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 845 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 846 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 847 } 848 849 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 850 IdentifierInfo *&Name, 851 SourceLocation NameLoc, 852 const Token &NextToken, 853 CorrectionCandidateCallback *CCC) { 854 DeclarationNameInfo NameInfo(Name, NameLoc); 855 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 856 857 assert(NextToken.isNot(tok::coloncolon) && 858 "parse nested name specifiers before calling ClassifyName"); 859 if (getLangOpts().CPlusPlus && SS.isSet() && 860 isCurrentClassName(*Name, S, &SS)) { 861 // Per [class.qual]p2, this names the constructors of SS, not the 862 // injected-class-name. We don't have a classification for that. 863 // There's not much point caching this result, since the parser 864 // will reject it later. 865 return NameClassification::Unknown(); 866 } 867 868 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 869 LookupParsedName(Result, S, &SS, !CurMethod); 870 871 if (SS.isInvalid()) 872 return NameClassification::Error(); 873 874 // For unqualified lookup in a class template in MSVC mode, look into 875 // dependent base classes where the primary class template is known. 876 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 877 if (ParsedType TypeInBase = 878 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 879 return TypeInBase; 880 } 881 882 // Perform lookup for Objective-C instance variables (including automatically 883 // synthesized instance variables), if we're in an Objective-C method. 884 // FIXME: This lookup really, really needs to be folded in to the normal 885 // unqualified lookup mechanism. 886 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 887 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 888 if (Ivar.isInvalid()) 889 return NameClassification::Error(); 890 if (Ivar.isUsable()) 891 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 892 893 // We defer builtin creation until after ivar lookup inside ObjC methods. 894 if (Result.empty()) 895 LookupBuiltin(Result); 896 } 897 898 bool SecondTry = false; 899 bool IsFilteredTemplateName = false; 900 901 Corrected: 902 switch (Result.getResultKind()) { 903 case LookupResult::NotFound: 904 // If an unqualified-id is followed by a '(', then we have a function 905 // call. 906 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 907 // In C++, this is an ADL-only call. 908 // FIXME: Reference? 909 if (getLangOpts().CPlusPlus) 910 return NameClassification::UndeclaredNonType(); 911 912 // C90 6.3.2.2: 913 // If the expression that precedes the parenthesized argument list in a 914 // function call consists solely of an identifier, and if no 915 // declaration is visible for this identifier, the identifier is 916 // implicitly declared exactly as if, in the innermost block containing 917 // the function call, the declaration 918 // 919 // extern int identifier (); 920 // 921 // appeared. 922 // 923 // We also allow this in C99 as an extension. 924 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 925 return NameClassification::NonType(D); 926 } 927 928 if (getLangOpts().CPlusPlus2a && SS.isEmpty() && NextToken.is(tok::less)) { 929 // In C++20 onwards, this could be an ADL-only call to a function 930 // template, and we're required to assume that this is a template name. 931 // 932 // FIXME: Find a way to still do typo correction in this case. 933 TemplateName Template = 934 Context.getAssumedTemplateName(NameInfo.getName()); 935 return NameClassification::UndeclaredTemplate(Template); 936 } 937 938 // In C, we first see whether there is a tag type by the same name, in 939 // which case it's likely that the user just forgot to write "enum", 940 // "struct", or "union". 941 if (!getLangOpts().CPlusPlus && !SecondTry && 942 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 943 break; 944 } 945 946 // Perform typo correction to determine if there is another name that is 947 // close to this name. 948 if (!SecondTry && CCC) { 949 SecondTry = true; 950 if (TypoCorrection Corrected = 951 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 952 &SS, *CCC, CTK_ErrorRecovery)) { 953 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 954 unsigned QualifiedDiag = diag::err_no_member_suggest; 955 956 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 957 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 958 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 959 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 960 UnqualifiedDiag = diag::err_no_template_suggest; 961 QualifiedDiag = diag::err_no_member_template_suggest; 962 } else if (UnderlyingFirstDecl && 963 (isa<TypeDecl>(UnderlyingFirstDecl) || 964 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 965 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 966 UnqualifiedDiag = diag::err_unknown_typename_suggest; 967 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 968 } 969 970 if (SS.isEmpty()) { 971 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 972 } else {// FIXME: is this even reachable? Test it. 973 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 974 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 975 Name->getName().equals(CorrectedStr); 976 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 977 << Name << computeDeclContext(SS, false) 978 << DroppedSpecifier << SS.getRange()); 979 } 980 981 // Update the name, so that the caller has the new name. 982 Name = Corrected.getCorrectionAsIdentifierInfo(); 983 984 // Typo correction corrected to a keyword. 985 if (Corrected.isKeyword()) 986 return Name; 987 988 // Also update the LookupResult... 989 // FIXME: This should probably go away at some point 990 Result.clear(); 991 Result.setLookupName(Corrected.getCorrection()); 992 if (FirstDecl) 993 Result.addDecl(FirstDecl); 994 995 // If we found an Objective-C instance variable, let 996 // LookupInObjCMethod build the appropriate expression to 997 // reference the ivar. 998 // FIXME: This is a gross hack. 999 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1000 DeclResult R = 1001 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1002 if (R.isInvalid()) 1003 return NameClassification::Error(); 1004 if (R.isUsable()) 1005 return NameClassification::NonType(Ivar); 1006 } 1007 1008 goto Corrected; 1009 } 1010 } 1011 1012 // We failed to correct; just fall through and let the parser deal with it. 1013 Result.suppressDiagnostics(); 1014 return NameClassification::Unknown(); 1015 1016 case LookupResult::NotFoundInCurrentInstantiation: { 1017 // We performed name lookup into the current instantiation, and there were 1018 // dependent bases, so we treat this result the same way as any other 1019 // dependent nested-name-specifier. 1020 1021 // C++ [temp.res]p2: 1022 // A name used in a template declaration or definition and that is 1023 // dependent on a template-parameter is assumed not to name a type 1024 // unless the applicable name lookup finds a type name or the name is 1025 // qualified by the keyword typename. 1026 // 1027 // FIXME: If the next token is '<', we might want to ask the parser to 1028 // perform some heroics to see if we actually have a 1029 // template-argument-list, which would indicate a missing 'template' 1030 // keyword here. 1031 return NameClassification::DependentNonType(); 1032 } 1033 1034 case LookupResult::Found: 1035 case LookupResult::FoundOverloaded: 1036 case LookupResult::FoundUnresolvedValue: 1037 break; 1038 1039 case LookupResult::Ambiguous: 1040 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1041 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1042 /*AllowDependent=*/false)) { 1043 // C++ [temp.local]p3: 1044 // A lookup that finds an injected-class-name (10.2) can result in an 1045 // ambiguity in certain cases (for example, if it is found in more than 1046 // one base class). If all of the injected-class-names that are found 1047 // refer to specializations of the same class template, and if the name 1048 // is followed by a template-argument-list, the reference refers to the 1049 // class template itself and not a specialization thereof, and is not 1050 // ambiguous. 1051 // 1052 // This filtering can make an ambiguous result into an unambiguous one, 1053 // so try again after filtering out template names. 1054 FilterAcceptableTemplateNames(Result); 1055 if (!Result.isAmbiguous()) { 1056 IsFilteredTemplateName = true; 1057 break; 1058 } 1059 } 1060 1061 // Diagnose the ambiguity and return an error. 1062 return NameClassification::Error(); 1063 } 1064 1065 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1066 (IsFilteredTemplateName || 1067 hasAnyAcceptableTemplateNames( 1068 Result, /*AllowFunctionTemplates=*/true, 1069 /*AllowDependent=*/false, 1070 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1071 getLangOpts().CPlusPlus2a))) { 1072 // C++ [temp.names]p3: 1073 // After name lookup (3.4) finds that a name is a template-name or that 1074 // an operator-function-id or a literal- operator-id refers to a set of 1075 // overloaded functions any member of which is a function template if 1076 // this is followed by a <, the < is always taken as the delimiter of a 1077 // template-argument-list and never as the less-than operator. 1078 // C++2a [temp.names]p2: 1079 // A name is also considered to refer to a template if it is an 1080 // unqualified-id followed by a < and name lookup finds either one 1081 // or more functions or finds nothing. 1082 if (!IsFilteredTemplateName) 1083 FilterAcceptableTemplateNames(Result); 1084 1085 bool IsFunctionTemplate; 1086 bool IsVarTemplate; 1087 TemplateName Template; 1088 if (Result.end() - Result.begin() > 1) { 1089 IsFunctionTemplate = true; 1090 Template = Context.getOverloadedTemplateName(Result.begin(), 1091 Result.end()); 1092 } else if (!Result.empty()) { 1093 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1094 *Result.begin(), /*AllowFunctionTemplates=*/true, 1095 /*AllowDependent=*/false)); 1096 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1097 IsVarTemplate = isa<VarTemplateDecl>(TD); 1098 1099 if (SS.isNotEmpty()) 1100 Template = 1101 Context.getQualifiedTemplateName(SS.getScopeRep(), 1102 /*TemplateKeyword=*/false, TD); 1103 else 1104 Template = TemplateName(TD); 1105 } else { 1106 // All results were non-template functions. This is a function template 1107 // name. 1108 IsFunctionTemplate = true; 1109 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1110 } 1111 1112 if (IsFunctionTemplate) { 1113 // Function templates always go through overload resolution, at which 1114 // point we'll perform the various checks (e.g., accessibility) we need 1115 // to based on which function we selected. 1116 Result.suppressDiagnostics(); 1117 1118 return NameClassification::FunctionTemplate(Template); 1119 } 1120 1121 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1122 : NameClassification::TypeTemplate(Template); 1123 } 1124 1125 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1126 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1127 DiagnoseUseOfDecl(Type, NameLoc); 1128 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1129 QualType T = Context.getTypeDeclType(Type); 1130 if (SS.isNotEmpty()) 1131 return buildNestedType(*this, SS, T, NameLoc); 1132 return ParsedType::make(T); 1133 } 1134 1135 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1136 if (!Class) { 1137 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1138 if (ObjCCompatibleAliasDecl *Alias = 1139 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1140 Class = Alias->getClassInterface(); 1141 } 1142 1143 if (Class) { 1144 DiagnoseUseOfDecl(Class, NameLoc); 1145 1146 if (NextToken.is(tok::period)) { 1147 // Interface. <something> is parsed as a property reference expression. 1148 // Just return "unknown" as a fall-through for now. 1149 Result.suppressDiagnostics(); 1150 return NameClassification::Unknown(); 1151 } 1152 1153 QualType T = Context.getObjCInterfaceType(Class); 1154 return ParsedType::make(T); 1155 } 1156 1157 if (isa<ConceptDecl>(FirstDecl)) 1158 return NameClassification::Concept( 1159 TemplateName(cast<TemplateDecl>(FirstDecl))); 1160 1161 // We can have a type template here if we're classifying a template argument. 1162 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1163 !isa<VarTemplateDecl>(FirstDecl)) 1164 return NameClassification::TypeTemplate( 1165 TemplateName(cast<TemplateDecl>(FirstDecl))); 1166 1167 // Check for a tag type hidden by a non-type decl in a few cases where it 1168 // seems likely a type is wanted instead of the non-type that was found. 1169 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1170 if ((NextToken.is(tok::identifier) || 1171 (NextIsOp && 1172 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1173 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1174 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1175 DiagnoseUseOfDecl(Type, NameLoc); 1176 QualType T = Context.getTypeDeclType(Type); 1177 if (SS.isNotEmpty()) 1178 return buildNestedType(*this, SS, T, NameLoc); 1179 return ParsedType::make(T); 1180 } 1181 1182 // FIXME: This is context-dependent. We need to defer building the member 1183 // expression until the classification is consumed. 1184 if (FirstDecl->isCXXClassMember()) 1185 return NameClassification::ContextIndependentExpr( 1186 BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr, 1187 S)); 1188 1189 // If we already know which single declaration is referenced, just annotate 1190 // that declaration directly. 1191 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1192 if (Result.isSingleResult() && !ADL) 1193 return NameClassification::NonType(Result.getRepresentativeDecl()); 1194 1195 // Build an UnresolvedLookupExpr. Note that this doesn't depend on the 1196 // context in which we performed classification, so it's safe to do now. 1197 return NameClassification::ContextIndependentExpr( 1198 BuildDeclarationNameExpr(SS, Result, ADL)); 1199 } 1200 1201 ExprResult 1202 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1203 SourceLocation NameLoc) { 1204 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1205 CXXScopeSpec SS; 1206 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1207 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1208 } 1209 1210 ExprResult 1211 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1212 IdentifierInfo *Name, 1213 SourceLocation NameLoc, 1214 bool IsAddressOfOperand) { 1215 DeclarationNameInfo NameInfo(Name, NameLoc); 1216 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1217 NameInfo, IsAddressOfOperand, 1218 /*TemplateArgs=*/nullptr); 1219 } 1220 1221 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1222 NamedDecl *Found, 1223 SourceLocation NameLoc, 1224 const Token &NextToken) { 1225 if (getCurMethodDecl() && SS.isEmpty()) 1226 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1227 return BuildIvarRefExpr(S, NameLoc, Ivar); 1228 1229 // Reconstruct the lookup result. 1230 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1231 Result.addDecl(Found); 1232 Result.resolveKind(); 1233 1234 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1235 return BuildDeclarationNameExpr(SS, Result, ADL); 1236 } 1237 1238 Sema::TemplateNameKindForDiagnostics 1239 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1240 auto *TD = Name.getAsTemplateDecl(); 1241 if (!TD) 1242 return TemplateNameKindForDiagnostics::DependentTemplate; 1243 if (isa<ClassTemplateDecl>(TD)) 1244 return TemplateNameKindForDiagnostics::ClassTemplate; 1245 if (isa<FunctionTemplateDecl>(TD)) 1246 return TemplateNameKindForDiagnostics::FunctionTemplate; 1247 if (isa<VarTemplateDecl>(TD)) 1248 return TemplateNameKindForDiagnostics::VarTemplate; 1249 if (isa<TypeAliasTemplateDecl>(TD)) 1250 return TemplateNameKindForDiagnostics::AliasTemplate; 1251 if (isa<TemplateTemplateParmDecl>(TD)) 1252 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1253 if (isa<ConceptDecl>(TD)) 1254 return TemplateNameKindForDiagnostics::Concept; 1255 return TemplateNameKindForDiagnostics::DependentTemplate; 1256 } 1257 1258 // Determines the context to return to after temporarily entering a 1259 // context. This depends in an unnecessarily complicated way on the 1260 // exact ordering of callbacks from the parser. 1261 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1262 1263 // Functions defined inline within classes aren't parsed until we've 1264 // finished parsing the top-level class, so the top-level class is 1265 // the context we'll need to return to. 1266 // A Lambda call operator whose parent is a class must not be treated 1267 // as an inline member function. A Lambda can be used legally 1268 // either as an in-class member initializer or a default argument. These 1269 // are parsed once the class has been marked complete and so the containing 1270 // context would be the nested class (when the lambda is defined in one); 1271 // If the class is not complete, then the lambda is being used in an 1272 // ill-formed fashion (such as to specify the width of a bit-field, or 1273 // in an array-bound) - in which case we still want to return the 1274 // lexically containing DC (which could be a nested class). 1275 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1276 DC = DC->getLexicalParent(); 1277 1278 // A function not defined within a class will always return to its 1279 // lexical context. 1280 if (!isa<CXXRecordDecl>(DC)) 1281 return DC; 1282 1283 // A C++ inline method/friend is parsed *after* the topmost class 1284 // it was declared in is fully parsed ("complete"); the topmost 1285 // class is the context we need to return to. 1286 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1287 DC = RD; 1288 1289 // Return the declaration context of the topmost class the inline method is 1290 // declared in. 1291 return DC; 1292 } 1293 1294 return DC->getLexicalParent(); 1295 } 1296 1297 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1298 assert(getContainingDC(DC) == CurContext && 1299 "The next DeclContext should be lexically contained in the current one."); 1300 CurContext = DC; 1301 S->setEntity(DC); 1302 } 1303 1304 void Sema::PopDeclContext() { 1305 assert(CurContext && "DeclContext imbalance!"); 1306 1307 CurContext = getContainingDC(CurContext); 1308 assert(CurContext && "Popped translation unit!"); 1309 } 1310 1311 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1312 Decl *D) { 1313 // Unlike PushDeclContext, the context to which we return is not necessarily 1314 // the containing DC of TD, because the new context will be some pre-existing 1315 // TagDecl definition instead of a fresh one. 1316 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1317 CurContext = cast<TagDecl>(D)->getDefinition(); 1318 assert(CurContext && "skipping definition of undefined tag"); 1319 // Start lookups from the parent of the current context; we don't want to look 1320 // into the pre-existing complete definition. 1321 S->setEntity(CurContext->getLookupParent()); 1322 return Result; 1323 } 1324 1325 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1326 CurContext = static_cast<decltype(CurContext)>(Context); 1327 } 1328 1329 /// EnterDeclaratorContext - Used when we must lookup names in the context 1330 /// of a declarator's nested name specifier. 1331 /// 1332 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1333 // C++0x [basic.lookup.unqual]p13: 1334 // A name used in the definition of a static data member of class 1335 // X (after the qualified-id of the static member) is looked up as 1336 // if the name was used in a member function of X. 1337 // C++0x [basic.lookup.unqual]p14: 1338 // If a variable member of a namespace is defined outside of the 1339 // scope of its namespace then any name used in the definition of 1340 // the variable member (after the declarator-id) is looked up as 1341 // if the definition of the variable member occurred in its 1342 // namespace. 1343 // Both of these imply that we should push a scope whose context 1344 // is the semantic context of the declaration. We can't use 1345 // PushDeclContext here because that context is not necessarily 1346 // lexically contained in the current context. Fortunately, 1347 // the containing scope should have the appropriate information. 1348 1349 assert(!S->getEntity() && "scope already has entity"); 1350 1351 #ifndef NDEBUG 1352 Scope *Ancestor = S->getParent(); 1353 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1354 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1355 #endif 1356 1357 CurContext = DC; 1358 S->setEntity(DC); 1359 } 1360 1361 void Sema::ExitDeclaratorContext(Scope *S) { 1362 assert(S->getEntity() == CurContext && "Context imbalance!"); 1363 1364 // Switch back to the lexical context. The safety of this is 1365 // enforced by an assert in EnterDeclaratorContext. 1366 Scope *Ancestor = S->getParent(); 1367 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1368 CurContext = Ancestor->getEntity(); 1369 1370 // We don't need to do anything with the scope, which is going to 1371 // disappear. 1372 } 1373 1374 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1375 // We assume that the caller has already called 1376 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1377 FunctionDecl *FD = D->getAsFunction(); 1378 if (!FD) 1379 return; 1380 1381 // Same implementation as PushDeclContext, but enters the context 1382 // from the lexical parent, rather than the top-level class. 1383 assert(CurContext == FD->getLexicalParent() && 1384 "The next DeclContext should be lexically contained in the current one."); 1385 CurContext = FD; 1386 S->setEntity(CurContext); 1387 1388 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1389 ParmVarDecl *Param = FD->getParamDecl(P); 1390 // If the parameter has an identifier, then add it to the scope 1391 if (Param->getIdentifier()) { 1392 S->AddDecl(Param); 1393 IdResolver.AddDecl(Param); 1394 } 1395 } 1396 } 1397 1398 void Sema::ActOnExitFunctionContext() { 1399 // Same implementation as PopDeclContext, but returns to the lexical parent, 1400 // rather than the top-level class. 1401 assert(CurContext && "DeclContext imbalance!"); 1402 CurContext = CurContext->getLexicalParent(); 1403 assert(CurContext && "Popped translation unit!"); 1404 } 1405 1406 /// Determine whether we allow overloading of the function 1407 /// PrevDecl with another declaration. 1408 /// 1409 /// This routine determines whether overloading is possible, not 1410 /// whether some new function is actually an overload. It will return 1411 /// true in C++ (where we can always provide overloads) or, as an 1412 /// extension, in C when the previous function is already an 1413 /// overloaded function declaration or has the "overloadable" 1414 /// attribute. 1415 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1416 ASTContext &Context, 1417 const FunctionDecl *New) { 1418 if (Context.getLangOpts().CPlusPlus) 1419 return true; 1420 1421 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1422 return true; 1423 1424 return Previous.getResultKind() == LookupResult::Found && 1425 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1426 New->hasAttr<OverloadableAttr>()); 1427 } 1428 1429 /// Add this decl to the scope shadowed decl chains. 1430 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1431 // Move up the scope chain until we find the nearest enclosing 1432 // non-transparent context. The declaration will be introduced into this 1433 // scope. 1434 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1435 S = S->getParent(); 1436 1437 // Add scoped declarations into their context, so that they can be 1438 // found later. Declarations without a context won't be inserted 1439 // into any context. 1440 if (AddToContext) 1441 CurContext->addDecl(D); 1442 1443 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1444 // are function-local declarations. 1445 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1446 !D->getDeclContext()->getRedeclContext()->Equals( 1447 D->getLexicalDeclContext()->getRedeclContext()) && 1448 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1449 return; 1450 1451 // Template instantiations should also not be pushed into scope. 1452 if (isa<FunctionDecl>(D) && 1453 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1454 return; 1455 1456 // If this replaces anything in the current scope, 1457 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1458 IEnd = IdResolver.end(); 1459 for (; I != IEnd; ++I) { 1460 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1461 S->RemoveDecl(*I); 1462 IdResolver.RemoveDecl(*I); 1463 1464 // Should only need to replace one decl. 1465 break; 1466 } 1467 } 1468 1469 S->AddDecl(D); 1470 1471 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1472 // Implicitly-generated labels may end up getting generated in an order that 1473 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1474 // the label at the appropriate place in the identifier chain. 1475 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1476 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1477 if (IDC == CurContext) { 1478 if (!S->isDeclScope(*I)) 1479 continue; 1480 } else if (IDC->Encloses(CurContext)) 1481 break; 1482 } 1483 1484 IdResolver.InsertDeclAfter(I, D); 1485 } else { 1486 IdResolver.AddDecl(D); 1487 } 1488 } 1489 1490 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1491 bool AllowInlineNamespace) { 1492 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1493 } 1494 1495 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1496 DeclContext *TargetDC = DC->getPrimaryContext(); 1497 do { 1498 if (DeclContext *ScopeDC = S->getEntity()) 1499 if (ScopeDC->getPrimaryContext() == TargetDC) 1500 return S; 1501 } while ((S = S->getParent())); 1502 1503 return nullptr; 1504 } 1505 1506 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1507 DeclContext*, 1508 ASTContext&); 1509 1510 /// Filters out lookup results that don't fall within the given scope 1511 /// as determined by isDeclInScope. 1512 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1513 bool ConsiderLinkage, 1514 bool AllowInlineNamespace) { 1515 LookupResult::Filter F = R.makeFilter(); 1516 while (F.hasNext()) { 1517 NamedDecl *D = F.next(); 1518 1519 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1520 continue; 1521 1522 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1523 continue; 1524 1525 F.erase(); 1526 } 1527 1528 F.done(); 1529 } 1530 1531 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1532 /// have compatible owning modules. 1533 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1534 // FIXME: The Modules TS is not clear about how friend declarations are 1535 // to be treated. It's not meaningful to have different owning modules for 1536 // linkage in redeclarations of the same entity, so for now allow the 1537 // redeclaration and change the owning modules to match. 1538 if (New->getFriendObjectKind() && 1539 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1540 New->setLocalOwningModule(Old->getOwningModule()); 1541 makeMergedDefinitionVisible(New); 1542 return false; 1543 } 1544 1545 Module *NewM = New->getOwningModule(); 1546 Module *OldM = Old->getOwningModule(); 1547 1548 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1549 NewM = NewM->Parent; 1550 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1551 OldM = OldM->Parent; 1552 1553 if (NewM == OldM) 1554 return false; 1555 1556 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1557 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1558 if (NewIsModuleInterface || OldIsModuleInterface) { 1559 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1560 // if a declaration of D [...] appears in the purview of a module, all 1561 // other such declarations shall appear in the purview of the same module 1562 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1563 << New 1564 << NewIsModuleInterface 1565 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1566 << OldIsModuleInterface 1567 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1568 Diag(Old->getLocation(), diag::note_previous_declaration); 1569 New->setInvalidDecl(); 1570 return true; 1571 } 1572 1573 return false; 1574 } 1575 1576 static bool isUsingDecl(NamedDecl *D) { 1577 return isa<UsingShadowDecl>(D) || 1578 isa<UnresolvedUsingTypenameDecl>(D) || 1579 isa<UnresolvedUsingValueDecl>(D); 1580 } 1581 1582 /// Removes using shadow declarations from the lookup results. 1583 static void RemoveUsingDecls(LookupResult &R) { 1584 LookupResult::Filter F = R.makeFilter(); 1585 while (F.hasNext()) 1586 if (isUsingDecl(F.next())) 1587 F.erase(); 1588 1589 F.done(); 1590 } 1591 1592 /// Check for this common pattern: 1593 /// @code 1594 /// class S { 1595 /// S(const S&); // DO NOT IMPLEMENT 1596 /// void operator=(const S&); // DO NOT IMPLEMENT 1597 /// }; 1598 /// @endcode 1599 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1600 // FIXME: Should check for private access too but access is set after we get 1601 // the decl here. 1602 if (D->doesThisDeclarationHaveABody()) 1603 return false; 1604 1605 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1606 return CD->isCopyConstructor(); 1607 return D->isCopyAssignmentOperator(); 1608 } 1609 1610 // We need this to handle 1611 // 1612 // typedef struct { 1613 // void *foo() { return 0; } 1614 // } A; 1615 // 1616 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1617 // for example. If 'A', foo will have external linkage. If we have '*A', 1618 // foo will have no linkage. Since we can't know until we get to the end 1619 // of the typedef, this function finds out if D might have non-external linkage. 1620 // Callers should verify at the end of the TU if it D has external linkage or 1621 // not. 1622 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1623 const DeclContext *DC = D->getDeclContext(); 1624 while (!DC->isTranslationUnit()) { 1625 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1626 if (!RD->hasNameForLinkage()) 1627 return true; 1628 } 1629 DC = DC->getParent(); 1630 } 1631 1632 return !D->isExternallyVisible(); 1633 } 1634 1635 // FIXME: This needs to be refactored; some other isInMainFile users want 1636 // these semantics. 1637 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1638 if (S.TUKind != TU_Complete) 1639 return false; 1640 return S.SourceMgr.isInMainFile(Loc); 1641 } 1642 1643 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1644 assert(D); 1645 1646 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1647 return false; 1648 1649 // Ignore all entities declared within templates, and out-of-line definitions 1650 // of members of class templates. 1651 if (D->getDeclContext()->isDependentContext() || 1652 D->getLexicalDeclContext()->isDependentContext()) 1653 return false; 1654 1655 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1656 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1657 return false; 1658 // A non-out-of-line declaration of a member specialization was implicitly 1659 // instantiated; it's the out-of-line declaration that we're interested in. 1660 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1661 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1662 return false; 1663 1664 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1665 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1666 return false; 1667 } else { 1668 // 'static inline' functions are defined in headers; don't warn. 1669 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1670 return false; 1671 } 1672 1673 if (FD->doesThisDeclarationHaveABody() && 1674 Context.DeclMustBeEmitted(FD)) 1675 return false; 1676 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1677 // Constants and utility variables are defined in headers with internal 1678 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1679 // like "inline".) 1680 if (!isMainFileLoc(*this, VD->getLocation())) 1681 return false; 1682 1683 if (Context.DeclMustBeEmitted(VD)) 1684 return false; 1685 1686 if (VD->isStaticDataMember() && 1687 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1688 return false; 1689 if (VD->isStaticDataMember() && 1690 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1691 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1692 return false; 1693 1694 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1695 return false; 1696 } else { 1697 return false; 1698 } 1699 1700 // Only warn for unused decls internal to the translation unit. 1701 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1702 // for inline functions defined in the main source file, for instance. 1703 return mightHaveNonExternalLinkage(D); 1704 } 1705 1706 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1707 if (!D) 1708 return; 1709 1710 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1711 const FunctionDecl *First = FD->getFirstDecl(); 1712 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1713 return; // First should already be in the vector. 1714 } 1715 1716 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1717 const VarDecl *First = VD->getFirstDecl(); 1718 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1719 return; // First should already be in the vector. 1720 } 1721 1722 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1723 UnusedFileScopedDecls.push_back(D); 1724 } 1725 1726 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1727 if (D->isInvalidDecl()) 1728 return false; 1729 1730 bool Referenced = false; 1731 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1732 // For a decomposition declaration, warn if none of the bindings are 1733 // referenced, instead of if the variable itself is referenced (which 1734 // it is, by the bindings' expressions). 1735 for (auto *BD : DD->bindings()) { 1736 if (BD->isReferenced()) { 1737 Referenced = true; 1738 break; 1739 } 1740 } 1741 } else if (!D->getDeclName()) { 1742 return false; 1743 } else if (D->isReferenced() || D->isUsed()) { 1744 Referenced = true; 1745 } 1746 1747 if (Referenced || D->hasAttr<UnusedAttr>() || 1748 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1749 return false; 1750 1751 if (isa<LabelDecl>(D)) 1752 return true; 1753 1754 // Except for labels, we only care about unused decls that are local to 1755 // functions. 1756 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1757 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1758 // For dependent types, the diagnostic is deferred. 1759 WithinFunction = 1760 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1761 if (!WithinFunction) 1762 return false; 1763 1764 if (isa<TypedefNameDecl>(D)) 1765 return true; 1766 1767 // White-list anything that isn't a local variable. 1768 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1769 return false; 1770 1771 // Types of valid local variables should be complete, so this should succeed. 1772 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1773 1774 // White-list anything with an __attribute__((unused)) type. 1775 const auto *Ty = VD->getType().getTypePtr(); 1776 1777 // Only look at the outermost level of typedef. 1778 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1779 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1780 return false; 1781 } 1782 1783 // If we failed to complete the type for some reason, or if the type is 1784 // dependent, don't diagnose the variable. 1785 if (Ty->isIncompleteType() || Ty->isDependentType()) 1786 return false; 1787 1788 // Look at the element type to ensure that the warning behaviour is 1789 // consistent for both scalars and arrays. 1790 Ty = Ty->getBaseElementTypeUnsafe(); 1791 1792 if (const TagType *TT = Ty->getAs<TagType>()) { 1793 const TagDecl *Tag = TT->getDecl(); 1794 if (Tag->hasAttr<UnusedAttr>()) 1795 return false; 1796 1797 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1798 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1799 return false; 1800 1801 if (const Expr *Init = VD->getInit()) { 1802 if (const ExprWithCleanups *Cleanups = 1803 dyn_cast<ExprWithCleanups>(Init)) 1804 Init = Cleanups->getSubExpr(); 1805 const CXXConstructExpr *Construct = 1806 dyn_cast<CXXConstructExpr>(Init); 1807 if (Construct && !Construct->isElidable()) { 1808 CXXConstructorDecl *CD = Construct->getConstructor(); 1809 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1810 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1811 return false; 1812 } 1813 1814 // Suppress the warning if we don't know how this is constructed, and 1815 // it could possibly be non-trivial constructor. 1816 if (Init->isTypeDependent()) 1817 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1818 if (!Ctor->isTrivial()) 1819 return false; 1820 } 1821 } 1822 } 1823 1824 // TODO: __attribute__((unused)) templates? 1825 } 1826 1827 return true; 1828 } 1829 1830 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1831 FixItHint &Hint) { 1832 if (isa<LabelDecl>(D)) { 1833 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1834 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1835 true); 1836 if (AfterColon.isInvalid()) 1837 return; 1838 Hint = FixItHint::CreateRemoval( 1839 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1840 } 1841 } 1842 1843 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1844 if (D->getTypeForDecl()->isDependentType()) 1845 return; 1846 1847 for (auto *TmpD : D->decls()) { 1848 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1849 DiagnoseUnusedDecl(T); 1850 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1851 DiagnoseUnusedNestedTypedefs(R); 1852 } 1853 } 1854 1855 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1856 /// unless they are marked attr(unused). 1857 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1858 if (!ShouldDiagnoseUnusedDecl(D)) 1859 return; 1860 1861 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1862 // typedefs can be referenced later on, so the diagnostics are emitted 1863 // at end-of-translation-unit. 1864 UnusedLocalTypedefNameCandidates.insert(TD); 1865 return; 1866 } 1867 1868 FixItHint Hint; 1869 GenerateFixForUnusedDecl(D, Context, Hint); 1870 1871 unsigned DiagID; 1872 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1873 DiagID = diag::warn_unused_exception_param; 1874 else if (isa<LabelDecl>(D)) 1875 DiagID = diag::warn_unused_label; 1876 else 1877 DiagID = diag::warn_unused_variable; 1878 1879 Diag(D->getLocation(), DiagID) << D << Hint; 1880 } 1881 1882 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1883 // Verify that we have no forward references left. If so, there was a goto 1884 // or address of a label taken, but no definition of it. Label fwd 1885 // definitions are indicated with a null substmt which is also not a resolved 1886 // MS inline assembly label name. 1887 bool Diagnose = false; 1888 if (L->isMSAsmLabel()) 1889 Diagnose = !L->isResolvedMSAsmLabel(); 1890 else 1891 Diagnose = L->getStmt() == nullptr; 1892 if (Diagnose) 1893 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1894 } 1895 1896 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1897 S->mergeNRVOIntoParent(); 1898 1899 if (S->decl_empty()) return; 1900 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1901 "Scope shouldn't contain decls!"); 1902 1903 for (auto *TmpD : S->decls()) { 1904 assert(TmpD && "This decl didn't get pushed??"); 1905 1906 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1907 NamedDecl *D = cast<NamedDecl>(TmpD); 1908 1909 // Diagnose unused variables in this scope. 1910 if (!S->hasUnrecoverableErrorOccurred()) { 1911 DiagnoseUnusedDecl(D); 1912 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1913 DiagnoseUnusedNestedTypedefs(RD); 1914 } 1915 1916 if (!D->getDeclName()) continue; 1917 1918 // If this was a forward reference to a label, verify it was defined. 1919 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1920 CheckPoppedLabel(LD, *this); 1921 1922 // Remove this name from our lexical scope, and warn on it if we haven't 1923 // already. 1924 IdResolver.RemoveDecl(D); 1925 auto ShadowI = ShadowingDecls.find(D); 1926 if (ShadowI != ShadowingDecls.end()) { 1927 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1928 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1929 << D << FD << FD->getParent(); 1930 Diag(FD->getLocation(), diag::note_previous_declaration); 1931 } 1932 ShadowingDecls.erase(ShadowI); 1933 } 1934 } 1935 } 1936 1937 /// Look for an Objective-C class in the translation unit. 1938 /// 1939 /// \param Id The name of the Objective-C class we're looking for. If 1940 /// typo-correction fixes this name, the Id will be updated 1941 /// to the fixed name. 1942 /// 1943 /// \param IdLoc The location of the name in the translation unit. 1944 /// 1945 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1946 /// if there is no class with the given name. 1947 /// 1948 /// \returns The declaration of the named Objective-C class, or NULL if the 1949 /// class could not be found. 1950 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1951 SourceLocation IdLoc, 1952 bool DoTypoCorrection) { 1953 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1954 // creation from this context. 1955 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1956 1957 if (!IDecl && DoTypoCorrection) { 1958 // Perform typo correction at the given location, but only if we 1959 // find an Objective-C class name. 1960 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1961 if (TypoCorrection C = 1962 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1963 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1964 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1965 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1966 Id = IDecl->getIdentifier(); 1967 } 1968 } 1969 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1970 // This routine must always return a class definition, if any. 1971 if (Def && Def->getDefinition()) 1972 Def = Def->getDefinition(); 1973 return Def; 1974 } 1975 1976 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1977 /// from S, where a non-field would be declared. This routine copes 1978 /// with the difference between C and C++ scoping rules in structs and 1979 /// unions. For example, the following code is well-formed in C but 1980 /// ill-formed in C++: 1981 /// @code 1982 /// struct S6 { 1983 /// enum { BAR } e; 1984 /// }; 1985 /// 1986 /// void test_S6() { 1987 /// struct S6 a; 1988 /// a.e = BAR; 1989 /// } 1990 /// @endcode 1991 /// For the declaration of BAR, this routine will return a different 1992 /// scope. The scope S will be the scope of the unnamed enumeration 1993 /// within S6. In C++, this routine will return the scope associated 1994 /// with S6, because the enumeration's scope is a transparent 1995 /// context but structures can contain non-field names. In C, this 1996 /// routine will return the translation unit scope, since the 1997 /// enumeration's scope is a transparent context and structures cannot 1998 /// contain non-field names. 1999 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2000 while (((S->getFlags() & Scope::DeclScope) == 0) || 2001 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2002 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2003 S = S->getParent(); 2004 return S; 2005 } 2006 2007 /// Looks up the declaration of "struct objc_super" and 2008 /// saves it for later use in building builtin declaration of 2009 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 2010 /// pre-existing declaration exists no action takes place. 2011 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 2012 IdentifierInfo *II) { 2013 if (!II->isStr("objc_msgSendSuper")) 2014 return; 2015 ASTContext &Context = ThisSema.Context; 2016 2017 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 2018 SourceLocation(), Sema::LookupTagName); 2019 ThisSema.LookupName(Result, S); 2020 if (Result.getResultKind() == LookupResult::Found) 2021 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 2022 Context.setObjCSuperType(Context.getTagDeclType(TD)); 2023 } 2024 2025 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2026 ASTContext::GetBuiltinTypeError Error) { 2027 switch (Error) { 2028 case ASTContext::GE_None: 2029 return ""; 2030 case ASTContext::GE_Missing_type: 2031 return BuiltinInfo.getHeaderName(ID); 2032 case ASTContext::GE_Missing_stdio: 2033 return "stdio.h"; 2034 case ASTContext::GE_Missing_setjmp: 2035 return "setjmp.h"; 2036 case ASTContext::GE_Missing_ucontext: 2037 return "ucontext.h"; 2038 } 2039 llvm_unreachable("unhandled error kind"); 2040 } 2041 2042 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2043 /// file scope. lazily create a decl for it. ForRedeclaration is true 2044 /// if we're creating this built-in in anticipation of redeclaring the 2045 /// built-in. 2046 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2047 Scope *S, bool ForRedeclaration, 2048 SourceLocation Loc) { 2049 LookupPredefedObjCSuperType(*this, S, II); 2050 2051 ASTContext::GetBuiltinTypeError Error; 2052 QualType R = Context.GetBuiltinType(ID, Error); 2053 if (Error) { 2054 if (!ForRedeclaration) 2055 return nullptr; 2056 2057 // If we have a builtin without an associated type we should not emit a 2058 // warning when we were not able to find a type for it. 2059 if (Error == ASTContext::GE_Missing_type) 2060 return nullptr; 2061 2062 // If we could not find a type for setjmp it is because the jmp_buf type was 2063 // not defined prior to the setjmp declaration. 2064 if (Error == ASTContext::GE_Missing_setjmp) { 2065 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2066 << Context.BuiltinInfo.getName(ID); 2067 return nullptr; 2068 } 2069 2070 // Generally, we emit a warning that the declaration requires the 2071 // appropriate header. 2072 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2073 << getHeaderName(Context.BuiltinInfo, ID, Error) 2074 << Context.BuiltinInfo.getName(ID); 2075 return nullptr; 2076 } 2077 2078 if (!ForRedeclaration && 2079 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2080 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2081 Diag(Loc, diag::ext_implicit_lib_function_decl) 2082 << Context.BuiltinInfo.getName(ID) << R; 2083 if (Context.BuiltinInfo.getHeaderName(ID) && 2084 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 2085 Diag(Loc, diag::note_include_header_or_declare) 2086 << Context.BuiltinInfo.getHeaderName(ID) 2087 << Context.BuiltinInfo.getName(ID); 2088 } 2089 2090 if (R.isNull()) 2091 return nullptr; 2092 2093 DeclContext *Parent = Context.getTranslationUnitDecl(); 2094 if (getLangOpts().CPlusPlus) { 2095 LinkageSpecDecl *CLinkageDecl = 2096 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 2097 LinkageSpecDecl::lang_c, false); 2098 CLinkageDecl->setImplicit(); 2099 Parent->addDecl(CLinkageDecl); 2100 Parent = CLinkageDecl; 2101 } 2102 2103 FunctionDecl *New = FunctionDecl::Create(Context, 2104 Parent, 2105 Loc, Loc, II, R, /*TInfo=*/nullptr, 2106 SC_Extern, 2107 false, 2108 R->isFunctionProtoType()); 2109 New->setImplicit(); 2110 2111 // Create Decl objects for each parameter, adding them to the 2112 // FunctionDecl. 2113 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 2114 SmallVector<ParmVarDecl*, 16> Params; 2115 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2116 ParmVarDecl *parm = 2117 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2118 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2119 SC_None, nullptr); 2120 parm->setScopeInfo(0, i); 2121 Params.push_back(parm); 2122 } 2123 New->setParams(Params); 2124 } 2125 2126 AddKnownFunctionAttributes(New); 2127 RegisterLocallyScopedExternCDecl(New, S); 2128 2129 // TUScope is the translation-unit scope to insert this function into. 2130 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2131 // relate Scopes to DeclContexts, and probably eliminate CurContext 2132 // entirely, but we're not there yet. 2133 DeclContext *SavedContext = CurContext; 2134 CurContext = Parent; 2135 PushOnScopeChains(New, TUScope); 2136 CurContext = SavedContext; 2137 return New; 2138 } 2139 2140 /// Typedef declarations don't have linkage, but they still denote the same 2141 /// entity if their types are the same. 2142 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2143 /// isSameEntity. 2144 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2145 TypedefNameDecl *Decl, 2146 LookupResult &Previous) { 2147 // This is only interesting when modules are enabled. 2148 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2149 return; 2150 2151 // Empty sets are uninteresting. 2152 if (Previous.empty()) 2153 return; 2154 2155 LookupResult::Filter Filter = Previous.makeFilter(); 2156 while (Filter.hasNext()) { 2157 NamedDecl *Old = Filter.next(); 2158 2159 // Non-hidden declarations are never ignored. 2160 if (S.isVisible(Old)) 2161 continue; 2162 2163 // Declarations of the same entity are not ignored, even if they have 2164 // different linkages. 2165 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2166 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2167 Decl->getUnderlyingType())) 2168 continue; 2169 2170 // If both declarations give a tag declaration a typedef name for linkage 2171 // purposes, then they declare the same entity. 2172 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2173 Decl->getAnonDeclWithTypedefName()) 2174 continue; 2175 } 2176 2177 Filter.erase(); 2178 } 2179 2180 Filter.done(); 2181 } 2182 2183 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2184 QualType OldType; 2185 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2186 OldType = OldTypedef->getUnderlyingType(); 2187 else 2188 OldType = Context.getTypeDeclType(Old); 2189 QualType NewType = New->getUnderlyingType(); 2190 2191 if (NewType->isVariablyModifiedType()) { 2192 // Must not redefine a typedef with a variably-modified type. 2193 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2194 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2195 << Kind << NewType; 2196 if (Old->getLocation().isValid()) 2197 notePreviousDefinition(Old, New->getLocation()); 2198 New->setInvalidDecl(); 2199 return true; 2200 } 2201 2202 if (OldType != NewType && 2203 !OldType->isDependentType() && 2204 !NewType->isDependentType() && 2205 !Context.hasSameType(OldType, NewType)) { 2206 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2207 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2208 << Kind << NewType << OldType; 2209 if (Old->getLocation().isValid()) 2210 notePreviousDefinition(Old, New->getLocation()); 2211 New->setInvalidDecl(); 2212 return true; 2213 } 2214 return false; 2215 } 2216 2217 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2218 /// same name and scope as a previous declaration 'Old'. Figure out 2219 /// how to resolve this situation, merging decls or emitting 2220 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2221 /// 2222 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2223 LookupResult &OldDecls) { 2224 // If the new decl is known invalid already, don't bother doing any 2225 // merging checks. 2226 if (New->isInvalidDecl()) return; 2227 2228 // Allow multiple definitions for ObjC built-in typedefs. 2229 // FIXME: Verify the underlying types are equivalent! 2230 if (getLangOpts().ObjC) { 2231 const IdentifierInfo *TypeID = New->getIdentifier(); 2232 switch (TypeID->getLength()) { 2233 default: break; 2234 case 2: 2235 { 2236 if (!TypeID->isStr("id")) 2237 break; 2238 QualType T = New->getUnderlyingType(); 2239 if (!T->isPointerType()) 2240 break; 2241 if (!T->isVoidPointerType()) { 2242 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2243 if (!PT->isStructureType()) 2244 break; 2245 } 2246 Context.setObjCIdRedefinitionType(T); 2247 // Install the built-in type for 'id', ignoring the current definition. 2248 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2249 return; 2250 } 2251 case 5: 2252 if (!TypeID->isStr("Class")) 2253 break; 2254 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2255 // Install the built-in type for 'Class', ignoring the current definition. 2256 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2257 return; 2258 case 3: 2259 if (!TypeID->isStr("SEL")) 2260 break; 2261 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2262 // Install the built-in type for 'SEL', ignoring the current definition. 2263 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2264 return; 2265 } 2266 // Fall through - the typedef name was not a builtin type. 2267 } 2268 2269 // Verify the old decl was also a type. 2270 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2271 if (!Old) { 2272 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2273 << New->getDeclName(); 2274 2275 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2276 if (OldD->getLocation().isValid()) 2277 notePreviousDefinition(OldD, New->getLocation()); 2278 2279 return New->setInvalidDecl(); 2280 } 2281 2282 // If the old declaration is invalid, just give up here. 2283 if (Old->isInvalidDecl()) 2284 return New->setInvalidDecl(); 2285 2286 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2287 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2288 auto *NewTag = New->getAnonDeclWithTypedefName(); 2289 NamedDecl *Hidden = nullptr; 2290 if (OldTag && NewTag && 2291 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2292 !hasVisibleDefinition(OldTag, &Hidden)) { 2293 // There is a definition of this tag, but it is not visible. Use it 2294 // instead of our tag. 2295 New->setTypeForDecl(OldTD->getTypeForDecl()); 2296 if (OldTD->isModed()) 2297 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2298 OldTD->getUnderlyingType()); 2299 else 2300 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2301 2302 // Make the old tag definition visible. 2303 makeMergedDefinitionVisible(Hidden); 2304 2305 // If this was an unscoped enumeration, yank all of its enumerators 2306 // out of the scope. 2307 if (isa<EnumDecl>(NewTag)) { 2308 Scope *EnumScope = getNonFieldDeclScope(S); 2309 for (auto *D : NewTag->decls()) { 2310 auto *ED = cast<EnumConstantDecl>(D); 2311 assert(EnumScope->isDeclScope(ED)); 2312 EnumScope->RemoveDecl(ED); 2313 IdResolver.RemoveDecl(ED); 2314 ED->getLexicalDeclContext()->removeDecl(ED); 2315 } 2316 } 2317 } 2318 } 2319 2320 // If the typedef types are not identical, reject them in all languages and 2321 // with any extensions enabled. 2322 if (isIncompatibleTypedef(Old, New)) 2323 return; 2324 2325 // The types match. Link up the redeclaration chain and merge attributes if 2326 // the old declaration was a typedef. 2327 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2328 New->setPreviousDecl(Typedef); 2329 mergeDeclAttributes(New, Old); 2330 } 2331 2332 if (getLangOpts().MicrosoftExt) 2333 return; 2334 2335 if (getLangOpts().CPlusPlus) { 2336 // C++ [dcl.typedef]p2: 2337 // In a given non-class scope, a typedef specifier can be used to 2338 // redefine the name of any type declared in that scope to refer 2339 // to the type to which it already refers. 2340 if (!isa<CXXRecordDecl>(CurContext)) 2341 return; 2342 2343 // C++0x [dcl.typedef]p4: 2344 // In a given class scope, a typedef specifier can be used to redefine 2345 // any class-name declared in that scope that is not also a typedef-name 2346 // to refer to the type to which it already refers. 2347 // 2348 // This wording came in via DR424, which was a correction to the 2349 // wording in DR56, which accidentally banned code like: 2350 // 2351 // struct S { 2352 // typedef struct A { } A; 2353 // }; 2354 // 2355 // in the C++03 standard. We implement the C++0x semantics, which 2356 // allow the above but disallow 2357 // 2358 // struct S { 2359 // typedef int I; 2360 // typedef int I; 2361 // }; 2362 // 2363 // since that was the intent of DR56. 2364 if (!isa<TypedefNameDecl>(Old)) 2365 return; 2366 2367 Diag(New->getLocation(), diag::err_redefinition) 2368 << New->getDeclName(); 2369 notePreviousDefinition(Old, New->getLocation()); 2370 return New->setInvalidDecl(); 2371 } 2372 2373 // Modules always permit redefinition of typedefs, as does C11. 2374 if (getLangOpts().Modules || getLangOpts().C11) 2375 return; 2376 2377 // If we have a redefinition of a typedef in C, emit a warning. This warning 2378 // is normally mapped to an error, but can be controlled with 2379 // -Wtypedef-redefinition. If either the original or the redefinition is 2380 // in a system header, don't emit this for compatibility with GCC. 2381 if (getDiagnostics().getSuppressSystemWarnings() && 2382 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2383 (Old->isImplicit() || 2384 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2385 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2386 return; 2387 2388 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2389 << New->getDeclName(); 2390 notePreviousDefinition(Old, New->getLocation()); 2391 } 2392 2393 /// DeclhasAttr - returns true if decl Declaration already has the target 2394 /// attribute. 2395 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2396 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2397 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2398 for (const auto *i : D->attrs()) 2399 if (i->getKind() == A->getKind()) { 2400 if (Ann) { 2401 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2402 return true; 2403 continue; 2404 } 2405 // FIXME: Don't hardcode this check 2406 if (OA && isa<OwnershipAttr>(i)) 2407 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2408 return true; 2409 } 2410 2411 return false; 2412 } 2413 2414 static bool isAttributeTargetADefinition(Decl *D) { 2415 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2416 return VD->isThisDeclarationADefinition(); 2417 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2418 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2419 return true; 2420 } 2421 2422 /// Merge alignment attributes from \p Old to \p New, taking into account the 2423 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2424 /// 2425 /// \return \c true if any attributes were added to \p New. 2426 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2427 // Look for alignas attributes on Old, and pick out whichever attribute 2428 // specifies the strictest alignment requirement. 2429 AlignedAttr *OldAlignasAttr = nullptr; 2430 AlignedAttr *OldStrictestAlignAttr = nullptr; 2431 unsigned OldAlign = 0; 2432 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2433 // FIXME: We have no way of representing inherited dependent alignments 2434 // in a case like: 2435 // template<int A, int B> struct alignas(A) X; 2436 // template<int A, int B> struct alignas(B) X {}; 2437 // For now, we just ignore any alignas attributes which are not on the 2438 // definition in such a case. 2439 if (I->isAlignmentDependent()) 2440 return false; 2441 2442 if (I->isAlignas()) 2443 OldAlignasAttr = I; 2444 2445 unsigned Align = I->getAlignment(S.Context); 2446 if (Align > OldAlign) { 2447 OldAlign = Align; 2448 OldStrictestAlignAttr = I; 2449 } 2450 } 2451 2452 // Look for alignas attributes on New. 2453 AlignedAttr *NewAlignasAttr = nullptr; 2454 unsigned NewAlign = 0; 2455 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2456 if (I->isAlignmentDependent()) 2457 return false; 2458 2459 if (I->isAlignas()) 2460 NewAlignasAttr = I; 2461 2462 unsigned Align = I->getAlignment(S.Context); 2463 if (Align > NewAlign) 2464 NewAlign = Align; 2465 } 2466 2467 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2468 // Both declarations have 'alignas' attributes. We require them to match. 2469 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2470 // fall short. (If two declarations both have alignas, they must both match 2471 // every definition, and so must match each other if there is a definition.) 2472 2473 // If either declaration only contains 'alignas(0)' specifiers, then it 2474 // specifies the natural alignment for the type. 2475 if (OldAlign == 0 || NewAlign == 0) { 2476 QualType Ty; 2477 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2478 Ty = VD->getType(); 2479 else 2480 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2481 2482 if (OldAlign == 0) 2483 OldAlign = S.Context.getTypeAlign(Ty); 2484 if (NewAlign == 0) 2485 NewAlign = S.Context.getTypeAlign(Ty); 2486 } 2487 2488 if (OldAlign != NewAlign) { 2489 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2490 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2491 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2492 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2493 } 2494 } 2495 2496 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2497 // C++11 [dcl.align]p6: 2498 // if any declaration of an entity has an alignment-specifier, 2499 // every defining declaration of that entity shall specify an 2500 // equivalent alignment. 2501 // C11 6.7.5/7: 2502 // If the definition of an object does not have an alignment 2503 // specifier, any other declaration of that object shall also 2504 // have no alignment specifier. 2505 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2506 << OldAlignasAttr; 2507 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2508 << OldAlignasAttr; 2509 } 2510 2511 bool AnyAdded = false; 2512 2513 // Ensure we have an attribute representing the strictest alignment. 2514 if (OldAlign > NewAlign) { 2515 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2516 Clone->setInherited(true); 2517 New->addAttr(Clone); 2518 AnyAdded = true; 2519 } 2520 2521 // Ensure we have an alignas attribute if the old declaration had one. 2522 if (OldAlignasAttr && !NewAlignasAttr && 2523 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2524 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2525 Clone->setInherited(true); 2526 New->addAttr(Clone); 2527 AnyAdded = true; 2528 } 2529 2530 return AnyAdded; 2531 } 2532 2533 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2534 const InheritableAttr *Attr, 2535 Sema::AvailabilityMergeKind AMK) { 2536 // This function copies an attribute Attr from a previous declaration to the 2537 // new declaration D if the new declaration doesn't itself have that attribute 2538 // yet or if that attribute allows duplicates. 2539 // If you're adding a new attribute that requires logic different from 2540 // "use explicit attribute on decl if present, else use attribute from 2541 // previous decl", for example if the attribute needs to be consistent 2542 // between redeclarations, you need to call a custom merge function here. 2543 InheritableAttr *NewAttr = nullptr; 2544 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2545 NewAttr = S.mergeAvailabilityAttr( 2546 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2547 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2548 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2549 AA->getPriority()); 2550 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2551 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2552 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2553 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2554 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2555 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2556 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2557 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2558 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2559 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2560 FA->getFirstArg()); 2561 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2562 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2563 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2564 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2565 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2566 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2567 IA->getInheritanceModel()); 2568 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2569 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2570 &S.Context.Idents.get(AA->getSpelling())); 2571 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2572 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2573 isa<CUDAGlobalAttr>(Attr))) { 2574 // CUDA target attributes are part of function signature for 2575 // overloading purposes and must not be merged. 2576 return false; 2577 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2578 NewAttr = S.mergeMinSizeAttr(D, *MA); 2579 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2580 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2581 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2582 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2583 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2584 NewAttr = S.mergeCommonAttr(D, *CommonA); 2585 else if (isa<AlignedAttr>(Attr)) 2586 // AlignedAttrs are handled separately, because we need to handle all 2587 // such attributes on a declaration at the same time. 2588 NewAttr = nullptr; 2589 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2590 (AMK == Sema::AMK_Override || 2591 AMK == Sema::AMK_ProtocolImplementation)) 2592 NewAttr = nullptr; 2593 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2594 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid()); 2595 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2596 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2597 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2598 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2599 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2600 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2601 2602 if (NewAttr) { 2603 NewAttr->setInherited(true); 2604 D->addAttr(NewAttr); 2605 if (isa<MSInheritanceAttr>(NewAttr)) 2606 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2607 return true; 2608 } 2609 2610 return false; 2611 } 2612 2613 static const NamedDecl *getDefinition(const Decl *D) { 2614 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2615 return TD->getDefinition(); 2616 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2617 const VarDecl *Def = VD->getDefinition(); 2618 if (Def) 2619 return Def; 2620 return VD->getActingDefinition(); 2621 } 2622 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2623 return FD->getDefinition(); 2624 return nullptr; 2625 } 2626 2627 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2628 for (const auto *Attribute : D->attrs()) 2629 if (Attribute->getKind() == Kind) 2630 return true; 2631 return false; 2632 } 2633 2634 /// checkNewAttributesAfterDef - If we already have a definition, check that 2635 /// there are no new attributes in this declaration. 2636 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2637 if (!New->hasAttrs()) 2638 return; 2639 2640 const NamedDecl *Def = getDefinition(Old); 2641 if (!Def || Def == New) 2642 return; 2643 2644 AttrVec &NewAttributes = New->getAttrs(); 2645 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2646 const Attr *NewAttribute = NewAttributes[I]; 2647 2648 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2649 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2650 Sema::SkipBodyInfo SkipBody; 2651 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2652 2653 // If we're skipping this definition, drop the "alias" attribute. 2654 if (SkipBody.ShouldSkip) { 2655 NewAttributes.erase(NewAttributes.begin() + I); 2656 --E; 2657 continue; 2658 } 2659 } else { 2660 VarDecl *VD = cast<VarDecl>(New); 2661 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2662 VarDecl::TentativeDefinition 2663 ? diag::err_alias_after_tentative 2664 : diag::err_redefinition; 2665 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2666 if (Diag == diag::err_redefinition) 2667 S.notePreviousDefinition(Def, VD->getLocation()); 2668 else 2669 S.Diag(Def->getLocation(), diag::note_previous_definition); 2670 VD->setInvalidDecl(); 2671 } 2672 ++I; 2673 continue; 2674 } 2675 2676 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2677 // Tentative definitions are only interesting for the alias check above. 2678 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2679 ++I; 2680 continue; 2681 } 2682 } 2683 2684 if (hasAttribute(Def, NewAttribute->getKind())) { 2685 ++I; 2686 continue; // regular attr merging will take care of validating this. 2687 } 2688 2689 if (isa<C11NoReturnAttr>(NewAttribute)) { 2690 // C's _Noreturn is allowed to be added to a function after it is defined. 2691 ++I; 2692 continue; 2693 } else if (isa<UuidAttr>(NewAttribute)) { 2694 // msvc will allow a subsequent definition to add an uuid to a class 2695 ++I; 2696 continue; 2697 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2698 if (AA->isAlignas()) { 2699 // C++11 [dcl.align]p6: 2700 // if any declaration of an entity has an alignment-specifier, 2701 // every defining declaration of that entity shall specify an 2702 // equivalent alignment. 2703 // C11 6.7.5/7: 2704 // If the definition of an object does not have an alignment 2705 // specifier, any other declaration of that object shall also 2706 // have no alignment specifier. 2707 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2708 << AA; 2709 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2710 << AA; 2711 NewAttributes.erase(NewAttributes.begin() + I); 2712 --E; 2713 continue; 2714 } 2715 } else if (isa<SelectAnyAttr>(NewAttribute) && 2716 cast<VarDecl>(New)->isInline() && 2717 !cast<VarDecl>(New)->isInlineSpecified()) { 2718 // Don't warn about applying selectany to implicitly inline variables. 2719 // Older compilers and language modes would require the use of selectany 2720 // to make such variables inline, and it would have no effect if we 2721 // honored it. 2722 ++I; 2723 continue; 2724 } 2725 2726 S.Diag(NewAttribute->getLocation(), 2727 diag::warn_attribute_precede_definition); 2728 S.Diag(Def->getLocation(), diag::note_previous_definition); 2729 NewAttributes.erase(NewAttributes.begin() + I); 2730 --E; 2731 } 2732 } 2733 2734 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2735 const ConstInitAttr *CIAttr, 2736 bool AttrBeforeInit) { 2737 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2738 2739 // Figure out a good way to write this specifier on the old declaration. 2740 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2741 // enough of the attribute list spelling information to extract that without 2742 // heroics. 2743 std::string SuitableSpelling; 2744 if (S.getLangOpts().CPlusPlus2a) 2745 SuitableSpelling = std::string( 2746 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2747 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2748 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2749 InsertLoc, {tok::l_square, tok::l_square, 2750 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2751 S.PP.getIdentifierInfo("require_constant_initialization"), 2752 tok::r_square, tok::r_square})); 2753 if (SuitableSpelling.empty()) 2754 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2755 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2756 S.PP.getIdentifierInfo("require_constant_initialization"), 2757 tok::r_paren, tok::r_paren})); 2758 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a) 2759 SuitableSpelling = "constinit"; 2760 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2761 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2762 if (SuitableSpelling.empty()) 2763 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2764 SuitableSpelling += " "; 2765 2766 if (AttrBeforeInit) { 2767 // extern constinit int a; 2768 // int a = 0; // error (missing 'constinit'), accepted as extension 2769 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2770 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2771 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2772 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2773 } else { 2774 // int a = 0; 2775 // constinit extern int a; // error (missing 'constinit') 2776 S.Diag(CIAttr->getLocation(), 2777 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2778 : diag::warn_require_const_init_added_too_late) 2779 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2780 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2781 << CIAttr->isConstinit() 2782 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2783 } 2784 } 2785 2786 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2787 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2788 AvailabilityMergeKind AMK) { 2789 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2790 UsedAttr *NewAttr = OldAttr->clone(Context); 2791 NewAttr->setInherited(true); 2792 New->addAttr(NewAttr); 2793 } 2794 2795 if (!Old->hasAttrs() && !New->hasAttrs()) 2796 return; 2797 2798 // [dcl.constinit]p1: 2799 // If the [constinit] specifier is applied to any declaration of a 2800 // variable, it shall be applied to the initializing declaration. 2801 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2802 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2803 if (bool(OldConstInit) != bool(NewConstInit)) { 2804 const auto *OldVD = cast<VarDecl>(Old); 2805 auto *NewVD = cast<VarDecl>(New); 2806 2807 // Find the initializing declaration. Note that we might not have linked 2808 // the new declaration into the redeclaration chain yet. 2809 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2810 if (!InitDecl && 2811 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2812 InitDecl = NewVD; 2813 2814 if (InitDecl == NewVD) { 2815 // This is the initializing declaration. If it would inherit 'constinit', 2816 // that's ill-formed. (Note that we do not apply this to the attribute 2817 // form). 2818 if (OldConstInit && OldConstInit->isConstinit()) 2819 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2820 /*AttrBeforeInit=*/true); 2821 } else if (NewConstInit) { 2822 // This is the first time we've been told that this declaration should 2823 // have a constant initializer. If we already saw the initializing 2824 // declaration, this is too late. 2825 if (InitDecl && InitDecl != NewVD) { 2826 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2827 /*AttrBeforeInit=*/false); 2828 NewVD->dropAttr<ConstInitAttr>(); 2829 } 2830 } 2831 } 2832 2833 // Attributes declared post-definition are currently ignored. 2834 checkNewAttributesAfterDef(*this, New, Old); 2835 2836 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2837 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2838 if (!OldA->isEquivalent(NewA)) { 2839 // This redeclaration changes __asm__ label. 2840 Diag(New->getLocation(), diag::err_different_asm_label); 2841 Diag(OldA->getLocation(), diag::note_previous_declaration); 2842 } 2843 } else if (Old->isUsed()) { 2844 // This redeclaration adds an __asm__ label to a declaration that has 2845 // already been ODR-used. 2846 Diag(New->getLocation(), diag::err_late_asm_label_name) 2847 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2848 } 2849 } 2850 2851 // Re-declaration cannot add abi_tag's. 2852 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2853 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2854 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2855 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2856 NewTag) == OldAbiTagAttr->tags_end()) { 2857 Diag(NewAbiTagAttr->getLocation(), 2858 diag::err_new_abi_tag_on_redeclaration) 2859 << NewTag; 2860 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2861 } 2862 } 2863 } else { 2864 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2865 Diag(Old->getLocation(), diag::note_previous_declaration); 2866 } 2867 } 2868 2869 // This redeclaration adds a section attribute. 2870 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2871 if (auto *VD = dyn_cast<VarDecl>(New)) { 2872 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2873 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2874 Diag(Old->getLocation(), diag::note_previous_declaration); 2875 } 2876 } 2877 } 2878 2879 // Redeclaration adds code-seg attribute. 2880 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2881 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2882 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2883 Diag(New->getLocation(), diag::warn_mismatched_section) 2884 << 0 /*codeseg*/; 2885 Diag(Old->getLocation(), diag::note_previous_declaration); 2886 } 2887 2888 if (!Old->hasAttrs()) 2889 return; 2890 2891 bool foundAny = New->hasAttrs(); 2892 2893 // Ensure that any moving of objects within the allocated map is done before 2894 // we process them. 2895 if (!foundAny) New->setAttrs(AttrVec()); 2896 2897 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2898 // Ignore deprecated/unavailable/availability attributes if requested. 2899 AvailabilityMergeKind LocalAMK = AMK_None; 2900 if (isa<DeprecatedAttr>(I) || 2901 isa<UnavailableAttr>(I) || 2902 isa<AvailabilityAttr>(I)) { 2903 switch (AMK) { 2904 case AMK_None: 2905 continue; 2906 2907 case AMK_Redeclaration: 2908 case AMK_Override: 2909 case AMK_ProtocolImplementation: 2910 LocalAMK = AMK; 2911 break; 2912 } 2913 } 2914 2915 // Already handled. 2916 if (isa<UsedAttr>(I)) 2917 continue; 2918 2919 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2920 foundAny = true; 2921 } 2922 2923 if (mergeAlignedAttrs(*this, New, Old)) 2924 foundAny = true; 2925 2926 if (!foundAny) New->dropAttrs(); 2927 } 2928 2929 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2930 /// to the new one. 2931 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2932 const ParmVarDecl *oldDecl, 2933 Sema &S) { 2934 // C++11 [dcl.attr.depend]p2: 2935 // The first declaration of a function shall specify the 2936 // carries_dependency attribute for its declarator-id if any declaration 2937 // of the function specifies the carries_dependency attribute. 2938 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2939 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2940 S.Diag(CDA->getLocation(), 2941 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2942 // Find the first declaration of the parameter. 2943 // FIXME: Should we build redeclaration chains for function parameters? 2944 const FunctionDecl *FirstFD = 2945 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2946 const ParmVarDecl *FirstVD = 2947 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2948 S.Diag(FirstVD->getLocation(), 2949 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2950 } 2951 2952 if (!oldDecl->hasAttrs()) 2953 return; 2954 2955 bool foundAny = newDecl->hasAttrs(); 2956 2957 // Ensure that any moving of objects within the allocated map is 2958 // done before we process them. 2959 if (!foundAny) newDecl->setAttrs(AttrVec()); 2960 2961 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2962 if (!DeclHasAttr(newDecl, I)) { 2963 InheritableAttr *newAttr = 2964 cast<InheritableParamAttr>(I->clone(S.Context)); 2965 newAttr->setInherited(true); 2966 newDecl->addAttr(newAttr); 2967 foundAny = true; 2968 } 2969 } 2970 2971 if (!foundAny) newDecl->dropAttrs(); 2972 } 2973 2974 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2975 const ParmVarDecl *OldParam, 2976 Sema &S) { 2977 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2978 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2979 if (*Oldnullability != *Newnullability) { 2980 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2981 << DiagNullabilityKind( 2982 *Newnullability, 2983 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2984 != 0)) 2985 << DiagNullabilityKind( 2986 *Oldnullability, 2987 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2988 != 0)); 2989 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2990 } 2991 } else { 2992 QualType NewT = NewParam->getType(); 2993 NewT = S.Context.getAttributedType( 2994 AttributedType::getNullabilityAttrKind(*Oldnullability), 2995 NewT, NewT); 2996 NewParam->setType(NewT); 2997 } 2998 } 2999 } 3000 3001 namespace { 3002 3003 /// Used in MergeFunctionDecl to keep track of function parameters in 3004 /// C. 3005 struct GNUCompatibleParamWarning { 3006 ParmVarDecl *OldParm; 3007 ParmVarDecl *NewParm; 3008 QualType PromotedType; 3009 }; 3010 3011 } // end anonymous namespace 3012 3013 // Determine whether the previous declaration was a definition, implicit 3014 // declaration, or a declaration. 3015 template <typename T> 3016 static std::pair<diag::kind, SourceLocation> 3017 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3018 diag::kind PrevDiag; 3019 SourceLocation OldLocation = Old->getLocation(); 3020 if (Old->isThisDeclarationADefinition()) 3021 PrevDiag = diag::note_previous_definition; 3022 else if (Old->isImplicit()) { 3023 PrevDiag = diag::note_previous_implicit_declaration; 3024 if (OldLocation.isInvalid()) 3025 OldLocation = New->getLocation(); 3026 } else 3027 PrevDiag = diag::note_previous_declaration; 3028 return std::make_pair(PrevDiag, OldLocation); 3029 } 3030 3031 /// canRedefineFunction - checks if a function can be redefined. Currently, 3032 /// only extern inline functions can be redefined, and even then only in 3033 /// GNU89 mode. 3034 static bool canRedefineFunction(const FunctionDecl *FD, 3035 const LangOptions& LangOpts) { 3036 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3037 !LangOpts.CPlusPlus && 3038 FD->isInlineSpecified() && 3039 FD->getStorageClass() == SC_Extern); 3040 } 3041 3042 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3043 const AttributedType *AT = T->getAs<AttributedType>(); 3044 while (AT && !AT->isCallingConv()) 3045 AT = AT->getModifiedType()->getAs<AttributedType>(); 3046 return AT; 3047 } 3048 3049 template <typename T> 3050 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3051 const DeclContext *DC = Old->getDeclContext(); 3052 if (DC->isRecord()) 3053 return false; 3054 3055 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3056 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3057 return true; 3058 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3059 return true; 3060 return false; 3061 } 3062 3063 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3064 static bool isExternC(VarTemplateDecl *) { return false; } 3065 3066 /// Check whether a redeclaration of an entity introduced by a 3067 /// using-declaration is valid, given that we know it's not an overload 3068 /// (nor a hidden tag declaration). 3069 template<typename ExpectedDecl> 3070 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3071 ExpectedDecl *New) { 3072 // C++11 [basic.scope.declarative]p4: 3073 // Given a set of declarations in a single declarative region, each of 3074 // which specifies the same unqualified name, 3075 // -- they shall all refer to the same entity, or all refer to functions 3076 // and function templates; or 3077 // -- exactly one declaration shall declare a class name or enumeration 3078 // name that is not a typedef name and the other declarations shall all 3079 // refer to the same variable or enumerator, or all refer to functions 3080 // and function templates; in this case the class name or enumeration 3081 // name is hidden (3.3.10). 3082 3083 // C++11 [namespace.udecl]p14: 3084 // If a function declaration in namespace scope or block scope has the 3085 // same name and the same parameter-type-list as a function introduced 3086 // by a using-declaration, and the declarations do not declare the same 3087 // function, the program is ill-formed. 3088 3089 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3090 if (Old && 3091 !Old->getDeclContext()->getRedeclContext()->Equals( 3092 New->getDeclContext()->getRedeclContext()) && 3093 !(isExternC(Old) && isExternC(New))) 3094 Old = nullptr; 3095 3096 if (!Old) { 3097 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3098 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3099 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3100 return true; 3101 } 3102 return false; 3103 } 3104 3105 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3106 const FunctionDecl *B) { 3107 assert(A->getNumParams() == B->getNumParams()); 3108 3109 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3110 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3111 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3112 if (AttrA == AttrB) 3113 return true; 3114 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3115 AttrA->isDynamic() == AttrB->isDynamic(); 3116 }; 3117 3118 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3119 } 3120 3121 /// If necessary, adjust the semantic declaration context for a qualified 3122 /// declaration to name the correct inline namespace within the qualifier. 3123 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3124 DeclaratorDecl *OldD) { 3125 // The only case where we need to update the DeclContext is when 3126 // redeclaration lookup for a qualified name finds a declaration 3127 // in an inline namespace within the context named by the qualifier: 3128 // 3129 // inline namespace N { int f(); } 3130 // int ::f(); // Sema DC needs adjusting from :: to N::. 3131 // 3132 // For unqualified declarations, the semantic context *can* change 3133 // along the redeclaration chain (for local extern declarations, 3134 // extern "C" declarations, and friend declarations in particular). 3135 if (!NewD->getQualifier()) 3136 return; 3137 3138 // NewD is probably already in the right context. 3139 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3140 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3141 if (NamedDC->Equals(SemaDC)) 3142 return; 3143 3144 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3145 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3146 "unexpected context for redeclaration"); 3147 3148 auto *LexDC = NewD->getLexicalDeclContext(); 3149 auto FixSemaDC = [=](NamedDecl *D) { 3150 if (!D) 3151 return; 3152 D->setDeclContext(SemaDC); 3153 D->setLexicalDeclContext(LexDC); 3154 }; 3155 3156 FixSemaDC(NewD); 3157 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3158 FixSemaDC(FD->getDescribedFunctionTemplate()); 3159 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3160 FixSemaDC(VD->getDescribedVarTemplate()); 3161 } 3162 3163 /// MergeFunctionDecl - We just parsed a function 'New' from 3164 /// declarator D which has the same name and scope as a previous 3165 /// declaration 'Old'. Figure out how to resolve this situation, 3166 /// merging decls or emitting diagnostics as appropriate. 3167 /// 3168 /// In C++, New and Old must be declarations that are not 3169 /// overloaded. Use IsOverload to determine whether New and Old are 3170 /// overloaded, and to select the Old declaration that New should be 3171 /// merged with. 3172 /// 3173 /// Returns true if there was an error, false otherwise. 3174 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3175 Scope *S, bool MergeTypeWithOld) { 3176 // Verify the old decl was also a function. 3177 FunctionDecl *Old = OldD->getAsFunction(); 3178 if (!Old) { 3179 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3180 if (New->getFriendObjectKind()) { 3181 Diag(New->getLocation(), diag::err_using_decl_friend); 3182 Diag(Shadow->getTargetDecl()->getLocation(), 3183 diag::note_using_decl_target); 3184 Diag(Shadow->getUsingDecl()->getLocation(), 3185 diag::note_using_decl) << 0; 3186 return true; 3187 } 3188 3189 // Check whether the two declarations might declare the same function. 3190 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3191 return true; 3192 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3193 } else { 3194 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3195 << New->getDeclName(); 3196 notePreviousDefinition(OldD, New->getLocation()); 3197 return true; 3198 } 3199 } 3200 3201 // If the old declaration is invalid, just give up here. 3202 if (Old->isInvalidDecl()) 3203 return true; 3204 3205 // Disallow redeclaration of some builtins. 3206 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3207 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3208 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3209 << Old << Old->getType(); 3210 return true; 3211 } 3212 3213 diag::kind PrevDiag; 3214 SourceLocation OldLocation; 3215 std::tie(PrevDiag, OldLocation) = 3216 getNoteDiagForInvalidRedeclaration(Old, New); 3217 3218 // Don't complain about this if we're in GNU89 mode and the old function 3219 // is an extern inline function. 3220 // Don't complain about specializations. They are not supposed to have 3221 // storage classes. 3222 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3223 New->getStorageClass() == SC_Static && 3224 Old->hasExternalFormalLinkage() && 3225 !New->getTemplateSpecializationInfo() && 3226 !canRedefineFunction(Old, getLangOpts())) { 3227 if (getLangOpts().MicrosoftExt) { 3228 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3229 Diag(OldLocation, PrevDiag); 3230 } else { 3231 Diag(New->getLocation(), diag::err_static_non_static) << New; 3232 Diag(OldLocation, PrevDiag); 3233 return true; 3234 } 3235 } 3236 3237 if (New->hasAttr<InternalLinkageAttr>() && 3238 !Old->hasAttr<InternalLinkageAttr>()) { 3239 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3240 << New->getDeclName(); 3241 notePreviousDefinition(Old, New->getLocation()); 3242 New->dropAttr<InternalLinkageAttr>(); 3243 } 3244 3245 if (CheckRedeclarationModuleOwnership(New, Old)) 3246 return true; 3247 3248 if (!getLangOpts().CPlusPlus) { 3249 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3250 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3251 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3252 << New << OldOvl; 3253 3254 // Try our best to find a decl that actually has the overloadable 3255 // attribute for the note. In most cases (e.g. programs with only one 3256 // broken declaration/definition), this won't matter. 3257 // 3258 // FIXME: We could do this if we juggled some extra state in 3259 // OverloadableAttr, rather than just removing it. 3260 const Decl *DiagOld = Old; 3261 if (OldOvl) { 3262 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3263 const auto *A = D->getAttr<OverloadableAttr>(); 3264 return A && !A->isImplicit(); 3265 }); 3266 // If we've implicitly added *all* of the overloadable attrs to this 3267 // chain, emitting a "previous redecl" note is pointless. 3268 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3269 } 3270 3271 if (DiagOld) 3272 Diag(DiagOld->getLocation(), 3273 diag::note_attribute_overloadable_prev_overload) 3274 << OldOvl; 3275 3276 if (OldOvl) 3277 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3278 else 3279 New->dropAttr<OverloadableAttr>(); 3280 } 3281 } 3282 3283 // If a function is first declared with a calling convention, but is later 3284 // declared or defined without one, all following decls assume the calling 3285 // convention of the first. 3286 // 3287 // It's OK if a function is first declared without a calling convention, 3288 // but is later declared or defined with the default calling convention. 3289 // 3290 // To test if either decl has an explicit calling convention, we look for 3291 // AttributedType sugar nodes on the type as written. If they are missing or 3292 // were canonicalized away, we assume the calling convention was implicit. 3293 // 3294 // Note also that we DO NOT return at this point, because we still have 3295 // other tests to run. 3296 QualType OldQType = Context.getCanonicalType(Old->getType()); 3297 QualType NewQType = Context.getCanonicalType(New->getType()); 3298 const FunctionType *OldType = cast<FunctionType>(OldQType); 3299 const FunctionType *NewType = cast<FunctionType>(NewQType); 3300 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3301 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3302 bool RequiresAdjustment = false; 3303 3304 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3305 FunctionDecl *First = Old->getFirstDecl(); 3306 const FunctionType *FT = 3307 First->getType().getCanonicalType()->castAs<FunctionType>(); 3308 FunctionType::ExtInfo FI = FT->getExtInfo(); 3309 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3310 if (!NewCCExplicit) { 3311 // Inherit the CC from the previous declaration if it was specified 3312 // there but not here. 3313 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3314 RequiresAdjustment = true; 3315 } else if (New->getBuiltinID()) { 3316 // Calling Conventions on a Builtin aren't really useful and setting a 3317 // default calling convention and cdecl'ing some builtin redeclarations is 3318 // common, so warn and ignore the calling convention on the redeclaration. 3319 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3320 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3321 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3322 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3323 RequiresAdjustment = true; 3324 } else { 3325 // Calling conventions aren't compatible, so complain. 3326 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3327 Diag(New->getLocation(), diag::err_cconv_change) 3328 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3329 << !FirstCCExplicit 3330 << (!FirstCCExplicit ? "" : 3331 FunctionType::getNameForCallConv(FI.getCC())); 3332 3333 // Put the note on the first decl, since it is the one that matters. 3334 Diag(First->getLocation(), diag::note_previous_declaration); 3335 return true; 3336 } 3337 } 3338 3339 // FIXME: diagnose the other way around? 3340 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3341 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3342 RequiresAdjustment = true; 3343 } 3344 3345 // Merge regparm attribute. 3346 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3347 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3348 if (NewTypeInfo.getHasRegParm()) { 3349 Diag(New->getLocation(), diag::err_regparm_mismatch) 3350 << NewType->getRegParmType() 3351 << OldType->getRegParmType(); 3352 Diag(OldLocation, diag::note_previous_declaration); 3353 return true; 3354 } 3355 3356 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3357 RequiresAdjustment = true; 3358 } 3359 3360 // Merge ns_returns_retained attribute. 3361 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3362 if (NewTypeInfo.getProducesResult()) { 3363 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3364 << "'ns_returns_retained'"; 3365 Diag(OldLocation, diag::note_previous_declaration); 3366 return true; 3367 } 3368 3369 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3370 RequiresAdjustment = true; 3371 } 3372 3373 if (OldTypeInfo.getNoCallerSavedRegs() != 3374 NewTypeInfo.getNoCallerSavedRegs()) { 3375 if (NewTypeInfo.getNoCallerSavedRegs()) { 3376 AnyX86NoCallerSavedRegistersAttr *Attr = 3377 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3378 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3379 Diag(OldLocation, diag::note_previous_declaration); 3380 return true; 3381 } 3382 3383 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3384 RequiresAdjustment = true; 3385 } 3386 3387 if (RequiresAdjustment) { 3388 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3389 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3390 New->setType(QualType(AdjustedType, 0)); 3391 NewQType = Context.getCanonicalType(New->getType()); 3392 } 3393 3394 // If this redeclaration makes the function inline, we may need to add it to 3395 // UndefinedButUsed. 3396 if (!Old->isInlined() && New->isInlined() && 3397 !New->hasAttr<GNUInlineAttr>() && 3398 !getLangOpts().GNUInline && 3399 Old->isUsed(false) && 3400 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3401 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3402 SourceLocation())); 3403 3404 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3405 // about it. 3406 if (New->hasAttr<GNUInlineAttr>() && 3407 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3408 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3409 } 3410 3411 // If pass_object_size params don't match up perfectly, this isn't a valid 3412 // redeclaration. 3413 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3414 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3415 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3416 << New->getDeclName(); 3417 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3418 return true; 3419 } 3420 3421 if (getLangOpts().CPlusPlus) { 3422 // C++1z [over.load]p2 3423 // Certain function declarations cannot be overloaded: 3424 // -- Function declarations that differ only in the return type, 3425 // the exception specification, or both cannot be overloaded. 3426 3427 // Check the exception specifications match. This may recompute the type of 3428 // both Old and New if it resolved exception specifications, so grab the 3429 // types again after this. Because this updates the type, we do this before 3430 // any of the other checks below, which may update the "de facto" NewQType 3431 // but do not necessarily update the type of New. 3432 if (CheckEquivalentExceptionSpec(Old, New)) 3433 return true; 3434 OldQType = Context.getCanonicalType(Old->getType()); 3435 NewQType = Context.getCanonicalType(New->getType()); 3436 3437 // Go back to the type source info to compare the declared return types, 3438 // per C++1y [dcl.type.auto]p13: 3439 // Redeclarations or specializations of a function or function template 3440 // with a declared return type that uses a placeholder type shall also 3441 // use that placeholder, not a deduced type. 3442 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3443 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3444 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3445 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3446 OldDeclaredReturnType)) { 3447 QualType ResQT; 3448 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3449 OldDeclaredReturnType->isObjCObjectPointerType()) 3450 // FIXME: This does the wrong thing for a deduced return type. 3451 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3452 if (ResQT.isNull()) { 3453 if (New->isCXXClassMember() && New->isOutOfLine()) 3454 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3455 << New << New->getReturnTypeSourceRange(); 3456 else 3457 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3458 << New->getReturnTypeSourceRange(); 3459 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3460 << Old->getReturnTypeSourceRange(); 3461 return true; 3462 } 3463 else 3464 NewQType = ResQT; 3465 } 3466 3467 QualType OldReturnType = OldType->getReturnType(); 3468 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3469 if (OldReturnType != NewReturnType) { 3470 // If this function has a deduced return type and has already been 3471 // defined, copy the deduced value from the old declaration. 3472 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3473 if (OldAT && OldAT->isDeduced()) { 3474 New->setType( 3475 SubstAutoType(New->getType(), 3476 OldAT->isDependentType() ? Context.DependentTy 3477 : OldAT->getDeducedType())); 3478 NewQType = Context.getCanonicalType( 3479 SubstAutoType(NewQType, 3480 OldAT->isDependentType() ? Context.DependentTy 3481 : OldAT->getDeducedType())); 3482 } 3483 } 3484 3485 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3486 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3487 if (OldMethod && NewMethod) { 3488 // Preserve triviality. 3489 NewMethod->setTrivial(OldMethod->isTrivial()); 3490 3491 // MSVC allows explicit template specialization at class scope: 3492 // 2 CXXMethodDecls referring to the same function will be injected. 3493 // We don't want a redeclaration error. 3494 bool IsClassScopeExplicitSpecialization = 3495 OldMethod->isFunctionTemplateSpecialization() && 3496 NewMethod->isFunctionTemplateSpecialization(); 3497 bool isFriend = NewMethod->getFriendObjectKind(); 3498 3499 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3500 !IsClassScopeExplicitSpecialization) { 3501 // -- Member function declarations with the same name and the 3502 // same parameter types cannot be overloaded if any of them 3503 // is a static member function declaration. 3504 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3505 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3506 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3507 return true; 3508 } 3509 3510 // C++ [class.mem]p1: 3511 // [...] A member shall not be declared twice in the 3512 // member-specification, except that a nested class or member 3513 // class template can be declared and then later defined. 3514 if (!inTemplateInstantiation()) { 3515 unsigned NewDiag; 3516 if (isa<CXXConstructorDecl>(OldMethod)) 3517 NewDiag = diag::err_constructor_redeclared; 3518 else if (isa<CXXDestructorDecl>(NewMethod)) 3519 NewDiag = diag::err_destructor_redeclared; 3520 else if (isa<CXXConversionDecl>(NewMethod)) 3521 NewDiag = diag::err_conv_function_redeclared; 3522 else 3523 NewDiag = diag::err_member_redeclared; 3524 3525 Diag(New->getLocation(), NewDiag); 3526 } else { 3527 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3528 << New << New->getType(); 3529 } 3530 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3531 return true; 3532 3533 // Complain if this is an explicit declaration of a special 3534 // member that was initially declared implicitly. 3535 // 3536 // As an exception, it's okay to befriend such methods in order 3537 // to permit the implicit constructor/destructor/operator calls. 3538 } else if (OldMethod->isImplicit()) { 3539 if (isFriend) { 3540 NewMethod->setImplicit(); 3541 } else { 3542 Diag(NewMethod->getLocation(), 3543 diag::err_definition_of_implicitly_declared_member) 3544 << New << getSpecialMember(OldMethod); 3545 return true; 3546 } 3547 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3548 Diag(NewMethod->getLocation(), 3549 diag::err_definition_of_explicitly_defaulted_member) 3550 << getSpecialMember(OldMethod); 3551 return true; 3552 } 3553 } 3554 3555 // C++11 [dcl.attr.noreturn]p1: 3556 // The first declaration of a function shall specify the noreturn 3557 // attribute if any declaration of that function specifies the noreturn 3558 // attribute. 3559 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3560 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3561 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3562 Diag(Old->getFirstDecl()->getLocation(), 3563 diag::note_noreturn_missing_first_decl); 3564 } 3565 3566 // C++11 [dcl.attr.depend]p2: 3567 // The first declaration of a function shall specify the 3568 // carries_dependency attribute for its declarator-id if any declaration 3569 // of the function specifies the carries_dependency attribute. 3570 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3571 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3572 Diag(CDA->getLocation(), 3573 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3574 Diag(Old->getFirstDecl()->getLocation(), 3575 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3576 } 3577 3578 // (C++98 8.3.5p3): 3579 // All declarations for a function shall agree exactly in both the 3580 // return type and the parameter-type-list. 3581 // We also want to respect all the extended bits except noreturn. 3582 3583 // noreturn should now match unless the old type info didn't have it. 3584 QualType OldQTypeForComparison = OldQType; 3585 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3586 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3587 const FunctionType *OldTypeForComparison 3588 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3589 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3590 assert(OldQTypeForComparison.isCanonical()); 3591 } 3592 3593 if (haveIncompatibleLanguageLinkages(Old, New)) { 3594 // As a special case, retain the language linkage from previous 3595 // declarations of a friend function as an extension. 3596 // 3597 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3598 // and is useful because there's otherwise no way to specify language 3599 // linkage within class scope. 3600 // 3601 // Check cautiously as the friend object kind isn't yet complete. 3602 if (New->getFriendObjectKind() != Decl::FOK_None) { 3603 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3604 Diag(OldLocation, PrevDiag); 3605 } else { 3606 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3607 Diag(OldLocation, PrevDiag); 3608 return true; 3609 } 3610 } 3611 3612 // If the function types are compatible, merge the declarations. Ignore the 3613 // exception specifier because it was already checked above in 3614 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3615 // about incompatible types under -fms-compatibility. 3616 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3617 NewQType)) 3618 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3619 3620 // If the types are imprecise (due to dependent constructs in friends or 3621 // local extern declarations), it's OK if they differ. We'll check again 3622 // during instantiation. 3623 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3624 return false; 3625 3626 // Fall through for conflicting redeclarations and redefinitions. 3627 } 3628 3629 // C: Function types need to be compatible, not identical. This handles 3630 // duplicate function decls like "void f(int); void f(enum X);" properly. 3631 if (!getLangOpts().CPlusPlus && 3632 Context.typesAreCompatible(OldQType, NewQType)) { 3633 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3634 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3635 const FunctionProtoType *OldProto = nullptr; 3636 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3637 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3638 // The old declaration provided a function prototype, but the 3639 // new declaration does not. Merge in the prototype. 3640 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3641 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3642 NewQType = 3643 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3644 OldProto->getExtProtoInfo()); 3645 New->setType(NewQType); 3646 New->setHasInheritedPrototype(); 3647 3648 // Synthesize parameters with the same types. 3649 SmallVector<ParmVarDecl*, 16> Params; 3650 for (const auto &ParamType : OldProto->param_types()) { 3651 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3652 SourceLocation(), nullptr, 3653 ParamType, /*TInfo=*/nullptr, 3654 SC_None, nullptr); 3655 Param->setScopeInfo(0, Params.size()); 3656 Param->setImplicit(); 3657 Params.push_back(Param); 3658 } 3659 3660 New->setParams(Params); 3661 } 3662 3663 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3664 } 3665 3666 // Check if the function types are compatible when pointer size address 3667 // spaces are ignored. 3668 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3669 return false; 3670 3671 // GNU C permits a K&R definition to follow a prototype declaration 3672 // if the declared types of the parameters in the K&R definition 3673 // match the types in the prototype declaration, even when the 3674 // promoted types of the parameters from the K&R definition differ 3675 // from the types in the prototype. GCC then keeps the types from 3676 // the prototype. 3677 // 3678 // If a variadic prototype is followed by a non-variadic K&R definition, 3679 // the K&R definition becomes variadic. This is sort of an edge case, but 3680 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3681 // C99 6.9.1p8. 3682 if (!getLangOpts().CPlusPlus && 3683 Old->hasPrototype() && !New->hasPrototype() && 3684 New->getType()->getAs<FunctionProtoType>() && 3685 Old->getNumParams() == New->getNumParams()) { 3686 SmallVector<QualType, 16> ArgTypes; 3687 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3688 const FunctionProtoType *OldProto 3689 = Old->getType()->getAs<FunctionProtoType>(); 3690 const FunctionProtoType *NewProto 3691 = New->getType()->getAs<FunctionProtoType>(); 3692 3693 // Determine whether this is the GNU C extension. 3694 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3695 NewProto->getReturnType()); 3696 bool LooseCompatible = !MergedReturn.isNull(); 3697 for (unsigned Idx = 0, End = Old->getNumParams(); 3698 LooseCompatible && Idx != End; ++Idx) { 3699 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3700 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3701 if (Context.typesAreCompatible(OldParm->getType(), 3702 NewProto->getParamType(Idx))) { 3703 ArgTypes.push_back(NewParm->getType()); 3704 } else if (Context.typesAreCompatible(OldParm->getType(), 3705 NewParm->getType(), 3706 /*CompareUnqualified=*/true)) { 3707 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3708 NewProto->getParamType(Idx) }; 3709 Warnings.push_back(Warn); 3710 ArgTypes.push_back(NewParm->getType()); 3711 } else 3712 LooseCompatible = false; 3713 } 3714 3715 if (LooseCompatible) { 3716 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3717 Diag(Warnings[Warn].NewParm->getLocation(), 3718 diag::ext_param_promoted_not_compatible_with_prototype) 3719 << Warnings[Warn].PromotedType 3720 << Warnings[Warn].OldParm->getType(); 3721 if (Warnings[Warn].OldParm->getLocation().isValid()) 3722 Diag(Warnings[Warn].OldParm->getLocation(), 3723 diag::note_previous_declaration); 3724 } 3725 3726 if (MergeTypeWithOld) 3727 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3728 OldProto->getExtProtoInfo())); 3729 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3730 } 3731 3732 // Fall through to diagnose conflicting types. 3733 } 3734 3735 // A function that has already been declared has been redeclared or 3736 // defined with a different type; show an appropriate diagnostic. 3737 3738 // If the previous declaration was an implicitly-generated builtin 3739 // declaration, then at the very least we should use a specialized note. 3740 unsigned BuiltinID; 3741 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3742 // If it's actually a library-defined builtin function like 'malloc' 3743 // or 'printf', just warn about the incompatible redeclaration. 3744 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3745 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3746 Diag(OldLocation, diag::note_previous_builtin_declaration) 3747 << Old << Old->getType(); 3748 3749 // If this is a global redeclaration, just forget hereafter 3750 // about the "builtin-ness" of the function. 3751 // 3752 // Doing this for local extern declarations is problematic. If 3753 // the builtin declaration remains visible, a second invalid 3754 // local declaration will produce a hard error; if it doesn't 3755 // remain visible, a single bogus local redeclaration (which is 3756 // actually only a warning) could break all the downstream code. 3757 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3758 New->getIdentifier()->revertBuiltin(); 3759 3760 return false; 3761 } 3762 3763 PrevDiag = diag::note_previous_builtin_declaration; 3764 } 3765 3766 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3767 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3768 return true; 3769 } 3770 3771 /// Completes the merge of two function declarations that are 3772 /// known to be compatible. 3773 /// 3774 /// This routine handles the merging of attributes and other 3775 /// properties of function declarations from the old declaration to 3776 /// the new declaration, once we know that New is in fact a 3777 /// redeclaration of Old. 3778 /// 3779 /// \returns false 3780 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3781 Scope *S, bool MergeTypeWithOld) { 3782 // Merge the attributes 3783 mergeDeclAttributes(New, Old); 3784 3785 // Merge "pure" flag. 3786 if (Old->isPure()) 3787 New->setPure(); 3788 3789 // Merge "used" flag. 3790 if (Old->getMostRecentDecl()->isUsed(false)) 3791 New->setIsUsed(); 3792 3793 // Merge attributes from the parameters. These can mismatch with K&R 3794 // declarations. 3795 if (New->getNumParams() == Old->getNumParams()) 3796 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3797 ParmVarDecl *NewParam = New->getParamDecl(i); 3798 ParmVarDecl *OldParam = Old->getParamDecl(i); 3799 mergeParamDeclAttributes(NewParam, OldParam, *this); 3800 mergeParamDeclTypes(NewParam, OldParam, *this); 3801 } 3802 3803 if (getLangOpts().CPlusPlus) 3804 return MergeCXXFunctionDecl(New, Old, S); 3805 3806 // Merge the function types so the we get the composite types for the return 3807 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3808 // was visible. 3809 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3810 if (!Merged.isNull() && MergeTypeWithOld) 3811 New->setType(Merged); 3812 3813 return false; 3814 } 3815 3816 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3817 ObjCMethodDecl *oldMethod) { 3818 // Merge the attributes, including deprecated/unavailable 3819 AvailabilityMergeKind MergeKind = 3820 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3821 ? AMK_ProtocolImplementation 3822 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3823 : AMK_Override; 3824 3825 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3826 3827 // Merge attributes from the parameters. 3828 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3829 oe = oldMethod->param_end(); 3830 for (ObjCMethodDecl::param_iterator 3831 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3832 ni != ne && oi != oe; ++ni, ++oi) 3833 mergeParamDeclAttributes(*ni, *oi, *this); 3834 3835 CheckObjCMethodOverride(newMethod, oldMethod); 3836 } 3837 3838 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3839 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3840 3841 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3842 ? diag::err_redefinition_different_type 3843 : diag::err_redeclaration_different_type) 3844 << New->getDeclName() << New->getType() << Old->getType(); 3845 3846 diag::kind PrevDiag; 3847 SourceLocation OldLocation; 3848 std::tie(PrevDiag, OldLocation) 3849 = getNoteDiagForInvalidRedeclaration(Old, New); 3850 S.Diag(OldLocation, PrevDiag); 3851 New->setInvalidDecl(); 3852 } 3853 3854 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3855 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3856 /// emitting diagnostics as appropriate. 3857 /// 3858 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3859 /// to here in AddInitializerToDecl. We can't check them before the initializer 3860 /// is attached. 3861 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3862 bool MergeTypeWithOld) { 3863 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3864 return; 3865 3866 QualType MergedT; 3867 if (getLangOpts().CPlusPlus) { 3868 if (New->getType()->isUndeducedType()) { 3869 // We don't know what the new type is until the initializer is attached. 3870 return; 3871 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3872 // These could still be something that needs exception specs checked. 3873 return MergeVarDeclExceptionSpecs(New, Old); 3874 } 3875 // C++ [basic.link]p10: 3876 // [...] the types specified by all declarations referring to a given 3877 // object or function shall be identical, except that declarations for an 3878 // array object can specify array types that differ by the presence or 3879 // absence of a major array bound (8.3.4). 3880 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3881 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3882 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3883 3884 // We are merging a variable declaration New into Old. If it has an array 3885 // bound, and that bound differs from Old's bound, we should diagnose the 3886 // mismatch. 3887 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3888 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3889 PrevVD = PrevVD->getPreviousDecl()) { 3890 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3891 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3892 continue; 3893 3894 if (!Context.hasSameType(NewArray, PrevVDTy)) 3895 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3896 } 3897 } 3898 3899 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3900 if (Context.hasSameType(OldArray->getElementType(), 3901 NewArray->getElementType())) 3902 MergedT = New->getType(); 3903 } 3904 // FIXME: Check visibility. New is hidden but has a complete type. If New 3905 // has no array bound, it should not inherit one from Old, if Old is not 3906 // visible. 3907 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3908 if (Context.hasSameType(OldArray->getElementType(), 3909 NewArray->getElementType())) 3910 MergedT = Old->getType(); 3911 } 3912 } 3913 else if (New->getType()->isObjCObjectPointerType() && 3914 Old->getType()->isObjCObjectPointerType()) { 3915 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3916 Old->getType()); 3917 } 3918 } else { 3919 // C 6.2.7p2: 3920 // All declarations that refer to the same object or function shall have 3921 // compatible type. 3922 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3923 } 3924 if (MergedT.isNull()) { 3925 // It's OK if we couldn't merge types if either type is dependent, for a 3926 // block-scope variable. In other cases (static data members of class 3927 // templates, variable templates, ...), we require the types to be 3928 // equivalent. 3929 // FIXME: The C++ standard doesn't say anything about this. 3930 if ((New->getType()->isDependentType() || 3931 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3932 // If the old type was dependent, we can't merge with it, so the new type 3933 // becomes dependent for now. We'll reproduce the original type when we 3934 // instantiate the TypeSourceInfo for the variable. 3935 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3936 New->setType(Context.DependentTy); 3937 return; 3938 } 3939 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3940 } 3941 3942 // Don't actually update the type on the new declaration if the old 3943 // declaration was an extern declaration in a different scope. 3944 if (MergeTypeWithOld) 3945 New->setType(MergedT); 3946 } 3947 3948 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3949 LookupResult &Previous) { 3950 // C11 6.2.7p4: 3951 // For an identifier with internal or external linkage declared 3952 // in a scope in which a prior declaration of that identifier is 3953 // visible, if the prior declaration specifies internal or 3954 // external linkage, the type of the identifier at the later 3955 // declaration becomes the composite type. 3956 // 3957 // If the variable isn't visible, we do not merge with its type. 3958 if (Previous.isShadowed()) 3959 return false; 3960 3961 if (S.getLangOpts().CPlusPlus) { 3962 // C++11 [dcl.array]p3: 3963 // If there is a preceding declaration of the entity in the same 3964 // scope in which the bound was specified, an omitted array bound 3965 // is taken to be the same as in that earlier declaration. 3966 return NewVD->isPreviousDeclInSameBlockScope() || 3967 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3968 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3969 } else { 3970 // If the old declaration was function-local, don't merge with its 3971 // type unless we're in the same function. 3972 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3973 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3974 } 3975 } 3976 3977 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3978 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3979 /// situation, merging decls or emitting diagnostics as appropriate. 3980 /// 3981 /// Tentative definition rules (C99 6.9.2p2) are checked by 3982 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3983 /// definitions here, since the initializer hasn't been attached. 3984 /// 3985 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3986 // If the new decl is already invalid, don't do any other checking. 3987 if (New->isInvalidDecl()) 3988 return; 3989 3990 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3991 return; 3992 3993 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3994 3995 // Verify the old decl was also a variable or variable template. 3996 VarDecl *Old = nullptr; 3997 VarTemplateDecl *OldTemplate = nullptr; 3998 if (Previous.isSingleResult()) { 3999 if (NewTemplate) { 4000 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4001 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4002 4003 if (auto *Shadow = 4004 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4005 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4006 return New->setInvalidDecl(); 4007 } else { 4008 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4009 4010 if (auto *Shadow = 4011 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4012 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4013 return New->setInvalidDecl(); 4014 } 4015 } 4016 if (!Old) { 4017 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4018 << New->getDeclName(); 4019 notePreviousDefinition(Previous.getRepresentativeDecl(), 4020 New->getLocation()); 4021 return New->setInvalidDecl(); 4022 } 4023 4024 // Ensure the template parameters are compatible. 4025 if (NewTemplate && 4026 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4027 OldTemplate->getTemplateParameters(), 4028 /*Complain=*/true, TPL_TemplateMatch)) 4029 return New->setInvalidDecl(); 4030 4031 // C++ [class.mem]p1: 4032 // A member shall not be declared twice in the member-specification [...] 4033 // 4034 // Here, we need only consider static data members. 4035 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4036 Diag(New->getLocation(), diag::err_duplicate_member) 4037 << New->getIdentifier(); 4038 Diag(Old->getLocation(), diag::note_previous_declaration); 4039 New->setInvalidDecl(); 4040 } 4041 4042 mergeDeclAttributes(New, Old); 4043 // Warn if an already-declared variable is made a weak_import in a subsequent 4044 // declaration 4045 if (New->hasAttr<WeakImportAttr>() && 4046 Old->getStorageClass() == SC_None && 4047 !Old->hasAttr<WeakImportAttr>()) { 4048 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4049 notePreviousDefinition(Old, New->getLocation()); 4050 // Remove weak_import attribute on new declaration. 4051 New->dropAttr<WeakImportAttr>(); 4052 } 4053 4054 if (New->hasAttr<InternalLinkageAttr>() && 4055 !Old->hasAttr<InternalLinkageAttr>()) { 4056 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4057 << New->getDeclName(); 4058 notePreviousDefinition(Old, New->getLocation()); 4059 New->dropAttr<InternalLinkageAttr>(); 4060 } 4061 4062 // Merge the types. 4063 VarDecl *MostRecent = Old->getMostRecentDecl(); 4064 if (MostRecent != Old) { 4065 MergeVarDeclTypes(New, MostRecent, 4066 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4067 if (New->isInvalidDecl()) 4068 return; 4069 } 4070 4071 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4072 if (New->isInvalidDecl()) 4073 return; 4074 4075 diag::kind PrevDiag; 4076 SourceLocation OldLocation; 4077 std::tie(PrevDiag, OldLocation) = 4078 getNoteDiagForInvalidRedeclaration(Old, New); 4079 4080 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4081 if (New->getStorageClass() == SC_Static && 4082 !New->isStaticDataMember() && 4083 Old->hasExternalFormalLinkage()) { 4084 if (getLangOpts().MicrosoftExt) { 4085 Diag(New->getLocation(), diag::ext_static_non_static) 4086 << New->getDeclName(); 4087 Diag(OldLocation, PrevDiag); 4088 } else { 4089 Diag(New->getLocation(), diag::err_static_non_static) 4090 << New->getDeclName(); 4091 Diag(OldLocation, PrevDiag); 4092 return New->setInvalidDecl(); 4093 } 4094 } 4095 // C99 6.2.2p4: 4096 // For an identifier declared with the storage-class specifier 4097 // extern in a scope in which a prior declaration of that 4098 // identifier is visible,23) if the prior declaration specifies 4099 // internal or external linkage, the linkage of the identifier at 4100 // the later declaration is the same as the linkage specified at 4101 // the prior declaration. If no prior declaration is visible, or 4102 // if the prior declaration specifies no linkage, then the 4103 // identifier has external linkage. 4104 if (New->hasExternalStorage() && Old->hasLinkage()) 4105 /* Okay */; 4106 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4107 !New->isStaticDataMember() && 4108 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4109 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4110 Diag(OldLocation, PrevDiag); 4111 return New->setInvalidDecl(); 4112 } 4113 4114 // Check if extern is followed by non-extern and vice-versa. 4115 if (New->hasExternalStorage() && 4116 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4117 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4118 Diag(OldLocation, PrevDiag); 4119 return New->setInvalidDecl(); 4120 } 4121 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4122 !New->hasExternalStorage()) { 4123 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4124 Diag(OldLocation, PrevDiag); 4125 return New->setInvalidDecl(); 4126 } 4127 4128 if (CheckRedeclarationModuleOwnership(New, Old)) 4129 return; 4130 4131 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4132 4133 // FIXME: The test for external storage here seems wrong? We still 4134 // need to check for mismatches. 4135 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4136 // Don't complain about out-of-line definitions of static members. 4137 !(Old->getLexicalDeclContext()->isRecord() && 4138 !New->getLexicalDeclContext()->isRecord())) { 4139 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4140 Diag(OldLocation, PrevDiag); 4141 return New->setInvalidDecl(); 4142 } 4143 4144 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4145 if (VarDecl *Def = Old->getDefinition()) { 4146 // C++1z [dcl.fcn.spec]p4: 4147 // If the definition of a variable appears in a translation unit before 4148 // its first declaration as inline, the program is ill-formed. 4149 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4150 Diag(Def->getLocation(), diag::note_previous_definition); 4151 } 4152 } 4153 4154 // If this redeclaration makes the variable inline, we may need to add it to 4155 // UndefinedButUsed. 4156 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4157 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4158 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4159 SourceLocation())); 4160 4161 if (New->getTLSKind() != Old->getTLSKind()) { 4162 if (!Old->getTLSKind()) { 4163 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4164 Diag(OldLocation, PrevDiag); 4165 } else if (!New->getTLSKind()) { 4166 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4167 Diag(OldLocation, PrevDiag); 4168 } else { 4169 // Do not allow redeclaration to change the variable between requiring 4170 // static and dynamic initialization. 4171 // FIXME: GCC allows this, but uses the TLS keyword on the first 4172 // declaration to determine the kind. Do we need to be compatible here? 4173 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4174 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4175 Diag(OldLocation, PrevDiag); 4176 } 4177 } 4178 4179 // C++ doesn't have tentative definitions, so go right ahead and check here. 4180 if (getLangOpts().CPlusPlus && 4181 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4182 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4183 Old->getCanonicalDecl()->isConstexpr()) { 4184 // This definition won't be a definition any more once it's been merged. 4185 Diag(New->getLocation(), 4186 diag::warn_deprecated_redundant_constexpr_static_def); 4187 } else if (VarDecl *Def = Old->getDefinition()) { 4188 if (checkVarDeclRedefinition(Def, New)) 4189 return; 4190 } 4191 } 4192 4193 if (haveIncompatibleLanguageLinkages(Old, New)) { 4194 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4195 Diag(OldLocation, PrevDiag); 4196 New->setInvalidDecl(); 4197 return; 4198 } 4199 4200 // Merge "used" flag. 4201 if (Old->getMostRecentDecl()->isUsed(false)) 4202 New->setIsUsed(); 4203 4204 // Keep a chain of previous declarations. 4205 New->setPreviousDecl(Old); 4206 if (NewTemplate) 4207 NewTemplate->setPreviousDecl(OldTemplate); 4208 adjustDeclContextForDeclaratorDecl(New, Old); 4209 4210 // Inherit access appropriately. 4211 New->setAccess(Old->getAccess()); 4212 if (NewTemplate) 4213 NewTemplate->setAccess(New->getAccess()); 4214 4215 if (Old->isInline()) 4216 New->setImplicitlyInline(); 4217 } 4218 4219 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4220 SourceManager &SrcMgr = getSourceManager(); 4221 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4222 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4223 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4224 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4225 auto &HSI = PP.getHeaderSearchInfo(); 4226 StringRef HdrFilename = 4227 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4228 4229 auto noteFromModuleOrInclude = [&](Module *Mod, 4230 SourceLocation IncLoc) -> bool { 4231 // Redefinition errors with modules are common with non modular mapped 4232 // headers, example: a non-modular header H in module A that also gets 4233 // included directly in a TU. Pointing twice to the same header/definition 4234 // is confusing, try to get better diagnostics when modules is on. 4235 if (IncLoc.isValid()) { 4236 if (Mod) { 4237 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4238 << HdrFilename.str() << Mod->getFullModuleName(); 4239 if (!Mod->DefinitionLoc.isInvalid()) 4240 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4241 << Mod->getFullModuleName(); 4242 } else { 4243 Diag(IncLoc, diag::note_redefinition_include_same_file) 4244 << HdrFilename.str(); 4245 } 4246 return true; 4247 } 4248 4249 return false; 4250 }; 4251 4252 // Is it the same file and same offset? Provide more information on why 4253 // this leads to a redefinition error. 4254 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4255 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4256 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4257 bool EmittedDiag = 4258 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4259 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4260 4261 // If the header has no guards, emit a note suggesting one. 4262 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4263 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4264 4265 if (EmittedDiag) 4266 return; 4267 } 4268 4269 // Redefinition coming from different files or couldn't do better above. 4270 if (Old->getLocation().isValid()) 4271 Diag(Old->getLocation(), diag::note_previous_definition); 4272 } 4273 4274 /// We've just determined that \p Old and \p New both appear to be definitions 4275 /// of the same variable. Either diagnose or fix the problem. 4276 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4277 if (!hasVisibleDefinition(Old) && 4278 (New->getFormalLinkage() == InternalLinkage || 4279 New->isInline() || 4280 New->getDescribedVarTemplate() || 4281 New->getNumTemplateParameterLists() || 4282 New->getDeclContext()->isDependentContext())) { 4283 // The previous definition is hidden, and multiple definitions are 4284 // permitted (in separate TUs). Demote this to a declaration. 4285 New->demoteThisDefinitionToDeclaration(); 4286 4287 // Make the canonical definition visible. 4288 if (auto *OldTD = Old->getDescribedVarTemplate()) 4289 makeMergedDefinitionVisible(OldTD); 4290 makeMergedDefinitionVisible(Old); 4291 return false; 4292 } else { 4293 Diag(New->getLocation(), diag::err_redefinition) << New; 4294 notePreviousDefinition(Old, New->getLocation()); 4295 New->setInvalidDecl(); 4296 return true; 4297 } 4298 } 4299 4300 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4301 /// no declarator (e.g. "struct foo;") is parsed. 4302 Decl * 4303 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4304 RecordDecl *&AnonRecord) { 4305 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4306 AnonRecord); 4307 } 4308 4309 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4310 // disambiguate entities defined in different scopes. 4311 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4312 // compatibility. 4313 // We will pick our mangling number depending on which version of MSVC is being 4314 // targeted. 4315 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4316 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4317 ? S->getMSCurManglingNumber() 4318 : S->getMSLastManglingNumber(); 4319 } 4320 4321 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4322 if (!Context.getLangOpts().CPlusPlus) 4323 return; 4324 4325 if (isa<CXXRecordDecl>(Tag->getParent())) { 4326 // If this tag is the direct child of a class, number it if 4327 // it is anonymous. 4328 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4329 return; 4330 MangleNumberingContext &MCtx = 4331 Context.getManglingNumberContext(Tag->getParent()); 4332 Context.setManglingNumber( 4333 Tag, MCtx.getManglingNumber( 4334 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4335 return; 4336 } 4337 4338 // If this tag isn't a direct child of a class, number it if it is local. 4339 MangleNumberingContext *MCtx; 4340 Decl *ManglingContextDecl; 4341 std::tie(MCtx, ManglingContextDecl) = 4342 getCurrentMangleNumberContext(Tag->getDeclContext()); 4343 if (MCtx) { 4344 Context.setManglingNumber( 4345 Tag, MCtx->getManglingNumber( 4346 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4347 } 4348 } 4349 4350 namespace { 4351 struct NonCLikeKind { 4352 enum { 4353 None, 4354 BaseClass, 4355 DefaultMemberInit, 4356 Lambda, 4357 Friend, 4358 OtherMember, 4359 Invalid, 4360 } Kind = None; 4361 SourceRange Range; 4362 4363 explicit operator bool() { return Kind != None; } 4364 }; 4365 } 4366 4367 /// Determine whether a class is C-like, according to the rules of C++ 4368 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4369 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4370 if (RD->isInvalidDecl()) 4371 return {NonCLikeKind::Invalid, {}}; 4372 4373 // C++ [dcl.typedef]p9: [P1766R1] 4374 // An unnamed class with a typedef name for linkage purposes shall not 4375 // 4376 // -- have any base classes 4377 if (RD->getNumBases()) 4378 return {NonCLikeKind::BaseClass, 4379 SourceRange(RD->bases_begin()->getBeginLoc(), 4380 RD->bases_end()[-1].getEndLoc())}; 4381 bool Invalid = false; 4382 for (Decl *D : RD->decls()) { 4383 // Don't complain about things we already diagnosed. 4384 if (D->isInvalidDecl()) { 4385 Invalid = true; 4386 continue; 4387 } 4388 4389 // -- have any [...] default member initializers 4390 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4391 if (FD->hasInClassInitializer()) { 4392 auto *Init = FD->getInClassInitializer(); 4393 return {NonCLikeKind::DefaultMemberInit, 4394 Init ? Init->getSourceRange() : D->getSourceRange()}; 4395 } 4396 continue; 4397 } 4398 4399 // FIXME: We don't allow friend declarations. This violates the wording of 4400 // P1766, but not the intent. 4401 if (isa<FriendDecl>(D)) 4402 return {NonCLikeKind::Friend, D->getSourceRange()}; 4403 4404 // -- declare any members other than non-static data members, member 4405 // enumerations, or member classes, 4406 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4407 isa<EnumDecl>(D)) 4408 continue; 4409 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4410 if (!MemberRD) 4411 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4412 4413 // -- contain a lambda-expression, 4414 if (MemberRD->isLambda()) 4415 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4416 4417 // and all member classes shall also satisfy these requirements 4418 // (recursively). 4419 if (MemberRD->isThisDeclarationADefinition()) { 4420 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4421 return Kind; 4422 } 4423 } 4424 4425 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4426 } 4427 4428 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4429 TypedefNameDecl *NewTD) { 4430 if (TagFromDeclSpec->isInvalidDecl()) 4431 return; 4432 4433 // Do nothing if the tag already has a name for linkage purposes. 4434 if (TagFromDeclSpec->hasNameForLinkage()) 4435 return; 4436 4437 // A well-formed anonymous tag must always be a TUK_Definition. 4438 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4439 4440 // The type must match the tag exactly; no qualifiers allowed. 4441 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4442 Context.getTagDeclType(TagFromDeclSpec))) { 4443 if (getLangOpts().CPlusPlus) 4444 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4445 return; 4446 } 4447 4448 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4449 // An unnamed class with a typedef name for linkage purposes shall [be 4450 // C-like]. 4451 // 4452 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4453 // shouldn't happen, but there are constructs that the language rule doesn't 4454 // disallow for which we can't reasonably avoid computing linkage early. 4455 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4456 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4457 : NonCLikeKind(); 4458 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4459 if (NonCLike || ChangesLinkage) { 4460 if (NonCLike.Kind == NonCLikeKind::Invalid) 4461 return; 4462 4463 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4464 if (ChangesLinkage) { 4465 // If the linkage changes, we can't accept this as an extension. 4466 if (NonCLike.Kind == NonCLikeKind::None) 4467 DiagID = diag::err_typedef_changes_linkage; 4468 else 4469 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4470 } 4471 4472 SourceLocation FixitLoc = 4473 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4474 llvm::SmallString<40> TextToInsert; 4475 TextToInsert += ' '; 4476 TextToInsert += NewTD->getIdentifier()->getName(); 4477 4478 Diag(FixitLoc, DiagID) 4479 << isa<TypeAliasDecl>(NewTD) 4480 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4481 if (NonCLike.Kind != NonCLikeKind::None) { 4482 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4483 << NonCLike.Kind - 1 << NonCLike.Range; 4484 } 4485 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4486 << NewTD << isa<TypeAliasDecl>(NewTD); 4487 4488 if (ChangesLinkage) 4489 return; 4490 } 4491 4492 // Otherwise, set this as the anon-decl typedef for the tag. 4493 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4494 } 4495 4496 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4497 switch (T) { 4498 case DeclSpec::TST_class: 4499 return 0; 4500 case DeclSpec::TST_struct: 4501 return 1; 4502 case DeclSpec::TST_interface: 4503 return 2; 4504 case DeclSpec::TST_union: 4505 return 3; 4506 case DeclSpec::TST_enum: 4507 return 4; 4508 default: 4509 llvm_unreachable("unexpected type specifier"); 4510 } 4511 } 4512 4513 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4514 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4515 /// parameters to cope with template friend declarations. 4516 Decl * 4517 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4518 MultiTemplateParamsArg TemplateParams, 4519 bool IsExplicitInstantiation, 4520 RecordDecl *&AnonRecord) { 4521 Decl *TagD = nullptr; 4522 TagDecl *Tag = nullptr; 4523 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4524 DS.getTypeSpecType() == DeclSpec::TST_struct || 4525 DS.getTypeSpecType() == DeclSpec::TST_interface || 4526 DS.getTypeSpecType() == DeclSpec::TST_union || 4527 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4528 TagD = DS.getRepAsDecl(); 4529 4530 if (!TagD) // We probably had an error 4531 return nullptr; 4532 4533 // Note that the above type specs guarantee that the 4534 // type rep is a Decl, whereas in many of the others 4535 // it's a Type. 4536 if (isa<TagDecl>(TagD)) 4537 Tag = cast<TagDecl>(TagD); 4538 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4539 Tag = CTD->getTemplatedDecl(); 4540 } 4541 4542 if (Tag) { 4543 handleTagNumbering(Tag, S); 4544 Tag->setFreeStanding(); 4545 if (Tag->isInvalidDecl()) 4546 return Tag; 4547 } 4548 4549 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4550 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4551 // or incomplete types shall not be restrict-qualified." 4552 if (TypeQuals & DeclSpec::TQ_restrict) 4553 Diag(DS.getRestrictSpecLoc(), 4554 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4555 << DS.getSourceRange(); 4556 } 4557 4558 if (DS.isInlineSpecified()) 4559 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4560 << getLangOpts().CPlusPlus17; 4561 4562 if (DS.hasConstexprSpecifier()) { 4563 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4564 // and definitions of functions and variables. 4565 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4566 // the declaration of a function or function template 4567 if (Tag) 4568 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4569 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4570 << DS.getConstexprSpecifier(); 4571 else 4572 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4573 << DS.getConstexprSpecifier(); 4574 // Don't emit warnings after this error. 4575 return TagD; 4576 } 4577 4578 DiagnoseFunctionSpecifiers(DS); 4579 4580 if (DS.isFriendSpecified()) { 4581 // If we're dealing with a decl but not a TagDecl, assume that 4582 // whatever routines created it handled the friendship aspect. 4583 if (TagD && !Tag) 4584 return nullptr; 4585 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4586 } 4587 4588 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4589 bool IsExplicitSpecialization = 4590 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4591 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4592 !IsExplicitInstantiation && !IsExplicitSpecialization && 4593 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4594 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4595 // nested-name-specifier unless it is an explicit instantiation 4596 // or an explicit specialization. 4597 // 4598 // FIXME: We allow class template partial specializations here too, per the 4599 // obvious intent of DR1819. 4600 // 4601 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4602 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4603 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4604 return nullptr; 4605 } 4606 4607 // Track whether this decl-specifier declares anything. 4608 bool DeclaresAnything = true; 4609 4610 // Handle anonymous struct definitions. 4611 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4612 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4613 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4614 if (getLangOpts().CPlusPlus || 4615 Record->getDeclContext()->isRecord()) { 4616 // If CurContext is a DeclContext that can contain statements, 4617 // RecursiveASTVisitor won't visit the decls that 4618 // BuildAnonymousStructOrUnion() will put into CurContext. 4619 // Also store them here so that they can be part of the 4620 // DeclStmt that gets created in this case. 4621 // FIXME: Also return the IndirectFieldDecls created by 4622 // BuildAnonymousStructOr union, for the same reason? 4623 if (CurContext->isFunctionOrMethod()) 4624 AnonRecord = Record; 4625 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4626 Context.getPrintingPolicy()); 4627 } 4628 4629 DeclaresAnything = false; 4630 } 4631 } 4632 4633 // C11 6.7.2.1p2: 4634 // A struct-declaration that does not declare an anonymous structure or 4635 // anonymous union shall contain a struct-declarator-list. 4636 // 4637 // This rule also existed in C89 and C99; the grammar for struct-declaration 4638 // did not permit a struct-declaration without a struct-declarator-list. 4639 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4640 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4641 // Check for Microsoft C extension: anonymous struct/union member. 4642 // Handle 2 kinds of anonymous struct/union: 4643 // struct STRUCT; 4644 // union UNION; 4645 // and 4646 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4647 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4648 if ((Tag && Tag->getDeclName()) || 4649 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4650 RecordDecl *Record = nullptr; 4651 if (Tag) 4652 Record = dyn_cast<RecordDecl>(Tag); 4653 else if (const RecordType *RT = 4654 DS.getRepAsType().get()->getAsStructureType()) 4655 Record = RT->getDecl(); 4656 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4657 Record = UT->getDecl(); 4658 4659 if (Record && getLangOpts().MicrosoftExt) { 4660 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4661 << Record->isUnion() << DS.getSourceRange(); 4662 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4663 } 4664 4665 DeclaresAnything = false; 4666 } 4667 } 4668 4669 // Skip all the checks below if we have a type error. 4670 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4671 (TagD && TagD->isInvalidDecl())) 4672 return TagD; 4673 4674 if (getLangOpts().CPlusPlus && 4675 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4676 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4677 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4678 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4679 DeclaresAnything = false; 4680 4681 if (!DS.isMissingDeclaratorOk()) { 4682 // Customize diagnostic for a typedef missing a name. 4683 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4684 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4685 << DS.getSourceRange(); 4686 else 4687 DeclaresAnything = false; 4688 } 4689 4690 if (DS.isModulePrivateSpecified() && 4691 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4692 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4693 << Tag->getTagKind() 4694 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4695 4696 ActOnDocumentableDecl(TagD); 4697 4698 // C 6.7/2: 4699 // A declaration [...] shall declare at least a declarator [...], a tag, 4700 // or the members of an enumeration. 4701 // C++ [dcl.dcl]p3: 4702 // [If there are no declarators], and except for the declaration of an 4703 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4704 // names into the program, or shall redeclare a name introduced by a 4705 // previous declaration. 4706 if (!DeclaresAnything) { 4707 // In C, we allow this as a (popular) extension / bug. Don't bother 4708 // producing further diagnostics for redundant qualifiers after this. 4709 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4710 return TagD; 4711 } 4712 4713 // C++ [dcl.stc]p1: 4714 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4715 // init-declarator-list of the declaration shall not be empty. 4716 // C++ [dcl.fct.spec]p1: 4717 // If a cv-qualifier appears in a decl-specifier-seq, the 4718 // init-declarator-list of the declaration shall not be empty. 4719 // 4720 // Spurious qualifiers here appear to be valid in C. 4721 unsigned DiagID = diag::warn_standalone_specifier; 4722 if (getLangOpts().CPlusPlus) 4723 DiagID = diag::ext_standalone_specifier; 4724 4725 // Note that a linkage-specification sets a storage class, but 4726 // 'extern "C" struct foo;' is actually valid and not theoretically 4727 // useless. 4728 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4729 if (SCS == DeclSpec::SCS_mutable) 4730 // Since mutable is not a viable storage class specifier in C, there is 4731 // no reason to treat it as an extension. Instead, diagnose as an error. 4732 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4733 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4734 Diag(DS.getStorageClassSpecLoc(), DiagID) 4735 << DeclSpec::getSpecifierName(SCS); 4736 } 4737 4738 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4739 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4740 << DeclSpec::getSpecifierName(TSCS); 4741 if (DS.getTypeQualifiers()) { 4742 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4743 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4744 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4745 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4746 // Restrict is covered above. 4747 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4748 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4749 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4750 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4751 } 4752 4753 // Warn about ignored type attributes, for example: 4754 // __attribute__((aligned)) struct A; 4755 // Attributes should be placed after tag to apply to type declaration. 4756 if (!DS.getAttributes().empty()) { 4757 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4758 if (TypeSpecType == DeclSpec::TST_class || 4759 TypeSpecType == DeclSpec::TST_struct || 4760 TypeSpecType == DeclSpec::TST_interface || 4761 TypeSpecType == DeclSpec::TST_union || 4762 TypeSpecType == DeclSpec::TST_enum) { 4763 for (const ParsedAttr &AL : DS.getAttributes()) 4764 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4765 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4766 } 4767 } 4768 4769 return TagD; 4770 } 4771 4772 /// We are trying to inject an anonymous member into the given scope; 4773 /// check if there's an existing declaration that can't be overloaded. 4774 /// 4775 /// \return true if this is a forbidden redeclaration 4776 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4777 Scope *S, 4778 DeclContext *Owner, 4779 DeclarationName Name, 4780 SourceLocation NameLoc, 4781 bool IsUnion) { 4782 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4783 Sema::ForVisibleRedeclaration); 4784 if (!SemaRef.LookupName(R, S)) return false; 4785 4786 // Pick a representative declaration. 4787 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4788 assert(PrevDecl && "Expected a non-null Decl"); 4789 4790 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4791 return false; 4792 4793 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4794 << IsUnion << Name; 4795 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4796 4797 return true; 4798 } 4799 4800 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4801 /// anonymous struct or union AnonRecord into the owning context Owner 4802 /// and scope S. This routine will be invoked just after we realize 4803 /// that an unnamed union or struct is actually an anonymous union or 4804 /// struct, e.g., 4805 /// 4806 /// @code 4807 /// union { 4808 /// int i; 4809 /// float f; 4810 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4811 /// // f into the surrounding scope.x 4812 /// @endcode 4813 /// 4814 /// This routine is recursive, injecting the names of nested anonymous 4815 /// structs/unions into the owning context and scope as well. 4816 static bool 4817 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4818 RecordDecl *AnonRecord, AccessSpecifier AS, 4819 SmallVectorImpl<NamedDecl *> &Chaining) { 4820 bool Invalid = false; 4821 4822 // Look every FieldDecl and IndirectFieldDecl with a name. 4823 for (auto *D : AnonRecord->decls()) { 4824 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4825 cast<NamedDecl>(D)->getDeclName()) { 4826 ValueDecl *VD = cast<ValueDecl>(D); 4827 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4828 VD->getLocation(), 4829 AnonRecord->isUnion())) { 4830 // C++ [class.union]p2: 4831 // The names of the members of an anonymous union shall be 4832 // distinct from the names of any other entity in the 4833 // scope in which the anonymous union is declared. 4834 Invalid = true; 4835 } else { 4836 // C++ [class.union]p2: 4837 // For the purpose of name lookup, after the anonymous union 4838 // definition, the members of the anonymous union are 4839 // considered to have been defined in the scope in which the 4840 // anonymous union is declared. 4841 unsigned OldChainingSize = Chaining.size(); 4842 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4843 Chaining.append(IF->chain_begin(), IF->chain_end()); 4844 else 4845 Chaining.push_back(VD); 4846 4847 assert(Chaining.size() >= 2); 4848 NamedDecl **NamedChain = 4849 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4850 for (unsigned i = 0; i < Chaining.size(); i++) 4851 NamedChain[i] = Chaining[i]; 4852 4853 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4854 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4855 VD->getType(), {NamedChain, Chaining.size()}); 4856 4857 for (const auto *Attr : VD->attrs()) 4858 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4859 4860 IndirectField->setAccess(AS); 4861 IndirectField->setImplicit(); 4862 SemaRef.PushOnScopeChains(IndirectField, S); 4863 4864 // That includes picking up the appropriate access specifier. 4865 if (AS != AS_none) IndirectField->setAccess(AS); 4866 4867 Chaining.resize(OldChainingSize); 4868 } 4869 } 4870 } 4871 4872 return Invalid; 4873 } 4874 4875 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4876 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4877 /// illegal input values are mapped to SC_None. 4878 static StorageClass 4879 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4880 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4881 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4882 "Parser allowed 'typedef' as storage class VarDecl."); 4883 switch (StorageClassSpec) { 4884 case DeclSpec::SCS_unspecified: return SC_None; 4885 case DeclSpec::SCS_extern: 4886 if (DS.isExternInLinkageSpec()) 4887 return SC_None; 4888 return SC_Extern; 4889 case DeclSpec::SCS_static: return SC_Static; 4890 case DeclSpec::SCS_auto: return SC_Auto; 4891 case DeclSpec::SCS_register: return SC_Register; 4892 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4893 // Illegal SCSs map to None: error reporting is up to the caller. 4894 case DeclSpec::SCS_mutable: // Fall through. 4895 case DeclSpec::SCS_typedef: return SC_None; 4896 } 4897 llvm_unreachable("unknown storage class specifier"); 4898 } 4899 4900 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4901 assert(Record->hasInClassInitializer()); 4902 4903 for (const auto *I : Record->decls()) { 4904 const auto *FD = dyn_cast<FieldDecl>(I); 4905 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4906 FD = IFD->getAnonField(); 4907 if (FD && FD->hasInClassInitializer()) 4908 return FD->getLocation(); 4909 } 4910 4911 llvm_unreachable("couldn't find in-class initializer"); 4912 } 4913 4914 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4915 SourceLocation DefaultInitLoc) { 4916 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4917 return; 4918 4919 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4920 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4921 } 4922 4923 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4924 CXXRecordDecl *AnonUnion) { 4925 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4926 return; 4927 4928 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4929 } 4930 4931 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4932 /// anonymous structure or union. Anonymous unions are a C++ feature 4933 /// (C++ [class.union]) and a C11 feature; anonymous structures 4934 /// are a C11 feature and GNU C++ extension. 4935 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4936 AccessSpecifier AS, 4937 RecordDecl *Record, 4938 const PrintingPolicy &Policy) { 4939 DeclContext *Owner = Record->getDeclContext(); 4940 4941 // Diagnose whether this anonymous struct/union is an extension. 4942 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4943 Diag(Record->getLocation(), diag::ext_anonymous_union); 4944 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4945 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4946 else if (!Record->isUnion() && !getLangOpts().C11) 4947 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4948 4949 // C and C++ require different kinds of checks for anonymous 4950 // structs/unions. 4951 bool Invalid = false; 4952 if (getLangOpts().CPlusPlus) { 4953 const char *PrevSpec = nullptr; 4954 if (Record->isUnion()) { 4955 // C++ [class.union]p6: 4956 // C++17 [class.union.anon]p2: 4957 // Anonymous unions declared in a named namespace or in the 4958 // global namespace shall be declared static. 4959 unsigned DiagID; 4960 DeclContext *OwnerScope = Owner->getRedeclContext(); 4961 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4962 (OwnerScope->isTranslationUnit() || 4963 (OwnerScope->isNamespace() && 4964 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 4965 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4966 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4967 4968 // Recover by adding 'static'. 4969 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4970 PrevSpec, DiagID, Policy); 4971 } 4972 // C++ [class.union]p6: 4973 // A storage class is not allowed in a declaration of an 4974 // anonymous union in a class scope. 4975 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4976 isa<RecordDecl>(Owner)) { 4977 Diag(DS.getStorageClassSpecLoc(), 4978 diag::err_anonymous_union_with_storage_spec) 4979 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4980 4981 // Recover by removing the storage specifier. 4982 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4983 SourceLocation(), 4984 PrevSpec, DiagID, Context.getPrintingPolicy()); 4985 } 4986 } 4987 4988 // Ignore const/volatile/restrict qualifiers. 4989 if (DS.getTypeQualifiers()) { 4990 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4991 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4992 << Record->isUnion() << "const" 4993 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4994 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4995 Diag(DS.getVolatileSpecLoc(), 4996 diag::ext_anonymous_struct_union_qualified) 4997 << Record->isUnion() << "volatile" 4998 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4999 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5000 Diag(DS.getRestrictSpecLoc(), 5001 diag::ext_anonymous_struct_union_qualified) 5002 << Record->isUnion() << "restrict" 5003 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5004 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5005 Diag(DS.getAtomicSpecLoc(), 5006 diag::ext_anonymous_struct_union_qualified) 5007 << Record->isUnion() << "_Atomic" 5008 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5009 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5010 Diag(DS.getUnalignedSpecLoc(), 5011 diag::ext_anonymous_struct_union_qualified) 5012 << Record->isUnion() << "__unaligned" 5013 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5014 5015 DS.ClearTypeQualifiers(); 5016 } 5017 5018 // C++ [class.union]p2: 5019 // The member-specification of an anonymous union shall only 5020 // define non-static data members. [Note: nested types and 5021 // functions cannot be declared within an anonymous union. ] 5022 for (auto *Mem : Record->decls()) { 5023 // Ignore invalid declarations; we already diagnosed them. 5024 if (Mem->isInvalidDecl()) 5025 continue; 5026 5027 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5028 // C++ [class.union]p3: 5029 // An anonymous union shall not have private or protected 5030 // members (clause 11). 5031 assert(FD->getAccess() != AS_none); 5032 if (FD->getAccess() != AS_public) { 5033 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5034 << Record->isUnion() << (FD->getAccess() == AS_protected); 5035 Invalid = true; 5036 } 5037 5038 // C++ [class.union]p1 5039 // An object of a class with a non-trivial constructor, a non-trivial 5040 // copy constructor, a non-trivial destructor, or a non-trivial copy 5041 // assignment operator cannot be a member of a union, nor can an 5042 // array of such objects. 5043 if (CheckNontrivialField(FD)) 5044 Invalid = true; 5045 } else if (Mem->isImplicit()) { 5046 // Any implicit members are fine. 5047 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5048 // This is a type that showed up in an 5049 // elaborated-type-specifier inside the anonymous struct or 5050 // union, but which actually declares a type outside of the 5051 // anonymous struct or union. It's okay. 5052 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5053 if (!MemRecord->isAnonymousStructOrUnion() && 5054 MemRecord->getDeclName()) { 5055 // Visual C++ allows type definition in anonymous struct or union. 5056 if (getLangOpts().MicrosoftExt) 5057 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5058 << Record->isUnion(); 5059 else { 5060 // This is a nested type declaration. 5061 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5062 << Record->isUnion(); 5063 Invalid = true; 5064 } 5065 } else { 5066 // This is an anonymous type definition within another anonymous type. 5067 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5068 // not part of standard C++. 5069 Diag(MemRecord->getLocation(), 5070 diag::ext_anonymous_record_with_anonymous_type) 5071 << Record->isUnion(); 5072 } 5073 } else if (isa<AccessSpecDecl>(Mem)) { 5074 // Any access specifier is fine. 5075 } else if (isa<StaticAssertDecl>(Mem)) { 5076 // In C++1z, static_assert declarations are also fine. 5077 } else { 5078 // We have something that isn't a non-static data 5079 // member. Complain about it. 5080 unsigned DK = diag::err_anonymous_record_bad_member; 5081 if (isa<TypeDecl>(Mem)) 5082 DK = diag::err_anonymous_record_with_type; 5083 else if (isa<FunctionDecl>(Mem)) 5084 DK = diag::err_anonymous_record_with_function; 5085 else if (isa<VarDecl>(Mem)) 5086 DK = diag::err_anonymous_record_with_static; 5087 5088 // Visual C++ allows type definition in anonymous struct or union. 5089 if (getLangOpts().MicrosoftExt && 5090 DK == diag::err_anonymous_record_with_type) 5091 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5092 << Record->isUnion(); 5093 else { 5094 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5095 Invalid = true; 5096 } 5097 } 5098 } 5099 5100 // C++11 [class.union]p8 (DR1460): 5101 // At most one variant member of a union may have a 5102 // brace-or-equal-initializer. 5103 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5104 Owner->isRecord()) 5105 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5106 cast<CXXRecordDecl>(Record)); 5107 } 5108 5109 if (!Record->isUnion() && !Owner->isRecord()) { 5110 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5111 << getLangOpts().CPlusPlus; 5112 Invalid = true; 5113 } 5114 5115 // C++ [dcl.dcl]p3: 5116 // [If there are no declarators], and except for the declaration of an 5117 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5118 // names into the program 5119 // C++ [class.mem]p2: 5120 // each such member-declaration shall either declare at least one member 5121 // name of the class or declare at least one unnamed bit-field 5122 // 5123 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5124 if (getLangOpts().CPlusPlus && Record->field_empty()) 5125 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5126 5127 // Mock up a declarator. 5128 Declarator Dc(DS, DeclaratorContext::MemberContext); 5129 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5130 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5131 5132 // Create a declaration for this anonymous struct/union. 5133 NamedDecl *Anon = nullptr; 5134 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5135 Anon = FieldDecl::Create( 5136 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5137 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5138 /*BitWidth=*/nullptr, /*Mutable=*/false, 5139 /*InitStyle=*/ICIS_NoInit); 5140 Anon->setAccess(AS); 5141 ProcessDeclAttributes(S, Anon, Dc); 5142 5143 if (getLangOpts().CPlusPlus) 5144 FieldCollector->Add(cast<FieldDecl>(Anon)); 5145 } else { 5146 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5147 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5148 if (SCSpec == DeclSpec::SCS_mutable) { 5149 // mutable can only appear on non-static class members, so it's always 5150 // an error here 5151 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5152 Invalid = true; 5153 SC = SC_None; 5154 } 5155 5156 assert(DS.getAttributes().empty() && "No attribute expected"); 5157 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5158 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5159 Context.getTypeDeclType(Record), TInfo, SC); 5160 5161 // Default-initialize the implicit variable. This initialization will be 5162 // trivial in almost all cases, except if a union member has an in-class 5163 // initializer: 5164 // union { int n = 0; }; 5165 ActOnUninitializedDecl(Anon); 5166 } 5167 Anon->setImplicit(); 5168 5169 // Mark this as an anonymous struct/union type. 5170 Record->setAnonymousStructOrUnion(true); 5171 5172 // Add the anonymous struct/union object to the current 5173 // context. We'll be referencing this object when we refer to one of 5174 // its members. 5175 Owner->addDecl(Anon); 5176 5177 // Inject the members of the anonymous struct/union into the owning 5178 // context and into the identifier resolver chain for name lookup 5179 // purposes. 5180 SmallVector<NamedDecl*, 2> Chain; 5181 Chain.push_back(Anon); 5182 5183 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5184 Invalid = true; 5185 5186 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5187 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5188 MangleNumberingContext *MCtx; 5189 Decl *ManglingContextDecl; 5190 std::tie(MCtx, ManglingContextDecl) = 5191 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5192 if (MCtx) { 5193 Context.setManglingNumber( 5194 NewVD, MCtx->getManglingNumber( 5195 NewVD, getMSManglingNumber(getLangOpts(), S))); 5196 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5197 } 5198 } 5199 } 5200 5201 if (Invalid) 5202 Anon->setInvalidDecl(); 5203 5204 return Anon; 5205 } 5206 5207 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5208 /// Microsoft C anonymous structure. 5209 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5210 /// Example: 5211 /// 5212 /// struct A { int a; }; 5213 /// struct B { struct A; int b; }; 5214 /// 5215 /// void foo() { 5216 /// B var; 5217 /// var.a = 3; 5218 /// } 5219 /// 5220 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5221 RecordDecl *Record) { 5222 assert(Record && "expected a record!"); 5223 5224 // Mock up a declarator. 5225 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 5226 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5227 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5228 5229 auto *ParentDecl = cast<RecordDecl>(CurContext); 5230 QualType RecTy = Context.getTypeDeclType(Record); 5231 5232 // Create a declaration for this anonymous struct. 5233 NamedDecl *Anon = 5234 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5235 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5236 /*BitWidth=*/nullptr, /*Mutable=*/false, 5237 /*InitStyle=*/ICIS_NoInit); 5238 Anon->setImplicit(); 5239 5240 // Add the anonymous struct object to the current context. 5241 CurContext->addDecl(Anon); 5242 5243 // Inject the members of the anonymous struct into the current 5244 // context and into the identifier resolver chain for name lookup 5245 // purposes. 5246 SmallVector<NamedDecl*, 2> Chain; 5247 Chain.push_back(Anon); 5248 5249 RecordDecl *RecordDef = Record->getDefinition(); 5250 if (RequireCompleteType(Anon->getLocation(), RecTy, 5251 diag::err_field_incomplete) || 5252 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5253 AS_none, Chain)) { 5254 Anon->setInvalidDecl(); 5255 ParentDecl->setInvalidDecl(); 5256 } 5257 5258 return Anon; 5259 } 5260 5261 /// GetNameForDeclarator - Determine the full declaration name for the 5262 /// given Declarator. 5263 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5264 return GetNameFromUnqualifiedId(D.getName()); 5265 } 5266 5267 /// Retrieves the declaration name from a parsed unqualified-id. 5268 DeclarationNameInfo 5269 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5270 DeclarationNameInfo NameInfo; 5271 NameInfo.setLoc(Name.StartLocation); 5272 5273 switch (Name.getKind()) { 5274 5275 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5276 case UnqualifiedIdKind::IK_Identifier: 5277 NameInfo.setName(Name.Identifier); 5278 return NameInfo; 5279 5280 case UnqualifiedIdKind::IK_DeductionGuideName: { 5281 // C++ [temp.deduct.guide]p3: 5282 // The simple-template-id shall name a class template specialization. 5283 // The template-name shall be the same identifier as the template-name 5284 // of the simple-template-id. 5285 // These together intend to imply that the template-name shall name a 5286 // class template. 5287 // FIXME: template<typename T> struct X {}; 5288 // template<typename T> using Y = X<T>; 5289 // Y(int) -> Y<int>; 5290 // satisfies these rules but does not name a class template. 5291 TemplateName TN = Name.TemplateName.get().get(); 5292 auto *Template = TN.getAsTemplateDecl(); 5293 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5294 Diag(Name.StartLocation, 5295 diag::err_deduction_guide_name_not_class_template) 5296 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5297 if (Template) 5298 Diag(Template->getLocation(), diag::note_template_decl_here); 5299 return DeclarationNameInfo(); 5300 } 5301 5302 NameInfo.setName( 5303 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5304 return NameInfo; 5305 } 5306 5307 case UnqualifiedIdKind::IK_OperatorFunctionId: 5308 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5309 Name.OperatorFunctionId.Operator)); 5310 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 5311 = Name.OperatorFunctionId.SymbolLocations[0]; 5312 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5313 = Name.EndLocation.getRawEncoding(); 5314 return NameInfo; 5315 5316 case UnqualifiedIdKind::IK_LiteralOperatorId: 5317 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5318 Name.Identifier)); 5319 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5320 return NameInfo; 5321 5322 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5323 TypeSourceInfo *TInfo; 5324 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5325 if (Ty.isNull()) 5326 return DeclarationNameInfo(); 5327 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5328 Context.getCanonicalType(Ty))); 5329 NameInfo.setNamedTypeInfo(TInfo); 5330 return NameInfo; 5331 } 5332 5333 case UnqualifiedIdKind::IK_ConstructorName: { 5334 TypeSourceInfo *TInfo; 5335 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5336 if (Ty.isNull()) 5337 return DeclarationNameInfo(); 5338 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5339 Context.getCanonicalType(Ty))); 5340 NameInfo.setNamedTypeInfo(TInfo); 5341 return NameInfo; 5342 } 5343 5344 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5345 // In well-formed code, we can only have a constructor 5346 // template-id that refers to the current context, so go there 5347 // to find the actual type being constructed. 5348 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5349 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5350 return DeclarationNameInfo(); 5351 5352 // Determine the type of the class being constructed. 5353 QualType CurClassType = Context.getTypeDeclType(CurClass); 5354 5355 // FIXME: Check two things: that the template-id names the same type as 5356 // CurClassType, and that the template-id does not occur when the name 5357 // was qualified. 5358 5359 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5360 Context.getCanonicalType(CurClassType))); 5361 // FIXME: should we retrieve TypeSourceInfo? 5362 NameInfo.setNamedTypeInfo(nullptr); 5363 return NameInfo; 5364 } 5365 5366 case UnqualifiedIdKind::IK_DestructorName: { 5367 TypeSourceInfo *TInfo; 5368 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5369 if (Ty.isNull()) 5370 return DeclarationNameInfo(); 5371 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5372 Context.getCanonicalType(Ty))); 5373 NameInfo.setNamedTypeInfo(TInfo); 5374 return NameInfo; 5375 } 5376 5377 case UnqualifiedIdKind::IK_TemplateId: { 5378 TemplateName TName = Name.TemplateId->Template.get(); 5379 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5380 return Context.getNameForTemplate(TName, TNameLoc); 5381 } 5382 5383 } // switch (Name.getKind()) 5384 5385 llvm_unreachable("Unknown name kind"); 5386 } 5387 5388 static QualType getCoreType(QualType Ty) { 5389 do { 5390 if (Ty->isPointerType() || Ty->isReferenceType()) 5391 Ty = Ty->getPointeeType(); 5392 else if (Ty->isArrayType()) 5393 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5394 else 5395 return Ty.withoutLocalFastQualifiers(); 5396 } while (true); 5397 } 5398 5399 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5400 /// and Definition have "nearly" matching parameters. This heuristic is 5401 /// used to improve diagnostics in the case where an out-of-line function 5402 /// definition doesn't match any declaration within the class or namespace. 5403 /// Also sets Params to the list of indices to the parameters that differ 5404 /// between the declaration and the definition. If hasSimilarParameters 5405 /// returns true and Params is empty, then all of the parameters match. 5406 static bool hasSimilarParameters(ASTContext &Context, 5407 FunctionDecl *Declaration, 5408 FunctionDecl *Definition, 5409 SmallVectorImpl<unsigned> &Params) { 5410 Params.clear(); 5411 if (Declaration->param_size() != Definition->param_size()) 5412 return false; 5413 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5414 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5415 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5416 5417 // The parameter types are identical 5418 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5419 continue; 5420 5421 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5422 QualType DefParamBaseTy = getCoreType(DefParamTy); 5423 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5424 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5425 5426 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5427 (DeclTyName && DeclTyName == DefTyName)) 5428 Params.push_back(Idx); 5429 else // The two parameters aren't even close 5430 return false; 5431 } 5432 5433 return true; 5434 } 5435 5436 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5437 /// declarator needs to be rebuilt in the current instantiation. 5438 /// Any bits of declarator which appear before the name are valid for 5439 /// consideration here. That's specifically the type in the decl spec 5440 /// and the base type in any member-pointer chunks. 5441 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5442 DeclarationName Name) { 5443 // The types we specifically need to rebuild are: 5444 // - typenames, typeofs, and decltypes 5445 // - types which will become injected class names 5446 // Of course, we also need to rebuild any type referencing such a 5447 // type. It's safest to just say "dependent", but we call out a 5448 // few cases here. 5449 5450 DeclSpec &DS = D.getMutableDeclSpec(); 5451 switch (DS.getTypeSpecType()) { 5452 case DeclSpec::TST_typename: 5453 case DeclSpec::TST_typeofType: 5454 case DeclSpec::TST_underlyingType: 5455 case DeclSpec::TST_atomic: { 5456 // Grab the type from the parser. 5457 TypeSourceInfo *TSI = nullptr; 5458 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5459 if (T.isNull() || !T->isDependentType()) break; 5460 5461 // Make sure there's a type source info. This isn't really much 5462 // of a waste; most dependent types should have type source info 5463 // attached already. 5464 if (!TSI) 5465 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5466 5467 // Rebuild the type in the current instantiation. 5468 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5469 if (!TSI) return true; 5470 5471 // Store the new type back in the decl spec. 5472 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5473 DS.UpdateTypeRep(LocType); 5474 break; 5475 } 5476 5477 case DeclSpec::TST_decltype: 5478 case DeclSpec::TST_typeofExpr: { 5479 Expr *E = DS.getRepAsExpr(); 5480 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5481 if (Result.isInvalid()) return true; 5482 DS.UpdateExprRep(Result.get()); 5483 break; 5484 } 5485 5486 default: 5487 // Nothing to do for these decl specs. 5488 break; 5489 } 5490 5491 // It doesn't matter what order we do this in. 5492 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5493 DeclaratorChunk &Chunk = D.getTypeObject(I); 5494 5495 // The only type information in the declarator which can come 5496 // before the declaration name is the base type of a member 5497 // pointer. 5498 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5499 continue; 5500 5501 // Rebuild the scope specifier in-place. 5502 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5503 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5504 return true; 5505 } 5506 5507 return false; 5508 } 5509 5510 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5511 D.setFunctionDefinitionKind(FDK_Declaration); 5512 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5513 5514 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5515 Dcl && Dcl->getDeclContext()->isFileContext()) 5516 Dcl->setTopLevelDeclInObjCContainer(); 5517 5518 if (getLangOpts().OpenCL) 5519 setCurrentOpenCLExtensionForDecl(Dcl); 5520 5521 return Dcl; 5522 } 5523 5524 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5525 /// If T is the name of a class, then each of the following shall have a 5526 /// name different from T: 5527 /// - every static data member of class T; 5528 /// - every member function of class T 5529 /// - every member of class T that is itself a type; 5530 /// \returns true if the declaration name violates these rules. 5531 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5532 DeclarationNameInfo NameInfo) { 5533 DeclarationName Name = NameInfo.getName(); 5534 5535 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5536 while (Record && Record->isAnonymousStructOrUnion()) 5537 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5538 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5539 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5540 return true; 5541 } 5542 5543 return false; 5544 } 5545 5546 /// Diagnose a declaration whose declarator-id has the given 5547 /// nested-name-specifier. 5548 /// 5549 /// \param SS The nested-name-specifier of the declarator-id. 5550 /// 5551 /// \param DC The declaration context to which the nested-name-specifier 5552 /// resolves. 5553 /// 5554 /// \param Name The name of the entity being declared. 5555 /// 5556 /// \param Loc The location of the name of the entity being declared. 5557 /// 5558 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5559 /// we're declaring an explicit / partial specialization / instantiation. 5560 /// 5561 /// \returns true if we cannot safely recover from this error, false otherwise. 5562 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5563 DeclarationName Name, 5564 SourceLocation Loc, bool IsTemplateId) { 5565 DeclContext *Cur = CurContext; 5566 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5567 Cur = Cur->getParent(); 5568 5569 // If the user provided a superfluous scope specifier that refers back to the 5570 // class in which the entity is already declared, diagnose and ignore it. 5571 // 5572 // class X { 5573 // void X::f(); 5574 // }; 5575 // 5576 // Note, it was once ill-formed to give redundant qualification in all 5577 // contexts, but that rule was removed by DR482. 5578 if (Cur->Equals(DC)) { 5579 if (Cur->isRecord()) { 5580 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5581 : diag::err_member_extra_qualification) 5582 << Name << FixItHint::CreateRemoval(SS.getRange()); 5583 SS.clear(); 5584 } else { 5585 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5586 } 5587 return false; 5588 } 5589 5590 // Check whether the qualifying scope encloses the scope of the original 5591 // declaration. For a template-id, we perform the checks in 5592 // CheckTemplateSpecializationScope. 5593 if (!Cur->Encloses(DC) && !IsTemplateId) { 5594 if (Cur->isRecord()) 5595 Diag(Loc, diag::err_member_qualification) 5596 << Name << SS.getRange(); 5597 else if (isa<TranslationUnitDecl>(DC)) 5598 Diag(Loc, diag::err_invalid_declarator_global_scope) 5599 << Name << SS.getRange(); 5600 else if (isa<FunctionDecl>(Cur)) 5601 Diag(Loc, diag::err_invalid_declarator_in_function) 5602 << Name << SS.getRange(); 5603 else if (isa<BlockDecl>(Cur)) 5604 Diag(Loc, diag::err_invalid_declarator_in_block) 5605 << Name << SS.getRange(); 5606 else 5607 Diag(Loc, diag::err_invalid_declarator_scope) 5608 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5609 5610 return true; 5611 } 5612 5613 if (Cur->isRecord()) { 5614 // Cannot qualify members within a class. 5615 Diag(Loc, diag::err_member_qualification) 5616 << Name << SS.getRange(); 5617 SS.clear(); 5618 5619 // C++ constructors and destructors with incorrect scopes can break 5620 // our AST invariants by having the wrong underlying types. If 5621 // that's the case, then drop this declaration entirely. 5622 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5623 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5624 !Context.hasSameType(Name.getCXXNameType(), 5625 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5626 return true; 5627 5628 return false; 5629 } 5630 5631 // C++11 [dcl.meaning]p1: 5632 // [...] "The nested-name-specifier of the qualified declarator-id shall 5633 // not begin with a decltype-specifer" 5634 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5635 while (SpecLoc.getPrefix()) 5636 SpecLoc = SpecLoc.getPrefix(); 5637 if (dyn_cast_or_null<DecltypeType>( 5638 SpecLoc.getNestedNameSpecifier()->getAsType())) 5639 Diag(Loc, diag::err_decltype_in_declarator) 5640 << SpecLoc.getTypeLoc().getSourceRange(); 5641 5642 return false; 5643 } 5644 5645 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5646 MultiTemplateParamsArg TemplateParamLists) { 5647 // TODO: consider using NameInfo for diagnostic. 5648 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5649 DeclarationName Name = NameInfo.getName(); 5650 5651 // All of these full declarators require an identifier. If it doesn't have 5652 // one, the ParsedFreeStandingDeclSpec action should be used. 5653 if (D.isDecompositionDeclarator()) { 5654 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5655 } else if (!Name) { 5656 if (!D.isInvalidType()) // Reject this if we think it is valid. 5657 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5658 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5659 return nullptr; 5660 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5661 return nullptr; 5662 5663 // The scope passed in may not be a decl scope. Zip up the scope tree until 5664 // we find one that is. 5665 while ((S->getFlags() & Scope::DeclScope) == 0 || 5666 (S->getFlags() & Scope::TemplateParamScope) != 0) 5667 S = S->getParent(); 5668 5669 DeclContext *DC = CurContext; 5670 if (D.getCXXScopeSpec().isInvalid()) 5671 D.setInvalidType(); 5672 else if (D.getCXXScopeSpec().isSet()) { 5673 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5674 UPPC_DeclarationQualifier)) 5675 return nullptr; 5676 5677 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5678 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5679 if (!DC || isa<EnumDecl>(DC)) { 5680 // If we could not compute the declaration context, it's because the 5681 // declaration context is dependent but does not refer to a class, 5682 // class template, or class template partial specialization. Complain 5683 // and return early, to avoid the coming semantic disaster. 5684 Diag(D.getIdentifierLoc(), 5685 diag::err_template_qualified_declarator_no_match) 5686 << D.getCXXScopeSpec().getScopeRep() 5687 << D.getCXXScopeSpec().getRange(); 5688 return nullptr; 5689 } 5690 bool IsDependentContext = DC->isDependentContext(); 5691 5692 if (!IsDependentContext && 5693 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5694 return nullptr; 5695 5696 // If a class is incomplete, do not parse entities inside it. 5697 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5698 Diag(D.getIdentifierLoc(), 5699 diag::err_member_def_undefined_record) 5700 << Name << DC << D.getCXXScopeSpec().getRange(); 5701 return nullptr; 5702 } 5703 if (!D.getDeclSpec().isFriendSpecified()) { 5704 if (diagnoseQualifiedDeclaration( 5705 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5706 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5707 if (DC->isRecord()) 5708 return nullptr; 5709 5710 D.setInvalidType(); 5711 } 5712 } 5713 5714 // Check whether we need to rebuild the type of the given 5715 // declaration in the current instantiation. 5716 if (EnteringContext && IsDependentContext && 5717 TemplateParamLists.size() != 0) { 5718 ContextRAII SavedContext(*this, DC); 5719 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5720 D.setInvalidType(); 5721 } 5722 } 5723 5724 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5725 QualType R = TInfo->getType(); 5726 5727 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5728 UPPC_DeclarationType)) 5729 D.setInvalidType(); 5730 5731 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5732 forRedeclarationInCurContext()); 5733 5734 // See if this is a redefinition of a variable in the same scope. 5735 if (!D.getCXXScopeSpec().isSet()) { 5736 bool IsLinkageLookup = false; 5737 bool CreateBuiltins = false; 5738 5739 // If the declaration we're planning to build will be a function 5740 // or object with linkage, then look for another declaration with 5741 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5742 // 5743 // If the declaration we're planning to build will be declared with 5744 // external linkage in the translation unit, create any builtin with 5745 // the same name. 5746 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5747 /* Do nothing*/; 5748 else if (CurContext->isFunctionOrMethod() && 5749 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5750 R->isFunctionType())) { 5751 IsLinkageLookup = true; 5752 CreateBuiltins = 5753 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5754 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5755 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5756 CreateBuiltins = true; 5757 5758 if (IsLinkageLookup) { 5759 Previous.clear(LookupRedeclarationWithLinkage); 5760 Previous.setRedeclarationKind(ForExternalRedeclaration); 5761 } 5762 5763 LookupName(Previous, S, CreateBuiltins); 5764 } else { // Something like "int foo::x;" 5765 LookupQualifiedName(Previous, DC); 5766 5767 // C++ [dcl.meaning]p1: 5768 // When the declarator-id is qualified, the declaration shall refer to a 5769 // previously declared member of the class or namespace to which the 5770 // qualifier refers (or, in the case of a namespace, of an element of the 5771 // inline namespace set of that namespace (7.3.1)) or to a specialization 5772 // thereof; [...] 5773 // 5774 // Note that we already checked the context above, and that we do not have 5775 // enough information to make sure that Previous contains the declaration 5776 // we want to match. For example, given: 5777 // 5778 // class X { 5779 // void f(); 5780 // void f(float); 5781 // }; 5782 // 5783 // void X::f(int) { } // ill-formed 5784 // 5785 // In this case, Previous will point to the overload set 5786 // containing the two f's declared in X, but neither of them 5787 // matches. 5788 5789 // C++ [dcl.meaning]p1: 5790 // [...] the member shall not merely have been introduced by a 5791 // using-declaration in the scope of the class or namespace nominated by 5792 // the nested-name-specifier of the declarator-id. 5793 RemoveUsingDecls(Previous); 5794 } 5795 5796 if (Previous.isSingleResult() && 5797 Previous.getFoundDecl()->isTemplateParameter()) { 5798 // Maybe we will complain about the shadowed template parameter. 5799 if (!D.isInvalidType()) 5800 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5801 Previous.getFoundDecl()); 5802 5803 // Just pretend that we didn't see the previous declaration. 5804 Previous.clear(); 5805 } 5806 5807 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5808 // Forget that the previous declaration is the injected-class-name. 5809 Previous.clear(); 5810 5811 // In C++, the previous declaration we find might be a tag type 5812 // (class or enum). In this case, the new declaration will hide the 5813 // tag type. Note that this applies to functions, function templates, and 5814 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5815 if (Previous.isSingleTagDecl() && 5816 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5817 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5818 Previous.clear(); 5819 5820 // Check that there are no default arguments other than in the parameters 5821 // of a function declaration (C++ only). 5822 if (getLangOpts().CPlusPlus) 5823 CheckExtraCXXDefaultArguments(D); 5824 5825 NamedDecl *New; 5826 5827 bool AddToScope = true; 5828 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5829 if (TemplateParamLists.size()) { 5830 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5831 return nullptr; 5832 } 5833 5834 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5835 } else if (R->isFunctionType()) { 5836 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5837 TemplateParamLists, 5838 AddToScope); 5839 } else { 5840 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5841 AddToScope); 5842 } 5843 5844 if (!New) 5845 return nullptr; 5846 5847 // If this has an identifier and is not a function template specialization, 5848 // add it to the scope stack. 5849 if (New->getDeclName() && AddToScope) 5850 PushOnScopeChains(New, S); 5851 5852 if (isInOpenMPDeclareTargetContext()) 5853 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5854 5855 return New; 5856 } 5857 5858 /// Helper method to turn variable array types into constant array 5859 /// types in certain situations which would otherwise be errors (for 5860 /// GCC compatibility). 5861 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5862 ASTContext &Context, 5863 bool &SizeIsNegative, 5864 llvm::APSInt &Oversized) { 5865 // This method tries to turn a variable array into a constant 5866 // array even when the size isn't an ICE. This is necessary 5867 // for compatibility with code that depends on gcc's buggy 5868 // constant expression folding, like struct {char x[(int)(char*)2];} 5869 SizeIsNegative = false; 5870 Oversized = 0; 5871 5872 if (T->isDependentType()) 5873 return QualType(); 5874 5875 QualifierCollector Qs; 5876 const Type *Ty = Qs.strip(T); 5877 5878 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5879 QualType Pointee = PTy->getPointeeType(); 5880 QualType FixedType = 5881 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5882 Oversized); 5883 if (FixedType.isNull()) return FixedType; 5884 FixedType = Context.getPointerType(FixedType); 5885 return Qs.apply(Context, FixedType); 5886 } 5887 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5888 QualType Inner = PTy->getInnerType(); 5889 QualType FixedType = 5890 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5891 Oversized); 5892 if (FixedType.isNull()) return FixedType; 5893 FixedType = Context.getParenType(FixedType); 5894 return Qs.apply(Context, FixedType); 5895 } 5896 5897 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5898 if (!VLATy) 5899 return QualType(); 5900 // FIXME: We should probably handle this case 5901 if (VLATy->getElementType()->isVariablyModifiedType()) 5902 return QualType(); 5903 5904 Expr::EvalResult Result; 5905 if (!VLATy->getSizeExpr() || 5906 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5907 return QualType(); 5908 5909 llvm::APSInt Res = Result.Val.getInt(); 5910 5911 // Check whether the array size is negative. 5912 if (Res.isSigned() && Res.isNegative()) { 5913 SizeIsNegative = true; 5914 return QualType(); 5915 } 5916 5917 // Check whether the array is too large to be addressed. 5918 unsigned ActiveSizeBits 5919 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5920 Res); 5921 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5922 Oversized = Res; 5923 return QualType(); 5924 } 5925 5926 return Context.getConstantArrayType( 5927 VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 5928 } 5929 5930 static void 5931 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5932 SrcTL = SrcTL.getUnqualifiedLoc(); 5933 DstTL = DstTL.getUnqualifiedLoc(); 5934 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5935 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5936 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5937 DstPTL.getPointeeLoc()); 5938 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5939 return; 5940 } 5941 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5942 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5943 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5944 DstPTL.getInnerLoc()); 5945 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5946 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5947 return; 5948 } 5949 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5950 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5951 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5952 TypeLoc DstElemTL = DstATL.getElementLoc(); 5953 DstElemTL.initializeFullCopy(SrcElemTL); 5954 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5955 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5956 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5957 } 5958 5959 /// Helper method to turn variable array types into constant array 5960 /// types in certain situations which would otherwise be errors (for 5961 /// GCC compatibility). 5962 static TypeSourceInfo* 5963 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5964 ASTContext &Context, 5965 bool &SizeIsNegative, 5966 llvm::APSInt &Oversized) { 5967 QualType FixedTy 5968 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5969 SizeIsNegative, Oversized); 5970 if (FixedTy.isNull()) 5971 return nullptr; 5972 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5973 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5974 FixedTInfo->getTypeLoc()); 5975 return FixedTInfo; 5976 } 5977 5978 /// Register the given locally-scoped extern "C" declaration so 5979 /// that it can be found later for redeclarations. We include any extern "C" 5980 /// declaration that is not visible in the translation unit here, not just 5981 /// function-scope declarations. 5982 void 5983 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5984 if (!getLangOpts().CPlusPlus && 5985 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5986 // Don't need to track declarations in the TU in C. 5987 return; 5988 5989 // Note that we have a locally-scoped external with this name. 5990 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5991 } 5992 5993 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5994 // FIXME: We can have multiple results via __attribute__((overloadable)). 5995 auto Result = Context.getExternCContextDecl()->lookup(Name); 5996 return Result.empty() ? nullptr : *Result.begin(); 5997 } 5998 5999 /// Diagnose function specifiers on a declaration of an identifier that 6000 /// does not identify a function. 6001 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6002 // FIXME: We should probably indicate the identifier in question to avoid 6003 // confusion for constructs like "virtual int a(), b;" 6004 if (DS.isVirtualSpecified()) 6005 Diag(DS.getVirtualSpecLoc(), 6006 diag::err_virtual_non_function); 6007 6008 if (DS.hasExplicitSpecifier()) 6009 Diag(DS.getExplicitSpecLoc(), 6010 diag::err_explicit_non_function); 6011 6012 if (DS.isNoreturnSpecified()) 6013 Diag(DS.getNoreturnSpecLoc(), 6014 diag::err_noreturn_non_function); 6015 } 6016 6017 NamedDecl* 6018 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6019 TypeSourceInfo *TInfo, LookupResult &Previous) { 6020 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6021 if (D.getCXXScopeSpec().isSet()) { 6022 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6023 << D.getCXXScopeSpec().getRange(); 6024 D.setInvalidType(); 6025 // Pretend we didn't see the scope specifier. 6026 DC = CurContext; 6027 Previous.clear(); 6028 } 6029 6030 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6031 6032 if (D.getDeclSpec().isInlineSpecified()) 6033 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6034 << getLangOpts().CPlusPlus17; 6035 if (D.getDeclSpec().hasConstexprSpecifier()) 6036 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6037 << 1 << D.getDeclSpec().getConstexprSpecifier(); 6038 6039 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6040 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6041 Diag(D.getName().StartLocation, 6042 diag::err_deduction_guide_invalid_specifier) 6043 << "typedef"; 6044 else 6045 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6046 << D.getName().getSourceRange(); 6047 return nullptr; 6048 } 6049 6050 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6051 if (!NewTD) return nullptr; 6052 6053 // Handle attributes prior to checking for duplicates in MergeVarDecl 6054 ProcessDeclAttributes(S, NewTD, D); 6055 6056 CheckTypedefForVariablyModifiedType(S, NewTD); 6057 6058 bool Redeclaration = D.isRedeclaration(); 6059 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6060 D.setRedeclaration(Redeclaration); 6061 return ND; 6062 } 6063 6064 void 6065 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6066 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6067 // then it shall have block scope. 6068 // Note that variably modified types must be fixed before merging the decl so 6069 // that redeclarations will match. 6070 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6071 QualType T = TInfo->getType(); 6072 if (T->isVariablyModifiedType()) { 6073 setFunctionHasBranchProtectedScope(); 6074 6075 if (S->getFnParent() == nullptr) { 6076 bool SizeIsNegative; 6077 llvm::APSInt Oversized; 6078 TypeSourceInfo *FixedTInfo = 6079 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6080 SizeIsNegative, 6081 Oversized); 6082 if (FixedTInfo) { 6083 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 6084 NewTD->setTypeSourceInfo(FixedTInfo); 6085 } else { 6086 if (SizeIsNegative) 6087 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6088 else if (T->isVariableArrayType()) 6089 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6090 else if (Oversized.getBoolValue()) 6091 Diag(NewTD->getLocation(), diag::err_array_too_large) 6092 << Oversized.toString(10); 6093 else 6094 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6095 NewTD->setInvalidDecl(); 6096 } 6097 } 6098 } 6099 } 6100 6101 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6102 /// declares a typedef-name, either using the 'typedef' type specifier or via 6103 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6104 NamedDecl* 6105 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6106 LookupResult &Previous, bool &Redeclaration) { 6107 6108 // Find the shadowed declaration before filtering for scope. 6109 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6110 6111 // Merge the decl with the existing one if appropriate. If the decl is 6112 // in an outer scope, it isn't the same thing. 6113 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6114 /*AllowInlineNamespace*/false); 6115 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6116 if (!Previous.empty()) { 6117 Redeclaration = true; 6118 MergeTypedefNameDecl(S, NewTD, Previous); 6119 } else { 6120 inferGslPointerAttribute(NewTD); 6121 } 6122 6123 if (ShadowedDecl && !Redeclaration) 6124 CheckShadow(NewTD, ShadowedDecl, Previous); 6125 6126 // If this is the C FILE type, notify the AST context. 6127 if (IdentifierInfo *II = NewTD->getIdentifier()) 6128 if (!NewTD->isInvalidDecl() && 6129 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6130 if (II->isStr("FILE")) 6131 Context.setFILEDecl(NewTD); 6132 else if (II->isStr("jmp_buf")) 6133 Context.setjmp_bufDecl(NewTD); 6134 else if (II->isStr("sigjmp_buf")) 6135 Context.setsigjmp_bufDecl(NewTD); 6136 else if (II->isStr("ucontext_t")) 6137 Context.setucontext_tDecl(NewTD); 6138 } 6139 6140 return NewTD; 6141 } 6142 6143 /// Determines whether the given declaration is an out-of-scope 6144 /// previous declaration. 6145 /// 6146 /// This routine should be invoked when name lookup has found a 6147 /// previous declaration (PrevDecl) that is not in the scope where a 6148 /// new declaration by the same name is being introduced. If the new 6149 /// declaration occurs in a local scope, previous declarations with 6150 /// linkage may still be considered previous declarations (C99 6151 /// 6.2.2p4-5, C++ [basic.link]p6). 6152 /// 6153 /// \param PrevDecl the previous declaration found by name 6154 /// lookup 6155 /// 6156 /// \param DC the context in which the new declaration is being 6157 /// declared. 6158 /// 6159 /// \returns true if PrevDecl is an out-of-scope previous declaration 6160 /// for a new delcaration with the same name. 6161 static bool 6162 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6163 ASTContext &Context) { 6164 if (!PrevDecl) 6165 return false; 6166 6167 if (!PrevDecl->hasLinkage()) 6168 return false; 6169 6170 if (Context.getLangOpts().CPlusPlus) { 6171 // C++ [basic.link]p6: 6172 // If there is a visible declaration of an entity with linkage 6173 // having the same name and type, ignoring entities declared 6174 // outside the innermost enclosing namespace scope, the block 6175 // scope declaration declares that same entity and receives the 6176 // linkage of the previous declaration. 6177 DeclContext *OuterContext = DC->getRedeclContext(); 6178 if (!OuterContext->isFunctionOrMethod()) 6179 // This rule only applies to block-scope declarations. 6180 return false; 6181 6182 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6183 if (PrevOuterContext->isRecord()) 6184 // We found a member function: ignore it. 6185 return false; 6186 6187 // Find the innermost enclosing namespace for the new and 6188 // previous declarations. 6189 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6190 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6191 6192 // The previous declaration is in a different namespace, so it 6193 // isn't the same function. 6194 if (!OuterContext->Equals(PrevOuterContext)) 6195 return false; 6196 } 6197 6198 return true; 6199 } 6200 6201 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6202 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6203 if (!SS.isSet()) return; 6204 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6205 } 6206 6207 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6208 QualType type = decl->getType(); 6209 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6210 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6211 // Various kinds of declaration aren't allowed to be __autoreleasing. 6212 unsigned kind = -1U; 6213 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6214 if (var->hasAttr<BlocksAttr>()) 6215 kind = 0; // __block 6216 else if (!var->hasLocalStorage()) 6217 kind = 1; // global 6218 } else if (isa<ObjCIvarDecl>(decl)) { 6219 kind = 3; // ivar 6220 } else if (isa<FieldDecl>(decl)) { 6221 kind = 2; // field 6222 } 6223 6224 if (kind != -1U) { 6225 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6226 << kind; 6227 } 6228 } else if (lifetime == Qualifiers::OCL_None) { 6229 // Try to infer lifetime. 6230 if (!type->isObjCLifetimeType()) 6231 return false; 6232 6233 lifetime = type->getObjCARCImplicitLifetime(); 6234 type = Context.getLifetimeQualifiedType(type, lifetime); 6235 decl->setType(type); 6236 } 6237 6238 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6239 // Thread-local variables cannot have lifetime. 6240 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6241 var->getTLSKind()) { 6242 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6243 << var->getType(); 6244 return true; 6245 } 6246 } 6247 6248 return false; 6249 } 6250 6251 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6252 if (Decl->getType().hasAddressSpace()) 6253 return; 6254 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6255 QualType Type = Var->getType(); 6256 if (Type->isSamplerT() || Type->isVoidType()) 6257 return; 6258 LangAS ImplAS = LangAS::opencl_private; 6259 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6260 Var->hasGlobalStorage()) 6261 ImplAS = LangAS::opencl_global; 6262 // If the original type from a decayed type is an array type and that array 6263 // type has no address space yet, deduce it now. 6264 if (auto DT = dyn_cast<DecayedType>(Type)) { 6265 auto OrigTy = DT->getOriginalType(); 6266 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6267 // Add the address space to the original array type and then propagate 6268 // that to the element type through `getAsArrayType`. 6269 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6270 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6271 // Re-generate the decayed type. 6272 Type = Context.getDecayedType(OrigTy); 6273 } 6274 } 6275 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6276 // Apply any qualifiers (including address space) from the array type to 6277 // the element type. This implements C99 6.7.3p8: "If the specification of 6278 // an array type includes any type qualifiers, the element type is so 6279 // qualified, not the array type." 6280 if (Type->isArrayType()) 6281 Type = QualType(Context.getAsArrayType(Type), 0); 6282 Decl->setType(Type); 6283 } 6284 } 6285 6286 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6287 // Ensure that an auto decl is deduced otherwise the checks below might cache 6288 // the wrong linkage. 6289 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6290 6291 // 'weak' only applies to declarations with external linkage. 6292 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6293 if (!ND.isExternallyVisible()) { 6294 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6295 ND.dropAttr<WeakAttr>(); 6296 } 6297 } 6298 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6299 if (ND.isExternallyVisible()) { 6300 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6301 ND.dropAttr<WeakRefAttr>(); 6302 ND.dropAttr<AliasAttr>(); 6303 } 6304 } 6305 6306 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6307 if (VD->hasInit()) { 6308 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6309 assert(VD->isThisDeclarationADefinition() && 6310 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6311 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6312 VD->dropAttr<AliasAttr>(); 6313 } 6314 } 6315 } 6316 6317 // 'selectany' only applies to externally visible variable declarations. 6318 // It does not apply to functions. 6319 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6320 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6321 S.Diag(Attr->getLocation(), 6322 diag::err_attribute_selectany_non_extern_data); 6323 ND.dropAttr<SelectAnyAttr>(); 6324 } 6325 } 6326 6327 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6328 auto *VD = dyn_cast<VarDecl>(&ND); 6329 bool IsAnonymousNS = false; 6330 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6331 if (VD) { 6332 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6333 while (NS && !IsAnonymousNS) { 6334 IsAnonymousNS = NS->isAnonymousNamespace(); 6335 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6336 } 6337 } 6338 // dll attributes require external linkage. Static locals may have external 6339 // linkage but still cannot be explicitly imported or exported. 6340 // In Microsoft mode, a variable defined in anonymous namespace must have 6341 // external linkage in order to be exported. 6342 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6343 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6344 (!AnonNSInMicrosoftMode && 6345 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6346 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6347 << &ND << Attr; 6348 ND.setInvalidDecl(); 6349 } 6350 } 6351 6352 // Virtual functions cannot be marked as 'notail'. 6353 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6354 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6355 if (MD->isVirtual()) { 6356 S.Diag(ND.getLocation(), 6357 diag::err_invalid_attribute_on_virtual_function) 6358 << Attr; 6359 ND.dropAttr<NotTailCalledAttr>(); 6360 } 6361 6362 // Check the attributes on the function type, if any. 6363 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6364 // Don't declare this variable in the second operand of the for-statement; 6365 // GCC miscompiles that by ending its lifetime before evaluating the 6366 // third operand. See gcc.gnu.org/PR86769. 6367 AttributedTypeLoc ATL; 6368 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6369 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6370 TL = ATL.getModifiedLoc()) { 6371 // The [[lifetimebound]] attribute can be applied to the implicit object 6372 // parameter of a non-static member function (other than a ctor or dtor) 6373 // by applying it to the function type. 6374 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6375 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6376 if (!MD || MD->isStatic()) { 6377 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6378 << !MD << A->getRange(); 6379 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6380 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6381 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6382 } 6383 } 6384 } 6385 } 6386 } 6387 6388 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6389 NamedDecl *NewDecl, 6390 bool IsSpecialization, 6391 bool IsDefinition) { 6392 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6393 return; 6394 6395 bool IsTemplate = false; 6396 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6397 OldDecl = OldTD->getTemplatedDecl(); 6398 IsTemplate = true; 6399 if (!IsSpecialization) 6400 IsDefinition = false; 6401 } 6402 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6403 NewDecl = NewTD->getTemplatedDecl(); 6404 IsTemplate = true; 6405 } 6406 6407 if (!OldDecl || !NewDecl) 6408 return; 6409 6410 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6411 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6412 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6413 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6414 6415 // dllimport and dllexport are inheritable attributes so we have to exclude 6416 // inherited attribute instances. 6417 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6418 (NewExportAttr && !NewExportAttr->isInherited()); 6419 6420 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6421 // the only exception being explicit specializations. 6422 // Implicitly generated declarations are also excluded for now because there 6423 // is no other way to switch these to use dllimport or dllexport. 6424 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6425 6426 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6427 // Allow with a warning for free functions and global variables. 6428 bool JustWarn = false; 6429 if (!OldDecl->isCXXClassMember()) { 6430 auto *VD = dyn_cast<VarDecl>(OldDecl); 6431 if (VD && !VD->getDescribedVarTemplate()) 6432 JustWarn = true; 6433 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6434 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6435 JustWarn = true; 6436 } 6437 6438 // We cannot change a declaration that's been used because IR has already 6439 // been emitted. Dllimported functions will still work though (modulo 6440 // address equality) as they can use the thunk. 6441 if (OldDecl->isUsed()) 6442 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6443 JustWarn = false; 6444 6445 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6446 : diag::err_attribute_dll_redeclaration; 6447 S.Diag(NewDecl->getLocation(), DiagID) 6448 << NewDecl 6449 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6450 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6451 if (!JustWarn) { 6452 NewDecl->setInvalidDecl(); 6453 return; 6454 } 6455 } 6456 6457 // A redeclaration is not allowed to drop a dllimport attribute, the only 6458 // exceptions being inline function definitions (except for function 6459 // templates), local extern declarations, qualified friend declarations or 6460 // special MSVC extension: in the last case, the declaration is treated as if 6461 // it were marked dllexport. 6462 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6463 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6464 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6465 // Ignore static data because out-of-line definitions are diagnosed 6466 // separately. 6467 IsStaticDataMember = VD->isStaticDataMember(); 6468 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6469 VarDecl::DeclarationOnly; 6470 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6471 IsInline = FD->isInlined(); 6472 IsQualifiedFriend = FD->getQualifier() && 6473 FD->getFriendObjectKind() == Decl::FOK_Declared; 6474 } 6475 6476 if (OldImportAttr && !HasNewAttr && 6477 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6478 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6479 if (IsMicrosoft && IsDefinition) { 6480 S.Diag(NewDecl->getLocation(), 6481 diag::warn_redeclaration_without_import_attribute) 6482 << NewDecl; 6483 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6484 NewDecl->dropAttr<DLLImportAttr>(); 6485 NewDecl->addAttr( 6486 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6487 } else { 6488 S.Diag(NewDecl->getLocation(), 6489 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6490 << NewDecl << OldImportAttr; 6491 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6492 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6493 OldDecl->dropAttr<DLLImportAttr>(); 6494 NewDecl->dropAttr<DLLImportAttr>(); 6495 } 6496 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6497 // In MinGW, seeing a function declared inline drops the dllimport 6498 // attribute. 6499 OldDecl->dropAttr<DLLImportAttr>(); 6500 NewDecl->dropAttr<DLLImportAttr>(); 6501 S.Diag(NewDecl->getLocation(), 6502 diag::warn_dllimport_dropped_from_inline_function) 6503 << NewDecl << OldImportAttr; 6504 } 6505 6506 // A specialization of a class template member function is processed here 6507 // since it's a redeclaration. If the parent class is dllexport, the 6508 // specialization inherits that attribute. This doesn't happen automatically 6509 // since the parent class isn't instantiated until later. 6510 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6511 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6512 !NewImportAttr && !NewExportAttr) { 6513 if (const DLLExportAttr *ParentExportAttr = 6514 MD->getParent()->getAttr<DLLExportAttr>()) { 6515 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6516 NewAttr->setInherited(true); 6517 NewDecl->addAttr(NewAttr); 6518 } 6519 } 6520 } 6521 } 6522 6523 /// Given that we are within the definition of the given function, 6524 /// will that definition behave like C99's 'inline', where the 6525 /// definition is discarded except for optimization purposes? 6526 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6527 // Try to avoid calling GetGVALinkageForFunction. 6528 6529 // All cases of this require the 'inline' keyword. 6530 if (!FD->isInlined()) return false; 6531 6532 // This is only possible in C++ with the gnu_inline attribute. 6533 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6534 return false; 6535 6536 // Okay, go ahead and call the relatively-more-expensive function. 6537 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6538 } 6539 6540 /// Determine whether a variable is extern "C" prior to attaching 6541 /// an initializer. We can't just call isExternC() here, because that 6542 /// will also compute and cache whether the declaration is externally 6543 /// visible, which might change when we attach the initializer. 6544 /// 6545 /// This can only be used if the declaration is known to not be a 6546 /// redeclaration of an internal linkage declaration. 6547 /// 6548 /// For instance: 6549 /// 6550 /// auto x = []{}; 6551 /// 6552 /// Attaching the initializer here makes this declaration not externally 6553 /// visible, because its type has internal linkage. 6554 /// 6555 /// FIXME: This is a hack. 6556 template<typename T> 6557 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6558 if (S.getLangOpts().CPlusPlus) { 6559 // In C++, the overloadable attribute negates the effects of extern "C". 6560 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6561 return false; 6562 6563 // So do CUDA's host/device attributes. 6564 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6565 D->template hasAttr<CUDAHostAttr>())) 6566 return false; 6567 } 6568 return D->isExternC(); 6569 } 6570 6571 static bool shouldConsiderLinkage(const VarDecl *VD) { 6572 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6573 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6574 isa<OMPDeclareMapperDecl>(DC)) 6575 return VD->hasExternalStorage(); 6576 if (DC->isFileContext()) 6577 return true; 6578 if (DC->isRecord()) 6579 return false; 6580 if (isa<RequiresExprBodyDecl>(DC)) 6581 return false; 6582 llvm_unreachable("Unexpected context"); 6583 } 6584 6585 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6586 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6587 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6588 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6589 return true; 6590 if (DC->isRecord()) 6591 return false; 6592 llvm_unreachable("Unexpected context"); 6593 } 6594 6595 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6596 ParsedAttr::Kind Kind) { 6597 // Check decl attributes on the DeclSpec. 6598 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6599 return true; 6600 6601 // Walk the declarator structure, checking decl attributes that were in a type 6602 // position to the decl itself. 6603 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6604 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6605 return true; 6606 } 6607 6608 // Finally, check attributes on the decl itself. 6609 return PD.getAttributes().hasAttribute(Kind); 6610 } 6611 6612 /// Adjust the \c DeclContext for a function or variable that might be a 6613 /// function-local external declaration. 6614 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6615 if (!DC->isFunctionOrMethod()) 6616 return false; 6617 6618 // If this is a local extern function or variable declared within a function 6619 // template, don't add it into the enclosing namespace scope until it is 6620 // instantiated; it might have a dependent type right now. 6621 if (DC->isDependentContext()) 6622 return true; 6623 6624 // C++11 [basic.link]p7: 6625 // When a block scope declaration of an entity with linkage is not found to 6626 // refer to some other declaration, then that entity is a member of the 6627 // innermost enclosing namespace. 6628 // 6629 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6630 // semantically-enclosing namespace, not a lexically-enclosing one. 6631 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6632 DC = DC->getParent(); 6633 return true; 6634 } 6635 6636 /// Returns true if given declaration has external C language linkage. 6637 static bool isDeclExternC(const Decl *D) { 6638 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6639 return FD->isExternC(); 6640 if (const auto *VD = dyn_cast<VarDecl>(D)) 6641 return VD->isExternC(); 6642 6643 llvm_unreachable("Unknown type of decl!"); 6644 } 6645 /// Returns true if there hasn't been any invalid type diagnosed. 6646 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, 6647 DeclContext *DC, QualType R) { 6648 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6649 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6650 // argument. 6651 if (R->isImageType() || R->isPipeType()) { 6652 Se.Diag(D.getIdentifierLoc(), 6653 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6654 << R; 6655 D.setInvalidType(); 6656 return false; 6657 } 6658 6659 // OpenCL v1.2 s6.9.r: 6660 // The event type cannot be used to declare a program scope variable. 6661 // OpenCL v2.0 s6.9.q: 6662 // The clk_event_t and reserve_id_t types cannot be declared in program 6663 // scope. 6664 if (NULL == S->getParent()) { 6665 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6666 Se.Diag(D.getIdentifierLoc(), 6667 diag::err_invalid_type_for_program_scope_var) 6668 << R; 6669 D.setInvalidType(); 6670 return false; 6671 } 6672 } 6673 6674 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6675 QualType NR = R; 6676 while (NR->isPointerType()) { 6677 if (NR->isFunctionPointerType()) { 6678 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6679 D.setInvalidType(); 6680 return false; 6681 } 6682 NR = NR->getPointeeType(); 6683 } 6684 6685 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6686 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6687 // half array type (unless the cl_khr_fp16 extension is enabled). 6688 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6689 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6690 D.setInvalidType(); 6691 return false; 6692 } 6693 } 6694 6695 // OpenCL v1.2 s6.9.r: 6696 // The event type cannot be used with the __local, __constant and __global 6697 // address space qualifiers. 6698 if (R->isEventT()) { 6699 if (R.getAddressSpace() != LangAS::opencl_private) { 6700 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6701 D.setInvalidType(); 6702 return false; 6703 } 6704 } 6705 6706 // C++ for OpenCL does not allow the thread_local storage qualifier. 6707 // OpenCL C does not support thread_local either, and 6708 // also reject all other thread storage class specifiers. 6709 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6710 if (TSC != TSCS_unspecified) { 6711 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; 6712 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6713 diag::err_opencl_unknown_type_specifier) 6714 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() 6715 << DeclSpec::getSpecifierName(TSC) << 1; 6716 D.setInvalidType(); 6717 return false; 6718 } 6719 6720 if (R->isSamplerT()) { 6721 // OpenCL v1.2 s6.9.b p4: 6722 // The sampler type cannot be used with the __local and __global address 6723 // space qualifiers. 6724 if (R.getAddressSpace() == LangAS::opencl_local || 6725 R.getAddressSpace() == LangAS::opencl_global) { 6726 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6727 D.setInvalidType(); 6728 } 6729 6730 // OpenCL v1.2 s6.12.14.1: 6731 // A global sampler must be declared with either the constant address 6732 // space qualifier or with the const qualifier. 6733 if (DC->isTranslationUnit() && 6734 !(R.getAddressSpace() == LangAS::opencl_constant || 6735 R.isConstQualified())) { 6736 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6737 D.setInvalidType(); 6738 } 6739 if (D.isInvalidType()) 6740 return false; 6741 } 6742 return true; 6743 } 6744 6745 NamedDecl *Sema::ActOnVariableDeclarator( 6746 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6747 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6748 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6749 QualType R = TInfo->getType(); 6750 DeclarationName Name = GetNameForDeclarator(D).getName(); 6751 6752 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6753 6754 if (D.isDecompositionDeclarator()) { 6755 // Take the name of the first declarator as our name for diagnostic 6756 // purposes. 6757 auto &Decomp = D.getDecompositionDeclarator(); 6758 if (!Decomp.bindings().empty()) { 6759 II = Decomp.bindings()[0].Name; 6760 Name = II; 6761 } 6762 } else if (!II) { 6763 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6764 return nullptr; 6765 } 6766 6767 6768 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6769 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6770 6771 // dllimport globals without explicit storage class are treated as extern. We 6772 // have to change the storage class this early to get the right DeclContext. 6773 if (SC == SC_None && !DC->isRecord() && 6774 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6775 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6776 SC = SC_Extern; 6777 6778 DeclContext *OriginalDC = DC; 6779 bool IsLocalExternDecl = SC == SC_Extern && 6780 adjustContextForLocalExternDecl(DC); 6781 6782 if (SCSpec == DeclSpec::SCS_mutable) { 6783 // mutable can only appear on non-static class members, so it's always 6784 // an error here 6785 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6786 D.setInvalidType(); 6787 SC = SC_None; 6788 } 6789 6790 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6791 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6792 D.getDeclSpec().getStorageClassSpecLoc())) { 6793 // In C++11, the 'register' storage class specifier is deprecated. 6794 // Suppress the warning in system macros, it's used in macros in some 6795 // popular C system headers, such as in glibc's htonl() macro. 6796 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6797 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6798 : diag::warn_deprecated_register) 6799 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6800 } 6801 6802 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6803 6804 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6805 // C99 6.9p2: The storage-class specifiers auto and register shall not 6806 // appear in the declaration specifiers in an external declaration. 6807 // Global Register+Asm is a GNU extension we support. 6808 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6809 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6810 D.setInvalidType(); 6811 } 6812 } 6813 6814 bool IsMemberSpecialization = false; 6815 bool IsVariableTemplateSpecialization = false; 6816 bool IsPartialSpecialization = false; 6817 bool IsVariableTemplate = false; 6818 VarDecl *NewVD = nullptr; 6819 VarTemplateDecl *NewTemplate = nullptr; 6820 TemplateParameterList *TemplateParams = nullptr; 6821 if (!getLangOpts().CPlusPlus) { 6822 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6823 II, R, TInfo, SC); 6824 6825 if (R->getContainedDeducedType()) 6826 ParsingInitForAutoVars.insert(NewVD); 6827 6828 if (D.isInvalidType()) 6829 NewVD->setInvalidDecl(); 6830 6831 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6832 NewVD->hasLocalStorage()) 6833 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6834 NTCUC_AutoVar, NTCUK_Destruct); 6835 } else { 6836 bool Invalid = false; 6837 6838 if (DC->isRecord() && !CurContext->isRecord()) { 6839 // This is an out-of-line definition of a static data member. 6840 switch (SC) { 6841 case SC_None: 6842 break; 6843 case SC_Static: 6844 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6845 diag::err_static_out_of_line) 6846 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6847 break; 6848 case SC_Auto: 6849 case SC_Register: 6850 case SC_Extern: 6851 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6852 // to names of variables declared in a block or to function parameters. 6853 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6854 // of class members 6855 6856 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6857 diag::err_storage_class_for_static_member) 6858 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6859 break; 6860 case SC_PrivateExtern: 6861 llvm_unreachable("C storage class in c++!"); 6862 } 6863 } 6864 6865 if (SC == SC_Static && CurContext->isRecord()) { 6866 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6867 // C++ [class.static.data]p2: 6868 // A static data member shall not be a direct member of an unnamed 6869 // or local class 6870 // FIXME: or of a (possibly indirectly) nested class thereof. 6871 if (RD->isLocalClass()) { 6872 Diag(D.getIdentifierLoc(), 6873 diag::err_static_data_member_not_allowed_in_local_class) 6874 << Name << RD->getDeclName() << RD->getTagKind(); 6875 } else if (!RD->getDeclName()) { 6876 Diag(D.getIdentifierLoc(), 6877 diag::err_static_data_member_not_allowed_in_anon_struct) 6878 << Name << RD->getTagKind(); 6879 Invalid = true; 6880 } else if (RD->isUnion()) { 6881 // C++98 [class.union]p1: If a union contains a static data member, 6882 // the program is ill-formed. C++11 drops this restriction. 6883 Diag(D.getIdentifierLoc(), 6884 getLangOpts().CPlusPlus11 6885 ? diag::warn_cxx98_compat_static_data_member_in_union 6886 : diag::ext_static_data_member_in_union) << Name; 6887 } 6888 } 6889 } 6890 6891 // Match up the template parameter lists with the scope specifier, then 6892 // determine whether we have a template or a template specialization. 6893 bool InvalidScope = false; 6894 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6895 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6896 D.getCXXScopeSpec(), 6897 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6898 ? D.getName().TemplateId 6899 : nullptr, 6900 TemplateParamLists, 6901 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 6902 Invalid |= InvalidScope; 6903 6904 if (TemplateParams) { 6905 if (!TemplateParams->size() && 6906 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6907 // There is an extraneous 'template<>' for this variable. Complain 6908 // about it, but allow the declaration of the variable. 6909 Diag(TemplateParams->getTemplateLoc(), 6910 diag::err_template_variable_noparams) 6911 << II 6912 << SourceRange(TemplateParams->getTemplateLoc(), 6913 TemplateParams->getRAngleLoc()); 6914 TemplateParams = nullptr; 6915 } else { 6916 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6917 // This is an explicit specialization or a partial specialization. 6918 // FIXME: Check that we can declare a specialization here. 6919 IsVariableTemplateSpecialization = true; 6920 IsPartialSpecialization = TemplateParams->size() > 0; 6921 } else { // if (TemplateParams->size() > 0) 6922 // This is a template declaration. 6923 IsVariableTemplate = true; 6924 6925 // Check that we can declare a template here. 6926 if (CheckTemplateDeclScope(S, TemplateParams)) 6927 return nullptr; 6928 6929 // Only C++1y supports variable templates (N3651). 6930 Diag(D.getIdentifierLoc(), 6931 getLangOpts().CPlusPlus14 6932 ? diag::warn_cxx11_compat_variable_template 6933 : diag::ext_variable_template); 6934 } 6935 } 6936 } else { 6937 assert((Invalid || 6938 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6939 "should have a 'template<>' for this decl"); 6940 } 6941 6942 if (IsVariableTemplateSpecialization) { 6943 SourceLocation TemplateKWLoc = 6944 TemplateParamLists.size() > 0 6945 ? TemplateParamLists[0]->getTemplateLoc() 6946 : SourceLocation(); 6947 DeclResult Res = ActOnVarTemplateSpecialization( 6948 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6949 IsPartialSpecialization); 6950 if (Res.isInvalid()) 6951 return nullptr; 6952 NewVD = cast<VarDecl>(Res.get()); 6953 AddToScope = false; 6954 } else if (D.isDecompositionDeclarator()) { 6955 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 6956 D.getIdentifierLoc(), R, TInfo, SC, 6957 Bindings); 6958 } else 6959 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 6960 D.getIdentifierLoc(), II, R, TInfo, SC); 6961 6962 // If this is supposed to be a variable template, create it as such. 6963 if (IsVariableTemplate) { 6964 NewTemplate = 6965 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6966 TemplateParams, NewVD); 6967 NewVD->setDescribedVarTemplate(NewTemplate); 6968 } 6969 6970 // If this decl has an auto type in need of deduction, make a note of the 6971 // Decl so we can diagnose uses of it in its own initializer. 6972 if (R->getContainedDeducedType()) 6973 ParsingInitForAutoVars.insert(NewVD); 6974 6975 if (D.isInvalidType() || Invalid) { 6976 NewVD->setInvalidDecl(); 6977 if (NewTemplate) 6978 NewTemplate->setInvalidDecl(); 6979 } 6980 6981 SetNestedNameSpecifier(*this, NewVD, D); 6982 6983 // If we have any template parameter lists that don't directly belong to 6984 // the variable (matching the scope specifier), store them. 6985 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6986 if (TemplateParamLists.size() > VDTemplateParamLists) 6987 NewVD->setTemplateParameterListsInfo( 6988 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6989 } 6990 6991 if (D.getDeclSpec().isInlineSpecified()) { 6992 if (!getLangOpts().CPlusPlus) { 6993 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6994 << 0; 6995 } else if (CurContext->isFunctionOrMethod()) { 6996 // 'inline' is not allowed on block scope variable declaration. 6997 Diag(D.getDeclSpec().getInlineSpecLoc(), 6998 diag::err_inline_declaration_block_scope) << Name 6999 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7000 } else { 7001 Diag(D.getDeclSpec().getInlineSpecLoc(), 7002 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7003 : diag::ext_inline_variable); 7004 NewVD->setInlineSpecified(); 7005 } 7006 } 7007 7008 // Set the lexical context. If the declarator has a C++ scope specifier, the 7009 // lexical context will be different from the semantic context. 7010 NewVD->setLexicalDeclContext(CurContext); 7011 if (NewTemplate) 7012 NewTemplate->setLexicalDeclContext(CurContext); 7013 7014 if (IsLocalExternDecl) { 7015 if (D.isDecompositionDeclarator()) 7016 for (auto *B : Bindings) 7017 B->setLocalExternDecl(); 7018 else 7019 NewVD->setLocalExternDecl(); 7020 } 7021 7022 bool EmitTLSUnsupportedError = false; 7023 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7024 // C++11 [dcl.stc]p4: 7025 // When thread_local is applied to a variable of block scope the 7026 // storage-class-specifier static is implied if it does not appear 7027 // explicitly. 7028 // Core issue: 'static' is not implied if the variable is declared 7029 // 'extern'. 7030 if (NewVD->hasLocalStorage() && 7031 (SCSpec != DeclSpec::SCS_unspecified || 7032 TSCS != DeclSpec::TSCS_thread_local || 7033 !DC->isFunctionOrMethod())) 7034 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7035 diag::err_thread_non_global) 7036 << DeclSpec::getSpecifierName(TSCS); 7037 else if (!Context.getTargetInfo().isTLSSupported()) { 7038 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 7039 // Postpone error emission until we've collected attributes required to 7040 // figure out whether it's a host or device variable and whether the 7041 // error should be ignored. 7042 EmitTLSUnsupportedError = true; 7043 // We still need to mark the variable as TLS so it shows up in AST with 7044 // proper storage class for other tools to use even if we're not going 7045 // to emit any code for it. 7046 NewVD->setTSCSpec(TSCS); 7047 } else 7048 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7049 diag::err_thread_unsupported); 7050 } else 7051 NewVD->setTSCSpec(TSCS); 7052 } 7053 7054 switch (D.getDeclSpec().getConstexprSpecifier()) { 7055 case CSK_unspecified: 7056 break; 7057 7058 case CSK_consteval: 7059 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7060 diag::err_constexpr_wrong_decl_kind) 7061 << D.getDeclSpec().getConstexprSpecifier(); 7062 LLVM_FALLTHROUGH; 7063 7064 case CSK_constexpr: 7065 NewVD->setConstexpr(true); 7066 // C++1z [dcl.spec.constexpr]p1: 7067 // A static data member declared with the constexpr specifier is 7068 // implicitly an inline variable. 7069 if (NewVD->isStaticDataMember() && 7070 (getLangOpts().CPlusPlus17 || 7071 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7072 NewVD->setImplicitlyInline(); 7073 break; 7074 7075 case CSK_constinit: 7076 if (!NewVD->hasGlobalStorage()) 7077 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7078 diag::err_constinit_local_variable); 7079 else 7080 NewVD->addAttr(ConstInitAttr::Create( 7081 Context, D.getDeclSpec().getConstexprSpecLoc(), 7082 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7083 break; 7084 } 7085 7086 // C99 6.7.4p3 7087 // An inline definition of a function with external linkage shall 7088 // not contain a definition of a modifiable object with static or 7089 // thread storage duration... 7090 // We only apply this when the function is required to be defined 7091 // elsewhere, i.e. when the function is not 'extern inline'. Note 7092 // that a local variable with thread storage duration still has to 7093 // be marked 'static'. Also note that it's possible to get these 7094 // semantics in C++ using __attribute__((gnu_inline)). 7095 if (SC == SC_Static && S->getFnParent() != nullptr && 7096 !NewVD->getType().isConstQualified()) { 7097 FunctionDecl *CurFD = getCurFunctionDecl(); 7098 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7099 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7100 diag::warn_static_local_in_extern_inline); 7101 MaybeSuggestAddingStaticToDecl(CurFD); 7102 } 7103 } 7104 7105 if (D.getDeclSpec().isModulePrivateSpecified()) { 7106 if (IsVariableTemplateSpecialization) 7107 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7108 << (IsPartialSpecialization ? 1 : 0) 7109 << FixItHint::CreateRemoval( 7110 D.getDeclSpec().getModulePrivateSpecLoc()); 7111 else if (IsMemberSpecialization) 7112 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7113 << 2 7114 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7115 else if (NewVD->hasLocalStorage()) 7116 Diag(NewVD->getLocation(), diag::err_module_private_local) 7117 << 0 << NewVD->getDeclName() 7118 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7119 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7120 else { 7121 NewVD->setModulePrivate(); 7122 if (NewTemplate) 7123 NewTemplate->setModulePrivate(); 7124 for (auto *B : Bindings) 7125 B->setModulePrivate(); 7126 } 7127 } 7128 7129 if (getLangOpts().OpenCL) { 7130 7131 deduceOpenCLAddressSpace(NewVD); 7132 7133 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); 7134 } 7135 7136 // Handle attributes prior to checking for duplicates in MergeVarDecl 7137 ProcessDeclAttributes(S, NewVD, D); 7138 7139 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 7140 if (EmitTLSUnsupportedError && 7141 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7142 (getLangOpts().OpenMPIsDevice && 7143 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7144 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7145 diag::err_thread_unsupported); 7146 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7147 // storage [duration]." 7148 if (SC == SC_None && S->getFnParent() != nullptr && 7149 (NewVD->hasAttr<CUDASharedAttr>() || 7150 NewVD->hasAttr<CUDAConstantAttr>())) { 7151 NewVD->setStorageClass(SC_Static); 7152 } 7153 } 7154 7155 // Ensure that dllimport globals without explicit storage class are treated as 7156 // extern. The storage class is set above using parsed attributes. Now we can 7157 // check the VarDecl itself. 7158 assert(!NewVD->hasAttr<DLLImportAttr>() || 7159 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7160 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7161 7162 // In auto-retain/release, infer strong retension for variables of 7163 // retainable type. 7164 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7165 NewVD->setInvalidDecl(); 7166 7167 // Handle GNU asm-label extension (encoded as an attribute). 7168 if (Expr *E = (Expr*)D.getAsmLabel()) { 7169 // The parser guarantees this is a string. 7170 StringLiteral *SE = cast<StringLiteral>(E); 7171 StringRef Label = SE->getString(); 7172 if (S->getFnParent() != nullptr) { 7173 switch (SC) { 7174 case SC_None: 7175 case SC_Auto: 7176 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7177 break; 7178 case SC_Register: 7179 // Local Named register 7180 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7181 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7182 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7183 break; 7184 case SC_Static: 7185 case SC_Extern: 7186 case SC_PrivateExtern: 7187 break; 7188 } 7189 } else if (SC == SC_Register) { 7190 // Global Named register 7191 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7192 const auto &TI = Context.getTargetInfo(); 7193 bool HasSizeMismatch; 7194 7195 if (!TI.isValidGCCRegisterName(Label)) 7196 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7197 else if (!TI.validateGlobalRegisterVariable(Label, 7198 Context.getTypeSize(R), 7199 HasSizeMismatch)) 7200 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7201 else if (HasSizeMismatch) 7202 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7203 } 7204 7205 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7206 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7207 NewVD->setInvalidDecl(true); 7208 } 7209 } 7210 7211 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7212 /*IsLiteralLabel=*/true, 7213 SE->getStrTokenLoc(0))); 7214 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7215 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7216 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7217 if (I != ExtnameUndeclaredIdentifiers.end()) { 7218 if (isDeclExternC(NewVD)) { 7219 NewVD->addAttr(I->second); 7220 ExtnameUndeclaredIdentifiers.erase(I); 7221 } else 7222 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7223 << /*Variable*/1 << NewVD; 7224 } 7225 } 7226 7227 // Find the shadowed declaration before filtering for scope. 7228 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7229 ? getShadowedDeclaration(NewVD, Previous) 7230 : nullptr; 7231 7232 // Don't consider existing declarations that are in a different 7233 // scope and are out-of-semantic-context declarations (if the new 7234 // declaration has linkage). 7235 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7236 D.getCXXScopeSpec().isNotEmpty() || 7237 IsMemberSpecialization || 7238 IsVariableTemplateSpecialization); 7239 7240 // Check whether the previous declaration is in the same block scope. This 7241 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7242 if (getLangOpts().CPlusPlus && 7243 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7244 NewVD->setPreviousDeclInSameBlockScope( 7245 Previous.isSingleResult() && !Previous.isShadowed() && 7246 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7247 7248 if (!getLangOpts().CPlusPlus) { 7249 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7250 } else { 7251 // If this is an explicit specialization of a static data member, check it. 7252 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7253 CheckMemberSpecialization(NewVD, Previous)) 7254 NewVD->setInvalidDecl(); 7255 7256 // Merge the decl with the existing one if appropriate. 7257 if (!Previous.empty()) { 7258 if (Previous.isSingleResult() && 7259 isa<FieldDecl>(Previous.getFoundDecl()) && 7260 D.getCXXScopeSpec().isSet()) { 7261 // The user tried to define a non-static data member 7262 // out-of-line (C++ [dcl.meaning]p1). 7263 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7264 << D.getCXXScopeSpec().getRange(); 7265 Previous.clear(); 7266 NewVD->setInvalidDecl(); 7267 } 7268 } else if (D.getCXXScopeSpec().isSet()) { 7269 // No previous declaration in the qualifying scope. 7270 Diag(D.getIdentifierLoc(), diag::err_no_member) 7271 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7272 << D.getCXXScopeSpec().getRange(); 7273 NewVD->setInvalidDecl(); 7274 } 7275 7276 if (!IsVariableTemplateSpecialization) 7277 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7278 7279 if (NewTemplate) { 7280 VarTemplateDecl *PrevVarTemplate = 7281 NewVD->getPreviousDecl() 7282 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7283 : nullptr; 7284 7285 // Check the template parameter list of this declaration, possibly 7286 // merging in the template parameter list from the previous variable 7287 // template declaration. 7288 if (CheckTemplateParameterList( 7289 TemplateParams, 7290 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7291 : nullptr, 7292 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7293 DC->isDependentContext()) 7294 ? TPC_ClassTemplateMember 7295 : TPC_VarTemplate)) 7296 NewVD->setInvalidDecl(); 7297 7298 // If we are providing an explicit specialization of a static variable 7299 // template, make a note of that. 7300 if (PrevVarTemplate && 7301 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7302 PrevVarTemplate->setMemberSpecialization(); 7303 } 7304 } 7305 7306 // Diagnose shadowed variables iff this isn't a redeclaration. 7307 if (ShadowedDecl && !D.isRedeclaration()) 7308 CheckShadow(NewVD, ShadowedDecl, Previous); 7309 7310 ProcessPragmaWeak(S, NewVD); 7311 7312 // If this is the first declaration of an extern C variable, update 7313 // the map of such variables. 7314 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7315 isIncompleteDeclExternC(*this, NewVD)) 7316 RegisterLocallyScopedExternCDecl(NewVD, S); 7317 7318 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7319 MangleNumberingContext *MCtx; 7320 Decl *ManglingContextDecl; 7321 std::tie(MCtx, ManglingContextDecl) = 7322 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7323 if (MCtx) { 7324 Context.setManglingNumber( 7325 NewVD, MCtx->getManglingNumber( 7326 NewVD, getMSManglingNumber(getLangOpts(), S))); 7327 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7328 } 7329 } 7330 7331 // Special handling of variable named 'main'. 7332 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7333 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7334 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7335 7336 // C++ [basic.start.main]p3 7337 // A program that declares a variable main at global scope is ill-formed. 7338 if (getLangOpts().CPlusPlus) 7339 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7340 7341 // In C, and external-linkage variable named main results in undefined 7342 // behavior. 7343 else if (NewVD->hasExternalFormalLinkage()) 7344 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7345 } 7346 7347 if (D.isRedeclaration() && !Previous.empty()) { 7348 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7349 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7350 D.isFunctionDefinition()); 7351 } 7352 7353 if (NewTemplate) { 7354 if (NewVD->isInvalidDecl()) 7355 NewTemplate->setInvalidDecl(); 7356 ActOnDocumentableDecl(NewTemplate); 7357 return NewTemplate; 7358 } 7359 7360 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7361 CompleteMemberSpecialization(NewVD, Previous); 7362 7363 return NewVD; 7364 } 7365 7366 /// Enum describing the %select options in diag::warn_decl_shadow. 7367 enum ShadowedDeclKind { 7368 SDK_Local, 7369 SDK_Global, 7370 SDK_StaticMember, 7371 SDK_Field, 7372 SDK_Typedef, 7373 SDK_Using 7374 }; 7375 7376 /// Determine what kind of declaration we're shadowing. 7377 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7378 const DeclContext *OldDC) { 7379 if (isa<TypeAliasDecl>(ShadowedDecl)) 7380 return SDK_Using; 7381 else if (isa<TypedefDecl>(ShadowedDecl)) 7382 return SDK_Typedef; 7383 else if (isa<RecordDecl>(OldDC)) 7384 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7385 7386 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7387 } 7388 7389 /// Return the location of the capture if the given lambda captures the given 7390 /// variable \p VD, or an invalid source location otherwise. 7391 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7392 const VarDecl *VD) { 7393 for (const Capture &Capture : LSI->Captures) { 7394 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7395 return Capture.getLocation(); 7396 } 7397 return SourceLocation(); 7398 } 7399 7400 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7401 const LookupResult &R) { 7402 // Only diagnose if we're shadowing an unambiguous field or variable. 7403 if (R.getResultKind() != LookupResult::Found) 7404 return false; 7405 7406 // Return false if warning is ignored. 7407 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7408 } 7409 7410 /// Return the declaration shadowed by the given variable \p D, or null 7411 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7412 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7413 const LookupResult &R) { 7414 if (!shouldWarnIfShadowedDecl(Diags, R)) 7415 return nullptr; 7416 7417 // Don't diagnose declarations at file scope. 7418 if (D->hasGlobalStorage()) 7419 return nullptr; 7420 7421 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7422 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7423 ? ShadowedDecl 7424 : nullptr; 7425 } 7426 7427 /// Return the declaration shadowed by the given typedef \p D, or null 7428 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7429 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7430 const LookupResult &R) { 7431 // Don't warn if typedef declaration is part of a class 7432 if (D->getDeclContext()->isRecord()) 7433 return nullptr; 7434 7435 if (!shouldWarnIfShadowedDecl(Diags, R)) 7436 return nullptr; 7437 7438 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7439 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7440 } 7441 7442 /// Diagnose variable or built-in function shadowing. Implements 7443 /// -Wshadow. 7444 /// 7445 /// This method is called whenever a VarDecl is added to a "useful" 7446 /// scope. 7447 /// 7448 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7449 /// \param R the lookup of the name 7450 /// 7451 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7452 const LookupResult &R) { 7453 DeclContext *NewDC = D->getDeclContext(); 7454 7455 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7456 // Fields are not shadowed by variables in C++ static methods. 7457 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7458 if (MD->isStatic()) 7459 return; 7460 7461 // Fields shadowed by constructor parameters are a special case. Usually 7462 // the constructor initializes the field with the parameter. 7463 if (isa<CXXConstructorDecl>(NewDC)) 7464 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7465 // Remember that this was shadowed so we can either warn about its 7466 // modification or its existence depending on warning settings. 7467 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7468 return; 7469 } 7470 } 7471 7472 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7473 if (shadowedVar->isExternC()) { 7474 // For shadowing external vars, make sure that we point to the global 7475 // declaration, not a locally scoped extern declaration. 7476 for (auto I : shadowedVar->redecls()) 7477 if (I->isFileVarDecl()) { 7478 ShadowedDecl = I; 7479 break; 7480 } 7481 } 7482 7483 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7484 7485 unsigned WarningDiag = diag::warn_decl_shadow; 7486 SourceLocation CaptureLoc; 7487 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7488 isa<CXXMethodDecl>(NewDC)) { 7489 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7490 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7491 if (RD->getLambdaCaptureDefault() == LCD_None) { 7492 // Try to avoid warnings for lambdas with an explicit capture list. 7493 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7494 // Warn only when the lambda captures the shadowed decl explicitly. 7495 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7496 if (CaptureLoc.isInvalid()) 7497 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7498 } else { 7499 // Remember that this was shadowed so we can avoid the warning if the 7500 // shadowed decl isn't captured and the warning settings allow it. 7501 cast<LambdaScopeInfo>(getCurFunction()) 7502 ->ShadowingDecls.push_back( 7503 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7504 return; 7505 } 7506 } 7507 7508 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7509 // A variable can't shadow a local variable in an enclosing scope, if 7510 // they are separated by a non-capturing declaration context. 7511 for (DeclContext *ParentDC = NewDC; 7512 ParentDC && !ParentDC->Equals(OldDC); 7513 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7514 // Only block literals, captured statements, and lambda expressions 7515 // can capture; other scopes don't. 7516 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7517 !isLambdaCallOperator(ParentDC)) { 7518 return; 7519 } 7520 } 7521 } 7522 } 7523 } 7524 7525 // Only warn about certain kinds of shadowing for class members. 7526 if (NewDC && NewDC->isRecord()) { 7527 // In particular, don't warn about shadowing non-class members. 7528 if (!OldDC->isRecord()) 7529 return; 7530 7531 // TODO: should we warn about static data members shadowing 7532 // static data members from base classes? 7533 7534 // TODO: don't diagnose for inaccessible shadowed members. 7535 // This is hard to do perfectly because we might friend the 7536 // shadowing context, but that's just a false negative. 7537 } 7538 7539 7540 DeclarationName Name = R.getLookupName(); 7541 7542 // Emit warning and note. 7543 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7544 return; 7545 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7546 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7547 if (!CaptureLoc.isInvalid()) 7548 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7549 << Name << /*explicitly*/ 1; 7550 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7551 } 7552 7553 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7554 /// when these variables are captured by the lambda. 7555 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7556 for (const auto &Shadow : LSI->ShadowingDecls) { 7557 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7558 // Try to avoid the warning when the shadowed decl isn't captured. 7559 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7560 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7561 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7562 ? diag::warn_decl_shadow_uncaptured_local 7563 : diag::warn_decl_shadow) 7564 << Shadow.VD->getDeclName() 7565 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7566 if (!CaptureLoc.isInvalid()) 7567 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7568 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7569 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7570 } 7571 } 7572 7573 /// Check -Wshadow without the advantage of a previous lookup. 7574 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7575 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7576 return; 7577 7578 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7579 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7580 LookupName(R, S); 7581 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7582 CheckShadow(D, ShadowedDecl, R); 7583 } 7584 7585 /// Check if 'E', which is an expression that is about to be modified, refers 7586 /// to a constructor parameter that shadows a field. 7587 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7588 // Quickly ignore expressions that can't be shadowing ctor parameters. 7589 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7590 return; 7591 E = E->IgnoreParenImpCasts(); 7592 auto *DRE = dyn_cast<DeclRefExpr>(E); 7593 if (!DRE) 7594 return; 7595 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7596 auto I = ShadowingDecls.find(D); 7597 if (I == ShadowingDecls.end()) 7598 return; 7599 const NamedDecl *ShadowedDecl = I->second; 7600 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7601 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7602 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7603 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7604 7605 // Avoid issuing multiple warnings about the same decl. 7606 ShadowingDecls.erase(I); 7607 } 7608 7609 /// Check for conflict between this global or extern "C" declaration and 7610 /// previous global or extern "C" declarations. This is only used in C++. 7611 template<typename T> 7612 static bool checkGlobalOrExternCConflict( 7613 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7614 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7615 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7616 7617 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7618 // The common case: this global doesn't conflict with any extern "C" 7619 // declaration. 7620 return false; 7621 } 7622 7623 if (Prev) { 7624 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7625 // Both the old and new declarations have C language linkage. This is a 7626 // redeclaration. 7627 Previous.clear(); 7628 Previous.addDecl(Prev); 7629 return true; 7630 } 7631 7632 // This is a global, non-extern "C" declaration, and there is a previous 7633 // non-global extern "C" declaration. Diagnose if this is a variable 7634 // declaration. 7635 if (!isa<VarDecl>(ND)) 7636 return false; 7637 } else { 7638 // The declaration is extern "C". Check for any declaration in the 7639 // translation unit which might conflict. 7640 if (IsGlobal) { 7641 // We have already performed the lookup into the translation unit. 7642 IsGlobal = false; 7643 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7644 I != E; ++I) { 7645 if (isa<VarDecl>(*I)) { 7646 Prev = *I; 7647 break; 7648 } 7649 } 7650 } else { 7651 DeclContext::lookup_result R = 7652 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7653 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7654 I != E; ++I) { 7655 if (isa<VarDecl>(*I)) { 7656 Prev = *I; 7657 break; 7658 } 7659 // FIXME: If we have any other entity with this name in global scope, 7660 // the declaration is ill-formed, but that is a defect: it breaks the 7661 // 'stat' hack, for instance. Only variables can have mangled name 7662 // clashes with extern "C" declarations, so only they deserve a 7663 // diagnostic. 7664 } 7665 } 7666 7667 if (!Prev) 7668 return false; 7669 } 7670 7671 // Use the first declaration's location to ensure we point at something which 7672 // is lexically inside an extern "C" linkage-spec. 7673 assert(Prev && "should have found a previous declaration to diagnose"); 7674 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7675 Prev = FD->getFirstDecl(); 7676 else 7677 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7678 7679 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7680 << IsGlobal << ND; 7681 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7682 << IsGlobal; 7683 return false; 7684 } 7685 7686 /// Apply special rules for handling extern "C" declarations. Returns \c true 7687 /// if we have found that this is a redeclaration of some prior entity. 7688 /// 7689 /// Per C++ [dcl.link]p6: 7690 /// Two declarations [for a function or variable] with C language linkage 7691 /// with the same name that appear in different scopes refer to the same 7692 /// [entity]. An entity with C language linkage shall not be declared with 7693 /// the same name as an entity in global scope. 7694 template<typename T> 7695 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7696 LookupResult &Previous) { 7697 if (!S.getLangOpts().CPlusPlus) { 7698 // In C, when declaring a global variable, look for a corresponding 'extern' 7699 // variable declared in function scope. We don't need this in C++, because 7700 // we find local extern decls in the surrounding file-scope DeclContext. 7701 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7702 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7703 Previous.clear(); 7704 Previous.addDecl(Prev); 7705 return true; 7706 } 7707 } 7708 return false; 7709 } 7710 7711 // A declaration in the translation unit can conflict with an extern "C" 7712 // declaration. 7713 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7714 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7715 7716 // An extern "C" declaration can conflict with a declaration in the 7717 // translation unit or can be a redeclaration of an extern "C" declaration 7718 // in another scope. 7719 if (isIncompleteDeclExternC(S,ND)) 7720 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7721 7722 // Neither global nor extern "C": nothing to do. 7723 return false; 7724 } 7725 7726 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7727 // If the decl is already known invalid, don't check it. 7728 if (NewVD->isInvalidDecl()) 7729 return; 7730 7731 QualType T = NewVD->getType(); 7732 7733 // Defer checking an 'auto' type until its initializer is attached. 7734 if (T->isUndeducedType()) 7735 return; 7736 7737 if (NewVD->hasAttrs()) 7738 CheckAlignasUnderalignment(NewVD); 7739 7740 if (T->isObjCObjectType()) { 7741 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7742 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7743 T = Context.getObjCObjectPointerType(T); 7744 NewVD->setType(T); 7745 } 7746 7747 // Emit an error if an address space was applied to decl with local storage. 7748 // This includes arrays of objects with address space qualifiers, but not 7749 // automatic variables that point to other address spaces. 7750 // ISO/IEC TR 18037 S5.1.2 7751 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7752 T.getAddressSpace() != LangAS::Default) { 7753 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7754 NewVD->setInvalidDecl(); 7755 return; 7756 } 7757 7758 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7759 // scope. 7760 if (getLangOpts().OpenCLVersion == 120 && 7761 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7762 NewVD->isStaticLocal()) { 7763 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7764 NewVD->setInvalidDecl(); 7765 return; 7766 } 7767 7768 if (getLangOpts().OpenCL) { 7769 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7770 if (NewVD->hasAttr<BlocksAttr>()) { 7771 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7772 return; 7773 } 7774 7775 if (T->isBlockPointerType()) { 7776 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7777 // can't use 'extern' storage class. 7778 if (!T.isConstQualified()) { 7779 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7780 << 0 /*const*/; 7781 NewVD->setInvalidDecl(); 7782 return; 7783 } 7784 if (NewVD->hasExternalStorage()) { 7785 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7786 NewVD->setInvalidDecl(); 7787 return; 7788 } 7789 } 7790 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7791 // __constant address space. 7792 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7793 // variables inside a function can also be declared in the global 7794 // address space. 7795 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7796 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7797 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7798 NewVD->hasExternalStorage()) { 7799 if (!T->isSamplerT() && 7800 !(T.getAddressSpace() == LangAS::opencl_constant || 7801 (T.getAddressSpace() == LangAS::opencl_global && 7802 (getLangOpts().OpenCLVersion == 200 || 7803 getLangOpts().OpenCLCPlusPlus)))) { 7804 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7805 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7806 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7807 << Scope << "global or constant"; 7808 else 7809 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7810 << Scope << "constant"; 7811 NewVD->setInvalidDecl(); 7812 return; 7813 } 7814 } else { 7815 if (T.getAddressSpace() == LangAS::opencl_global) { 7816 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7817 << 1 /*is any function*/ << "global"; 7818 NewVD->setInvalidDecl(); 7819 return; 7820 } 7821 if (T.getAddressSpace() == LangAS::opencl_constant || 7822 T.getAddressSpace() == LangAS::opencl_local) { 7823 FunctionDecl *FD = getCurFunctionDecl(); 7824 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7825 // in functions. 7826 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7827 if (T.getAddressSpace() == LangAS::opencl_constant) 7828 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7829 << 0 /*non-kernel only*/ << "constant"; 7830 else 7831 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7832 << 0 /*non-kernel only*/ << "local"; 7833 NewVD->setInvalidDecl(); 7834 return; 7835 } 7836 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7837 // in the outermost scope of a kernel function. 7838 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7839 if (!getCurScope()->isFunctionScope()) { 7840 if (T.getAddressSpace() == LangAS::opencl_constant) 7841 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7842 << "constant"; 7843 else 7844 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7845 << "local"; 7846 NewVD->setInvalidDecl(); 7847 return; 7848 } 7849 } 7850 } else if (T.getAddressSpace() != LangAS::opencl_private && 7851 // If we are parsing a template we didn't deduce an addr 7852 // space yet. 7853 T.getAddressSpace() != LangAS::Default) { 7854 // Do not allow other address spaces on automatic variable. 7855 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7856 NewVD->setInvalidDecl(); 7857 return; 7858 } 7859 } 7860 } 7861 7862 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7863 && !NewVD->hasAttr<BlocksAttr>()) { 7864 if (getLangOpts().getGC() != LangOptions::NonGC) 7865 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7866 else { 7867 assert(!getLangOpts().ObjCAutoRefCount); 7868 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7869 } 7870 } 7871 7872 bool isVM = T->isVariablyModifiedType(); 7873 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7874 NewVD->hasAttr<BlocksAttr>()) 7875 setFunctionHasBranchProtectedScope(); 7876 7877 if ((isVM && NewVD->hasLinkage()) || 7878 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7879 bool SizeIsNegative; 7880 llvm::APSInt Oversized; 7881 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7882 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7883 QualType FixedT; 7884 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7885 FixedT = FixedTInfo->getType(); 7886 else if (FixedTInfo) { 7887 // Type and type-as-written are canonically different. We need to fix up 7888 // both types separately. 7889 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7890 Oversized); 7891 } 7892 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7893 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7894 // FIXME: This won't give the correct result for 7895 // int a[10][n]; 7896 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7897 7898 if (NewVD->isFileVarDecl()) 7899 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7900 << SizeRange; 7901 else if (NewVD->isStaticLocal()) 7902 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7903 << SizeRange; 7904 else 7905 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7906 << SizeRange; 7907 NewVD->setInvalidDecl(); 7908 return; 7909 } 7910 7911 if (!FixedTInfo) { 7912 if (NewVD->isFileVarDecl()) 7913 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7914 else 7915 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7916 NewVD->setInvalidDecl(); 7917 return; 7918 } 7919 7920 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7921 NewVD->setType(FixedT); 7922 NewVD->setTypeSourceInfo(FixedTInfo); 7923 } 7924 7925 if (T->isVoidType()) { 7926 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7927 // of objects and functions. 7928 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7929 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7930 << T; 7931 NewVD->setInvalidDecl(); 7932 return; 7933 } 7934 } 7935 7936 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7937 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7938 NewVD->setInvalidDecl(); 7939 return; 7940 } 7941 7942 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7943 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7944 NewVD->setInvalidDecl(); 7945 return; 7946 } 7947 7948 if (NewVD->isConstexpr() && !T->isDependentType() && 7949 RequireLiteralType(NewVD->getLocation(), T, 7950 diag::err_constexpr_var_non_literal)) { 7951 NewVD->setInvalidDecl(); 7952 return; 7953 } 7954 } 7955 7956 /// Perform semantic checking on a newly-created variable 7957 /// declaration. 7958 /// 7959 /// This routine performs all of the type-checking required for a 7960 /// variable declaration once it has been built. It is used both to 7961 /// check variables after they have been parsed and their declarators 7962 /// have been translated into a declaration, and to check variables 7963 /// that have been instantiated from a template. 7964 /// 7965 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7966 /// 7967 /// Returns true if the variable declaration is a redeclaration. 7968 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7969 CheckVariableDeclarationType(NewVD); 7970 7971 // If the decl is already known invalid, don't check it. 7972 if (NewVD->isInvalidDecl()) 7973 return false; 7974 7975 // If we did not find anything by this name, look for a non-visible 7976 // extern "C" declaration with the same name. 7977 if (Previous.empty() && 7978 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7979 Previous.setShadowed(); 7980 7981 if (!Previous.empty()) { 7982 MergeVarDecl(NewVD, Previous); 7983 return true; 7984 } 7985 return false; 7986 } 7987 7988 namespace { 7989 struct FindOverriddenMethod { 7990 Sema *S; 7991 CXXMethodDecl *Method; 7992 7993 /// Member lookup function that determines whether a given C++ 7994 /// method overrides a method in a base class, to be used with 7995 /// CXXRecordDecl::lookupInBases(). 7996 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7997 RecordDecl *BaseRecord = 7998 Specifier->getType()->castAs<RecordType>()->getDecl(); 7999 8000 DeclarationName Name = Method->getDeclName(); 8001 8002 // FIXME: Do we care about other names here too? 8003 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8004 // We really want to find the base class destructor here. 8005 QualType T = S->Context.getTypeDeclType(BaseRecord); 8006 CanQualType CT = S->Context.getCanonicalType(T); 8007 8008 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 8009 } 8010 8011 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 8012 Path.Decls = Path.Decls.slice(1)) { 8013 NamedDecl *D = Path.Decls.front(); 8014 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 8015 if (MD->isVirtual() && 8016 !S->IsOverload( 8017 Method, MD, /*UseMemberUsingDeclRules=*/false, 8018 /*ConsiderCudaAttrs=*/true, 8019 // C++2a [class.virtual]p2 does not consider requires clauses 8020 // when overriding. 8021 /*ConsiderRequiresClauses=*/false)) 8022 return true; 8023 } 8024 } 8025 8026 return false; 8027 } 8028 }; 8029 8030 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 8031 } // end anonymous namespace 8032 8033 /// Report an error regarding overriding, along with any relevant 8034 /// overridden methods. 8035 /// 8036 /// \param DiagID the primary error to report. 8037 /// \param MD the overriding method. 8038 /// \param OEK which overrides to include as notes. 8039 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 8040 OverrideErrorKind OEK = OEK_All) { 8041 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 8042 for (const CXXMethodDecl *O : MD->overridden_methods()) { 8043 // This check (& the OEK parameter) could be replaced by a predicate, but 8044 // without lambdas that would be overkill. This is still nicer than writing 8045 // out the diag loop 3 times. 8046 if ((OEK == OEK_All) || 8047 (OEK == OEK_NonDeleted && !O->isDeleted()) || 8048 (OEK == OEK_Deleted && O->isDeleted())) 8049 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 8050 } 8051 } 8052 8053 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8054 /// and if so, check that it's a valid override and remember it. 8055 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8056 // Look for methods in base classes that this method might override. 8057 CXXBasePaths Paths; 8058 FindOverriddenMethod FOM; 8059 FOM.Method = MD; 8060 FOM.S = this; 8061 bool hasDeletedOverridenMethods = false; 8062 bool hasNonDeletedOverridenMethods = false; 8063 bool AddedAny = false; 8064 if (DC->lookupInBases(FOM, Paths)) { 8065 for (auto *I : Paths.found_decls()) { 8066 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 8067 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 8068 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 8069 !CheckOverridingFunctionAttributes(MD, OldMD) && 8070 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 8071 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 8072 hasDeletedOverridenMethods |= OldMD->isDeleted(); 8073 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 8074 AddedAny = true; 8075 } 8076 } 8077 } 8078 } 8079 8080 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 8081 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 8082 } 8083 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 8084 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 8085 } 8086 8087 return AddedAny; 8088 } 8089 8090 namespace { 8091 // Struct for holding all of the extra arguments needed by 8092 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8093 struct ActOnFDArgs { 8094 Scope *S; 8095 Declarator &D; 8096 MultiTemplateParamsArg TemplateParamLists; 8097 bool AddToScope; 8098 }; 8099 } // end anonymous namespace 8100 8101 namespace { 8102 8103 // Callback to only accept typo corrections that have a non-zero edit distance. 8104 // Also only accept corrections that have the same parent decl. 8105 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8106 public: 8107 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8108 CXXRecordDecl *Parent) 8109 : Context(Context), OriginalFD(TypoFD), 8110 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8111 8112 bool ValidateCandidate(const TypoCorrection &candidate) override { 8113 if (candidate.getEditDistance() == 0) 8114 return false; 8115 8116 SmallVector<unsigned, 1> MismatchedParams; 8117 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8118 CDeclEnd = candidate.end(); 8119 CDecl != CDeclEnd; ++CDecl) { 8120 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8121 8122 if (FD && !FD->hasBody() && 8123 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8124 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8125 CXXRecordDecl *Parent = MD->getParent(); 8126 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8127 return true; 8128 } else if (!ExpectedParent) { 8129 return true; 8130 } 8131 } 8132 } 8133 8134 return false; 8135 } 8136 8137 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8138 return std::make_unique<DifferentNameValidatorCCC>(*this); 8139 } 8140 8141 private: 8142 ASTContext &Context; 8143 FunctionDecl *OriginalFD; 8144 CXXRecordDecl *ExpectedParent; 8145 }; 8146 8147 } // end anonymous namespace 8148 8149 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8150 TypoCorrectedFunctionDefinitions.insert(F); 8151 } 8152 8153 /// Generate diagnostics for an invalid function redeclaration. 8154 /// 8155 /// This routine handles generating the diagnostic messages for an invalid 8156 /// function redeclaration, including finding possible similar declarations 8157 /// or performing typo correction if there are no previous declarations with 8158 /// the same name. 8159 /// 8160 /// Returns a NamedDecl iff typo correction was performed and substituting in 8161 /// the new declaration name does not cause new errors. 8162 static NamedDecl *DiagnoseInvalidRedeclaration( 8163 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8164 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8165 DeclarationName Name = NewFD->getDeclName(); 8166 DeclContext *NewDC = NewFD->getDeclContext(); 8167 SmallVector<unsigned, 1> MismatchedParams; 8168 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8169 TypoCorrection Correction; 8170 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8171 unsigned DiagMsg = 8172 IsLocalFriend ? diag::err_no_matching_local_friend : 8173 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8174 diag::err_member_decl_does_not_match; 8175 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8176 IsLocalFriend ? Sema::LookupLocalFriendName 8177 : Sema::LookupOrdinaryName, 8178 Sema::ForVisibleRedeclaration); 8179 8180 NewFD->setInvalidDecl(); 8181 if (IsLocalFriend) 8182 SemaRef.LookupName(Prev, S); 8183 else 8184 SemaRef.LookupQualifiedName(Prev, NewDC); 8185 assert(!Prev.isAmbiguous() && 8186 "Cannot have an ambiguity in previous-declaration lookup"); 8187 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8188 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8189 MD ? MD->getParent() : nullptr); 8190 if (!Prev.empty()) { 8191 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8192 Func != FuncEnd; ++Func) { 8193 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8194 if (FD && 8195 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8196 // Add 1 to the index so that 0 can mean the mismatch didn't 8197 // involve a parameter 8198 unsigned ParamNum = 8199 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8200 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8201 } 8202 } 8203 // If the qualified name lookup yielded nothing, try typo correction 8204 } else if ((Correction = SemaRef.CorrectTypo( 8205 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8206 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8207 IsLocalFriend ? nullptr : NewDC))) { 8208 // Set up everything for the call to ActOnFunctionDeclarator 8209 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8210 ExtraArgs.D.getIdentifierLoc()); 8211 Previous.clear(); 8212 Previous.setLookupName(Correction.getCorrection()); 8213 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8214 CDeclEnd = Correction.end(); 8215 CDecl != CDeclEnd; ++CDecl) { 8216 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8217 if (FD && !FD->hasBody() && 8218 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8219 Previous.addDecl(FD); 8220 } 8221 } 8222 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8223 8224 NamedDecl *Result; 8225 // Retry building the function declaration with the new previous 8226 // declarations, and with errors suppressed. 8227 { 8228 // Trap errors. 8229 Sema::SFINAETrap Trap(SemaRef); 8230 8231 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8232 // pieces need to verify the typo-corrected C++ declaration and hopefully 8233 // eliminate the need for the parameter pack ExtraArgs. 8234 Result = SemaRef.ActOnFunctionDeclarator( 8235 ExtraArgs.S, ExtraArgs.D, 8236 Correction.getCorrectionDecl()->getDeclContext(), 8237 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8238 ExtraArgs.AddToScope); 8239 8240 if (Trap.hasErrorOccurred()) 8241 Result = nullptr; 8242 } 8243 8244 if (Result) { 8245 // Determine which correction we picked. 8246 Decl *Canonical = Result->getCanonicalDecl(); 8247 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8248 I != E; ++I) 8249 if ((*I)->getCanonicalDecl() == Canonical) 8250 Correction.setCorrectionDecl(*I); 8251 8252 // Let Sema know about the correction. 8253 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8254 SemaRef.diagnoseTypo( 8255 Correction, 8256 SemaRef.PDiag(IsLocalFriend 8257 ? diag::err_no_matching_local_friend_suggest 8258 : diag::err_member_decl_does_not_match_suggest) 8259 << Name << NewDC << IsDefinition); 8260 return Result; 8261 } 8262 8263 // Pretend the typo correction never occurred 8264 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8265 ExtraArgs.D.getIdentifierLoc()); 8266 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8267 Previous.clear(); 8268 Previous.setLookupName(Name); 8269 } 8270 8271 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8272 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8273 8274 bool NewFDisConst = false; 8275 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8276 NewFDisConst = NewMD->isConst(); 8277 8278 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8279 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8280 NearMatch != NearMatchEnd; ++NearMatch) { 8281 FunctionDecl *FD = NearMatch->first; 8282 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8283 bool FDisConst = MD && MD->isConst(); 8284 bool IsMember = MD || !IsLocalFriend; 8285 8286 // FIXME: These notes are poorly worded for the local friend case. 8287 if (unsigned Idx = NearMatch->second) { 8288 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8289 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8290 if (Loc.isInvalid()) Loc = FD->getLocation(); 8291 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8292 : diag::note_local_decl_close_param_match) 8293 << Idx << FDParam->getType() 8294 << NewFD->getParamDecl(Idx - 1)->getType(); 8295 } else if (FDisConst != NewFDisConst) { 8296 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8297 << NewFDisConst << FD->getSourceRange().getEnd(); 8298 } else 8299 SemaRef.Diag(FD->getLocation(), 8300 IsMember ? diag::note_member_def_close_match 8301 : diag::note_local_decl_close_match); 8302 } 8303 return nullptr; 8304 } 8305 8306 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8307 switch (D.getDeclSpec().getStorageClassSpec()) { 8308 default: llvm_unreachable("Unknown storage class!"); 8309 case DeclSpec::SCS_auto: 8310 case DeclSpec::SCS_register: 8311 case DeclSpec::SCS_mutable: 8312 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8313 diag::err_typecheck_sclass_func); 8314 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8315 D.setInvalidType(); 8316 break; 8317 case DeclSpec::SCS_unspecified: break; 8318 case DeclSpec::SCS_extern: 8319 if (D.getDeclSpec().isExternInLinkageSpec()) 8320 return SC_None; 8321 return SC_Extern; 8322 case DeclSpec::SCS_static: { 8323 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8324 // C99 6.7.1p5: 8325 // The declaration of an identifier for a function that has 8326 // block scope shall have no explicit storage-class specifier 8327 // other than extern 8328 // See also (C++ [dcl.stc]p4). 8329 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8330 diag::err_static_block_func); 8331 break; 8332 } else 8333 return SC_Static; 8334 } 8335 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8336 } 8337 8338 // No explicit storage class has already been returned 8339 return SC_None; 8340 } 8341 8342 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8343 DeclContext *DC, QualType &R, 8344 TypeSourceInfo *TInfo, 8345 StorageClass SC, 8346 bool &IsVirtualOkay) { 8347 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8348 DeclarationName Name = NameInfo.getName(); 8349 8350 FunctionDecl *NewFD = nullptr; 8351 bool isInline = D.getDeclSpec().isInlineSpecified(); 8352 8353 if (!SemaRef.getLangOpts().CPlusPlus) { 8354 // Determine whether the function was written with a 8355 // prototype. This true when: 8356 // - there is a prototype in the declarator, or 8357 // - the type R of the function is some kind of typedef or other non- 8358 // attributed reference to a type name (which eventually refers to a 8359 // function type). 8360 bool HasPrototype = 8361 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8362 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8363 8364 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8365 R, TInfo, SC, isInline, HasPrototype, 8366 CSK_unspecified, 8367 /*TrailingRequiresClause=*/nullptr); 8368 if (D.isInvalidType()) 8369 NewFD->setInvalidDecl(); 8370 8371 return NewFD; 8372 } 8373 8374 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8375 8376 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8377 if (ConstexprKind == CSK_constinit) { 8378 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8379 diag::err_constexpr_wrong_decl_kind) 8380 << ConstexprKind; 8381 ConstexprKind = CSK_unspecified; 8382 D.getMutableDeclSpec().ClearConstexprSpec(); 8383 } 8384 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8385 8386 // Check that the return type is not an abstract class type. 8387 // For record types, this is done by the AbstractClassUsageDiagnoser once 8388 // the class has been completely parsed. 8389 if (!DC->isRecord() && 8390 SemaRef.RequireNonAbstractType( 8391 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8392 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8393 D.setInvalidType(); 8394 8395 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8396 // This is a C++ constructor declaration. 8397 assert(DC->isRecord() && 8398 "Constructors can only be declared in a member context"); 8399 8400 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8401 return CXXConstructorDecl::Create( 8402 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8403 TInfo, ExplicitSpecifier, isInline, 8404 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8405 TrailingRequiresClause); 8406 8407 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8408 // This is a C++ destructor declaration. 8409 if (DC->isRecord()) { 8410 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8411 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8412 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8413 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8414 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8415 TrailingRequiresClause); 8416 8417 // If the destructor needs an implicit exception specification, set it 8418 // now. FIXME: It'd be nice to be able to create the right type to start 8419 // with, but the type needs to reference the destructor declaration. 8420 if (SemaRef.getLangOpts().CPlusPlus11) 8421 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8422 8423 IsVirtualOkay = true; 8424 return NewDD; 8425 8426 } else { 8427 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8428 D.setInvalidType(); 8429 8430 // Create a FunctionDecl to satisfy the function definition parsing 8431 // code path. 8432 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8433 D.getIdentifierLoc(), Name, R, TInfo, SC, 8434 isInline, 8435 /*hasPrototype=*/true, ConstexprKind, 8436 TrailingRequiresClause); 8437 } 8438 8439 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8440 if (!DC->isRecord()) { 8441 SemaRef.Diag(D.getIdentifierLoc(), 8442 diag::err_conv_function_not_member); 8443 return nullptr; 8444 } 8445 8446 SemaRef.CheckConversionDeclarator(D, R, SC); 8447 if (D.isInvalidType()) 8448 return nullptr; 8449 8450 IsVirtualOkay = true; 8451 return CXXConversionDecl::Create( 8452 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8453 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8454 TrailingRequiresClause); 8455 8456 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8457 if (TrailingRequiresClause) 8458 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8459 diag::err_trailing_requires_clause_on_deduction_guide) 8460 << TrailingRequiresClause->getSourceRange(); 8461 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8462 8463 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8464 ExplicitSpecifier, NameInfo, R, TInfo, 8465 D.getEndLoc()); 8466 } else if (DC->isRecord()) { 8467 // If the name of the function is the same as the name of the record, 8468 // then this must be an invalid constructor that has a return type. 8469 // (The parser checks for a return type and makes the declarator a 8470 // constructor if it has no return type). 8471 if (Name.getAsIdentifierInfo() && 8472 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8473 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8474 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8475 << SourceRange(D.getIdentifierLoc()); 8476 return nullptr; 8477 } 8478 8479 // This is a C++ method declaration. 8480 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8481 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8482 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8483 TrailingRequiresClause); 8484 IsVirtualOkay = !Ret->isStatic(); 8485 return Ret; 8486 } else { 8487 bool isFriend = 8488 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8489 if (!isFriend && SemaRef.CurContext->isRecord()) 8490 return nullptr; 8491 8492 // Determine whether the function was written with a 8493 // prototype. This true when: 8494 // - we're in C++ (where every function has a prototype), 8495 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8496 R, TInfo, SC, isInline, true /*HasPrototype*/, 8497 ConstexprKind, TrailingRequiresClause); 8498 } 8499 } 8500 8501 enum OpenCLParamType { 8502 ValidKernelParam, 8503 PtrPtrKernelParam, 8504 PtrKernelParam, 8505 InvalidAddrSpacePtrKernelParam, 8506 InvalidKernelParam, 8507 RecordKernelParam 8508 }; 8509 8510 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8511 // Size dependent types are just typedefs to normal integer types 8512 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8513 // integers other than by their names. 8514 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8515 8516 // Remove typedefs one by one until we reach a typedef 8517 // for a size dependent type. 8518 QualType DesugaredTy = Ty; 8519 do { 8520 ArrayRef<StringRef> Names(SizeTypeNames); 8521 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8522 if (Names.end() != Match) 8523 return true; 8524 8525 Ty = DesugaredTy; 8526 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8527 } while (DesugaredTy != Ty); 8528 8529 return false; 8530 } 8531 8532 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8533 if (PT->isPointerType()) { 8534 QualType PointeeType = PT->getPointeeType(); 8535 if (PointeeType->isPointerType()) 8536 return PtrPtrKernelParam; 8537 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8538 PointeeType.getAddressSpace() == LangAS::opencl_private || 8539 PointeeType.getAddressSpace() == LangAS::Default) 8540 return InvalidAddrSpacePtrKernelParam; 8541 return PtrKernelParam; 8542 } 8543 8544 // OpenCL v1.2 s6.9.k: 8545 // Arguments to kernel functions in a program cannot be declared with the 8546 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8547 // uintptr_t or a struct and/or union that contain fields declared to be one 8548 // of these built-in scalar types. 8549 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8550 return InvalidKernelParam; 8551 8552 if (PT->isImageType()) 8553 return PtrKernelParam; 8554 8555 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8556 return InvalidKernelParam; 8557 8558 // OpenCL extension spec v1.2 s9.5: 8559 // This extension adds support for half scalar and vector types as built-in 8560 // types that can be used for arithmetic operations, conversions etc. 8561 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8562 return InvalidKernelParam; 8563 8564 if (PT->isRecordType()) 8565 return RecordKernelParam; 8566 8567 // Look into an array argument to check if it has a forbidden type. 8568 if (PT->isArrayType()) { 8569 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8570 // Call ourself to check an underlying type of an array. Since the 8571 // getPointeeOrArrayElementType returns an innermost type which is not an 8572 // array, this recursive call only happens once. 8573 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8574 } 8575 8576 return ValidKernelParam; 8577 } 8578 8579 static void checkIsValidOpenCLKernelParameter( 8580 Sema &S, 8581 Declarator &D, 8582 ParmVarDecl *Param, 8583 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8584 QualType PT = Param->getType(); 8585 8586 // Cache the valid types we encounter to avoid rechecking structs that are 8587 // used again 8588 if (ValidTypes.count(PT.getTypePtr())) 8589 return; 8590 8591 switch (getOpenCLKernelParameterType(S, PT)) { 8592 case PtrPtrKernelParam: 8593 // OpenCL v1.2 s6.9.a: 8594 // A kernel function argument cannot be declared as a 8595 // pointer to a pointer type. 8596 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8597 D.setInvalidType(); 8598 return; 8599 8600 case InvalidAddrSpacePtrKernelParam: 8601 // OpenCL v1.0 s6.5: 8602 // __kernel function arguments declared to be a pointer of a type can point 8603 // to one of the following address spaces only : __global, __local or 8604 // __constant. 8605 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8606 D.setInvalidType(); 8607 return; 8608 8609 // OpenCL v1.2 s6.9.k: 8610 // Arguments to kernel functions in a program cannot be declared with the 8611 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8612 // uintptr_t or a struct and/or union that contain fields declared to be 8613 // one of these built-in scalar types. 8614 8615 case InvalidKernelParam: 8616 // OpenCL v1.2 s6.8 n: 8617 // A kernel function argument cannot be declared 8618 // of event_t type. 8619 // Do not diagnose half type since it is diagnosed as invalid argument 8620 // type for any function elsewhere. 8621 if (!PT->isHalfType()) { 8622 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8623 8624 // Explain what typedefs are involved. 8625 const TypedefType *Typedef = nullptr; 8626 while ((Typedef = PT->getAs<TypedefType>())) { 8627 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8628 // SourceLocation may be invalid for a built-in type. 8629 if (Loc.isValid()) 8630 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8631 PT = Typedef->desugar(); 8632 } 8633 } 8634 8635 D.setInvalidType(); 8636 return; 8637 8638 case PtrKernelParam: 8639 case ValidKernelParam: 8640 ValidTypes.insert(PT.getTypePtr()); 8641 return; 8642 8643 case RecordKernelParam: 8644 break; 8645 } 8646 8647 // Track nested structs we will inspect 8648 SmallVector<const Decl *, 4> VisitStack; 8649 8650 // Track where we are in the nested structs. Items will migrate from 8651 // VisitStack to HistoryStack as we do the DFS for bad field. 8652 SmallVector<const FieldDecl *, 4> HistoryStack; 8653 HistoryStack.push_back(nullptr); 8654 8655 // At this point we already handled everything except of a RecordType or 8656 // an ArrayType of a RecordType. 8657 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8658 const RecordType *RecTy = 8659 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8660 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8661 8662 VisitStack.push_back(RecTy->getDecl()); 8663 assert(VisitStack.back() && "First decl null?"); 8664 8665 do { 8666 const Decl *Next = VisitStack.pop_back_val(); 8667 if (!Next) { 8668 assert(!HistoryStack.empty()); 8669 // Found a marker, we have gone up a level 8670 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8671 ValidTypes.insert(Hist->getType().getTypePtr()); 8672 8673 continue; 8674 } 8675 8676 // Adds everything except the original parameter declaration (which is not a 8677 // field itself) to the history stack. 8678 const RecordDecl *RD; 8679 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8680 HistoryStack.push_back(Field); 8681 8682 QualType FieldTy = Field->getType(); 8683 // Other field types (known to be valid or invalid) are handled while we 8684 // walk around RecordDecl::fields(). 8685 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8686 "Unexpected type."); 8687 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8688 8689 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8690 } else { 8691 RD = cast<RecordDecl>(Next); 8692 } 8693 8694 // Add a null marker so we know when we've gone back up a level 8695 VisitStack.push_back(nullptr); 8696 8697 for (const auto *FD : RD->fields()) { 8698 QualType QT = FD->getType(); 8699 8700 if (ValidTypes.count(QT.getTypePtr())) 8701 continue; 8702 8703 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8704 if (ParamType == ValidKernelParam) 8705 continue; 8706 8707 if (ParamType == RecordKernelParam) { 8708 VisitStack.push_back(FD); 8709 continue; 8710 } 8711 8712 // OpenCL v1.2 s6.9.p: 8713 // Arguments to kernel functions that are declared to be a struct or union 8714 // do not allow OpenCL objects to be passed as elements of the struct or 8715 // union. 8716 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8717 ParamType == InvalidAddrSpacePtrKernelParam) { 8718 S.Diag(Param->getLocation(), 8719 diag::err_record_with_pointers_kernel_param) 8720 << PT->isUnionType() 8721 << PT; 8722 } else { 8723 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8724 } 8725 8726 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8727 << OrigRecDecl->getDeclName(); 8728 8729 // We have an error, now let's go back up through history and show where 8730 // the offending field came from 8731 for (ArrayRef<const FieldDecl *>::const_iterator 8732 I = HistoryStack.begin() + 1, 8733 E = HistoryStack.end(); 8734 I != E; ++I) { 8735 const FieldDecl *OuterField = *I; 8736 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8737 << OuterField->getType(); 8738 } 8739 8740 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8741 << QT->isPointerType() 8742 << QT; 8743 D.setInvalidType(); 8744 return; 8745 } 8746 } while (!VisitStack.empty()); 8747 } 8748 8749 /// Find the DeclContext in which a tag is implicitly declared if we see an 8750 /// elaborated type specifier in the specified context, and lookup finds 8751 /// nothing. 8752 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8753 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8754 DC = DC->getParent(); 8755 return DC; 8756 } 8757 8758 /// Find the Scope in which a tag is implicitly declared if we see an 8759 /// elaborated type specifier in the specified context, and lookup finds 8760 /// nothing. 8761 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8762 while (S->isClassScope() || 8763 (LangOpts.CPlusPlus && 8764 S->isFunctionPrototypeScope()) || 8765 ((S->getFlags() & Scope::DeclScope) == 0) || 8766 (S->getEntity() && S->getEntity()->isTransparentContext())) 8767 S = S->getParent(); 8768 return S; 8769 } 8770 8771 NamedDecl* 8772 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8773 TypeSourceInfo *TInfo, LookupResult &Previous, 8774 MultiTemplateParamsArg TemplateParamListsRef, 8775 bool &AddToScope) { 8776 QualType R = TInfo->getType(); 8777 8778 assert(R->isFunctionType()); 8779 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8780 for (TemplateParameterList *TPL : TemplateParamListsRef) 8781 TemplateParamLists.push_back(TPL); 8782 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8783 if (!TemplateParamLists.empty() && 8784 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8785 TemplateParamLists.back() = Invented; 8786 else 8787 TemplateParamLists.push_back(Invented); 8788 } 8789 8790 // TODO: consider using NameInfo for diagnostic. 8791 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8792 DeclarationName Name = NameInfo.getName(); 8793 StorageClass SC = getFunctionStorageClass(*this, D); 8794 8795 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8796 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8797 diag::err_invalid_thread) 8798 << DeclSpec::getSpecifierName(TSCS); 8799 8800 if (D.isFirstDeclarationOfMember()) 8801 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8802 D.getIdentifierLoc()); 8803 8804 bool isFriend = false; 8805 FunctionTemplateDecl *FunctionTemplate = nullptr; 8806 bool isMemberSpecialization = false; 8807 bool isFunctionTemplateSpecialization = false; 8808 8809 bool isDependentClassScopeExplicitSpecialization = false; 8810 bool HasExplicitTemplateArgs = false; 8811 TemplateArgumentListInfo TemplateArgs; 8812 8813 bool isVirtualOkay = false; 8814 8815 DeclContext *OriginalDC = DC; 8816 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8817 8818 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8819 isVirtualOkay); 8820 if (!NewFD) return nullptr; 8821 8822 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8823 NewFD->setTopLevelDeclInObjCContainer(); 8824 8825 // Set the lexical context. If this is a function-scope declaration, or has a 8826 // C++ scope specifier, or is the object of a friend declaration, the lexical 8827 // context will be different from the semantic context. 8828 NewFD->setLexicalDeclContext(CurContext); 8829 8830 if (IsLocalExternDecl) 8831 NewFD->setLocalExternDecl(); 8832 8833 if (getLangOpts().CPlusPlus) { 8834 bool isInline = D.getDeclSpec().isInlineSpecified(); 8835 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8836 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8837 isFriend = D.getDeclSpec().isFriendSpecified(); 8838 if (isFriend && !isInline && D.isFunctionDefinition()) { 8839 // C++ [class.friend]p5 8840 // A function can be defined in a friend declaration of a 8841 // class . . . . Such a function is implicitly inline. 8842 NewFD->setImplicitlyInline(); 8843 } 8844 8845 // If this is a method defined in an __interface, and is not a constructor 8846 // or an overloaded operator, then set the pure flag (isVirtual will already 8847 // return true). 8848 if (const CXXRecordDecl *Parent = 8849 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8850 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8851 NewFD->setPure(true); 8852 8853 // C++ [class.union]p2 8854 // A union can have member functions, but not virtual functions. 8855 if (isVirtual && Parent->isUnion()) 8856 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8857 } 8858 8859 SetNestedNameSpecifier(*this, NewFD, D); 8860 isMemberSpecialization = false; 8861 isFunctionTemplateSpecialization = false; 8862 if (D.isInvalidType()) 8863 NewFD->setInvalidDecl(); 8864 8865 // Match up the template parameter lists with the scope specifier, then 8866 // determine whether we have a template or a template specialization. 8867 bool Invalid = false; 8868 TemplateParameterList *TemplateParams = 8869 MatchTemplateParametersToScopeSpecifier( 8870 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8871 D.getCXXScopeSpec(), 8872 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8873 ? D.getName().TemplateId 8874 : nullptr, 8875 TemplateParamLists, isFriend, isMemberSpecialization, 8876 Invalid); 8877 if (TemplateParams) { 8878 if (TemplateParams->size() > 0) { 8879 // This is a function template 8880 8881 // Check that we can declare a template here. 8882 if (CheckTemplateDeclScope(S, TemplateParams)) 8883 NewFD->setInvalidDecl(); 8884 8885 // A destructor cannot be a template. 8886 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8887 Diag(NewFD->getLocation(), diag::err_destructor_template); 8888 NewFD->setInvalidDecl(); 8889 } 8890 8891 // If we're adding a template to a dependent context, we may need to 8892 // rebuilding some of the types used within the template parameter list, 8893 // now that we know what the current instantiation is. 8894 if (DC->isDependentContext()) { 8895 ContextRAII SavedContext(*this, DC); 8896 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8897 Invalid = true; 8898 } 8899 8900 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8901 NewFD->getLocation(), 8902 Name, TemplateParams, 8903 NewFD); 8904 FunctionTemplate->setLexicalDeclContext(CurContext); 8905 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8906 8907 // For source fidelity, store the other template param lists. 8908 if (TemplateParamLists.size() > 1) { 8909 NewFD->setTemplateParameterListsInfo(Context, 8910 ArrayRef<TemplateParameterList *>(TemplateParamLists) 8911 .drop_back(1)); 8912 } 8913 } else { 8914 // This is a function template specialization. 8915 isFunctionTemplateSpecialization = true; 8916 // For source fidelity, store all the template param lists. 8917 if (TemplateParamLists.size() > 0) 8918 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8919 8920 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8921 if (isFriend) { 8922 // We want to remove the "template<>", found here. 8923 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8924 8925 // If we remove the template<> and the name is not a 8926 // template-id, we're actually silently creating a problem: 8927 // the friend declaration will refer to an untemplated decl, 8928 // and clearly the user wants a template specialization. So 8929 // we need to insert '<>' after the name. 8930 SourceLocation InsertLoc; 8931 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8932 InsertLoc = D.getName().getSourceRange().getEnd(); 8933 InsertLoc = getLocForEndOfToken(InsertLoc); 8934 } 8935 8936 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8937 << Name << RemoveRange 8938 << FixItHint::CreateRemoval(RemoveRange) 8939 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8940 } 8941 } 8942 } else { 8943 // All template param lists were matched against the scope specifier: 8944 // this is NOT (an explicit specialization of) a template. 8945 if (TemplateParamLists.size() > 0) 8946 // For source fidelity, store all the template param lists. 8947 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8948 } 8949 8950 if (Invalid) { 8951 NewFD->setInvalidDecl(); 8952 if (FunctionTemplate) 8953 FunctionTemplate->setInvalidDecl(); 8954 } 8955 8956 // C++ [dcl.fct.spec]p5: 8957 // The virtual specifier shall only be used in declarations of 8958 // nonstatic class member functions that appear within a 8959 // member-specification of a class declaration; see 10.3. 8960 // 8961 if (isVirtual && !NewFD->isInvalidDecl()) { 8962 if (!isVirtualOkay) { 8963 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8964 diag::err_virtual_non_function); 8965 } else if (!CurContext->isRecord()) { 8966 // 'virtual' was specified outside of the class. 8967 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8968 diag::err_virtual_out_of_class) 8969 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8970 } else if (NewFD->getDescribedFunctionTemplate()) { 8971 // C++ [temp.mem]p3: 8972 // A member function template shall not be virtual. 8973 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8974 diag::err_virtual_member_function_template) 8975 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8976 } else { 8977 // Okay: Add virtual to the method. 8978 NewFD->setVirtualAsWritten(true); 8979 } 8980 8981 if (getLangOpts().CPlusPlus14 && 8982 NewFD->getReturnType()->isUndeducedType()) 8983 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8984 } 8985 8986 if (getLangOpts().CPlusPlus14 && 8987 (NewFD->isDependentContext() || 8988 (isFriend && CurContext->isDependentContext())) && 8989 NewFD->getReturnType()->isUndeducedType()) { 8990 // If the function template is referenced directly (for instance, as a 8991 // member of the current instantiation), pretend it has a dependent type. 8992 // This is not really justified by the standard, but is the only sane 8993 // thing to do. 8994 // FIXME: For a friend function, we have not marked the function as being 8995 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8996 const FunctionProtoType *FPT = 8997 NewFD->getType()->castAs<FunctionProtoType>(); 8998 QualType Result = 8999 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9000 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9001 FPT->getExtProtoInfo())); 9002 } 9003 9004 // C++ [dcl.fct.spec]p3: 9005 // The inline specifier shall not appear on a block scope function 9006 // declaration. 9007 if (isInline && !NewFD->isInvalidDecl()) { 9008 if (CurContext->isFunctionOrMethod()) { 9009 // 'inline' is not allowed on block scope function declaration. 9010 Diag(D.getDeclSpec().getInlineSpecLoc(), 9011 diag::err_inline_declaration_block_scope) << Name 9012 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9013 } 9014 } 9015 9016 // C++ [dcl.fct.spec]p6: 9017 // The explicit specifier shall be used only in the declaration of a 9018 // constructor or conversion function within its class definition; 9019 // see 12.3.1 and 12.3.2. 9020 if (hasExplicit && !NewFD->isInvalidDecl() && 9021 !isa<CXXDeductionGuideDecl>(NewFD)) { 9022 if (!CurContext->isRecord()) { 9023 // 'explicit' was specified outside of the class. 9024 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9025 diag::err_explicit_out_of_class) 9026 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9027 } else if (!isa<CXXConstructorDecl>(NewFD) && 9028 !isa<CXXConversionDecl>(NewFD)) { 9029 // 'explicit' was specified on a function that wasn't a constructor 9030 // or conversion function. 9031 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9032 diag::err_explicit_non_ctor_or_conv_function) 9033 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9034 } 9035 } 9036 9037 if (ConstexprSpecKind ConstexprKind = 9038 D.getDeclSpec().getConstexprSpecifier()) { 9039 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9040 // are implicitly inline. 9041 NewFD->setImplicitlyInline(); 9042 9043 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9044 // be either constructors or to return a literal type. Therefore, 9045 // destructors cannot be declared constexpr. 9046 if (isa<CXXDestructorDecl>(NewFD) && 9047 (!getLangOpts().CPlusPlus2a || ConstexprKind == CSK_consteval)) { 9048 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9049 << ConstexprKind; 9050 NewFD->setConstexprKind(getLangOpts().CPlusPlus2a ? CSK_unspecified : CSK_constexpr); 9051 } 9052 // C++20 [dcl.constexpr]p2: An allocation function, or a 9053 // deallocation function shall not be declared with the consteval 9054 // specifier. 9055 if (ConstexprKind == CSK_consteval && 9056 (NewFD->getOverloadedOperator() == OO_New || 9057 NewFD->getOverloadedOperator() == OO_Array_New || 9058 NewFD->getOverloadedOperator() == OO_Delete || 9059 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9060 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9061 diag::err_invalid_consteval_decl_kind) 9062 << NewFD; 9063 NewFD->setConstexprKind(CSK_constexpr); 9064 } 9065 } 9066 9067 // If __module_private__ was specified, mark the function accordingly. 9068 if (D.getDeclSpec().isModulePrivateSpecified()) { 9069 if (isFunctionTemplateSpecialization) { 9070 SourceLocation ModulePrivateLoc 9071 = D.getDeclSpec().getModulePrivateSpecLoc(); 9072 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9073 << 0 9074 << FixItHint::CreateRemoval(ModulePrivateLoc); 9075 } else { 9076 NewFD->setModulePrivate(); 9077 if (FunctionTemplate) 9078 FunctionTemplate->setModulePrivate(); 9079 } 9080 } 9081 9082 if (isFriend) { 9083 if (FunctionTemplate) { 9084 FunctionTemplate->setObjectOfFriendDecl(); 9085 FunctionTemplate->setAccess(AS_public); 9086 } 9087 NewFD->setObjectOfFriendDecl(); 9088 NewFD->setAccess(AS_public); 9089 } 9090 9091 // If a function is defined as defaulted or deleted, mark it as such now. 9092 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 9093 // definition kind to FDK_Definition. 9094 switch (D.getFunctionDefinitionKind()) { 9095 case FDK_Declaration: 9096 case FDK_Definition: 9097 break; 9098 9099 case FDK_Defaulted: 9100 NewFD->setDefaulted(); 9101 break; 9102 9103 case FDK_Deleted: 9104 NewFD->setDeletedAsWritten(); 9105 break; 9106 } 9107 9108 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9109 D.isFunctionDefinition()) { 9110 // C++ [class.mfct]p2: 9111 // A member function may be defined (8.4) in its class definition, in 9112 // which case it is an inline member function (7.1.2) 9113 NewFD->setImplicitlyInline(); 9114 } 9115 9116 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9117 !CurContext->isRecord()) { 9118 // C++ [class.static]p1: 9119 // A data or function member of a class may be declared static 9120 // in a class definition, in which case it is a static member of 9121 // the class. 9122 9123 // Complain about the 'static' specifier if it's on an out-of-line 9124 // member function definition. 9125 9126 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9127 // member function template declaration and class member template 9128 // declaration (MSVC versions before 2015), warn about this. 9129 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9130 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9131 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9132 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9133 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9134 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9135 } 9136 9137 // C++11 [except.spec]p15: 9138 // A deallocation function with no exception-specification is treated 9139 // as if it were specified with noexcept(true). 9140 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9141 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9142 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9143 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9144 NewFD->setType(Context.getFunctionType( 9145 FPT->getReturnType(), FPT->getParamTypes(), 9146 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9147 } 9148 9149 // Filter out previous declarations that don't match the scope. 9150 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9151 D.getCXXScopeSpec().isNotEmpty() || 9152 isMemberSpecialization || 9153 isFunctionTemplateSpecialization); 9154 9155 // Handle GNU asm-label extension (encoded as an attribute). 9156 if (Expr *E = (Expr*) D.getAsmLabel()) { 9157 // The parser guarantees this is a string. 9158 StringLiteral *SE = cast<StringLiteral>(E); 9159 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9160 /*IsLiteralLabel=*/true, 9161 SE->getStrTokenLoc(0))); 9162 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9163 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9164 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9165 if (I != ExtnameUndeclaredIdentifiers.end()) { 9166 if (isDeclExternC(NewFD)) { 9167 NewFD->addAttr(I->second); 9168 ExtnameUndeclaredIdentifiers.erase(I); 9169 } else 9170 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9171 << /*Variable*/0 << NewFD; 9172 } 9173 } 9174 9175 // Copy the parameter declarations from the declarator D to the function 9176 // declaration NewFD, if they are available. First scavenge them into Params. 9177 SmallVector<ParmVarDecl*, 16> Params; 9178 unsigned FTIIdx; 9179 if (D.isFunctionDeclarator(FTIIdx)) { 9180 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9181 9182 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9183 // function that takes no arguments, not a function that takes a 9184 // single void argument. 9185 // We let through "const void" here because Sema::GetTypeForDeclarator 9186 // already checks for that case. 9187 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9188 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9189 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9190 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9191 Param->setDeclContext(NewFD); 9192 Params.push_back(Param); 9193 9194 if (Param->isInvalidDecl()) 9195 NewFD->setInvalidDecl(); 9196 } 9197 } 9198 9199 if (!getLangOpts().CPlusPlus) { 9200 // In C, find all the tag declarations from the prototype and move them 9201 // into the function DeclContext. Remove them from the surrounding tag 9202 // injection context of the function, which is typically but not always 9203 // the TU. 9204 DeclContext *PrototypeTagContext = 9205 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9206 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9207 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9208 9209 // We don't want to reparent enumerators. Look at their parent enum 9210 // instead. 9211 if (!TD) { 9212 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9213 TD = cast<EnumDecl>(ECD->getDeclContext()); 9214 } 9215 if (!TD) 9216 continue; 9217 DeclContext *TagDC = TD->getLexicalDeclContext(); 9218 if (!TagDC->containsDecl(TD)) 9219 continue; 9220 TagDC->removeDecl(TD); 9221 TD->setDeclContext(NewFD); 9222 NewFD->addDecl(TD); 9223 9224 // Preserve the lexical DeclContext if it is not the surrounding tag 9225 // injection context of the FD. In this example, the semantic context of 9226 // E will be f and the lexical context will be S, while both the 9227 // semantic and lexical contexts of S will be f: 9228 // void f(struct S { enum E { a } f; } s); 9229 if (TagDC != PrototypeTagContext) 9230 TD->setLexicalDeclContext(TagDC); 9231 } 9232 } 9233 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9234 // When we're declaring a function with a typedef, typeof, etc as in the 9235 // following example, we'll need to synthesize (unnamed) 9236 // parameters for use in the declaration. 9237 // 9238 // @code 9239 // typedef void fn(int); 9240 // fn f; 9241 // @endcode 9242 9243 // Synthesize a parameter for each argument type. 9244 for (const auto &AI : FT->param_types()) { 9245 ParmVarDecl *Param = 9246 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9247 Param->setScopeInfo(0, Params.size()); 9248 Params.push_back(Param); 9249 } 9250 } else { 9251 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9252 "Should not need args for typedef of non-prototype fn"); 9253 } 9254 9255 // Finally, we know we have the right number of parameters, install them. 9256 NewFD->setParams(Params); 9257 9258 if (D.getDeclSpec().isNoreturnSpecified()) 9259 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9260 D.getDeclSpec().getNoreturnSpecLoc(), 9261 AttributeCommonInfo::AS_Keyword)); 9262 9263 // Functions returning a variably modified type violate C99 6.7.5.2p2 9264 // because all functions have linkage. 9265 if (!NewFD->isInvalidDecl() && 9266 NewFD->getReturnType()->isVariablyModifiedType()) { 9267 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9268 NewFD->setInvalidDecl(); 9269 } 9270 9271 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9272 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9273 !NewFD->hasAttr<SectionAttr>()) 9274 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9275 Context, PragmaClangTextSection.SectionName, 9276 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9277 9278 // Apply an implicit SectionAttr if #pragma code_seg is active. 9279 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9280 !NewFD->hasAttr<SectionAttr>()) { 9281 NewFD->addAttr(SectionAttr::CreateImplicit( 9282 Context, CodeSegStack.CurrentValue->getString(), 9283 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9284 SectionAttr::Declspec_allocate)); 9285 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9286 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9287 ASTContext::PSF_Read, 9288 NewFD)) 9289 NewFD->dropAttr<SectionAttr>(); 9290 } 9291 9292 // Apply an implicit CodeSegAttr from class declspec or 9293 // apply an implicit SectionAttr from #pragma code_seg if active. 9294 if (!NewFD->hasAttr<CodeSegAttr>()) { 9295 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9296 D.isFunctionDefinition())) { 9297 NewFD->addAttr(SAttr); 9298 } 9299 } 9300 9301 // Handle attributes. 9302 ProcessDeclAttributes(S, NewFD, D); 9303 9304 if (getLangOpts().OpenCL) { 9305 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9306 // type declaration will generate a compilation error. 9307 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9308 if (AddressSpace != LangAS::Default) { 9309 Diag(NewFD->getLocation(), 9310 diag::err_opencl_return_value_with_address_space); 9311 NewFD->setInvalidDecl(); 9312 } 9313 } 9314 9315 if (!getLangOpts().CPlusPlus) { 9316 // Perform semantic checking on the function declaration. 9317 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9318 CheckMain(NewFD, D.getDeclSpec()); 9319 9320 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9321 CheckMSVCRTEntryPoint(NewFD); 9322 9323 if (!NewFD->isInvalidDecl()) 9324 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9325 isMemberSpecialization)); 9326 else if (!Previous.empty()) 9327 // Recover gracefully from an invalid redeclaration. 9328 D.setRedeclaration(true); 9329 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9330 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9331 "previous declaration set still overloaded"); 9332 9333 // Diagnose no-prototype function declarations with calling conventions that 9334 // don't support variadic calls. Only do this in C and do it after merging 9335 // possibly prototyped redeclarations. 9336 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9337 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9338 CallingConv CC = FT->getExtInfo().getCC(); 9339 if (!supportsVariadicCall(CC)) { 9340 // Windows system headers sometimes accidentally use stdcall without 9341 // (void) parameters, so we relax this to a warning. 9342 int DiagID = 9343 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9344 Diag(NewFD->getLocation(), DiagID) 9345 << FunctionType::getNameForCallConv(CC); 9346 } 9347 } 9348 9349 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9350 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9351 checkNonTrivialCUnion(NewFD->getReturnType(), 9352 NewFD->getReturnTypeSourceRange().getBegin(), 9353 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9354 } else { 9355 // C++11 [replacement.functions]p3: 9356 // The program's definitions shall not be specified as inline. 9357 // 9358 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9359 // 9360 // Suppress the diagnostic if the function is __attribute__((used)), since 9361 // that forces an external definition to be emitted. 9362 if (D.getDeclSpec().isInlineSpecified() && 9363 NewFD->isReplaceableGlobalAllocationFunction() && 9364 !NewFD->hasAttr<UsedAttr>()) 9365 Diag(D.getDeclSpec().getInlineSpecLoc(), 9366 diag::ext_operator_new_delete_declared_inline) 9367 << NewFD->getDeclName(); 9368 9369 // If the declarator is a template-id, translate the parser's template 9370 // argument list into our AST format. 9371 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9372 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9373 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9374 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9375 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9376 TemplateId->NumArgs); 9377 translateTemplateArguments(TemplateArgsPtr, 9378 TemplateArgs); 9379 9380 HasExplicitTemplateArgs = true; 9381 9382 if (NewFD->isInvalidDecl()) { 9383 HasExplicitTemplateArgs = false; 9384 } else if (FunctionTemplate) { 9385 // Function template with explicit template arguments. 9386 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9387 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9388 9389 HasExplicitTemplateArgs = false; 9390 } else { 9391 assert((isFunctionTemplateSpecialization || 9392 D.getDeclSpec().isFriendSpecified()) && 9393 "should have a 'template<>' for this decl"); 9394 // "friend void foo<>(int);" is an implicit specialization decl. 9395 isFunctionTemplateSpecialization = true; 9396 } 9397 } else if (isFriend && isFunctionTemplateSpecialization) { 9398 // This combination is only possible in a recovery case; the user 9399 // wrote something like: 9400 // template <> friend void foo(int); 9401 // which we're recovering from as if the user had written: 9402 // friend void foo<>(int); 9403 // Go ahead and fake up a template id. 9404 HasExplicitTemplateArgs = true; 9405 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9406 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9407 } 9408 9409 // We do not add HD attributes to specializations here because 9410 // they may have different constexpr-ness compared to their 9411 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9412 // may end up with different effective targets. Instead, a 9413 // specialization inherits its target attributes from its template 9414 // in the CheckFunctionTemplateSpecialization() call below. 9415 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9416 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9417 9418 // If it's a friend (and only if it's a friend), it's possible 9419 // that either the specialized function type or the specialized 9420 // template is dependent, and therefore matching will fail. In 9421 // this case, don't check the specialization yet. 9422 bool InstantiationDependent = false; 9423 if (isFunctionTemplateSpecialization && isFriend && 9424 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9425 TemplateSpecializationType::anyDependentTemplateArguments( 9426 TemplateArgs, 9427 InstantiationDependent))) { 9428 assert(HasExplicitTemplateArgs && 9429 "friend function specialization without template args"); 9430 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9431 Previous)) 9432 NewFD->setInvalidDecl(); 9433 } else if (isFunctionTemplateSpecialization) { 9434 if (CurContext->isDependentContext() && CurContext->isRecord() 9435 && !isFriend) { 9436 isDependentClassScopeExplicitSpecialization = true; 9437 } else if (!NewFD->isInvalidDecl() && 9438 CheckFunctionTemplateSpecialization( 9439 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9440 Previous)) 9441 NewFD->setInvalidDecl(); 9442 9443 // C++ [dcl.stc]p1: 9444 // A storage-class-specifier shall not be specified in an explicit 9445 // specialization (14.7.3) 9446 FunctionTemplateSpecializationInfo *Info = 9447 NewFD->getTemplateSpecializationInfo(); 9448 if (Info && SC != SC_None) { 9449 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9450 Diag(NewFD->getLocation(), 9451 diag::err_explicit_specialization_inconsistent_storage_class) 9452 << SC 9453 << FixItHint::CreateRemoval( 9454 D.getDeclSpec().getStorageClassSpecLoc()); 9455 9456 else 9457 Diag(NewFD->getLocation(), 9458 diag::ext_explicit_specialization_storage_class) 9459 << FixItHint::CreateRemoval( 9460 D.getDeclSpec().getStorageClassSpecLoc()); 9461 } 9462 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9463 if (CheckMemberSpecialization(NewFD, Previous)) 9464 NewFD->setInvalidDecl(); 9465 } 9466 9467 // Perform semantic checking on the function declaration. 9468 if (!isDependentClassScopeExplicitSpecialization) { 9469 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9470 CheckMain(NewFD, D.getDeclSpec()); 9471 9472 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9473 CheckMSVCRTEntryPoint(NewFD); 9474 9475 if (!NewFD->isInvalidDecl()) 9476 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9477 isMemberSpecialization)); 9478 else if (!Previous.empty()) 9479 // Recover gracefully from an invalid redeclaration. 9480 D.setRedeclaration(true); 9481 } 9482 9483 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9484 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9485 "previous declaration set still overloaded"); 9486 9487 NamedDecl *PrincipalDecl = (FunctionTemplate 9488 ? cast<NamedDecl>(FunctionTemplate) 9489 : NewFD); 9490 9491 if (isFriend && NewFD->getPreviousDecl()) { 9492 AccessSpecifier Access = AS_public; 9493 if (!NewFD->isInvalidDecl()) 9494 Access = NewFD->getPreviousDecl()->getAccess(); 9495 9496 NewFD->setAccess(Access); 9497 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9498 } 9499 9500 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9501 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9502 PrincipalDecl->setNonMemberOperator(); 9503 9504 // If we have a function template, check the template parameter 9505 // list. This will check and merge default template arguments. 9506 if (FunctionTemplate) { 9507 FunctionTemplateDecl *PrevTemplate = 9508 FunctionTemplate->getPreviousDecl(); 9509 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9510 PrevTemplate ? PrevTemplate->getTemplateParameters() 9511 : nullptr, 9512 D.getDeclSpec().isFriendSpecified() 9513 ? (D.isFunctionDefinition() 9514 ? TPC_FriendFunctionTemplateDefinition 9515 : TPC_FriendFunctionTemplate) 9516 : (D.getCXXScopeSpec().isSet() && 9517 DC && DC->isRecord() && 9518 DC->isDependentContext()) 9519 ? TPC_ClassTemplateMember 9520 : TPC_FunctionTemplate); 9521 } 9522 9523 if (NewFD->isInvalidDecl()) { 9524 // Ignore all the rest of this. 9525 } else if (!D.isRedeclaration()) { 9526 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9527 AddToScope }; 9528 // Fake up an access specifier if it's supposed to be a class member. 9529 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9530 NewFD->setAccess(AS_public); 9531 9532 // Qualified decls generally require a previous declaration. 9533 if (D.getCXXScopeSpec().isSet()) { 9534 // ...with the major exception of templated-scope or 9535 // dependent-scope friend declarations. 9536 9537 // TODO: we currently also suppress this check in dependent 9538 // contexts because (1) the parameter depth will be off when 9539 // matching friend templates and (2) we might actually be 9540 // selecting a friend based on a dependent factor. But there 9541 // are situations where these conditions don't apply and we 9542 // can actually do this check immediately. 9543 // 9544 // Unless the scope is dependent, it's always an error if qualified 9545 // redeclaration lookup found nothing at all. Diagnose that now; 9546 // nothing will diagnose that error later. 9547 if (isFriend && 9548 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9549 (!Previous.empty() && CurContext->isDependentContext()))) { 9550 // ignore these 9551 } else { 9552 // The user tried to provide an out-of-line definition for a 9553 // function that is a member of a class or namespace, but there 9554 // was no such member function declared (C++ [class.mfct]p2, 9555 // C++ [namespace.memdef]p2). For example: 9556 // 9557 // class X { 9558 // void f() const; 9559 // }; 9560 // 9561 // void X::f() { } // ill-formed 9562 // 9563 // Complain about this problem, and attempt to suggest close 9564 // matches (e.g., those that differ only in cv-qualifiers and 9565 // whether the parameter types are references). 9566 9567 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9568 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9569 AddToScope = ExtraArgs.AddToScope; 9570 return Result; 9571 } 9572 } 9573 9574 // Unqualified local friend declarations are required to resolve 9575 // to something. 9576 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9577 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9578 *this, Previous, NewFD, ExtraArgs, true, S)) { 9579 AddToScope = ExtraArgs.AddToScope; 9580 return Result; 9581 } 9582 } 9583 } else if (!D.isFunctionDefinition() && 9584 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9585 !isFriend && !isFunctionTemplateSpecialization && 9586 !isMemberSpecialization) { 9587 // An out-of-line member function declaration must also be a 9588 // definition (C++ [class.mfct]p2). 9589 // Note that this is not the case for explicit specializations of 9590 // function templates or member functions of class templates, per 9591 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9592 // extension for compatibility with old SWIG code which likes to 9593 // generate them. 9594 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9595 << D.getCXXScopeSpec().getRange(); 9596 } 9597 } 9598 9599 ProcessPragmaWeak(S, NewFD); 9600 checkAttributesAfterMerging(*this, *NewFD); 9601 9602 AddKnownFunctionAttributes(NewFD); 9603 9604 if (NewFD->hasAttr<OverloadableAttr>() && 9605 !NewFD->getType()->getAs<FunctionProtoType>()) { 9606 Diag(NewFD->getLocation(), 9607 diag::err_attribute_overloadable_no_prototype) 9608 << NewFD; 9609 9610 // Turn this into a variadic function with no parameters. 9611 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9612 FunctionProtoType::ExtProtoInfo EPI( 9613 Context.getDefaultCallingConvention(true, false)); 9614 EPI.Variadic = true; 9615 EPI.ExtInfo = FT->getExtInfo(); 9616 9617 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9618 NewFD->setType(R); 9619 } 9620 9621 // If there's a #pragma GCC visibility in scope, and this isn't a class 9622 // member, set the visibility of this function. 9623 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9624 AddPushedVisibilityAttribute(NewFD); 9625 9626 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9627 // marking the function. 9628 AddCFAuditedAttribute(NewFD); 9629 9630 // If this is a function definition, check if we have to apply optnone due to 9631 // a pragma. 9632 if(D.isFunctionDefinition()) 9633 AddRangeBasedOptnone(NewFD); 9634 9635 // If this is the first declaration of an extern C variable, update 9636 // the map of such variables. 9637 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9638 isIncompleteDeclExternC(*this, NewFD)) 9639 RegisterLocallyScopedExternCDecl(NewFD, S); 9640 9641 // Set this FunctionDecl's range up to the right paren. 9642 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9643 9644 if (D.isRedeclaration() && !Previous.empty()) { 9645 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9646 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9647 isMemberSpecialization || 9648 isFunctionTemplateSpecialization, 9649 D.isFunctionDefinition()); 9650 } 9651 9652 if (getLangOpts().CUDA) { 9653 IdentifierInfo *II = NewFD->getIdentifier(); 9654 if (II && II->isStr(getCudaConfigureFuncName()) && 9655 !NewFD->isInvalidDecl() && 9656 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9657 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9658 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9659 << getCudaConfigureFuncName(); 9660 Context.setcudaConfigureCallDecl(NewFD); 9661 } 9662 9663 // Variadic functions, other than a *declaration* of printf, are not allowed 9664 // in device-side CUDA code, unless someone passed 9665 // -fcuda-allow-variadic-functions. 9666 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9667 (NewFD->hasAttr<CUDADeviceAttr>() || 9668 NewFD->hasAttr<CUDAGlobalAttr>()) && 9669 !(II && II->isStr("printf") && NewFD->isExternC() && 9670 !D.isFunctionDefinition())) { 9671 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9672 } 9673 } 9674 9675 MarkUnusedFileScopedDecl(NewFD); 9676 9677 9678 9679 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9680 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9681 if ((getLangOpts().OpenCLVersion >= 120) 9682 && (SC == SC_Static)) { 9683 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9684 D.setInvalidType(); 9685 } 9686 9687 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9688 if (!NewFD->getReturnType()->isVoidType()) { 9689 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9690 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9691 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9692 : FixItHint()); 9693 D.setInvalidType(); 9694 } 9695 9696 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9697 for (auto Param : NewFD->parameters()) 9698 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9699 9700 if (getLangOpts().OpenCLCPlusPlus) { 9701 if (DC->isRecord()) { 9702 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9703 D.setInvalidType(); 9704 } 9705 if (FunctionTemplate) { 9706 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9707 D.setInvalidType(); 9708 } 9709 } 9710 } 9711 9712 if (getLangOpts().CPlusPlus) { 9713 if (FunctionTemplate) { 9714 if (NewFD->isInvalidDecl()) 9715 FunctionTemplate->setInvalidDecl(); 9716 return FunctionTemplate; 9717 } 9718 9719 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9720 CompleteMemberSpecialization(NewFD, Previous); 9721 } 9722 9723 for (const ParmVarDecl *Param : NewFD->parameters()) { 9724 QualType PT = Param->getType(); 9725 9726 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9727 // types. 9728 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9729 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9730 QualType ElemTy = PipeTy->getElementType(); 9731 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9732 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9733 D.setInvalidType(); 9734 } 9735 } 9736 } 9737 } 9738 9739 // Here we have an function template explicit specialization at class scope. 9740 // The actual specialization will be postponed to template instatiation 9741 // time via the ClassScopeFunctionSpecializationDecl node. 9742 if (isDependentClassScopeExplicitSpecialization) { 9743 ClassScopeFunctionSpecializationDecl *NewSpec = 9744 ClassScopeFunctionSpecializationDecl::Create( 9745 Context, CurContext, NewFD->getLocation(), 9746 cast<CXXMethodDecl>(NewFD), 9747 HasExplicitTemplateArgs, TemplateArgs); 9748 CurContext->addDecl(NewSpec); 9749 AddToScope = false; 9750 } 9751 9752 // Diagnose availability attributes. Availability cannot be used on functions 9753 // that are run during load/unload. 9754 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9755 if (NewFD->hasAttr<ConstructorAttr>()) { 9756 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9757 << 1; 9758 NewFD->dropAttr<AvailabilityAttr>(); 9759 } 9760 if (NewFD->hasAttr<DestructorAttr>()) { 9761 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9762 << 2; 9763 NewFD->dropAttr<AvailabilityAttr>(); 9764 } 9765 } 9766 9767 // Diagnose no_builtin attribute on function declaration that are not a 9768 // definition. 9769 // FIXME: We should really be doing this in 9770 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9771 // the FunctionDecl and at this point of the code 9772 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9773 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9774 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9775 switch (D.getFunctionDefinitionKind()) { 9776 case FDK_Defaulted: 9777 case FDK_Deleted: 9778 Diag(NBA->getLocation(), 9779 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9780 << NBA->getSpelling(); 9781 break; 9782 case FDK_Declaration: 9783 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9784 << NBA->getSpelling(); 9785 break; 9786 case FDK_Definition: 9787 break; 9788 } 9789 9790 return NewFD; 9791 } 9792 9793 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9794 /// when __declspec(code_seg) "is applied to a class, all member functions of 9795 /// the class and nested classes -- this includes compiler-generated special 9796 /// member functions -- are put in the specified segment." 9797 /// The actual behavior is a little more complicated. The Microsoft compiler 9798 /// won't check outer classes if there is an active value from #pragma code_seg. 9799 /// The CodeSeg is always applied from the direct parent but only from outer 9800 /// classes when the #pragma code_seg stack is empty. See: 9801 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9802 /// available since MS has removed the page. 9803 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9804 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9805 if (!Method) 9806 return nullptr; 9807 const CXXRecordDecl *Parent = Method->getParent(); 9808 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9809 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9810 NewAttr->setImplicit(true); 9811 return NewAttr; 9812 } 9813 9814 // The Microsoft compiler won't check outer classes for the CodeSeg 9815 // when the #pragma code_seg stack is active. 9816 if (S.CodeSegStack.CurrentValue) 9817 return nullptr; 9818 9819 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9820 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9821 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9822 NewAttr->setImplicit(true); 9823 return NewAttr; 9824 } 9825 } 9826 return nullptr; 9827 } 9828 9829 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9830 /// containing class. Otherwise it will return implicit SectionAttr if the 9831 /// function is a definition and there is an active value on CodeSegStack 9832 /// (from the current #pragma code-seg value). 9833 /// 9834 /// \param FD Function being declared. 9835 /// \param IsDefinition Whether it is a definition or just a declarartion. 9836 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9837 /// nullptr if no attribute should be added. 9838 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9839 bool IsDefinition) { 9840 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9841 return A; 9842 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9843 CodeSegStack.CurrentValue) 9844 return SectionAttr::CreateImplicit( 9845 getASTContext(), CodeSegStack.CurrentValue->getString(), 9846 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9847 SectionAttr::Declspec_allocate); 9848 return nullptr; 9849 } 9850 9851 /// Determines if we can perform a correct type check for \p D as a 9852 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9853 /// best-effort check. 9854 /// 9855 /// \param NewD The new declaration. 9856 /// \param OldD The old declaration. 9857 /// \param NewT The portion of the type of the new declaration to check. 9858 /// \param OldT The portion of the type of the old declaration to check. 9859 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9860 QualType NewT, QualType OldT) { 9861 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9862 return true; 9863 9864 // For dependently-typed local extern declarations and friends, we can't 9865 // perform a correct type check in general until instantiation: 9866 // 9867 // int f(); 9868 // template<typename T> void g() { T f(); } 9869 // 9870 // (valid if g() is only instantiated with T = int). 9871 if (NewT->isDependentType() && 9872 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9873 return false; 9874 9875 // Similarly, if the previous declaration was a dependent local extern 9876 // declaration, we don't really know its type yet. 9877 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9878 return false; 9879 9880 return true; 9881 } 9882 9883 /// Checks if the new declaration declared in dependent context must be 9884 /// put in the same redeclaration chain as the specified declaration. 9885 /// 9886 /// \param D Declaration that is checked. 9887 /// \param PrevDecl Previous declaration found with proper lookup method for the 9888 /// same declaration name. 9889 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9890 /// belongs to. 9891 /// 9892 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9893 if (!D->getLexicalDeclContext()->isDependentContext()) 9894 return true; 9895 9896 // Don't chain dependent friend function definitions until instantiation, to 9897 // permit cases like 9898 // 9899 // void func(); 9900 // template<typename T> class C1 { friend void func() {} }; 9901 // template<typename T> class C2 { friend void func() {} }; 9902 // 9903 // ... which is valid if only one of C1 and C2 is ever instantiated. 9904 // 9905 // FIXME: This need only apply to function definitions. For now, we proxy 9906 // this by checking for a file-scope function. We do not want this to apply 9907 // to friend declarations nominating member functions, because that gets in 9908 // the way of access checks. 9909 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9910 return false; 9911 9912 auto *VD = dyn_cast<ValueDecl>(D); 9913 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 9914 return !VD || !PrevVD || 9915 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 9916 PrevVD->getType()); 9917 } 9918 9919 /// Check the target attribute of the function for MultiVersion 9920 /// validity. 9921 /// 9922 /// Returns true if there was an error, false otherwise. 9923 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9924 const auto *TA = FD->getAttr<TargetAttr>(); 9925 assert(TA && "MultiVersion Candidate requires a target attribute"); 9926 ParsedTargetAttr ParseInfo = TA->parse(); 9927 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9928 enum ErrType { Feature = 0, Architecture = 1 }; 9929 9930 if (!ParseInfo.Architecture.empty() && 9931 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9932 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9933 << Architecture << ParseInfo.Architecture; 9934 return true; 9935 } 9936 9937 for (const auto &Feat : ParseInfo.Features) { 9938 auto BareFeat = StringRef{Feat}.substr(1); 9939 if (Feat[0] == '-') { 9940 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9941 << Feature << ("no-" + BareFeat).str(); 9942 return true; 9943 } 9944 9945 if (!TargetInfo.validateCpuSupports(BareFeat) || 9946 !TargetInfo.isValidFeatureName(BareFeat)) { 9947 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9948 << Feature << BareFeat; 9949 return true; 9950 } 9951 } 9952 return false; 9953 } 9954 9955 // Provide a white-list of attributes that are allowed to be combined with 9956 // multiversion functions. 9957 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 9958 MultiVersionKind MVType) { 9959 switch (Kind) { 9960 default: 9961 return false; 9962 case attr::Used: 9963 return MVType == MultiVersionKind::Target; 9964 } 9965 } 9966 9967 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, 9968 MultiVersionKind MVType) { 9969 for (const Attr *A : FD->attrs()) { 9970 switch (A->getKind()) { 9971 case attr::CPUDispatch: 9972 case attr::CPUSpecific: 9973 if (MVType != MultiVersionKind::CPUDispatch && 9974 MVType != MultiVersionKind::CPUSpecific) 9975 return true; 9976 break; 9977 case attr::Target: 9978 if (MVType != MultiVersionKind::Target) 9979 return true; 9980 break; 9981 default: 9982 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 9983 return true; 9984 break; 9985 } 9986 } 9987 return false; 9988 } 9989 9990 bool Sema::areMultiversionVariantFunctionsCompatible( 9991 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 9992 const PartialDiagnostic &NoProtoDiagID, 9993 const PartialDiagnosticAt &NoteCausedDiagIDAt, 9994 const PartialDiagnosticAt &NoSupportDiagIDAt, 9995 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 9996 bool ConstexprSupported, bool CLinkageMayDiffer) { 9997 enum DoesntSupport { 9998 FuncTemplates = 0, 9999 VirtFuncs = 1, 10000 DeducedReturn = 2, 10001 Constructors = 3, 10002 Destructors = 4, 10003 DeletedFuncs = 5, 10004 DefaultedFuncs = 6, 10005 ConstexprFuncs = 7, 10006 ConstevalFuncs = 8, 10007 }; 10008 enum Different { 10009 CallingConv = 0, 10010 ReturnType = 1, 10011 ConstexprSpec = 2, 10012 InlineSpec = 3, 10013 StorageClass = 4, 10014 Linkage = 5, 10015 }; 10016 10017 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10018 !OldFD->getType()->getAs<FunctionProtoType>()) { 10019 Diag(OldFD->getLocation(), NoProtoDiagID); 10020 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10021 return true; 10022 } 10023 10024 if (NoProtoDiagID.getDiagID() != 0 && 10025 !NewFD->getType()->getAs<FunctionProtoType>()) 10026 return Diag(NewFD->getLocation(), NoProtoDiagID); 10027 10028 if (!TemplatesSupported && 10029 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10030 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10031 << FuncTemplates; 10032 10033 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10034 if (NewCXXFD->isVirtual()) 10035 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10036 << VirtFuncs; 10037 10038 if (isa<CXXConstructorDecl>(NewCXXFD)) 10039 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10040 << Constructors; 10041 10042 if (isa<CXXDestructorDecl>(NewCXXFD)) 10043 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10044 << Destructors; 10045 } 10046 10047 if (NewFD->isDeleted()) 10048 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10049 << DeletedFuncs; 10050 10051 if (NewFD->isDefaulted()) 10052 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10053 << DefaultedFuncs; 10054 10055 if (!ConstexprSupported && NewFD->isConstexpr()) 10056 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10057 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10058 10059 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10060 const auto *NewType = cast<FunctionType>(NewQType); 10061 QualType NewReturnType = NewType->getReturnType(); 10062 10063 if (NewReturnType->isUndeducedType()) 10064 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10065 << DeducedReturn; 10066 10067 // Ensure the return type is identical. 10068 if (OldFD) { 10069 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10070 const auto *OldType = cast<FunctionType>(OldQType); 10071 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10072 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10073 10074 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10075 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10076 10077 QualType OldReturnType = OldType->getReturnType(); 10078 10079 if (OldReturnType != NewReturnType) 10080 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10081 10082 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10083 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10084 10085 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10086 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10087 10088 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10089 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10090 10091 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10092 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10093 10094 if (CheckEquivalentExceptionSpec( 10095 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10096 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10097 return true; 10098 } 10099 return false; 10100 } 10101 10102 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10103 const FunctionDecl *NewFD, 10104 bool CausesMV, 10105 MultiVersionKind MVType) { 10106 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10107 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10108 if (OldFD) 10109 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10110 return true; 10111 } 10112 10113 bool IsCPUSpecificCPUDispatchMVType = 10114 MVType == MultiVersionKind::CPUDispatch || 10115 MVType == MultiVersionKind::CPUSpecific; 10116 10117 // For now, disallow all other attributes. These should be opt-in, but 10118 // an analysis of all of them is a future FIXME. 10119 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { 10120 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) 10121 << IsCPUSpecificCPUDispatchMVType; 10122 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10123 return true; 10124 } 10125 10126 if (HasNonMultiVersionAttributes(NewFD, MVType)) 10127 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) 10128 << IsCPUSpecificCPUDispatchMVType; 10129 10130 // Only allow transition to MultiVersion if it hasn't been used. 10131 if (OldFD && CausesMV && OldFD->isUsed(false)) 10132 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10133 10134 return S.areMultiversionVariantFunctionsCompatible( 10135 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10136 PartialDiagnosticAt(NewFD->getLocation(), 10137 S.PDiag(diag::note_multiversioning_caused_here)), 10138 PartialDiagnosticAt(NewFD->getLocation(), 10139 S.PDiag(diag::err_multiversion_doesnt_support) 10140 << IsCPUSpecificCPUDispatchMVType), 10141 PartialDiagnosticAt(NewFD->getLocation(), 10142 S.PDiag(diag::err_multiversion_diff)), 10143 /*TemplatesSupported=*/false, 10144 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10145 /*CLinkageMayDiffer=*/false); 10146 } 10147 10148 /// Check the validity of a multiversion function declaration that is the 10149 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10150 /// 10151 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10152 /// 10153 /// Returns true if there was an error, false otherwise. 10154 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10155 MultiVersionKind MVType, 10156 const TargetAttr *TA) { 10157 assert(MVType != MultiVersionKind::None && 10158 "Function lacks multiversion attribute"); 10159 10160 // Target only causes MV if it is default, otherwise this is a normal 10161 // function. 10162 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10163 return false; 10164 10165 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10166 FD->setInvalidDecl(); 10167 return true; 10168 } 10169 10170 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10171 FD->setInvalidDecl(); 10172 return true; 10173 } 10174 10175 FD->setIsMultiVersion(); 10176 return false; 10177 } 10178 10179 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10180 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10181 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10182 return true; 10183 } 10184 10185 return false; 10186 } 10187 10188 static bool CheckTargetCausesMultiVersioning( 10189 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10190 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10191 LookupResult &Previous) { 10192 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10193 ParsedTargetAttr NewParsed = NewTA->parse(); 10194 // Sort order doesn't matter, it just needs to be consistent. 10195 llvm::sort(NewParsed.Features); 10196 10197 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10198 // to change, this is a simple redeclaration. 10199 if (!NewTA->isDefaultVersion() && 10200 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10201 return false; 10202 10203 // Otherwise, this decl causes MultiVersioning. 10204 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10205 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10206 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10207 NewFD->setInvalidDecl(); 10208 return true; 10209 } 10210 10211 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10212 MultiVersionKind::Target)) { 10213 NewFD->setInvalidDecl(); 10214 return true; 10215 } 10216 10217 if (CheckMultiVersionValue(S, NewFD)) { 10218 NewFD->setInvalidDecl(); 10219 return true; 10220 } 10221 10222 // If this is 'default', permit the forward declaration. 10223 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10224 Redeclaration = true; 10225 OldDecl = OldFD; 10226 OldFD->setIsMultiVersion(); 10227 NewFD->setIsMultiVersion(); 10228 return false; 10229 } 10230 10231 if (CheckMultiVersionValue(S, OldFD)) { 10232 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10233 NewFD->setInvalidDecl(); 10234 return true; 10235 } 10236 10237 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10238 10239 if (OldParsed == NewParsed) { 10240 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10241 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10242 NewFD->setInvalidDecl(); 10243 return true; 10244 } 10245 10246 for (const auto *FD : OldFD->redecls()) { 10247 const auto *CurTA = FD->getAttr<TargetAttr>(); 10248 // We allow forward declarations before ANY multiversioning attributes, but 10249 // nothing after the fact. 10250 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10251 (!CurTA || CurTA->isInherited())) { 10252 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10253 << 0; 10254 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10255 NewFD->setInvalidDecl(); 10256 return true; 10257 } 10258 } 10259 10260 OldFD->setIsMultiVersion(); 10261 NewFD->setIsMultiVersion(); 10262 Redeclaration = false; 10263 MergeTypeWithPrevious = false; 10264 OldDecl = nullptr; 10265 Previous.clear(); 10266 return false; 10267 } 10268 10269 /// Check the validity of a new function declaration being added to an existing 10270 /// multiversioned declaration collection. 10271 static bool CheckMultiVersionAdditionalDecl( 10272 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10273 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10274 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10275 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10276 LookupResult &Previous) { 10277 10278 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10279 // Disallow mixing of multiversioning types. 10280 if ((OldMVType == MultiVersionKind::Target && 10281 NewMVType != MultiVersionKind::Target) || 10282 (NewMVType == MultiVersionKind::Target && 10283 OldMVType != MultiVersionKind::Target)) { 10284 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10285 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10286 NewFD->setInvalidDecl(); 10287 return true; 10288 } 10289 10290 ParsedTargetAttr NewParsed; 10291 if (NewTA) { 10292 NewParsed = NewTA->parse(); 10293 llvm::sort(NewParsed.Features); 10294 } 10295 10296 bool UseMemberUsingDeclRules = 10297 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10298 10299 // Next, check ALL non-overloads to see if this is a redeclaration of a 10300 // previous member of the MultiVersion set. 10301 for (NamedDecl *ND : Previous) { 10302 FunctionDecl *CurFD = ND->getAsFunction(); 10303 if (!CurFD) 10304 continue; 10305 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10306 continue; 10307 10308 if (NewMVType == MultiVersionKind::Target) { 10309 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10310 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10311 NewFD->setIsMultiVersion(); 10312 Redeclaration = true; 10313 OldDecl = ND; 10314 return false; 10315 } 10316 10317 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10318 if (CurParsed == NewParsed) { 10319 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10320 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10321 NewFD->setInvalidDecl(); 10322 return true; 10323 } 10324 } else { 10325 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10326 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10327 // Handle CPUDispatch/CPUSpecific versions. 10328 // Only 1 CPUDispatch function is allowed, this will make it go through 10329 // the redeclaration errors. 10330 if (NewMVType == MultiVersionKind::CPUDispatch && 10331 CurFD->hasAttr<CPUDispatchAttr>()) { 10332 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10333 std::equal( 10334 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10335 NewCPUDisp->cpus_begin(), 10336 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10337 return Cur->getName() == New->getName(); 10338 })) { 10339 NewFD->setIsMultiVersion(); 10340 Redeclaration = true; 10341 OldDecl = ND; 10342 return false; 10343 } 10344 10345 // If the declarations don't match, this is an error condition. 10346 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10347 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10348 NewFD->setInvalidDecl(); 10349 return true; 10350 } 10351 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10352 10353 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10354 std::equal( 10355 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10356 NewCPUSpec->cpus_begin(), 10357 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10358 return Cur->getName() == New->getName(); 10359 })) { 10360 NewFD->setIsMultiVersion(); 10361 Redeclaration = true; 10362 OldDecl = ND; 10363 return false; 10364 } 10365 10366 // Only 1 version of CPUSpecific is allowed for each CPU. 10367 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10368 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10369 if (CurII == NewII) { 10370 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10371 << NewII; 10372 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10373 NewFD->setInvalidDecl(); 10374 return true; 10375 } 10376 } 10377 } 10378 } 10379 // If the two decls aren't the same MVType, there is no possible error 10380 // condition. 10381 } 10382 } 10383 10384 // Else, this is simply a non-redecl case. Checking the 'value' is only 10385 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10386 // handled in the attribute adding step. 10387 if (NewMVType == MultiVersionKind::Target && 10388 CheckMultiVersionValue(S, NewFD)) { 10389 NewFD->setInvalidDecl(); 10390 return true; 10391 } 10392 10393 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10394 !OldFD->isMultiVersion(), NewMVType)) { 10395 NewFD->setInvalidDecl(); 10396 return true; 10397 } 10398 10399 // Permit forward declarations in the case where these two are compatible. 10400 if (!OldFD->isMultiVersion()) { 10401 OldFD->setIsMultiVersion(); 10402 NewFD->setIsMultiVersion(); 10403 Redeclaration = true; 10404 OldDecl = OldFD; 10405 return false; 10406 } 10407 10408 NewFD->setIsMultiVersion(); 10409 Redeclaration = false; 10410 MergeTypeWithPrevious = false; 10411 OldDecl = nullptr; 10412 Previous.clear(); 10413 return false; 10414 } 10415 10416 10417 /// Check the validity of a mulitversion function declaration. 10418 /// Also sets the multiversion'ness' of the function itself. 10419 /// 10420 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10421 /// 10422 /// Returns true if there was an error, false otherwise. 10423 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10424 bool &Redeclaration, NamedDecl *&OldDecl, 10425 bool &MergeTypeWithPrevious, 10426 LookupResult &Previous) { 10427 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10428 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10429 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10430 10431 // Mixing Multiversioning types is prohibited. 10432 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10433 (NewCPUDisp && NewCPUSpec)) { 10434 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10435 NewFD->setInvalidDecl(); 10436 return true; 10437 } 10438 10439 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10440 10441 // Main isn't allowed to become a multiversion function, however it IS 10442 // permitted to have 'main' be marked with the 'target' optimization hint. 10443 if (NewFD->isMain()) { 10444 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10445 MVType == MultiVersionKind::CPUDispatch || 10446 MVType == MultiVersionKind::CPUSpecific) { 10447 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10448 NewFD->setInvalidDecl(); 10449 return true; 10450 } 10451 return false; 10452 } 10453 10454 if (!OldDecl || !OldDecl->getAsFunction() || 10455 OldDecl->getDeclContext()->getRedeclContext() != 10456 NewFD->getDeclContext()->getRedeclContext()) { 10457 // If there's no previous declaration, AND this isn't attempting to cause 10458 // multiversioning, this isn't an error condition. 10459 if (MVType == MultiVersionKind::None) 10460 return false; 10461 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10462 } 10463 10464 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10465 10466 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10467 return false; 10468 10469 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10470 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10471 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10472 NewFD->setInvalidDecl(); 10473 return true; 10474 } 10475 10476 // Handle the target potentially causes multiversioning case. 10477 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10478 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10479 Redeclaration, OldDecl, 10480 MergeTypeWithPrevious, Previous); 10481 10482 // At this point, we have a multiversion function decl (in OldFD) AND an 10483 // appropriate attribute in the current function decl. Resolve that these are 10484 // still compatible with previous declarations. 10485 return CheckMultiVersionAdditionalDecl( 10486 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10487 OldDecl, MergeTypeWithPrevious, Previous); 10488 } 10489 10490 /// Perform semantic checking of a new function declaration. 10491 /// 10492 /// Performs semantic analysis of the new function declaration 10493 /// NewFD. This routine performs all semantic checking that does not 10494 /// require the actual declarator involved in the declaration, and is 10495 /// used both for the declaration of functions as they are parsed 10496 /// (called via ActOnDeclarator) and for the declaration of functions 10497 /// that have been instantiated via C++ template instantiation (called 10498 /// via InstantiateDecl). 10499 /// 10500 /// \param IsMemberSpecialization whether this new function declaration is 10501 /// a member specialization (that replaces any definition provided by the 10502 /// previous declaration). 10503 /// 10504 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10505 /// 10506 /// \returns true if the function declaration is a redeclaration. 10507 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10508 LookupResult &Previous, 10509 bool IsMemberSpecialization) { 10510 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10511 "Variably modified return types are not handled here"); 10512 10513 // Determine whether the type of this function should be merged with 10514 // a previous visible declaration. This never happens for functions in C++, 10515 // and always happens in C if the previous declaration was visible. 10516 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10517 !Previous.isShadowed(); 10518 10519 bool Redeclaration = false; 10520 NamedDecl *OldDecl = nullptr; 10521 bool MayNeedOverloadableChecks = false; 10522 10523 // Merge or overload the declaration with an existing declaration of 10524 // the same name, if appropriate. 10525 if (!Previous.empty()) { 10526 // Determine whether NewFD is an overload of PrevDecl or 10527 // a declaration that requires merging. If it's an overload, 10528 // there's no more work to do here; we'll just add the new 10529 // function to the scope. 10530 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10531 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10532 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10533 Redeclaration = true; 10534 OldDecl = Candidate; 10535 } 10536 } else { 10537 MayNeedOverloadableChecks = true; 10538 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10539 /*NewIsUsingDecl*/ false)) { 10540 case Ovl_Match: 10541 Redeclaration = true; 10542 break; 10543 10544 case Ovl_NonFunction: 10545 Redeclaration = true; 10546 break; 10547 10548 case Ovl_Overload: 10549 Redeclaration = false; 10550 break; 10551 } 10552 } 10553 } 10554 10555 // Check for a previous extern "C" declaration with this name. 10556 if (!Redeclaration && 10557 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10558 if (!Previous.empty()) { 10559 // This is an extern "C" declaration with the same name as a previous 10560 // declaration, and thus redeclares that entity... 10561 Redeclaration = true; 10562 OldDecl = Previous.getFoundDecl(); 10563 MergeTypeWithPrevious = false; 10564 10565 // ... except in the presence of __attribute__((overloadable)). 10566 if (OldDecl->hasAttr<OverloadableAttr>() || 10567 NewFD->hasAttr<OverloadableAttr>()) { 10568 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10569 MayNeedOverloadableChecks = true; 10570 Redeclaration = false; 10571 OldDecl = nullptr; 10572 } 10573 } 10574 } 10575 } 10576 10577 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10578 MergeTypeWithPrevious, Previous)) 10579 return Redeclaration; 10580 10581 // C++11 [dcl.constexpr]p8: 10582 // A constexpr specifier for a non-static member function that is not 10583 // a constructor declares that member function to be const. 10584 // 10585 // This needs to be delayed until we know whether this is an out-of-line 10586 // definition of a static member function. 10587 // 10588 // This rule is not present in C++1y, so we produce a backwards 10589 // compatibility warning whenever it happens in C++11. 10590 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10591 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10592 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10593 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10594 CXXMethodDecl *OldMD = nullptr; 10595 if (OldDecl) 10596 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10597 if (!OldMD || !OldMD->isStatic()) { 10598 const FunctionProtoType *FPT = 10599 MD->getType()->castAs<FunctionProtoType>(); 10600 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10601 EPI.TypeQuals.addConst(); 10602 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10603 FPT->getParamTypes(), EPI)); 10604 10605 // Warn that we did this, if we're not performing template instantiation. 10606 // In that case, we'll have warned already when the template was defined. 10607 if (!inTemplateInstantiation()) { 10608 SourceLocation AddConstLoc; 10609 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10610 .IgnoreParens().getAs<FunctionTypeLoc>()) 10611 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10612 10613 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10614 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10615 } 10616 } 10617 } 10618 10619 if (Redeclaration) { 10620 // NewFD and OldDecl represent declarations that need to be 10621 // merged. 10622 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10623 NewFD->setInvalidDecl(); 10624 return Redeclaration; 10625 } 10626 10627 Previous.clear(); 10628 Previous.addDecl(OldDecl); 10629 10630 if (FunctionTemplateDecl *OldTemplateDecl = 10631 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10632 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10633 FunctionTemplateDecl *NewTemplateDecl 10634 = NewFD->getDescribedFunctionTemplate(); 10635 assert(NewTemplateDecl && "Template/non-template mismatch"); 10636 10637 // The call to MergeFunctionDecl above may have created some state in 10638 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10639 // can add it as a redeclaration. 10640 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10641 10642 NewFD->setPreviousDeclaration(OldFD); 10643 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10644 if (NewFD->isCXXClassMember()) { 10645 NewFD->setAccess(OldTemplateDecl->getAccess()); 10646 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10647 } 10648 10649 // If this is an explicit specialization of a member that is a function 10650 // template, mark it as a member specialization. 10651 if (IsMemberSpecialization && 10652 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10653 NewTemplateDecl->setMemberSpecialization(); 10654 assert(OldTemplateDecl->isMemberSpecialization()); 10655 // Explicit specializations of a member template do not inherit deleted 10656 // status from the parent member template that they are specializing. 10657 if (OldFD->isDeleted()) { 10658 // FIXME: This assert will not hold in the presence of modules. 10659 assert(OldFD->getCanonicalDecl() == OldFD); 10660 // FIXME: We need an update record for this AST mutation. 10661 OldFD->setDeletedAsWritten(false); 10662 } 10663 } 10664 10665 } else { 10666 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10667 auto *OldFD = cast<FunctionDecl>(OldDecl); 10668 // This needs to happen first so that 'inline' propagates. 10669 NewFD->setPreviousDeclaration(OldFD); 10670 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10671 if (NewFD->isCXXClassMember()) 10672 NewFD->setAccess(OldFD->getAccess()); 10673 } 10674 } 10675 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10676 !NewFD->getAttr<OverloadableAttr>()) { 10677 assert((Previous.empty() || 10678 llvm::any_of(Previous, 10679 [](const NamedDecl *ND) { 10680 return ND->hasAttr<OverloadableAttr>(); 10681 })) && 10682 "Non-redecls shouldn't happen without overloadable present"); 10683 10684 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10685 const auto *FD = dyn_cast<FunctionDecl>(ND); 10686 return FD && !FD->hasAttr<OverloadableAttr>(); 10687 }); 10688 10689 if (OtherUnmarkedIter != Previous.end()) { 10690 Diag(NewFD->getLocation(), 10691 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10692 Diag((*OtherUnmarkedIter)->getLocation(), 10693 diag::note_attribute_overloadable_prev_overload) 10694 << false; 10695 10696 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10697 } 10698 } 10699 10700 // Semantic checking for this function declaration (in isolation). 10701 10702 if (getLangOpts().CPlusPlus) { 10703 // C++-specific checks. 10704 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10705 CheckConstructor(Constructor); 10706 } else if (CXXDestructorDecl *Destructor = 10707 dyn_cast<CXXDestructorDecl>(NewFD)) { 10708 CXXRecordDecl *Record = Destructor->getParent(); 10709 QualType ClassType = Context.getTypeDeclType(Record); 10710 10711 // FIXME: Shouldn't we be able to perform this check even when the class 10712 // type is dependent? Both gcc and edg can handle that. 10713 if (!ClassType->isDependentType()) { 10714 DeclarationName Name 10715 = Context.DeclarationNames.getCXXDestructorName( 10716 Context.getCanonicalType(ClassType)); 10717 if (NewFD->getDeclName() != Name) { 10718 Diag(NewFD->getLocation(), diag::err_destructor_name); 10719 NewFD->setInvalidDecl(); 10720 return Redeclaration; 10721 } 10722 } 10723 } else if (CXXConversionDecl *Conversion 10724 = dyn_cast<CXXConversionDecl>(NewFD)) { 10725 ActOnConversionDeclarator(Conversion); 10726 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10727 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10728 CheckDeductionGuideTemplate(TD); 10729 10730 // A deduction guide is not on the list of entities that can be 10731 // explicitly specialized. 10732 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10733 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10734 << /*explicit specialization*/ 1; 10735 } 10736 10737 // Find any virtual functions that this function overrides. 10738 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10739 if (!Method->isFunctionTemplateSpecialization() && 10740 !Method->getDescribedFunctionTemplate() && 10741 Method->isCanonicalDecl()) { 10742 if (AddOverriddenMethods(Method->getParent(), Method)) { 10743 // If the function was marked as "static", we have a problem. 10744 if (NewFD->getStorageClass() == SC_Static) { 10745 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 10746 } 10747 } 10748 } 10749 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10750 // C++2a [class.virtual]p6 10751 // A virtual method shall not have a requires-clause. 10752 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10753 diag::err_constrained_virtual_method); 10754 10755 if (Method->isStatic()) 10756 checkThisInStaticMemberFunctionType(Method); 10757 } 10758 10759 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10760 if (NewFD->isOverloadedOperator() && 10761 CheckOverloadedOperatorDeclaration(NewFD)) { 10762 NewFD->setInvalidDecl(); 10763 return Redeclaration; 10764 } 10765 10766 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10767 if (NewFD->getLiteralIdentifier() && 10768 CheckLiteralOperatorDeclaration(NewFD)) { 10769 NewFD->setInvalidDecl(); 10770 return Redeclaration; 10771 } 10772 10773 // In C++, check default arguments now that we have merged decls. Unless 10774 // the lexical context is the class, because in this case this is done 10775 // during delayed parsing anyway. 10776 if (!CurContext->isRecord()) 10777 CheckCXXDefaultArguments(NewFD); 10778 10779 // If this function declares a builtin function, check the type of this 10780 // declaration against the expected type for the builtin. 10781 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10782 ASTContext::GetBuiltinTypeError Error; 10783 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 10784 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10785 // If the type of the builtin differs only in its exception 10786 // specification, that's OK. 10787 // FIXME: If the types do differ in this way, it would be better to 10788 // retain the 'noexcept' form of the type. 10789 if (!T.isNull() && 10790 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10791 NewFD->getType())) 10792 // The type of this function differs from the type of the builtin, 10793 // so forget about the builtin entirely. 10794 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10795 } 10796 10797 // If this function is declared as being extern "C", then check to see if 10798 // the function returns a UDT (class, struct, or union type) that is not C 10799 // compatible, and if it does, warn the user. 10800 // But, issue any diagnostic on the first declaration only. 10801 if (Previous.empty() && NewFD->isExternC()) { 10802 QualType R = NewFD->getReturnType(); 10803 if (R->isIncompleteType() && !R->isVoidType()) 10804 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10805 << NewFD << R; 10806 else if (!R.isPODType(Context) && !R->isVoidType() && 10807 !R->isObjCObjectPointerType()) 10808 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10809 } 10810 10811 // C++1z [dcl.fct]p6: 10812 // [...] whether the function has a non-throwing exception-specification 10813 // [is] part of the function type 10814 // 10815 // This results in an ABI break between C++14 and C++17 for functions whose 10816 // declared type includes an exception-specification in a parameter or 10817 // return type. (Exception specifications on the function itself are OK in 10818 // most cases, and exception specifications are not permitted in most other 10819 // contexts where they could make it into a mangling.) 10820 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10821 auto HasNoexcept = [&](QualType T) -> bool { 10822 // Strip off declarator chunks that could be between us and a function 10823 // type. We don't need to look far, exception specifications are very 10824 // restricted prior to C++17. 10825 if (auto *RT = T->getAs<ReferenceType>()) 10826 T = RT->getPointeeType(); 10827 else if (T->isAnyPointerType()) 10828 T = T->getPointeeType(); 10829 else if (auto *MPT = T->getAs<MemberPointerType>()) 10830 T = MPT->getPointeeType(); 10831 if (auto *FPT = T->getAs<FunctionProtoType>()) 10832 if (FPT->isNothrow()) 10833 return true; 10834 return false; 10835 }; 10836 10837 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10838 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10839 for (QualType T : FPT->param_types()) 10840 AnyNoexcept |= HasNoexcept(T); 10841 if (AnyNoexcept) 10842 Diag(NewFD->getLocation(), 10843 diag::warn_cxx17_compat_exception_spec_in_signature) 10844 << NewFD; 10845 } 10846 10847 if (!Redeclaration && LangOpts.CUDA) 10848 checkCUDATargetOverload(NewFD, Previous); 10849 } 10850 return Redeclaration; 10851 } 10852 10853 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10854 // C++11 [basic.start.main]p3: 10855 // A program that [...] declares main to be inline, static or 10856 // constexpr is ill-formed. 10857 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10858 // appear in a declaration of main. 10859 // static main is not an error under C99, but we should warn about it. 10860 // We accept _Noreturn main as an extension. 10861 if (FD->getStorageClass() == SC_Static) 10862 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10863 ? diag::err_static_main : diag::warn_static_main) 10864 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10865 if (FD->isInlineSpecified()) 10866 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10867 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10868 if (DS.isNoreturnSpecified()) { 10869 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10870 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10871 Diag(NoreturnLoc, diag::ext_noreturn_main); 10872 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10873 << FixItHint::CreateRemoval(NoreturnRange); 10874 } 10875 if (FD->isConstexpr()) { 10876 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10877 << FD->isConsteval() 10878 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10879 FD->setConstexprKind(CSK_unspecified); 10880 } 10881 10882 if (getLangOpts().OpenCL) { 10883 Diag(FD->getLocation(), diag::err_opencl_no_main) 10884 << FD->hasAttr<OpenCLKernelAttr>(); 10885 FD->setInvalidDecl(); 10886 return; 10887 } 10888 10889 QualType T = FD->getType(); 10890 assert(T->isFunctionType() && "function decl is not of function type"); 10891 const FunctionType* FT = T->castAs<FunctionType>(); 10892 10893 // Set default calling convention for main() 10894 if (FT->getCallConv() != CC_C) { 10895 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10896 FD->setType(QualType(FT, 0)); 10897 T = Context.getCanonicalType(FD->getType()); 10898 } 10899 10900 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10901 // In C with GNU extensions we allow main() to have non-integer return 10902 // type, but we should warn about the extension, and we disable the 10903 // implicit-return-zero rule. 10904 10905 // GCC in C mode accepts qualified 'int'. 10906 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10907 FD->setHasImplicitReturnZero(true); 10908 else { 10909 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10910 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10911 if (RTRange.isValid()) 10912 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10913 << FixItHint::CreateReplacement(RTRange, "int"); 10914 } 10915 } else { 10916 // In C and C++, main magically returns 0 if you fall off the end; 10917 // set the flag which tells us that. 10918 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 10919 10920 // All the standards say that main() should return 'int'. 10921 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 10922 FD->setHasImplicitReturnZero(true); 10923 else { 10924 // Otherwise, this is just a flat-out error. 10925 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10926 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 10927 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 10928 : FixItHint()); 10929 FD->setInvalidDecl(true); 10930 } 10931 } 10932 10933 // Treat protoless main() as nullary. 10934 if (isa<FunctionNoProtoType>(FT)) return; 10935 10936 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 10937 unsigned nparams = FTP->getNumParams(); 10938 assert(FD->getNumParams() == nparams); 10939 10940 bool HasExtraParameters = (nparams > 3); 10941 10942 if (FTP->isVariadic()) { 10943 Diag(FD->getLocation(), diag::ext_variadic_main); 10944 // FIXME: if we had information about the location of the ellipsis, we 10945 // could add a FixIt hint to remove it as a parameter. 10946 } 10947 10948 // Darwin passes an undocumented fourth argument of type char**. If 10949 // other platforms start sprouting these, the logic below will start 10950 // getting shifty. 10951 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 10952 HasExtraParameters = false; 10953 10954 if (HasExtraParameters) { 10955 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 10956 FD->setInvalidDecl(true); 10957 nparams = 3; 10958 } 10959 10960 // FIXME: a lot of the following diagnostics would be improved 10961 // if we had some location information about types. 10962 10963 QualType CharPP = 10964 Context.getPointerType(Context.getPointerType(Context.CharTy)); 10965 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 10966 10967 for (unsigned i = 0; i < nparams; ++i) { 10968 QualType AT = FTP->getParamType(i); 10969 10970 bool mismatch = true; 10971 10972 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 10973 mismatch = false; 10974 else if (Expected[i] == CharPP) { 10975 // As an extension, the following forms are okay: 10976 // char const ** 10977 // char const * const * 10978 // char * const * 10979 10980 QualifierCollector qs; 10981 const PointerType* PT; 10982 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 10983 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 10984 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 10985 Context.CharTy)) { 10986 qs.removeConst(); 10987 mismatch = !qs.empty(); 10988 } 10989 } 10990 10991 if (mismatch) { 10992 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 10993 // TODO: suggest replacing given type with expected type 10994 FD->setInvalidDecl(true); 10995 } 10996 } 10997 10998 if (nparams == 1 && !FD->isInvalidDecl()) { 10999 Diag(FD->getLocation(), diag::warn_main_one_arg); 11000 } 11001 11002 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11003 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11004 FD->setInvalidDecl(); 11005 } 11006 } 11007 11008 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11009 QualType T = FD->getType(); 11010 assert(T->isFunctionType() && "function decl is not of function type"); 11011 const FunctionType *FT = T->castAs<FunctionType>(); 11012 11013 // Set an implicit return of 'zero' if the function can return some integral, 11014 // enumeration, pointer or nullptr type. 11015 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11016 FT->getReturnType()->isAnyPointerType() || 11017 FT->getReturnType()->isNullPtrType()) 11018 // DllMain is exempt because a return value of zero means it failed. 11019 if (FD->getName() != "DllMain") 11020 FD->setHasImplicitReturnZero(true); 11021 11022 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11023 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11024 FD->setInvalidDecl(); 11025 } 11026 } 11027 11028 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11029 // FIXME: Need strict checking. In C89, we need to check for 11030 // any assignment, increment, decrement, function-calls, or 11031 // commas outside of a sizeof. In C99, it's the same list, 11032 // except that the aforementioned are allowed in unevaluated 11033 // expressions. Everything else falls under the 11034 // "may accept other forms of constant expressions" exception. 11035 // (We never end up here for C++, so the constant expression 11036 // rules there don't matter.) 11037 const Expr *Culprit; 11038 if (Init->isConstantInitializer(Context, false, &Culprit)) 11039 return false; 11040 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11041 << Culprit->getSourceRange(); 11042 return true; 11043 } 11044 11045 namespace { 11046 // Visits an initialization expression to see if OrigDecl is evaluated in 11047 // its own initialization and throws a warning if it does. 11048 class SelfReferenceChecker 11049 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11050 Sema &S; 11051 Decl *OrigDecl; 11052 bool isRecordType; 11053 bool isPODType; 11054 bool isReferenceType; 11055 11056 bool isInitList; 11057 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11058 11059 public: 11060 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11061 11062 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11063 S(S), OrigDecl(OrigDecl) { 11064 isPODType = false; 11065 isRecordType = false; 11066 isReferenceType = false; 11067 isInitList = false; 11068 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11069 isPODType = VD->getType().isPODType(S.Context); 11070 isRecordType = VD->getType()->isRecordType(); 11071 isReferenceType = VD->getType()->isReferenceType(); 11072 } 11073 } 11074 11075 // For most expressions, just call the visitor. For initializer lists, 11076 // track the index of the field being initialized since fields are 11077 // initialized in order allowing use of previously initialized fields. 11078 void CheckExpr(Expr *E) { 11079 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11080 if (!InitList) { 11081 Visit(E); 11082 return; 11083 } 11084 11085 // Track and increment the index here. 11086 isInitList = true; 11087 InitFieldIndex.push_back(0); 11088 for (auto Child : InitList->children()) { 11089 CheckExpr(cast<Expr>(Child)); 11090 ++InitFieldIndex.back(); 11091 } 11092 InitFieldIndex.pop_back(); 11093 } 11094 11095 // Returns true if MemberExpr is checked and no further checking is needed. 11096 // Returns false if additional checking is required. 11097 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11098 llvm::SmallVector<FieldDecl*, 4> Fields; 11099 Expr *Base = E; 11100 bool ReferenceField = false; 11101 11102 // Get the field members used. 11103 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11104 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11105 if (!FD) 11106 return false; 11107 Fields.push_back(FD); 11108 if (FD->getType()->isReferenceType()) 11109 ReferenceField = true; 11110 Base = ME->getBase()->IgnoreParenImpCasts(); 11111 } 11112 11113 // Keep checking only if the base Decl is the same. 11114 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11115 if (!DRE || DRE->getDecl() != OrigDecl) 11116 return false; 11117 11118 // A reference field can be bound to an unininitialized field. 11119 if (CheckReference && !ReferenceField) 11120 return true; 11121 11122 // Convert FieldDecls to their index number. 11123 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11124 for (const FieldDecl *I : llvm::reverse(Fields)) 11125 UsedFieldIndex.push_back(I->getFieldIndex()); 11126 11127 // See if a warning is needed by checking the first difference in index 11128 // numbers. If field being used has index less than the field being 11129 // initialized, then the use is safe. 11130 for (auto UsedIter = UsedFieldIndex.begin(), 11131 UsedEnd = UsedFieldIndex.end(), 11132 OrigIter = InitFieldIndex.begin(), 11133 OrigEnd = InitFieldIndex.end(); 11134 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11135 if (*UsedIter < *OrigIter) 11136 return true; 11137 if (*UsedIter > *OrigIter) 11138 break; 11139 } 11140 11141 // TODO: Add a different warning which will print the field names. 11142 HandleDeclRefExpr(DRE); 11143 return true; 11144 } 11145 11146 // For most expressions, the cast is directly above the DeclRefExpr. 11147 // For conditional operators, the cast can be outside the conditional 11148 // operator if both expressions are DeclRefExpr's. 11149 void HandleValue(Expr *E) { 11150 E = E->IgnoreParens(); 11151 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11152 HandleDeclRefExpr(DRE); 11153 return; 11154 } 11155 11156 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11157 Visit(CO->getCond()); 11158 HandleValue(CO->getTrueExpr()); 11159 HandleValue(CO->getFalseExpr()); 11160 return; 11161 } 11162 11163 if (BinaryConditionalOperator *BCO = 11164 dyn_cast<BinaryConditionalOperator>(E)) { 11165 Visit(BCO->getCond()); 11166 HandleValue(BCO->getFalseExpr()); 11167 return; 11168 } 11169 11170 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11171 HandleValue(OVE->getSourceExpr()); 11172 return; 11173 } 11174 11175 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11176 if (BO->getOpcode() == BO_Comma) { 11177 Visit(BO->getLHS()); 11178 HandleValue(BO->getRHS()); 11179 return; 11180 } 11181 } 11182 11183 if (isa<MemberExpr>(E)) { 11184 if (isInitList) { 11185 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11186 false /*CheckReference*/)) 11187 return; 11188 } 11189 11190 Expr *Base = E->IgnoreParenImpCasts(); 11191 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11192 // Check for static member variables and don't warn on them. 11193 if (!isa<FieldDecl>(ME->getMemberDecl())) 11194 return; 11195 Base = ME->getBase()->IgnoreParenImpCasts(); 11196 } 11197 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11198 HandleDeclRefExpr(DRE); 11199 return; 11200 } 11201 11202 Visit(E); 11203 } 11204 11205 // Reference types not handled in HandleValue are handled here since all 11206 // uses of references are bad, not just r-value uses. 11207 void VisitDeclRefExpr(DeclRefExpr *E) { 11208 if (isReferenceType) 11209 HandleDeclRefExpr(E); 11210 } 11211 11212 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11213 if (E->getCastKind() == CK_LValueToRValue) { 11214 HandleValue(E->getSubExpr()); 11215 return; 11216 } 11217 11218 Inherited::VisitImplicitCastExpr(E); 11219 } 11220 11221 void VisitMemberExpr(MemberExpr *E) { 11222 if (isInitList) { 11223 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11224 return; 11225 } 11226 11227 // Don't warn on arrays since they can be treated as pointers. 11228 if (E->getType()->canDecayToPointerType()) return; 11229 11230 // Warn when a non-static method call is followed by non-static member 11231 // field accesses, which is followed by a DeclRefExpr. 11232 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11233 bool Warn = (MD && !MD->isStatic()); 11234 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11235 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11236 if (!isa<FieldDecl>(ME->getMemberDecl())) 11237 Warn = false; 11238 Base = ME->getBase()->IgnoreParenImpCasts(); 11239 } 11240 11241 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11242 if (Warn) 11243 HandleDeclRefExpr(DRE); 11244 return; 11245 } 11246 11247 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11248 // Visit that expression. 11249 Visit(Base); 11250 } 11251 11252 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11253 Expr *Callee = E->getCallee(); 11254 11255 if (isa<UnresolvedLookupExpr>(Callee)) 11256 return Inherited::VisitCXXOperatorCallExpr(E); 11257 11258 Visit(Callee); 11259 for (auto Arg: E->arguments()) 11260 HandleValue(Arg->IgnoreParenImpCasts()); 11261 } 11262 11263 void VisitUnaryOperator(UnaryOperator *E) { 11264 // For POD record types, addresses of its own members are well-defined. 11265 if (E->getOpcode() == UO_AddrOf && isRecordType && 11266 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11267 if (!isPODType) 11268 HandleValue(E->getSubExpr()); 11269 return; 11270 } 11271 11272 if (E->isIncrementDecrementOp()) { 11273 HandleValue(E->getSubExpr()); 11274 return; 11275 } 11276 11277 Inherited::VisitUnaryOperator(E); 11278 } 11279 11280 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11281 11282 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11283 if (E->getConstructor()->isCopyConstructor()) { 11284 Expr *ArgExpr = E->getArg(0); 11285 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11286 if (ILE->getNumInits() == 1) 11287 ArgExpr = ILE->getInit(0); 11288 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11289 if (ICE->getCastKind() == CK_NoOp) 11290 ArgExpr = ICE->getSubExpr(); 11291 HandleValue(ArgExpr); 11292 return; 11293 } 11294 Inherited::VisitCXXConstructExpr(E); 11295 } 11296 11297 void VisitCallExpr(CallExpr *E) { 11298 // Treat std::move as a use. 11299 if (E->isCallToStdMove()) { 11300 HandleValue(E->getArg(0)); 11301 return; 11302 } 11303 11304 Inherited::VisitCallExpr(E); 11305 } 11306 11307 void VisitBinaryOperator(BinaryOperator *E) { 11308 if (E->isCompoundAssignmentOp()) { 11309 HandleValue(E->getLHS()); 11310 Visit(E->getRHS()); 11311 return; 11312 } 11313 11314 Inherited::VisitBinaryOperator(E); 11315 } 11316 11317 // A custom visitor for BinaryConditionalOperator is needed because the 11318 // regular visitor would check the condition and true expression separately 11319 // but both point to the same place giving duplicate diagnostics. 11320 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11321 Visit(E->getCond()); 11322 Visit(E->getFalseExpr()); 11323 } 11324 11325 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11326 Decl* ReferenceDecl = DRE->getDecl(); 11327 if (OrigDecl != ReferenceDecl) return; 11328 unsigned diag; 11329 if (isReferenceType) { 11330 diag = diag::warn_uninit_self_reference_in_reference_init; 11331 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11332 diag = diag::warn_static_self_reference_in_init; 11333 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11334 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11335 DRE->getDecl()->getType()->isRecordType()) { 11336 diag = diag::warn_uninit_self_reference_in_init; 11337 } else { 11338 // Local variables will be handled by the CFG analysis. 11339 return; 11340 } 11341 11342 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11343 S.PDiag(diag) 11344 << DRE->getDecl() << OrigDecl->getLocation() 11345 << DRE->getSourceRange()); 11346 } 11347 }; 11348 11349 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11350 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11351 bool DirectInit) { 11352 // Parameters arguments are occassionially constructed with itself, 11353 // for instance, in recursive functions. Skip them. 11354 if (isa<ParmVarDecl>(OrigDecl)) 11355 return; 11356 11357 E = E->IgnoreParens(); 11358 11359 // Skip checking T a = a where T is not a record or reference type. 11360 // Doing so is a way to silence uninitialized warnings. 11361 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11362 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11363 if (ICE->getCastKind() == CK_LValueToRValue) 11364 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11365 if (DRE->getDecl() == OrigDecl) 11366 return; 11367 11368 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11369 } 11370 } // end anonymous namespace 11371 11372 namespace { 11373 // Simple wrapper to add the name of a variable or (if no variable is 11374 // available) a DeclarationName into a diagnostic. 11375 struct VarDeclOrName { 11376 VarDecl *VDecl; 11377 DeclarationName Name; 11378 11379 friend const Sema::SemaDiagnosticBuilder & 11380 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11381 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11382 } 11383 }; 11384 } // end anonymous namespace 11385 11386 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11387 DeclarationName Name, QualType Type, 11388 TypeSourceInfo *TSI, 11389 SourceRange Range, bool DirectInit, 11390 Expr *Init) { 11391 bool IsInitCapture = !VDecl; 11392 assert((!VDecl || !VDecl->isInitCapture()) && 11393 "init captures are expected to be deduced prior to initialization"); 11394 11395 VarDeclOrName VN{VDecl, Name}; 11396 11397 DeducedType *Deduced = Type->getContainedDeducedType(); 11398 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11399 11400 // C++11 [dcl.spec.auto]p3 11401 if (!Init) { 11402 assert(VDecl && "no init for init capture deduction?"); 11403 11404 // Except for class argument deduction, and then for an initializing 11405 // declaration only, i.e. no static at class scope or extern. 11406 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11407 VDecl->hasExternalStorage() || 11408 VDecl->isStaticDataMember()) { 11409 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11410 << VDecl->getDeclName() << Type; 11411 return QualType(); 11412 } 11413 } 11414 11415 ArrayRef<Expr*> DeduceInits; 11416 if (Init) 11417 DeduceInits = Init; 11418 11419 if (DirectInit) { 11420 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11421 DeduceInits = PL->exprs(); 11422 } 11423 11424 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11425 assert(VDecl && "non-auto type for init capture deduction?"); 11426 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11427 InitializationKind Kind = InitializationKind::CreateForInit( 11428 VDecl->getLocation(), DirectInit, Init); 11429 // FIXME: Initialization should not be taking a mutable list of inits. 11430 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11431 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11432 InitsCopy); 11433 } 11434 11435 if (DirectInit) { 11436 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11437 DeduceInits = IL->inits(); 11438 } 11439 11440 // Deduction only works if we have exactly one source expression. 11441 if (DeduceInits.empty()) { 11442 // It isn't possible to write this directly, but it is possible to 11443 // end up in this situation with "auto x(some_pack...);" 11444 Diag(Init->getBeginLoc(), IsInitCapture 11445 ? diag::err_init_capture_no_expression 11446 : diag::err_auto_var_init_no_expression) 11447 << VN << Type << Range; 11448 return QualType(); 11449 } 11450 11451 if (DeduceInits.size() > 1) { 11452 Diag(DeduceInits[1]->getBeginLoc(), 11453 IsInitCapture ? diag::err_init_capture_multiple_expressions 11454 : diag::err_auto_var_init_multiple_expressions) 11455 << VN << Type << Range; 11456 return QualType(); 11457 } 11458 11459 Expr *DeduceInit = DeduceInits[0]; 11460 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11461 Diag(Init->getBeginLoc(), IsInitCapture 11462 ? diag::err_init_capture_paren_braces 11463 : diag::err_auto_var_init_paren_braces) 11464 << isa<InitListExpr>(Init) << VN << Type << Range; 11465 return QualType(); 11466 } 11467 11468 // Expressions default to 'id' when we're in a debugger. 11469 bool DefaultedAnyToId = false; 11470 if (getLangOpts().DebuggerCastResultToId && 11471 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11472 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11473 if (Result.isInvalid()) { 11474 return QualType(); 11475 } 11476 Init = Result.get(); 11477 DefaultedAnyToId = true; 11478 } 11479 11480 // C++ [dcl.decomp]p1: 11481 // If the assignment-expression [...] has array type A and no ref-qualifier 11482 // is present, e has type cv A 11483 if (VDecl && isa<DecompositionDecl>(VDecl) && 11484 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11485 DeduceInit->getType()->isConstantArrayType()) 11486 return Context.getQualifiedType(DeduceInit->getType(), 11487 Type.getQualifiers()); 11488 11489 QualType DeducedType; 11490 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11491 if (!IsInitCapture) 11492 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11493 else if (isa<InitListExpr>(Init)) 11494 Diag(Range.getBegin(), 11495 diag::err_init_capture_deduction_failure_from_init_list) 11496 << VN 11497 << (DeduceInit->getType().isNull() ? TSI->getType() 11498 : DeduceInit->getType()) 11499 << DeduceInit->getSourceRange(); 11500 else 11501 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11502 << VN << TSI->getType() 11503 << (DeduceInit->getType().isNull() ? TSI->getType() 11504 : DeduceInit->getType()) 11505 << DeduceInit->getSourceRange(); 11506 } 11507 11508 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11509 // 'id' instead of a specific object type prevents most of our usual 11510 // checks. 11511 // We only want to warn outside of template instantiations, though: 11512 // inside a template, the 'id' could have come from a parameter. 11513 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11514 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11515 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11516 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11517 } 11518 11519 return DeducedType; 11520 } 11521 11522 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11523 Expr *Init) { 11524 QualType DeducedType = deduceVarTypeFromInitializer( 11525 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11526 VDecl->getSourceRange(), DirectInit, Init); 11527 if (DeducedType.isNull()) { 11528 VDecl->setInvalidDecl(); 11529 return true; 11530 } 11531 11532 VDecl->setType(DeducedType); 11533 assert(VDecl->isLinkageValid()); 11534 11535 // In ARC, infer lifetime. 11536 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11537 VDecl->setInvalidDecl(); 11538 11539 if (getLangOpts().OpenCL) 11540 deduceOpenCLAddressSpace(VDecl); 11541 11542 // If this is a redeclaration, check that the type we just deduced matches 11543 // the previously declared type. 11544 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11545 // We never need to merge the type, because we cannot form an incomplete 11546 // array of auto, nor deduce such a type. 11547 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11548 } 11549 11550 // Check the deduced type is valid for a variable declaration. 11551 CheckVariableDeclarationType(VDecl); 11552 return VDecl->isInvalidDecl(); 11553 } 11554 11555 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11556 SourceLocation Loc) { 11557 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11558 Init = CE->getSubExpr(); 11559 11560 QualType InitType = Init->getType(); 11561 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11562 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11563 "shouldn't be called if type doesn't have a non-trivial C struct"); 11564 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11565 for (auto I : ILE->inits()) { 11566 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11567 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11568 continue; 11569 SourceLocation SL = I->getExprLoc(); 11570 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11571 } 11572 return; 11573 } 11574 11575 if (isa<ImplicitValueInitExpr>(Init)) { 11576 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11577 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11578 NTCUK_Init); 11579 } else { 11580 // Assume all other explicit initializers involving copying some existing 11581 // object. 11582 // TODO: ignore any explicit initializers where we can guarantee 11583 // copy-elision. 11584 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11585 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11586 } 11587 } 11588 11589 namespace { 11590 11591 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11592 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11593 // in the source code or implicitly by the compiler if it is in a union 11594 // defined in a system header and has non-trivial ObjC ownership 11595 // qualifications. We don't want those fields to participate in determining 11596 // whether the containing union is non-trivial. 11597 return FD->hasAttr<UnavailableAttr>(); 11598 } 11599 11600 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11601 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11602 void> { 11603 using Super = 11604 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11605 void>; 11606 11607 DiagNonTrivalCUnionDefaultInitializeVisitor( 11608 QualType OrigTy, SourceLocation OrigLoc, 11609 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11610 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11611 11612 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11613 const FieldDecl *FD, bool InNonTrivialUnion) { 11614 if (const auto *AT = S.Context.getAsArrayType(QT)) 11615 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11616 InNonTrivialUnion); 11617 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11618 } 11619 11620 void visitARCStrong(QualType QT, const FieldDecl *FD, 11621 bool InNonTrivialUnion) { 11622 if (InNonTrivialUnion) 11623 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11624 << 1 << 0 << QT << FD->getName(); 11625 } 11626 11627 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11628 if (InNonTrivialUnion) 11629 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11630 << 1 << 0 << QT << FD->getName(); 11631 } 11632 11633 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11634 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11635 if (RD->isUnion()) { 11636 if (OrigLoc.isValid()) { 11637 bool IsUnion = false; 11638 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11639 IsUnion = OrigRD->isUnion(); 11640 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11641 << 0 << OrigTy << IsUnion << UseContext; 11642 // Reset OrigLoc so that this diagnostic is emitted only once. 11643 OrigLoc = SourceLocation(); 11644 } 11645 InNonTrivialUnion = true; 11646 } 11647 11648 if (InNonTrivialUnion) 11649 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11650 << 0 << 0 << QT.getUnqualifiedType() << ""; 11651 11652 for (const FieldDecl *FD : RD->fields()) 11653 if (!shouldIgnoreForRecordTriviality(FD)) 11654 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11655 } 11656 11657 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11658 11659 // The non-trivial C union type or the struct/union type that contains a 11660 // non-trivial C union. 11661 QualType OrigTy; 11662 SourceLocation OrigLoc; 11663 Sema::NonTrivialCUnionContext UseContext; 11664 Sema &S; 11665 }; 11666 11667 struct DiagNonTrivalCUnionDestructedTypeVisitor 11668 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11669 using Super = 11670 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11671 11672 DiagNonTrivalCUnionDestructedTypeVisitor( 11673 QualType OrigTy, SourceLocation OrigLoc, 11674 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11675 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11676 11677 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11678 const FieldDecl *FD, bool InNonTrivialUnion) { 11679 if (const auto *AT = S.Context.getAsArrayType(QT)) 11680 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11681 InNonTrivialUnion); 11682 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11683 } 11684 11685 void visitARCStrong(QualType QT, const FieldDecl *FD, 11686 bool InNonTrivialUnion) { 11687 if (InNonTrivialUnion) 11688 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11689 << 1 << 1 << QT << FD->getName(); 11690 } 11691 11692 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11693 if (InNonTrivialUnion) 11694 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11695 << 1 << 1 << QT << FD->getName(); 11696 } 11697 11698 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11699 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11700 if (RD->isUnion()) { 11701 if (OrigLoc.isValid()) { 11702 bool IsUnion = false; 11703 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11704 IsUnion = OrigRD->isUnion(); 11705 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11706 << 1 << OrigTy << IsUnion << UseContext; 11707 // Reset OrigLoc so that this diagnostic is emitted only once. 11708 OrigLoc = SourceLocation(); 11709 } 11710 InNonTrivialUnion = true; 11711 } 11712 11713 if (InNonTrivialUnion) 11714 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11715 << 0 << 1 << QT.getUnqualifiedType() << ""; 11716 11717 for (const FieldDecl *FD : RD->fields()) 11718 if (!shouldIgnoreForRecordTriviality(FD)) 11719 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11720 } 11721 11722 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11723 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11724 bool InNonTrivialUnion) {} 11725 11726 // The non-trivial C union type or the struct/union type that contains a 11727 // non-trivial C union. 11728 QualType OrigTy; 11729 SourceLocation OrigLoc; 11730 Sema::NonTrivialCUnionContext UseContext; 11731 Sema &S; 11732 }; 11733 11734 struct DiagNonTrivalCUnionCopyVisitor 11735 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11736 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11737 11738 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11739 Sema::NonTrivialCUnionContext UseContext, 11740 Sema &S) 11741 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11742 11743 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11744 const FieldDecl *FD, bool InNonTrivialUnion) { 11745 if (const auto *AT = S.Context.getAsArrayType(QT)) 11746 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11747 InNonTrivialUnion); 11748 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11749 } 11750 11751 void visitARCStrong(QualType QT, const FieldDecl *FD, 11752 bool InNonTrivialUnion) { 11753 if (InNonTrivialUnion) 11754 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11755 << 1 << 2 << QT << FD->getName(); 11756 } 11757 11758 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11759 if (InNonTrivialUnion) 11760 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11761 << 1 << 2 << QT << FD->getName(); 11762 } 11763 11764 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11765 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11766 if (RD->isUnion()) { 11767 if (OrigLoc.isValid()) { 11768 bool IsUnion = false; 11769 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11770 IsUnion = OrigRD->isUnion(); 11771 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11772 << 2 << OrigTy << IsUnion << UseContext; 11773 // Reset OrigLoc so that this diagnostic is emitted only once. 11774 OrigLoc = SourceLocation(); 11775 } 11776 InNonTrivialUnion = true; 11777 } 11778 11779 if (InNonTrivialUnion) 11780 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11781 << 0 << 2 << QT.getUnqualifiedType() << ""; 11782 11783 for (const FieldDecl *FD : RD->fields()) 11784 if (!shouldIgnoreForRecordTriviality(FD)) 11785 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11786 } 11787 11788 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 11789 const FieldDecl *FD, bool InNonTrivialUnion) {} 11790 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11791 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 11792 bool InNonTrivialUnion) {} 11793 11794 // The non-trivial C union type or the struct/union type that contains a 11795 // non-trivial C union. 11796 QualType OrigTy; 11797 SourceLocation OrigLoc; 11798 Sema::NonTrivialCUnionContext UseContext; 11799 Sema &S; 11800 }; 11801 11802 } // namespace 11803 11804 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 11805 NonTrivialCUnionContext UseContext, 11806 unsigned NonTrivialKind) { 11807 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11808 QT.hasNonTrivialToPrimitiveDestructCUnion() || 11809 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 11810 "shouldn't be called if type doesn't have a non-trivial C union"); 11811 11812 if ((NonTrivialKind & NTCUK_Init) && 11813 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11814 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 11815 .visit(QT, nullptr, false); 11816 if ((NonTrivialKind & NTCUK_Destruct) && 11817 QT.hasNonTrivialToPrimitiveDestructCUnion()) 11818 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 11819 .visit(QT, nullptr, false); 11820 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 11821 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 11822 .visit(QT, nullptr, false); 11823 } 11824 11825 /// AddInitializerToDecl - Adds the initializer Init to the 11826 /// declaration dcl. If DirectInit is true, this is C++ direct 11827 /// initialization rather than copy initialization. 11828 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11829 // If there is no declaration, there was an error parsing it. Just ignore 11830 // the initializer. 11831 if (!RealDecl || RealDecl->isInvalidDecl()) { 11832 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11833 return; 11834 } 11835 11836 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11837 // Pure-specifiers are handled in ActOnPureSpecifier. 11838 Diag(Method->getLocation(), diag::err_member_function_initialization) 11839 << Method->getDeclName() << Init->getSourceRange(); 11840 Method->setInvalidDecl(); 11841 return; 11842 } 11843 11844 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 11845 if (!VDecl) { 11846 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 11847 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 11848 RealDecl->setInvalidDecl(); 11849 return; 11850 } 11851 11852 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11853 if (VDecl->getType()->isUndeducedType()) { 11854 // Attempt typo correction early so that the type of the init expression can 11855 // be deduced based on the chosen correction if the original init contains a 11856 // TypoExpr. 11857 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11858 if (!Res.isUsable()) { 11859 RealDecl->setInvalidDecl(); 11860 return; 11861 } 11862 Init = Res.get(); 11863 11864 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11865 return; 11866 } 11867 11868 // dllimport cannot be used on variable definitions. 11869 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11870 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11871 VDecl->setInvalidDecl(); 11872 return; 11873 } 11874 11875 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11876 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11877 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11878 VDecl->setInvalidDecl(); 11879 return; 11880 } 11881 11882 if (!VDecl->getType()->isDependentType()) { 11883 // A definition must end up with a complete type, which means it must be 11884 // complete with the restriction that an array type might be completed by 11885 // the initializer; note that later code assumes this restriction. 11886 QualType BaseDeclType = VDecl->getType(); 11887 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 11888 BaseDeclType = Array->getElementType(); 11889 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 11890 diag::err_typecheck_decl_incomplete_type)) { 11891 RealDecl->setInvalidDecl(); 11892 return; 11893 } 11894 11895 // The variable can not have an abstract class type. 11896 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 11897 diag::err_abstract_type_in_decl, 11898 AbstractVariableType)) 11899 VDecl->setInvalidDecl(); 11900 } 11901 11902 // If adding the initializer will turn this declaration into a definition, 11903 // and we already have a definition for this variable, diagnose or otherwise 11904 // handle the situation. 11905 VarDecl *Def; 11906 if ((Def = VDecl->getDefinition()) && Def != VDecl && 11907 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 11908 !VDecl->isThisDeclarationADemotedDefinition() && 11909 checkVarDeclRedefinition(Def, VDecl)) 11910 return; 11911 11912 if (getLangOpts().CPlusPlus) { 11913 // C++ [class.static.data]p4 11914 // If a static data member is of const integral or const 11915 // enumeration type, its declaration in the class definition can 11916 // specify a constant-initializer which shall be an integral 11917 // constant expression (5.19). In that case, the member can appear 11918 // in integral constant expressions. The member shall still be 11919 // defined in a namespace scope if it is used in the program and the 11920 // namespace scope definition shall not contain an initializer. 11921 // 11922 // We already performed a redefinition check above, but for static 11923 // data members we also need to check whether there was an in-class 11924 // declaration with an initializer. 11925 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 11926 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 11927 << VDecl->getDeclName(); 11928 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 11929 diag::note_previous_initializer) 11930 << 0; 11931 return; 11932 } 11933 11934 if (VDecl->hasLocalStorage()) 11935 setFunctionHasBranchProtectedScope(); 11936 11937 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 11938 VDecl->setInvalidDecl(); 11939 return; 11940 } 11941 } 11942 11943 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 11944 // a kernel function cannot be initialized." 11945 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 11946 Diag(VDecl->getLocation(), diag::err_local_cant_init); 11947 VDecl->setInvalidDecl(); 11948 return; 11949 } 11950 11951 // Get the decls type and save a reference for later, since 11952 // CheckInitializerTypes may change it. 11953 QualType DclT = VDecl->getType(), SavT = DclT; 11954 11955 // Expressions default to 'id' when we're in a debugger 11956 // and we are assigning it to a variable of Objective-C pointer type. 11957 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 11958 Init->getType() == Context.UnknownAnyTy) { 11959 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11960 if (Result.isInvalid()) { 11961 VDecl->setInvalidDecl(); 11962 return; 11963 } 11964 Init = Result.get(); 11965 } 11966 11967 // Perform the initialization. 11968 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 11969 if (!VDecl->isInvalidDecl()) { 11970 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11971 InitializationKind Kind = InitializationKind::CreateForInit( 11972 VDecl->getLocation(), DirectInit, Init); 11973 11974 MultiExprArg Args = Init; 11975 if (CXXDirectInit) 11976 Args = MultiExprArg(CXXDirectInit->getExprs(), 11977 CXXDirectInit->getNumExprs()); 11978 11979 // Try to correct any TypoExprs in the initialization arguments. 11980 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 11981 ExprResult Res = CorrectDelayedTyposInExpr( 11982 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 11983 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 11984 return Init.Failed() ? ExprError() : E; 11985 }); 11986 if (Res.isInvalid()) { 11987 VDecl->setInvalidDecl(); 11988 } else if (Res.get() != Args[Idx]) { 11989 Args[Idx] = Res.get(); 11990 } 11991 } 11992 if (VDecl->isInvalidDecl()) 11993 return; 11994 11995 InitializationSequence InitSeq(*this, Entity, Kind, Args, 11996 /*TopLevelOfInitList=*/false, 11997 /*TreatUnavailableAsInvalid=*/false); 11998 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 11999 if (Result.isInvalid()) { 12000 VDecl->setInvalidDecl(); 12001 return; 12002 } 12003 12004 Init = Result.getAs<Expr>(); 12005 } 12006 12007 // Check for self-references within variable initializers. 12008 // Variables declared within a function/method body (except for references) 12009 // are handled by a dataflow analysis. 12010 // This is undefined behavior in C++, but valid in C. 12011 if (getLangOpts().CPlusPlus) { 12012 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12013 VDecl->getType()->isReferenceType()) { 12014 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12015 } 12016 } 12017 12018 // If the type changed, it means we had an incomplete type that was 12019 // completed by the initializer. For example: 12020 // int ary[] = { 1, 3, 5 }; 12021 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12022 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12023 VDecl->setType(DclT); 12024 12025 if (!VDecl->isInvalidDecl()) { 12026 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12027 12028 if (VDecl->hasAttr<BlocksAttr>()) 12029 checkRetainCycles(VDecl, Init); 12030 12031 // It is safe to assign a weak reference into a strong variable. 12032 // Although this code can still have problems: 12033 // id x = self.weakProp; 12034 // id y = self.weakProp; 12035 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12036 // paths through the function. This should be revisited if 12037 // -Wrepeated-use-of-weak is made flow-sensitive. 12038 if (FunctionScopeInfo *FSI = getCurFunction()) 12039 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12040 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12041 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12042 Init->getBeginLoc())) 12043 FSI->markSafeWeakUse(Init); 12044 } 12045 12046 // The initialization is usually a full-expression. 12047 // 12048 // FIXME: If this is a braced initialization of an aggregate, it is not 12049 // an expression, and each individual field initializer is a separate 12050 // full-expression. For instance, in: 12051 // 12052 // struct Temp { ~Temp(); }; 12053 // struct S { S(Temp); }; 12054 // struct T { S a, b; } t = { Temp(), Temp() } 12055 // 12056 // we should destroy the first Temp before constructing the second. 12057 ExprResult Result = 12058 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12059 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12060 if (Result.isInvalid()) { 12061 VDecl->setInvalidDecl(); 12062 return; 12063 } 12064 Init = Result.get(); 12065 12066 // Attach the initializer to the decl. 12067 VDecl->setInit(Init); 12068 12069 if (VDecl->isLocalVarDecl()) { 12070 // Don't check the initializer if the declaration is malformed. 12071 if (VDecl->isInvalidDecl()) { 12072 // do nothing 12073 12074 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12075 // This is true even in C++ for OpenCL. 12076 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12077 CheckForConstantInitializer(Init, DclT); 12078 12079 // Otherwise, C++ does not restrict the initializer. 12080 } else if (getLangOpts().CPlusPlus) { 12081 // do nothing 12082 12083 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12084 // static storage duration shall be constant expressions or string literals. 12085 } else if (VDecl->getStorageClass() == SC_Static) { 12086 CheckForConstantInitializer(Init, DclT); 12087 12088 // C89 is stricter than C99 for aggregate initializers. 12089 // C89 6.5.7p3: All the expressions [...] in an initializer list 12090 // for an object that has aggregate or union type shall be 12091 // constant expressions. 12092 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12093 isa<InitListExpr>(Init)) { 12094 const Expr *Culprit; 12095 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12096 Diag(Culprit->getExprLoc(), 12097 diag::ext_aggregate_init_not_constant) 12098 << Culprit->getSourceRange(); 12099 } 12100 } 12101 12102 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12103 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12104 if (VDecl->hasLocalStorage()) 12105 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12106 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12107 VDecl->getLexicalDeclContext()->isRecord()) { 12108 // This is an in-class initialization for a static data member, e.g., 12109 // 12110 // struct S { 12111 // static const int value = 17; 12112 // }; 12113 12114 // C++ [class.mem]p4: 12115 // A member-declarator can contain a constant-initializer only 12116 // if it declares a static member (9.4) of const integral or 12117 // const enumeration type, see 9.4.2. 12118 // 12119 // C++11 [class.static.data]p3: 12120 // If a non-volatile non-inline const static data member is of integral 12121 // or enumeration type, its declaration in the class definition can 12122 // specify a brace-or-equal-initializer in which every initializer-clause 12123 // that is an assignment-expression is a constant expression. A static 12124 // data member of literal type can be declared in the class definition 12125 // with the constexpr specifier; if so, its declaration shall specify a 12126 // brace-or-equal-initializer in which every initializer-clause that is 12127 // an assignment-expression is a constant expression. 12128 12129 // Do nothing on dependent types. 12130 if (DclT->isDependentType()) { 12131 12132 // Allow any 'static constexpr' members, whether or not they are of literal 12133 // type. We separately check that every constexpr variable is of literal 12134 // type. 12135 } else if (VDecl->isConstexpr()) { 12136 12137 // Require constness. 12138 } else if (!DclT.isConstQualified()) { 12139 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12140 << Init->getSourceRange(); 12141 VDecl->setInvalidDecl(); 12142 12143 // We allow integer constant expressions in all cases. 12144 } else if (DclT->isIntegralOrEnumerationType()) { 12145 // Check whether the expression is a constant expression. 12146 SourceLocation Loc; 12147 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12148 // In C++11, a non-constexpr const static data member with an 12149 // in-class initializer cannot be volatile. 12150 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12151 else if (Init->isValueDependent()) 12152 ; // Nothing to check. 12153 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12154 ; // Ok, it's an ICE! 12155 else if (Init->getType()->isScopedEnumeralType() && 12156 Init->isCXX11ConstantExpr(Context)) 12157 ; // Ok, it is a scoped-enum constant expression. 12158 else if (Init->isEvaluatable(Context)) { 12159 // If we can constant fold the initializer through heroics, accept it, 12160 // but report this as a use of an extension for -pedantic. 12161 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12162 << Init->getSourceRange(); 12163 } else { 12164 // Otherwise, this is some crazy unknown case. Report the issue at the 12165 // location provided by the isIntegerConstantExpr failed check. 12166 Diag(Loc, diag::err_in_class_initializer_non_constant) 12167 << Init->getSourceRange(); 12168 VDecl->setInvalidDecl(); 12169 } 12170 12171 // We allow foldable floating-point constants as an extension. 12172 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12173 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12174 // it anyway and provide a fixit to add the 'constexpr'. 12175 if (getLangOpts().CPlusPlus11) { 12176 Diag(VDecl->getLocation(), 12177 diag::ext_in_class_initializer_float_type_cxx11) 12178 << DclT << Init->getSourceRange(); 12179 Diag(VDecl->getBeginLoc(), 12180 diag::note_in_class_initializer_float_type_cxx11) 12181 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12182 } else { 12183 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12184 << DclT << Init->getSourceRange(); 12185 12186 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12187 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12188 << Init->getSourceRange(); 12189 VDecl->setInvalidDecl(); 12190 } 12191 } 12192 12193 // Suggest adding 'constexpr' in C++11 for literal types. 12194 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12195 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12196 << DclT << Init->getSourceRange() 12197 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12198 VDecl->setConstexpr(true); 12199 12200 } else { 12201 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12202 << DclT << Init->getSourceRange(); 12203 VDecl->setInvalidDecl(); 12204 } 12205 } else if (VDecl->isFileVarDecl()) { 12206 // In C, extern is typically used to avoid tentative definitions when 12207 // declaring variables in headers, but adding an intializer makes it a 12208 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12209 // In C++, extern is often used to give implictly static const variables 12210 // external linkage, so don't warn in that case. If selectany is present, 12211 // this might be header code intended for C and C++ inclusion, so apply the 12212 // C++ rules. 12213 if (VDecl->getStorageClass() == SC_Extern && 12214 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12215 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12216 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12217 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12218 Diag(VDecl->getLocation(), diag::warn_extern_init); 12219 12220 // In Microsoft C++ mode, a const variable defined in namespace scope has 12221 // external linkage by default if the variable is declared with 12222 // __declspec(dllexport). 12223 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12224 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12225 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12226 VDecl->setStorageClass(SC_Extern); 12227 12228 // C99 6.7.8p4. All file scoped initializers need to be constant. 12229 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12230 CheckForConstantInitializer(Init, DclT); 12231 } 12232 12233 QualType InitType = Init->getType(); 12234 if (!InitType.isNull() && 12235 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12236 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12237 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12238 12239 // We will represent direct-initialization similarly to copy-initialization: 12240 // int x(1); -as-> int x = 1; 12241 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12242 // 12243 // Clients that want to distinguish between the two forms, can check for 12244 // direct initializer using VarDecl::getInitStyle(). 12245 // A major benefit is that clients that don't particularly care about which 12246 // exactly form was it (like the CodeGen) can handle both cases without 12247 // special case code. 12248 12249 // C++ 8.5p11: 12250 // The form of initialization (using parentheses or '=') is generally 12251 // insignificant, but does matter when the entity being initialized has a 12252 // class type. 12253 if (CXXDirectInit) { 12254 assert(DirectInit && "Call-style initializer must be direct init."); 12255 VDecl->setInitStyle(VarDecl::CallInit); 12256 } else if (DirectInit) { 12257 // This must be list-initialization. No other way is direct-initialization. 12258 VDecl->setInitStyle(VarDecl::ListInit); 12259 } 12260 12261 CheckCompleteVariableDeclaration(VDecl); 12262 } 12263 12264 /// ActOnInitializerError - Given that there was an error parsing an 12265 /// initializer for the given declaration, try to return to some form 12266 /// of sanity. 12267 void Sema::ActOnInitializerError(Decl *D) { 12268 // Our main concern here is re-establishing invariants like "a 12269 // variable's type is either dependent or complete". 12270 if (!D || D->isInvalidDecl()) return; 12271 12272 VarDecl *VD = dyn_cast<VarDecl>(D); 12273 if (!VD) return; 12274 12275 // Bindings are not usable if we can't make sense of the initializer. 12276 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12277 for (auto *BD : DD->bindings()) 12278 BD->setInvalidDecl(); 12279 12280 // Auto types are meaningless if we can't make sense of the initializer. 12281 if (ParsingInitForAutoVars.count(D)) { 12282 D->setInvalidDecl(); 12283 return; 12284 } 12285 12286 QualType Ty = VD->getType(); 12287 if (Ty->isDependentType()) return; 12288 12289 // Require a complete type. 12290 if (RequireCompleteType(VD->getLocation(), 12291 Context.getBaseElementType(Ty), 12292 diag::err_typecheck_decl_incomplete_type)) { 12293 VD->setInvalidDecl(); 12294 return; 12295 } 12296 12297 // Require a non-abstract type. 12298 if (RequireNonAbstractType(VD->getLocation(), Ty, 12299 diag::err_abstract_type_in_decl, 12300 AbstractVariableType)) { 12301 VD->setInvalidDecl(); 12302 return; 12303 } 12304 12305 // Don't bother complaining about constructors or destructors, 12306 // though. 12307 } 12308 12309 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12310 // If there is no declaration, there was an error parsing it. Just ignore it. 12311 if (!RealDecl) 12312 return; 12313 12314 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12315 QualType Type = Var->getType(); 12316 12317 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12318 if (isa<DecompositionDecl>(RealDecl)) { 12319 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12320 Var->setInvalidDecl(); 12321 return; 12322 } 12323 12324 if (Type->isUndeducedType() && 12325 DeduceVariableDeclarationType(Var, false, nullptr)) 12326 return; 12327 12328 // C++11 [class.static.data]p3: A static data member can be declared with 12329 // the constexpr specifier; if so, its declaration shall specify 12330 // a brace-or-equal-initializer. 12331 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12332 // the definition of a variable [...] or the declaration of a static data 12333 // member. 12334 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12335 !Var->isThisDeclarationADemotedDefinition()) { 12336 if (Var->isStaticDataMember()) { 12337 // C++1z removes the relevant rule; the in-class declaration is always 12338 // a definition there. 12339 if (!getLangOpts().CPlusPlus17 && 12340 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12341 Diag(Var->getLocation(), 12342 diag::err_constexpr_static_mem_var_requires_init) 12343 << Var->getDeclName(); 12344 Var->setInvalidDecl(); 12345 return; 12346 } 12347 } else { 12348 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12349 Var->setInvalidDecl(); 12350 return; 12351 } 12352 } 12353 12354 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12355 // be initialized. 12356 if (!Var->isInvalidDecl() && 12357 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12358 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12359 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12360 Var->setInvalidDecl(); 12361 return; 12362 } 12363 12364 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12365 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12366 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12367 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12368 NTCUC_DefaultInitializedObject, NTCUK_Init); 12369 12370 12371 switch (DefKind) { 12372 case VarDecl::Definition: 12373 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12374 break; 12375 12376 // We have an out-of-line definition of a static data member 12377 // that has an in-class initializer, so we type-check this like 12378 // a declaration. 12379 // 12380 LLVM_FALLTHROUGH; 12381 12382 case VarDecl::DeclarationOnly: 12383 // It's only a declaration. 12384 12385 // Block scope. C99 6.7p7: If an identifier for an object is 12386 // declared with no linkage (C99 6.2.2p6), the type for the 12387 // object shall be complete. 12388 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12389 !Var->hasLinkage() && !Var->isInvalidDecl() && 12390 RequireCompleteType(Var->getLocation(), Type, 12391 diag::err_typecheck_decl_incomplete_type)) 12392 Var->setInvalidDecl(); 12393 12394 // Make sure that the type is not abstract. 12395 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12396 RequireNonAbstractType(Var->getLocation(), Type, 12397 diag::err_abstract_type_in_decl, 12398 AbstractVariableType)) 12399 Var->setInvalidDecl(); 12400 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12401 Var->getStorageClass() == SC_PrivateExtern) { 12402 Diag(Var->getLocation(), diag::warn_private_extern); 12403 Diag(Var->getLocation(), diag::note_private_extern); 12404 } 12405 12406 if (Context.getTargetInfo().allowDebugInfoForExternalVar() && 12407 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12408 ExternalDeclarations.push_back(Var); 12409 12410 return; 12411 12412 case VarDecl::TentativeDefinition: 12413 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12414 // object that has file scope without an initializer, and without a 12415 // storage-class specifier or with the storage-class specifier "static", 12416 // constitutes a tentative definition. Note: A tentative definition with 12417 // external linkage is valid (C99 6.2.2p5). 12418 if (!Var->isInvalidDecl()) { 12419 if (const IncompleteArrayType *ArrayT 12420 = Context.getAsIncompleteArrayType(Type)) { 12421 if (RequireCompleteType(Var->getLocation(), 12422 ArrayT->getElementType(), 12423 diag::err_illegal_decl_array_incomplete_type)) 12424 Var->setInvalidDecl(); 12425 } else if (Var->getStorageClass() == SC_Static) { 12426 // C99 6.9.2p3: If the declaration of an identifier for an object is 12427 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12428 // declared type shall not be an incomplete type. 12429 // NOTE: code such as the following 12430 // static struct s; 12431 // struct s { int a; }; 12432 // is accepted by gcc. Hence here we issue a warning instead of 12433 // an error and we do not invalidate the static declaration. 12434 // NOTE: to avoid multiple warnings, only check the first declaration. 12435 if (Var->isFirstDecl()) 12436 RequireCompleteType(Var->getLocation(), Type, 12437 diag::ext_typecheck_decl_incomplete_type); 12438 } 12439 } 12440 12441 // Record the tentative definition; we're done. 12442 if (!Var->isInvalidDecl()) 12443 TentativeDefinitions.push_back(Var); 12444 return; 12445 } 12446 12447 // Provide a specific diagnostic for uninitialized variable 12448 // definitions with incomplete array type. 12449 if (Type->isIncompleteArrayType()) { 12450 Diag(Var->getLocation(), 12451 diag::err_typecheck_incomplete_array_needs_initializer); 12452 Var->setInvalidDecl(); 12453 return; 12454 } 12455 12456 // Provide a specific diagnostic for uninitialized variable 12457 // definitions with reference type. 12458 if (Type->isReferenceType()) { 12459 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12460 << Var->getDeclName() 12461 << SourceRange(Var->getLocation(), Var->getLocation()); 12462 Var->setInvalidDecl(); 12463 return; 12464 } 12465 12466 // Do not attempt to type-check the default initializer for a 12467 // variable with dependent type. 12468 if (Type->isDependentType()) 12469 return; 12470 12471 if (Var->isInvalidDecl()) 12472 return; 12473 12474 if (!Var->hasAttr<AliasAttr>()) { 12475 if (RequireCompleteType(Var->getLocation(), 12476 Context.getBaseElementType(Type), 12477 diag::err_typecheck_decl_incomplete_type)) { 12478 Var->setInvalidDecl(); 12479 return; 12480 } 12481 } else { 12482 return; 12483 } 12484 12485 // The variable can not have an abstract class type. 12486 if (RequireNonAbstractType(Var->getLocation(), Type, 12487 diag::err_abstract_type_in_decl, 12488 AbstractVariableType)) { 12489 Var->setInvalidDecl(); 12490 return; 12491 } 12492 12493 // Check for jumps past the implicit initializer. C++0x 12494 // clarifies that this applies to a "variable with automatic 12495 // storage duration", not a "local variable". 12496 // C++11 [stmt.dcl]p3 12497 // A program that jumps from a point where a variable with automatic 12498 // storage duration is not in scope to a point where it is in scope is 12499 // ill-formed unless the variable has scalar type, class type with a 12500 // trivial default constructor and a trivial destructor, a cv-qualified 12501 // version of one of these types, or an array of one of the preceding 12502 // types and is declared without an initializer. 12503 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12504 if (const RecordType *Record 12505 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12506 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12507 // Mark the function (if we're in one) for further checking even if the 12508 // looser rules of C++11 do not require such checks, so that we can 12509 // diagnose incompatibilities with C++98. 12510 if (!CXXRecord->isPOD()) 12511 setFunctionHasBranchProtectedScope(); 12512 } 12513 } 12514 // In OpenCL, we can't initialize objects in the __local address space, 12515 // even implicitly, so don't synthesize an implicit initializer. 12516 if (getLangOpts().OpenCL && 12517 Var->getType().getAddressSpace() == LangAS::opencl_local) 12518 return; 12519 // C++03 [dcl.init]p9: 12520 // If no initializer is specified for an object, and the 12521 // object is of (possibly cv-qualified) non-POD class type (or 12522 // array thereof), the object shall be default-initialized; if 12523 // the object is of const-qualified type, the underlying class 12524 // type shall have a user-declared default 12525 // constructor. Otherwise, if no initializer is specified for 12526 // a non- static object, the object and its subobjects, if 12527 // any, have an indeterminate initial value); if the object 12528 // or any of its subobjects are of const-qualified type, the 12529 // program is ill-formed. 12530 // C++0x [dcl.init]p11: 12531 // If no initializer is specified for an object, the object is 12532 // default-initialized; [...]. 12533 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12534 InitializationKind Kind 12535 = InitializationKind::CreateDefault(Var->getLocation()); 12536 12537 InitializationSequence InitSeq(*this, Entity, Kind, None); 12538 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12539 if (Init.isInvalid()) 12540 Var->setInvalidDecl(); 12541 else if (Init.get()) { 12542 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12543 // This is important for template substitution. 12544 Var->setInitStyle(VarDecl::CallInit); 12545 } 12546 12547 CheckCompleteVariableDeclaration(Var); 12548 } 12549 } 12550 12551 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12552 // If there is no declaration, there was an error parsing it. Ignore it. 12553 if (!D) 12554 return; 12555 12556 VarDecl *VD = dyn_cast<VarDecl>(D); 12557 if (!VD) { 12558 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12559 D->setInvalidDecl(); 12560 return; 12561 } 12562 12563 VD->setCXXForRangeDecl(true); 12564 12565 // for-range-declaration cannot be given a storage class specifier. 12566 int Error = -1; 12567 switch (VD->getStorageClass()) { 12568 case SC_None: 12569 break; 12570 case SC_Extern: 12571 Error = 0; 12572 break; 12573 case SC_Static: 12574 Error = 1; 12575 break; 12576 case SC_PrivateExtern: 12577 Error = 2; 12578 break; 12579 case SC_Auto: 12580 Error = 3; 12581 break; 12582 case SC_Register: 12583 Error = 4; 12584 break; 12585 } 12586 if (Error != -1) { 12587 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12588 << VD->getDeclName() << Error; 12589 D->setInvalidDecl(); 12590 } 12591 } 12592 12593 StmtResult 12594 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12595 IdentifierInfo *Ident, 12596 ParsedAttributes &Attrs, 12597 SourceLocation AttrEnd) { 12598 // C++1y [stmt.iter]p1: 12599 // A range-based for statement of the form 12600 // for ( for-range-identifier : for-range-initializer ) statement 12601 // is equivalent to 12602 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12603 DeclSpec DS(Attrs.getPool().getFactory()); 12604 12605 const char *PrevSpec; 12606 unsigned DiagID; 12607 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12608 getPrintingPolicy()); 12609 12610 Declarator D(DS, DeclaratorContext::ForContext); 12611 D.SetIdentifier(Ident, IdentLoc); 12612 D.takeAttributes(Attrs, AttrEnd); 12613 12614 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12615 IdentLoc); 12616 Decl *Var = ActOnDeclarator(S, D); 12617 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12618 FinalizeDeclaration(Var); 12619 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12620 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12621 } 12622 12623 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12624 if (var->isInvalidDecl()) return; 12625 12626 if (getLangOpts().OpenCL) { 12627 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12628 // initialiser 12629 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12630 !var->hasInit()) { 12631 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12632 << 1 /*Init*/; 12633 var->setInvalidDecl(); 12634 return; 12635 } 12636 } 12637 12638 // In Objective-C, don't allow jumps past the implicit initialization of a 12639 // local retaining variable. 12640 if (getLangOpts().ObjC && 12641 var->hasLocalStorage()) { 12642 switch (var->getType().getObjCLifetime()) { 12643 case Qualifiers::OCL_None: 12644 case Qualifiers::OCL_ExplicitNone: 12645 case Qualifiers::OCL_Autoreleasing: 12646 break; 12647 12648 case Qualifiers::OCL_Weak: 12649 case Qualifiers::OCL_Strong: 12650 setFunctionHasBranchProtectedScope(); 12651 break; 12652 } 12653 } 12654 12655 if (var->hasLocalStorage() && 12656 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12657 setFunctionHasBranchProtectedScope(); 12658 12659 // Warn about externally-visible variables being defined without a 12660 // prior declaration. We only want to do this for global 12661 // declarations, but we also specifically need to avoid doing it for 12662 // class members because the linkage of an anonymous class can 12663 // change if it's later given a typedef name. 12664 if (var->isThisDeclarationADefinition() && 12665 var->getDeclContext()->getRedeclContext()->isFileContext() && 12666 var->isExternallyVisible() && var->hasLinkage() && 12667 !var->isInline() && !var->getDescribedVarTemplate() && 12668 !isa<VarTemplatePartialSpecializationDecl>(var) && 12669 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12670 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12671 var->getLocation())) { 12672 // Find a previous declaration that's not a definition. 12673 VarDecl *prev = var->getPreviousDecl(); 12674 while (prev && prev->isThisDeclarationADefinition()) 12675 prev = prev->getPreviousDecl(); 12676 12677 if (!prev) { 12678 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12679 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12680 << /* variable */ 0; 12681 } 12682 } 12683 12684 // Cache the result of checking for constant initialization. 12685 Optional<bool> CacheHasConstInit; 12686 const Expr *CacheCulprit = nullptr; 12687 auto checkConstInit = [&]() mutable { 12688 if (!CacheHasConstInit) 12689 CacheHasConstInit = var->getInit()->isConstantInitializer( 12690 Context, var->getType()->isReferenceType(), &CacheCulprit); 12691 return *CacheHasConstInit; 12692 }; 12693 12694 if (var->getTLSKind() == VarDecl::TLS_Static) { 12695 if (var->getType().isDestructedType()) { 12696 // GNU C++98 edits for __thread, [basic.start.term]p3: 12697 // The type of an object with thread storage duration shall not 12698 // have a non-trivial destructor. 12699 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12700 if (getLangOpts().CPlusPlus11) 12701 Diag(var->getLocation(), diag::note_use_thread_local); 12702 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12703 if (!checkConstInit()) { 12704 // GNU C++98 edits for __thread, [basic.start.init]p4: 12705 // An object of thread storage duration shall not require dynamic 12706 // initialization. 12707 // FIXME: Need strict checking here. 12708 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12709 << CacheCulprit->getSourceRange(); 12710 if (getLangOpts().CPlusPlus11) 12711 Diag(var->getLocation(), diag::note_use_thread_local); 12712 } 12713 } 12714 } 12715 12716 // Apply section attributes and pragmas to global variables. 12717 bool GlobalStorage = var->hasGlobalStorage(); 12718 if (GlobalStorage && var->isThisDeclarationADefinition() && 12719 !inTemplateInstantiation()) { 12720 PragmaStack<StringLiteral *> *Stack = nullptr; 12721 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 12722 if (var->getType().isConstQualified()) 12723 Stack = &ConstSegStack; 12724 else if (!var->getInit()) { 12725 Stack = &BSSSegStack; 12726 SectionFlags |= ASTContext::PSF_Write; 12727 } else { 12728 Stack = &DataSegStack; 12729 SectionFlags |= ASTContext::PSF_Write; 12730 } 12731 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) 12732 var->addAttr(SectionAttr::CreateImplicit( 12733 Context, Stack->CurrentValue->getString(), 12734 Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 12735 SectionAttr::Declspec_allocate)); 12736 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 12737 if (UnifySection(SA->getName(), SectionFlags, var)) 12738 var->dropAttr<SectionAttr>(); 12739 12740 // Apply the init_seg attribute if this has an initializer. If the 12741 // initializer turns out to not be dynamic, we'll end up ignoring this 12742 // attribute. 12743 if (CurInitSeg && var->getInit()) 12744 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 12745 CurInitSegLoc, 12746 AttributeCommonInfo::AS_Pragma)); 12747 } 12748 12749 // All the following checks are C++ only. 12750 if (!getLangOpts().CPlusPlus) { 12751 // If this variable must be emitted, add it as an initializer for the 12752 // current module. 12753 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12754 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12755 return; 12756 } 12757 12758 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 12759 CheckCompleteDecompositionDeclaration(DD); 12760 12761 QualType type = var->getType(); 12762 if (type->isDependentType()) return; 12763 12764 if (var->hasAttr<BlocksAttr>()) 12765 getCurFunction()->addByrefBlockVar(var); 12766 12767 Expr *Init = var->getInit(); 12768 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 12769 QualType baseType = Context.getBaseElementType(type); 12770 12771 if (Init && !Init->isValueDependent()) { 12772 if (var->isConstexpr()) { 12773 SmallVector<PartialDiagnosticAt, 8> Notes; 12774 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 12775 SourceLocation DiagLoc = var->getLocation(); 12776 // If the note doesn't add any useful information other than a source 12777 // location, fold it into the primary diagnostic. 12778 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12779 diag::note_invalid_subexpr_in_const_expr) { 12780 DiagLoc = Notes[0].first; 12781 Notes.clear(); 12782 } 12783 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 12784 << var << Init->getSourceRange(); 12785 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12786 Diag(Notes[I].first, Notes[I].second); 12787 } 12788 } else if (var->mightBeUsableInConstantExpressions(Context)) { 12789 // Check whether the initializer of a const variable of integral or 12790 // enumeration type is an ICE now, since we can't tell whether it was 12791 // initialized by a constant expression if we check later. 12792 var->checkInitIsICE(); 12793 } 12794 12795 // Don't emit further diagnostics about constexpr globals since they 12796 // were just diagnosed. 12797 if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) { 12798 // FIXME: Need strict checking in C++03 here. 12799 bool DiagErr = getLangOpts().CPlusPlus11 12800 ? !var->checkInitIsICE() : !checkConstInit(); 12801 if (DiagErr) { 12802 auto *Attr = var->getAttr<ConstInitAttr>(); 12803 Diag(var->getLocation(), diag::err_require_constant_init_failed) 12804 << Init->getSourceRange(); 12805 Diag(Attr->getLocation(), 12806 diag::note_declared_required_constant_init_here) 12807 << Attr->getRange() << Attr->isConstinit(); 12808 if (getLangOpts().CPlusPlus11) { 12809 APValue Value; 12810 SmallVector<PartialDiagnosticAt, 8> Notes; 12811 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 12812 for (auto &it : Notes) 12813 Diag(it.first, it.second); 12814 } else { 12815 Diag(CacheCulprit->getExprLoc(), 12816 diag::note_invalid_subexpr_in_const_expr) 12817 << CacheCulprit->getSourceRange(); 12818 } 12819 } 12820 } 12821 else if (!var->isConstexpr() && IsGlobal && 12822 !getDiagnostics().isIgnored(diag::warn_global_constructor, 12823 var->getLocation())) { 12824 // Warn about globals which don't have a constant initializer. Don't 12825 // warn about globals with a non-trivial destructor because we already 12826 // warned about them. 12827 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 12828 if (!(RD && !RD->hasTrivialDestructor())) { 12829 if (!checkConstInit()) 12830 Diag(var->getLocation(), diag::warn_global_constructor) 12831 << Init->getSourceRange(); 12832 } 12833 } 12834 } 12835 12836 // Require the destructor. 12837 if (const RecordType *recordType = baseType->getAs<RecordType>()) 12838 FinalizeVarWithDestructor(var, recordType); 12839 12840 // If this variable must be emitted, add it as an initializer for the current 12841 // module. 12842 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12843 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12844 } 12845 12846 /// Determines if a variable's alignment is dependent. 12847 static bool hasDependentAlignment(VarDecl *VD) { 12848 if (VD->getType()->isDependentType()) 12849 return true; 12850 for (auto *I : VD->specific_attrs<AlignedAttr>()) 12851 if (I->isAlignmentDependent()) 12852 return true; 12853 return false; 12854 } 12855 12856 /// Check if VD needs to be dllexport/dllimport due to being in a 12857 /// dllexport/import function. 12858 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 12859 assert(VD->isStaticLocal()); 12860 12861 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12862 12863 // Find outermost function when VD is in lambda function. 12864 while (FD && !getDLLAttr(FD) && 12865 !FD->hasAttr<DLLExportStaticLocalAttr>() && 12866 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 12867 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 12868 } 12869 12870 if (!FD) 12871 return; 12872 12873 // Static locals inherit dll attributes from their function. 12874 if (Attr *A = getDLLAttr(FD)) { 12875 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 12876 NewAttr->setInherited(true); 12877 VD->addAttr(NewAttr); 12878 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 12879 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 12880 NewAttr->setInherited(true); 12881 VD->addAttr(NewAttr); 12882 12883 // Export this function to enforce exporting this static variable even 12884 // if it is not used in this compilation unit. 12885 if (!FD->hasAttr<DLLExportAttr>()) 12886 FD->addAttr(NewAttr); 12887 12888 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 12889 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 12890 NewAttr->setInherited(true); 12891 VD->addAttr(NewAttr); 12892 } 12893 } 12894 12895 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 12896 /// any semantic actions necessary after any initializer has been attached. 12897 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 12898 // Note that we are no longer parsing the initializer for this declaration. 12899 ParsingInitForAutoVars.erase(ThisDecl); 12900 12901 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 12902 if (!VD) 12903 return; 12904 12905 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 12906 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 12907 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 12908 if (PragmaClangBSSSection.Valid) 12909 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 12910 Context, PragmaClangBSSSection.SectionName, 12911 PragmaClangBSSSection.PragmaLocation, 12912 AttributeCommonInfo::AS_Pragma)); 12913 if (PragmaClangDataSection.Valid) 12914 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 12915 Context, PragmaClangDataSection.SectionName, 12916 PragmaClangDataSection.PragmaLocation, 12917 AttributeCommonInfo::AS_Pragma)); 12918 if (PragmaClangRodataSection.Valid) 12919 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 12920 Context, PragmaClangRodataSection.SectionName, 12921 PragmaClangRodataSection.PragmaLocation, 12922 AttributeCommonInfo::AS_Pragma)); 12923 if (PragmaClangRelroSection.Valid) 12924 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 12925 Context, PragmaClangRelroSection.SectionName, 12926 PragmaClangRelroSection.PragmaLocation, 12927 AttributeCommonInfo::AS_Pragma)); 12928 } 12929 12930 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 12931 for (auto *BD : DD->bindings()) { 12932 FinalizeDeclaration(BD); 12933 } 12934 } 12935 12936 checkAttributesAfterMerging(*this, *VD); 12937 12938 // Perform TLS alignment check here after attributes attached to the variable 12939 // which may affect the alignment have been processed. Only perform the check 12940 // if the target has a maximum TLS alignment (zero means no constraints). 12941 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 12942 // Protect the check so that it's not performed on dependent types and 12943 // dependent alignments (we can't determine the alignment in that case). 12944 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 12945 !VD->isInvalidDecl()) { 12946 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 12947 if (Context.getDeclAlign(VD) > MaxAlignChars) { 12948 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 12949 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 12950 << (unsigned)MaxAlignChars.getQuantity(); 12951 } 12952 } 12953 } 12954 12955 if (VD->isStaticLocal()) { 12956 CheckStaticLocalForDllExport(VD); 12957 12958 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 12959 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 12960 // function, only __shared__ variables or variables without any device 12961 // memory qualifiers may be declared with static storage class. 12962 // Note: It is unclear how a function-scope non-const static variable 12963 // without device memory qualifier is implemented, therefore only static 12964 // const variable without device memory qualifier is allowed. 12965 [&]() { 12966 if (!getLangOpts().CUDA) 12967 return; 12968 if (VD->hasAttr<CUDASharedAttr>()) 12969 return; 12970 if (VD->getType().isConstQualified() && 12971 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 12972 return; 12973 if (CUDADiagIfDeviceCode(VD->getLocation(), 12974 diag::err_device_static_local_var) 12975 << CurrentCUDATarget()) 12976 VD->setInvalidDecl(); 12977 }(); 12978 } 12979 } 12980 12981 // Perform check for initializers of device-side global variables. 12982 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 12983 // 7.5). We must also apply the same checks to all __shared__ 12984 // variables whether they are local or not. CUDA also allows 12985 // constant initializers for __constant__ and __device__ variables. 12986 if (getLangOpts().CUDA) 12987 checkAllowedCUDAInitializer(VD); 12988 12989 // Grab the dllimport or dllexport attribute off of the VarDecl. 12990 const InheritableAttr *DLLAttr = getDLLAttr(VD); 12991 12992 // Imported static data members cannot be defined out-of-line. 12993 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 12994 if (VD->isStaticDataMember() && VD->isOutOfLine() && 12995 VD->isThisDeclarationADefinition()) { 12996 // We allow definitions of dllimport class template static data members 12997 // with a warning. 12998 CXXRecordDecl *Context = 12999 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13000 bool IsClassTemplateMember = 13001 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13002 Context->getDescribedClassTemplate(); 13003 13004 Diag(VD->getLocation(), 13005 IsClassTemplateMember 13006 ? diag::warn_attribute_dllimport_static_field_definition 13007 : diag::err_attribute_dllimport_static_field_definition); 13008 Diag(IA->getLocation(), diag::note_attribute); 13009 if (!IsClassTemplateMember) 13010 VD->setInvalidDecl(); 13011 } 13012 } 13013 13014 // dllimport/dllexport variables cannot be thread local, their TLS index 13015 // isn't exported with the variable. 13016 if (DLLAttr && VD->getTLSKind()) { 13017 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13018 if (F && getDLLAttr(F)) { 13019 assert(VD->isStaticLocal()); 13020 // But if this is a static local in a dlimport/dllexport function, the 13021 // function will never be inlined, which means the var would never be 13022 // imported, so having it marked import/export is safe. 13023 } else { 13024 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13025 << DLLAttr; 13026 VD->setInvalidDecl(); 13027 } 13028 } 13029 13030 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13031 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13032 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 13033 VD->dropAttr<UsedAttr>(); 13034 } 13035 } 13036 13037 const DeclContext *DC = VD->getDeclContext(); 13038 // If there's a #pragma GCC visibility in scope, and this isn't a class 13039 // member, set the visibility of this variable. 13040 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13041 AddPushedVisibilityAttribute(VD); 13042 13043 // FIXME: Warn on unused var template partial specializations. 13044 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13045 MarkUnusedFileScopedDecl(VD); 13046 13047 // Now we have parsed the initializer and can update the table of magic 13048 // tag values. 13049 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13050 !VD->getType()->isIntegralOrEnumerationType()) 13051 return; 13052 13053 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13054 const Expr *MagicValueExpr = VD->getInit(); 13055 if (!MagicValueExpr) { 13056 continue; 13057 } 13058 llvm::APSInt MagicValueInt; 13059 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 13060 Diag(I->getRange().getBegin(), 13061 diag::err_type_tag_for_datatype_not_ice) 13062 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13063 continue; 13064 } 13065 if (MagicValueInt.getActiveBits() > 64) { 13066 Diag(I->getRange().getBegin(), 13067 diag::err_type_tag_for_datatype_too_large) 13068 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13069 continue; 13070 } 13071 uint64_t MagicValue = MagicValueInt.getZExtValue(); 13072 RegisterTypeTagForDatatype(I->getArgumentKind(), 13073 MagicValue, 13074 I->getMatchingCType(), 13075 I->getLayoutCompatible(), 13076 I->getMustBeNull()); 13077 } 13078 } 13079 13080 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13081 auto *VD = dyn_cast<VarDecl>(DD); 13082 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13083 } 13084 13085 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13086 ArrayRef<Decl *> Group) { 13087 SmallVector<Decl*, 8> Decls; 13088 13089 if (DS.isTypeSpecOwned()) 13090 Decls.push_back(DS.getRepAsDecl()); 13091 13092 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13093 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13094 bool DiagnosedMultipleDecomps = false; 13095 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13096 bool DiagnosedNonDeducedAuto = false; 13097 13098 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13099 if (Decl *D = Group[i]) { 13100 // For declarators, there are some additional syntactic-ish checks we need 13101 // to perform. 13102 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13103 if (!FirstDeclaratorInGroup) 13104 FirstDeclaratorInGroup = DD; 13105 if (!FirstDecompDeclaratorInGroup) 13106 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13107 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13108 !hasDeducedAuto(DD)) 13109 FirstNonDeducedAutoInGroup = DD; 13110 13111 if (FirstDeclaratorInGroup != DD) { 13112 // A decomposition declaration cannot be combined with any other 13113 // declaration in the same group. 13114 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13115 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13116 diag::err_decomp_decl_not_alone) 13117 << FirstDeclaratorInGroup->getSourceRange() 13118 << DD->getSourceRange(); 13119 DiagnosedMultipleDecomps = true; 13120 } 13121 13122 // A declarator that uses 'auto' in any way other than to declare a 13123 // variable with a deduced type cannot be combined with any other 13124 // declarator in the same group. 13125 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13126 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13127 diag::err_auto_non_deduced_not_alone) 13128 << FirstNonDeducedAutoInGroup->getType() 13129 ->hasAutoForTrailingReturnType() 13130 << FirstDeclaratorInGroup->getSourceRange() 13131 << DD->getSourceRange(); 13132 DiagnosedNonDeducedAuto = true; 13133 } 13134 } 13135 } 13136 13137 Decls.push_back(D); 13138 } 13139 } 13140 13141 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13142 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13143 handleTagNumbering(Tag, S); 13144 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13145 getLangOpts().CPlusPlus) 13146 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13147 } 13148 } 13149 13150 return BuildDeclaratorGroup(Decls); 13151 } 13152 13153 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13154 /// group, performing any necessary semantic checking. 13155 Sema::DeclGroupPtrTy 13156 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13157 // C++14 [dcl.spec.auto]p7: (DR1347) 13158 // If the type that replaces the placeholder type is not the same in each 13159 // deduction, the program is ill-formed. 13160 if (Group.size() > 1) { 13161 QualType Deduced; 13162 VarDecl *DeducedDecl = nullptr; 13163 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13164 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13165 if (!D || D->isInvalidDecl()) 13166 break; 13167 DeducedType *DT = D->getType()->getContainedDeducedType(); 13168 if (!DT || DT->getDeducedType().isNull()) 13169 continue; 13170 if (Deduced.isNull()) { 13171 Deduced = DT->getDeducedType(); 13172 DeducedDecl = D; 13173 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13174 auto *AT = dyn_cast<AutoType>(DT); 13175 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13176 diag::err_auto_different_deductions) 13177 << (AT ? (unsigned)AT->getKeyword() : 3) 13178 << Deduced << DeducedDecl->getDeclName() 13179 << DT->getDeducedType() << D->getDeclName() 13180 << DeducedDecl->getInit()->getSourceRange() 13181 << D->getInit()->getSourceRange(); 13182 D->setInvalidDecl(); 13183 break; 13184 } 13185 } 13186 } 13187 13188 ActOnDocumentableDecls(Group); 13189 13190 return DeclGroupPtrTy::make( 13191 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13192 } 13193 13194 void Sema::ActOnDocumentableDecl(Decl *D) { 13195 ActOnDocumentableDecls(D); 13196 } 13197 13198 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13199 // Don't parse the comment if Doxygen diagnostics are ignored. 13200 if (Group.empty() || !Group[0]) 13201 return; 13202 13203 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13204 Group[0]->getLocation()) && 13205 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13206 Group[0]->getLocation())) 13207 return; 13208 13209 if (Group.size() >= 2) { 13210 // This is a decl group. Normally it will contain only declarations 13211 // produced from declarator list. But in case we have any definitions or 13212 // additional declaration references: 13213 // 'typedef struct S {} S;' 13214 // 'typedef struct S *S;' 13215 // 'struct S *pS;' 13216 // FinalizeDeclaratorGroup adds these as separate declarations. 13217 Decl *MaybeTagDecl = Group[0]; 13218 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13219 Group = Group.slice(1); 13220 } 13221 } 13222 13223 // FIMXE: We assume every Decl in the group is in the same file. 13224 // This is false when preprocessor constructs the group from decls in 13225 // different files (e. g. macros or #include). 13226 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13227 } 13228 13229 /// Common checks for a parameter-declaration that should apply to both function 13230 /// parameters and non-type template parameters. 13231 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13232 // Check that there are no default arguments inside the type of this 13233 // parameter. 13234 if (getLangOpts().CPlusPlus) 13235 CheckExtraCXXDefaultArguments(D); 13236 13237 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13238 if (D.getCXXScopeSpec().isSet()) { 13239 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13240 << D.getCXXScopeSpec().getRange(); 13241 } 13242 13243 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13244 // simple identifier except [...irrelevant cases...]. 13245 switch (D.getName().getKind()) { 13246 case UnqualifiedIdKind::IK_Identifier: 13247 break; 13248 13249 case UnqualifiedIdKind::IK_OperatorFunctionId: 13250 case UnqualifiedIdKind::IK_ConversionFunctionId: 13251 case UnqualifiedIdKind::IK_LiteralOperatorId: 13252 case UnqualifiedIdKind::IK_ConstructorName: 13253 case UnqualifiedIdKind::IK_DestructorName: 13254 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13255 case UnqualifiedIdKind::IK_DeductionGuideName: 13256 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13257 << GetNameForDeclarator(D).getName(); 13258 break; 13259 13260 case UnqualifiedIdKind::IK_TemplateId: 13261 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13262 // GetNameForDeclarator would not produce a useful name in this case. 13263 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13264 break; 13265 } 13266 } 13267 13268 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13269 /// to introduce parameters into function prototype scope. 13270 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13271 const DeclSpec &DS = D.getDeclSpec(); 13272 13273 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13274 13275 // C++03 [dcl.stc]p2 also permits 'auto'. 13276 StorageClass SC = SC_None; 13277 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13278 SC = SC_Register; 13279 // In C++11, the 'register' storage class specifier is deprecated. 13280 // In C++17, it is not allowed, but we tolerate it as an extension. 13281 if (getLangOpts().CPlusPlus11) { 13282 Diag(DS.getStorageClassSpecLoc(), 13283 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13284 : diag::warn_deprecated_register) 13285 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13286 } 13287 } else if (getLangOpts().CPlusPlus && 13288 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13289 SC = SC_Auto; 13290 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13291 Diag(DS.getStorageClassSpecLoc(), 13292 diag::err_invalid_storage_class_in_func_decl); 13293 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13294 } 13295 13296 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13297 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13298 << DeclSpec::getSpecifierName(TSCS); 13299 if (DS.isInlineSpecified()) 13300 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13301 << getLangOpts().CPlusPlus17; 13302 if (DS.hasConstexprSpecifier()) 13303 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13304 << 0 << D.getDeclSpec().getConstexprSpecifier(); 13305 13306 DiagnoseFunctionSpecifiers(DS); 13307 13308 CheckFunctionOrTemplateParamDeclarator(S, D); 13309 13310 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13311 QualType parmDeclType = TInfo->getType(); 13312 13313 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13314 IdentifierInfo *II = D.getIdentifier(); 13315 if (II) { 13316 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13317 ForVisibleRedeclaration); 13318 LookupName(R, S); 13319 if (R.isSingleResult()) { 13320 NamedDecl *PrevDecl = R.getFoundDecl(); 13321 if (PrevDecl->isTemplateParameter()) { 13322 // Maybe we will complain about the shadowed template parameter. 13323 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13324 // Just pretend that we didn't see the previous declaration. 13325 PrevDecl = nullptr; 13326 } else if (S->isDeclScope(PrevDecl)) { 13327 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13328 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13329 13330 // Recover by removing the name 13331 II = nullptr; 13332 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13333 D.setInvalidType(true); 13334 } 13335 } 13336 } 13337 13338 // Temporarily put parameter variables in the translation unit, not 13339 // the enclosing context. This prevents them from accidentally 13340 // looking like class members in C++. 13341 ParmVarDecl *New = 13342 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13343 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13344 13345 if (D.isInvalidType()) 13346 New->setInvalidDecl(); 13347 13348 assert(S->isFunctionPrototypeScope()); 13349 assert(S->getFunctionPrototypeDepth() >= 1); 13350 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13351 S->getNextFunctionPrototypeIndex()); 13352 13353 // Add the parameter declaration into this scope. 13354 S->AddDecl(New); 13355 if (II) 13356 IdResolver.AddDecl(New); 13357 13358 ProcessDeclAttributes(S, New, D); 13359 13360 if (D.getDeclSpec().isModulePrivateSpecified()) 13361 Diag(New->getLocation(), diag::err_module_private_local) 13362 << 1 << New->getDeclName() 13363 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13364 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13365 13366 if (New->hasAttr<BlocksAttr>()) { 13367 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13368 } 13369 13370 if (getLangOpts().OpenCL) 13371 deduceOpenCLAddressSpace(New); 13372 13373 return New; 13374 } 13375 13376 /// Synthesizes a variable for a parameter arising from a 13377 /// typedef. 13378 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13379 SourceLocation Loc, 13380 QualType T) { 13381 /* FIXME: setting StartLoc == Loc. 13382 Would it be worth to modify callers so as to provide proper source 13383 location for the unnamed parameters, embedding the parameter's type? */ 13384 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13385 T, Context.getTrivialTypeSourceInfo(T, Loc), 13386 SC_None, nullptr); 13387 Param->setImplicit(); 13388 return Param; 13389 } 13390 13391 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13392 // Don't diagnose unused-parameter errors in template instantiations; we 13393 // will already have done so in the template itself. 13394 if (inTemplateInstantiation()) 13395 return; 13396 13397 for (const ParmVarDecl *Parameter : Parameters) { 13398 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13399 !Parameter->hasAttr<UnusedAttr>()) { 13400 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13401 << Parameter->getDeclName(); 13402 } 13403 } 13404 } 13405 13406 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13407 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13408 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13409 return; 13410 13411 // Warn if the return value is pass-by-value and larger than the specified 13412 // threshold. 13413 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13414 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13415 if (Size > LangOpts.NumLargeByValueCopy) 13416 Diag(D->getLocation(), diag::warn_return_value_size) 13417 << D->getDeclName() << Size; 13418 } 13419 13420 // Warn if any parameter is pass-by-value and larger than the specified 13421 // threshold. 13422 for (const ParmVarDecl *Parameter : Parameters) { 13423 QualType T = Parameter->getType(); 13424 if (T->isDependentType() || !T.isPODType(Context)) 13425 continue; 13426 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13427 if (Size > LangOpts.NumLargeByValueCopy) 13428 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13429 << Parameter->getDeclName() << Size; 13430 } 13431 } 13432 13433 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13434 SourceLocation NameLoc, IdentifierInfo *Name, 13435 QualType T, TypeSourceInfo *TSInfo, 13436 StorageClass SC) { 13437 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13438 if (getLangOpts().ObjCAutoRefCount && 13439 T.getObjCLifetime() == Qualifiers::OCL_None && 13440 T->isObjCLifetimeType()) { 13441 13442 Qualifiers::ObjCLifetime lifetime; 13443 13444 // Special cases for arrays: 13445 // - if it's const, use __unsafe_unretained 13446 // - otherwise, it's an error 13447 if (T->isArrayType()) { 13448 if (!T.isConstQualified()) { 13449 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13450 DelayedDiagnostics.add( 13451 sema::DelayedDiagnostic::makeForbiddenType( 13452 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13453 else 13454 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13455 << TSInfo->getTypeLoc().getSourceRange(); 13456 } 13457 lifetime = Qualifiers::OCL_ExplicitNone; 13458 } else { 13459 lifetime = T->getObjCARCImplicitLifetime(); 13460 } 13461 T = Context.getLifetimeQualifiedType(T, lifetime); 13462 } 13463 13464 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13465 Context.getAdjustedParameterType(T), 13466 TSInfo, SC, nullptr); 13467 13468 // Make a note if we created a new pack in the scope of a lambda, so that 13469 // we know that references to that pack must also be expanded within the 13470 // lambda scope. 13471 if (New->isParameterPack()) 13472 if (auto *LSI = getEnclosingLambda()) 13473 LSI->LocalPacks.push_back(New); 13474 13475 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13476 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13477 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13478 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13479 13480 // Parameters can not be abstract class types. 13481 // For record types, this is done by the AbstractClassUsageDiagnoser once 13482 // the class has been completely parsed. 13483 if (!CurContext->isRecord() && 13484 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13485 AbstractParamType)) 13486 New->setInvalidDecl(); 13487 13488 // Parameter declarators cannot be interface types. All ObjC objects are 13489 // passed by reference. 13490 if (T->isObjCObjectType()) { 13491 SourceLocation TypeEndLoc = 13492 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13493 Diag(NameLoc, 13494 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13495 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13496 T = Context.getObjCObjectPointerType(T); 13497 New->setType(T); 13498 } 13499 13500 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13501 // duration shall not be qualified by an address-space qualifier." 13502 // Since all parameters have automatic store duration, they can not have 13503 // an address space. 13504 if (T.getAddressSpace() != LangAS::Default && 13505 // OpenCL allows function arguments declared to be an array of a type 13506 // to be qualified with an address space. 13507 !(getLangOpts().OpenCL && 13508 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13509 Diag(NameLoc, diag::err_arg_with_address_space); 13510 New->setInvalidDecl(); 13511 } 13512 13513 return New; 13514 } 13515 13516 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13517 SourceLocation LocAfterDecls) { 13518 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13519 13520 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13521 // for a K&R function. 13522 if (!FTI.hasPrototype) { 13523 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13524 --i; 13525 if (FTI.Params[i].Param == nullptr) { 13526 SmallString<256> Code; 13527 llvm::raw_svector_ostream(Code) 13528 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13529 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13530 << FTI.Params[i].Ident 13531 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13532 13533 // Implicitly declare the argument as type 'int' for lack of a better 13534 // type. 13535 AttributeFactory attrs; 13536 DeclSpec DS(attrs); 13537 const char* PrevSpec; // unused 13538 unsigned DiagID; // unused 13539 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13540 DiagID, Context.getPrintingPolicy()); 13541 // Use the identifier location for the type source range. 13542 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13543 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13544 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 13545 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13546 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13547 } 13548 } 13549 } 13550 } 13551 13552 Decl * 13553 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13554 MultiTemplateParamsArg TemplateParameterLists, 13555 SkipBodyInfo *SkipBody) { 13556 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13557 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13558 Scope *ParentScope = FnBodyScope->getParent(); 13559 13560 D.setFunctionDefinitionKind(FDK_Definition); 13561 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13562 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13563 } 13564 13565 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13566 Consumer.HandleInlineFunctionDefinition(D); 13567 } 13568 13569 static bool 13570 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13571 const FunctionDecl *&PossiblePrototype) { 13572 // Don't warn about invalid declarations. 13573 if (FD->isInvalidDecl()) 13574 return false; 13575 13576 // Or declarations that aren't global. 13577 if (!FD->isGlobal()) 13578 return false; 13579 13580 // Don't warn about C++ member functions. 13581 if (isa<CXXMethodDecl>(FD)) 13582 return false; 13583 13584 // Don't warn about 'main'. 13585 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13586 if (IdentifierInfo *II = FD->getIdentifier()) 13587 if (II->isStr("main")) 13588 return false; 13589 13590 // Don't warn about inline functions. 13591 if (FD->isInlined()) 13592 return false; 13593 13594 // Don't warn about function templates. 13595 if (FD->getDescribedFunctionTemplate()) 13596 return false; 13597 13598 // Don't warn about function template specializations. 13599 if (FD->isFunctionTemplateSpecialization()) 13600 return false; 13601 13602 // Don't warn for OpenCL kernels. 13603 if (FD->hasAttr<OpenCLKernelAttr>()) 13604 return false; 13605 13606 // Don't warn on explicitly deleted functions. 13607 if (FD->isDeleted()) 13608 return false; 13609 13610 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13611 Prev; Prev = Prev->getPreviousDecl()) { 13612 // Ignore any declarations that occur in function or method 13613 // scope, because they aren't visible from the header. 13614 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13615 continue; 13616 13617 PossiblePrototype = Prev; 13618 return Prev->getType()->isFunctionNoProtoType(); 13619 } 13620 13621 return true; 13622 } 13623 13624 void 13625 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13626 const FunctionDecl *EffectiveDefinition, 13627 SkipBodyInfo *SkipBody) { 13628 const FunctionDecl *Definition = EffectiveDefinition; 13629 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 13630 // If this is a friend function defined in a class template, it does not 13631 // have a body until it is used, nevertheless it is a definition, see 13632 // [temp.inst]p2: 13633 // 13634 // ... for the purpose of determining whether an instantiated redeclaration 13635 // is valid according to [basic.def.odr] and [class.mem], a declaration that 13636 // corresponds to a definition in the template is considered to be a 13637 // definition. 13638 // 13639 // The following code must produce redefinition error: 13640 // 13641 // template<typename T> struct C20 { friend void func_20() {} }; 13642 // C20<int> c20i; 13643 // void func_20() {} 13644 // 13645 for (auto I : FD->redecls()) { 13646 if (I != FD && !I->isInvalidDecl() && 13647 I->getFriendObjectKind() != Decl::FOK_None) { 13648 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 13649 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13650 // A merged copy of the same function, instantiated as a member of 13651 // the same class, is OK. 13652 if (declaresSameEntity(OrigFD, Original) && 13653 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 13654 cast<Decl>(FD->getLexicalDeclContext()))) 13655 continue; 13656 } 13657 13658 if (Original->isThisDeclarationADefinition()) { 13659 Definition = I; 13660 break; 13661 } 13662 } 13663 } 13664 } 13665 } 13666 13667 if (!Definition) 13668 // Similar to friend functions a friend function template may be a 13669 // definition and do not have a body if it is instantiated in a class 13670 // template. 13671 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 13672 for (auto I : FTD->redecls()) { 13673 auto D = cast<FunctionTemplateDecl>(I); 13674 if (D != FTD) { 13675 assert(!D->isThisDeclarationADefinition() && 13676 "More than one definition in redeclaration chain"); 13677 if (D->getFriendObjectKind() != Decl::FOK_None) 13678 if (FunctionTemplateDecl *FT = 13679 D->getInstantiatedFromMemberTemplate()) { 13680 if (FT->isThisDeclarationADefinition()) { 13681 Definition = D->getTemplatedDecl(); 13682 break; 13683 } 13684 } 13685 } 13686 } 13687 } 13688 13689 if (!Definition) 13690 return; 13691 13692 if (canRedefineFunction(Definition, getLangOpts())) 13693 return; 13694 13695 // Don't emit an error when this is redefinition of a typo-corrected 13696 // definition. 13697 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13698 return; 13699 13700 // If we don't have a visible definition of the function, and it's inline or 13701 // a template, skip the new definition. 13702 if (SkipBody && !hasVisibleDefinition(Definition) && 13703 (Definition->getFormalLinkage() == InternalLinkage || 13704 Definition->isInlined() || 13705 Definition->getDescribedFunctionTemplate() || 13706 Definition->getNumTemplateParameterLists())) { 13707 SkipBody->ShouldSkip = true; 13708 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 13709 if (auto *TD = Definition->getDescribedFunctionTemplate()) 13710 makeMergedDefinitionVisible(TD); 13711 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 13712 return; 13713 } 13714 13715 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 13716 Definition->getStorageClass() == SC_Extern) 13717 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 13718 << FD->getDeclName() << getLangOpts().CPlusPlus; 13719 else 13720 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 13721 13722 Diag(Definition->getLocation(), diag::note_previous_definition); 13723 FD->setInvalidDecl(); 13724 } 13725 13726 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 13727 Sema &S) { 13728 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 13729 13730 LambdaScopeInfo *LSI = S.PushLambdaScope(); 13731 LSI->CallOperator = CallOperator; 13732 LSI->Lambda = LambdaClass; 13733 LSI->ReturnType = CallOperator->getReturnType(); 13734 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 13735 13736 if (LCD == LCD_None) 13737 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 13738 else if (LCD == LCD_ByCopy) 13739 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 13740 else if (LCD == LCD_ByRef) 13741 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 13742 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 13743 13744 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 13745 LSI->Mutable = !CallOperator->isConst(); 13746 13747 // Add the captures to the LSI so they can be noted as already 13748 // captured within tryCaptureVar. 13749 auto I = LambdaClass->field_begin(); 13750 for (const auto &C : LambdaClass->captures()) { 13751 if (C.capturesVariable()) { 13752 VarDecl *VD = C.getCapturedVar(); 13753 if (VD->isInitCapture()) 13754 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 13755 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 13756 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 13757 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 13758 /*EllipsisLoc*/C.isPackExpansion() 13759 ? C.getEllipsisLoc() : SourceLocation(), 13760 I->getType(), /*Invalid*/false); 13761 13762 } else if (C.capturesThis()) { 13763 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 13764 C.getCaptureKind() == LCK_StarThis); 13765 } else { 13766 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 13767 I->getType()); 13768 } 13769 ++I; 13770 } 13771 } 13772 13773 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 13774 SkipBodyInfo *SkipBody) { 13775 if (!D) { 13776 // Parsing the function declaration failed in some way. Push on a fake scope 13777 // anyway so we can try to parse the function body. 13778 PushFunctionScope(); 13779 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13780 return D; 13781 } 13782 13783 FunctionDecl *FD = nullptr; 13784 13785 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 13786 FD = FunTmpl->getTemplatedDecl(); 13787 else 13788 FD = cast<FunctionDecl>(D); 13789 13790 // Do not push if it is a lambda because one is already pushed when building 13791 // the lambda in ActOnStartOfLambdaDefinition(). 13792 if (!isLambdaCallOperator(FD)) 13793 PushExpressionEvaluationContext( 13794 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 13795 : ExprEvalContexts.back().Context); 13796 13797 // Check for defining attributes before the check for redefinition. 13798 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 13799 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 13800 FD->dropAttr<AliasAttr>(); 13801 FD->setInvalidDecl(); 13802 } 13803 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 13804 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 13805 FD->dropAttr<IFuncAttr>(); 13806 FD->setInvalidDecl(); 13807 } 13808 13809 // See if this is a redefinition. If 'will have body' is already set, then 13810 // these checks were already performed when it was set. 13811 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 13812 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 13813 13814 // If we're skipping the body, we're done. Don't enter the scope. 13815 if (SkipBody && SkipBody->ShouldSkip) 13816 return D; 13817 } 13818 13819 // Mark this function as "will have a body eventually". This lets users to 13820 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 13821 // this function. 13822 FD->setWillHaveBody(); 13823 13824 // If we are instantiating a generic lambda call operator, push 13825 // a LambdaScopeInfo onto the function stack. But use the information 13826 // that's already been calculated (ActOnLambdaExpr) to prime the current 13827 // LambdaScopeInfo. 13828 // When the template operator is being specialized, the LambdaScopeInfo, 13829 // has to be properly restored so that tryCaptureVariable doesn't try 13830 // and capture any new variables. In addition when calculating potential 13831 // captures during transformation of nested lambdas, it is necessary to 13832 // have the LSI properly restored. 13833 if (isGenericLambdaCallOperatorSpecialization(FD)) { 13834 assert(inTemplateInstantiation() && 13835 "There should be an active template instantiation on the stack " 13836 "when instantiating a generic lambda!"); 13837 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 13838 } else { 13839 // Enter a new function scope 13840 PushFunctionScope(); 13841 } 13842 13843 // Builtin functions cannot be defined. 13844 if (unsigned BuiltinID = FD->getBuiltinID()) { 13845 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 13846 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 13847 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 13848 FD->setInvalidDecl(); 13849 } 13850 } 13851 13852 // The return type of a function definition must be complete 13853 // (C99 6.9.1p3, C++ [dcl.fct]p6). 13854 QualType ResultType = FD->getReturnType(); 13855 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 13856 !FD->isInvalidDecl() && 13857 RequireCompleteType(FD->getLocation(), ResultType, 13858 diag::err_func_def_incomplete_result)) 13859 FD->setInvalidDecl(); 13860 13861 if (FnBodyScope) 13862 PushDeclContext(FnBodyScope, FD); 13863 13864 // Check the validity of our function parameters 13865 CheckParmsForFunctionDef(FD->parameters(), 13866 /*CheckParameterNames=*/true); 13867 13868 // Add non-parameter declarations already in the function to the current 13869 // scope. 13870 if (FnBodyScope) { 13871 for (Decl *NPD : FD->decls()) { 13872 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 13873 if (!NonParmDecl) 13874 continue; 13875 assert(!isa<ParmVarDecl>(NonParmDecl) && 13876 "parameters should not be in newly created FD yet"); 13877 13878 // If the decl has a name, make it accessible in the current scope. 13879 if (NonParmDecl->getDeclName()) 13880 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 13881 13882 // Similarly, dive into enums and fish their constants out, making them 13883 // accessible in this scope. 13884 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 13885 for (auto *EI : ED->enumerators()) 13886 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 13887 } 13888 } 13889 } 13890 13891 // Introduce our parameters into the function scope 13892 for (auto Param : FD->parameters()) { 13893 Param->setOwningFunction(FD); 13894 13895 // If this has an identifier, add it to the scope stack. 13896 if (Param->getIdentifier() && FnBodyScope) { 13897 CheckShadow(FnBodyScope, Param); 13898 13899 PushOnScopeChains(Param, FnBodyScope); 13900 } 13901 } 13902 13903 // Ensure that the function's exception specification is instantiated. 13904 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 13905 ResolveExceptionSpec(D->getLocation(), FPT); 13906 13907 // dllimport cannot be applied to non-inline function definitions. 13908 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 13909 !FD->isTemplateInstantiation()) { 13910 assert(!FD->hasAttr<DLLExportAttr>()); 13911 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 13912 FD->setInvalidDecl(); 13913 return D; 13914 } 13915 // We want to attach documentation to original Decl (which might be 13916 // a function template). 13917 ActOnDocumentableDecl(D); 13918 if (getCurLexicalContext()->isObjCContainer() && 13919 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 13920 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 13921 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 13922 13923 return D; 13924 } 13925 13926 /// Given the set of return statements within a function body, 13927 /// compute the variables that are subject to the named return value 13928 /// optimization. 13929 /// 13930 /// Each of the variables that is subject to the named return value 13931 /// optimization will be marked as NRVO variables in the AST, and any 13932 /// return statement that has a marked NRVO variable as its NRVO candidate can 13933 /// use the named return value optimization. 13934 /// 13935 /// This function applies a very simplistic algorithm for NRVO: if every return 13936 /// statement in the scope of a variable has the same NRVO candidate, that 13937 /// candidate is an NRVO variable. 13938 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 13939 ReturnStmt **Returns = Scope->Returns.data(); 13940 13941 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 13942 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 13943 if (!NRVOCandidate->isNRVOVariable()) 13944 Returns[I]->setNRVOCandidate(nullptr); 13945 } 13946 } 13947 } 13948 13949 bool Sema::canDelayFunctionBody(const Declarator &D) { 13950 // We can't delay parsing the body of a constexpr function template (yet). 13951 if (D.getDeclSpec().hasConstexprSpecifier()) 13952 return false; 13953 13954 // We can't delay parsing the body of a function template with a deduced 13955 // return type (yet). 13956 if (D.getDeclSpec().hasAutoTypeSpec()) { 13957 // If the placeholder introduces a non-deduced trailing return type, 13958 // we can still delay parsing it. 13959 if (D.getNumTypeObjects()) { 13960 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 13961 if (Outer.Kind == DeclaratorChunk::Function && 13962 Outer.Fun.hasTrailingReturnType()) { 13963 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 13964 return Ty.isNull() || !Ty->isUndeducedType(); 13965 } 13966 } 13967 return false; 13968 } 13969 13970 return true; 13971 } 13972 13973 bool Sema::canSkipFunctionBody(Decl *D) { 13974 // We cannot skip the body of a function (or function template) which is 13975 // constexpr, since we may need to evaluate its body in order to parse the 13976 // rest of the file. 13977 // We cannot skip the body of a function with an undeduced return type, 13978 // because any callers of that function need to know the type. 13979 if (const FunctionDecl *FD = D->getAsFunction()) { 13980 if (FD->isConstexpr()) 13981 return false; 13982 // We can't simply call Type::isUndeducedType here, because inside template 13983 // auto can be deduced to a dependent type, which is not considered 13984 // "undeduced". 13985 if (FD->getReturnType()->getContainedDeducedType()) 13986 return false; 13987 } 13988 return Consumer.shouldSkipFunctionBody(D); 13989 } 13990 13991 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 13992 if (!Decl) 13993 return nullptr; 13994 if (FunctionDecl *FD = Decl->getAsFunction()) 13995 FD->setHasSkippedBody(); 13996 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 13997 MD->setHasSkippedBody(); 13998 return Decl; 13999 } 14000 14001 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14002 return ActOnFinishFunctionBody(D, BodyArg, false); 14003 } 14004 14005 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14006 /// body. 14007 class ExitFunctionBodyRAII { 14008 public: 14009 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14010 ~ExitFunctionBodyRAII() { 14011 if (!IsLambda) 14012 S.PopExpressionEvaluationContext(); 14013 } 14014 14015 private: 14016 Sema &S; 14017 bool IsLambda = false; 14018 }; 14019 14020 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14021 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14022 14023 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14024 if (EscapeInfo.count(BD)) 14025 return EscapeInfo[BD]; 14026 14027 bool R = false; 14028 const BlockDecl *CurBD = BD; 14029 14030 do { 14031 R = !CurBD->doesNotEscape(); 14032 if (R) 14033 break; 14034 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14035 } while (CurBD); 14036 14037 return EscapeInfo[BD] = R; 14038 }; 14039 14040 // If the location where 'self' is implicitly retained is inside a escaping 14041 // block, emit a diagnostic. 14042 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14043 S.ImplicitlyRetainedSelfLocs) 14044 if (IsOrNestedInEscapingBlock(P.second)) 14045 S.Diag(P.first, diag::warn_implicitly_retains_self) 14046 << FixItHint::CreateInsertion(P.first, "self->"); 14047 } 14048 14049 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14050 bool IsInstantiation) { 14051 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14052 14053 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14054 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14055 14056 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) 14057 CheckCompletedCoroutineBody(FD, Body); 14058 14059 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14060 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14061 // meant to pop the context added in ActOnStartOfFunctionDef(). 14062 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14063 14064 if (FD) { 14065 FD->setBody(Body); 14066 FD->setWillHaveBody(false); 14067 14068 if (getLangOpts().CPlusPlus14) { 14069 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14070 FD->getReturnType()->isUndeducedType()) { 14071 // If the function has a deduced result type but contains no 'return' 14072 // statements, the result type as written must be exactly 'auto', and 14073 // the deduced result type is 'void'. 14074 if (!FD->getReturnType()->getAs<AutoType>()) { 14075 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14076 << FD->getReturnType(); 14077 FD->setInvalidDecl(); 14078 } else { 14079 // Substitute 'void' for the 'auto' in the type. 14080 TypeLoc ResultType = getReturnTypeLoc(FD); 14081 Context.adjustDeducedFunctionResultType( 14082 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14083 } 14084 } 14085 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14086 // In C++11, we don't use 'auto' deduction rules for lambda call 14087 // operators because we don't support return type deduction. 14088 auto *LSI = getCurLambda(); 14089 if (LSI->HasImplicitReturnType) { 14090 deduceClosureReturnType(*LSI); 14091 14092 // C++11 [expr.prim.lambda]p4: 14093 // [...] if there are no return statements in the compound-statement 14094 // [the deduced type is] the type void 14095 QualType RetType = 14096 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14097 14098 // Update the return type to the deduced type. 14099 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14100 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14101 Proto->getExtProtoInfo())); 14102 } 14103 } 14104 14105 // If the function implicitly returns zero (like 'main') or is naked, 14106 // don't complain about missing return statements. 14107 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14108 WP.disableCheckFallThrough(); 14109 14110 // MSVC permits the use of pure specifier (=0) on function definition, 14111 // defined at class scope, warn about this non-standard construct. 14112 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14113 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14114 14115 if (!FD->isInvalidDecl()) { 14116 // Don't diagnose unused parameters of defaulted or deleted functions. 14117 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14118 DiagnoseUnusedParameters(FD->parameters()); 14119 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14120 FD->getReturnType(), FD); 14121 14122 // If this is a structor, we need a vtable. 14123 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14124 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14125 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14126 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14127 14128 // Try to apply the named return value optimization. We have to check 14129 // if we can do this here because lambdas keep return statements around 14130 // to deduce an implicit return type. 14131 if (FD->getReturnType()->isRecordType() && 14132 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14133 computeNRVO(Body, getCurFunction()); 14134 } 14135 14136 // GNU warning -Wmissing-prototypes: 14137 // Warn if a global function is defined without a previous 14138 // prototype declaration. This warning is issued even if the 14139 // definition itself provides a prototype. The aim is to detect 14140 // global functions that fail to be declared in header files. 14141 const FunctionDecl *PossiblePrototype = nullptr; 14142 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14143 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14144 14145 if (PossiblePrototype) { 14146 // We found a declaration that is not a prototype, 14147 // but that could be a zero-parameter prototype 14148 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14149 TypeLoc TL = TI->getTypeLoc(); 14150 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14151 Diag(PossiblePrototype->getLocation(), 14152 diag::note_declaration_not_a_prototype) 14153 << (FD->getNumParams() != 0) 14154 << (FD->getNumParams() == 0 14155 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14156 : FixItHint{}); 14157 } 14158 } else { 14159 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14160 << /* function */ 1 14161 << (FD->getStorageClass() == SC_None 14162 ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(), 14163 "static ") 14164 : FixItHint{}); 14165 } 14166 14167 // GNU warning -Wstrict-prototypes 14168 // Warn if K&R function is defined without a previous declaration. 14169 // This warning is issued only if the definition itself does not provide 14170 // a prototype. Only K&R definitions do not provide a prototype. 14171 if (!FD->hasWrittenPrototype()) { 14172 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14173 TypeLoc TL = TI->getTypeLoc(); 14174 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14175 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14176 } 14177 } 14178 14179 // Warn on CPUDispatch with an actual body. 14180 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14181 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14182 if (!CmpndBody->body_empty()) 14183 Diag(CmpndBody->body_front()->getBeginLoc(), 14184 diag::warn_dispatch_body_ignored); 14185 14186 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14187 const CXXMethodDecl *KeyFunction; 14188 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14189 MD->isVirtual() && 14190 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14191 MD == KeyFunction->getCanonicalDecl()) { 14192 // Update the key-function state if necessary for this ABI. 14193 if (FD->isInlined() && 14194 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14195 Context.setNonKeyFunction(MD); 14196 14197 // If the newly-chosen key function is already defined, then we 14198 // need to mark the vtable as used retroactively. 14199 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14200 const FunctionDecl *Definition; 14201 if (KeyFunction && KeyFunction->isDefined(Definition)) 14202 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14203 } else { 14204 // We just defined they key function; mark the vtable as used. 14205 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14206 } 14207 } 14208 } 14209 14210 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14211 "Function parsing confused"); 14212 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14213 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14214 MD->setBody(Body); 14215 if (!MD->isInvalidDecl()) { 14216 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14217 MD->getReturnType(), MD); 14218 14219 if (Body) 14220 computeNRVO(Body, getCurFunction()); 14221 } 14222 if (getCurFunction()->ObjCShouldCallSuper) { 14223 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14224 << MD->getSelector().getAsString(); 14225 getCurFunction()->ObjCShouldCallSuper = false; 14226 } 14227 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 14228 const ObjCMethodDecl *InitMethod = nullptr; 14229 bool isDesignated = 14230 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14231 assert(isDesignated && InitMethod); 14232 (void)isDesignated; 14233 14234 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14235 auto IFace = MD->getClassInterface(); 14236 if (!IFace) 14237 return false; 14238 auto SuperD = IFace->getSuperClass(); 14239 if (!SuperD) 14240 return false; 14241 return SuperD->getIdentifier() == 14242 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14243 }; 14244 // Don't issue this warning for unavailable inits or direct subclasses 14245 // of NSObject. 14246 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14247 Diag(MD->getLocation(), 14248 diag::warn_objc_designated_init_missing_super_call); 14249 Diag(InitMethod->getLocation(), 14250 diag::note_objc_designated_init_marked_here); 14251 } 14252 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 14253 } 14254 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 14255 // Don't issue this warning for unavaialable inits. 14256 if (!MD->isUnavailable()) 14257 Diag(MD->getLocation(), 14258 diag::warn_objc_secondary_init_missing_init_call); 14259 getCurFunction()->ObjCWarnForNoInitDelegation = false; 14260 } 14261 14262 diagnoseImplicitlyRetainedSelf(*this); 14263 } else { 14264 // Parsing the function declaration failed in some way. Pop the fake scope 14265 // we pushed on. 14266 PopFunctionScopeInfo(ActivePolicy, dcl); 14267 return nullptr; 14268 } 14269 14270 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14271 DiagnoseUnguardedAvailabilityViolations(dcl); 14272 14273 assert(!getCurFunction()->ObjCShouldCallSuper && 14274 "This should only be set for ObjC methods, which should have been " 14275 "handled in the block above."); 14276 14277 // Verify and clean out per-function state. 14278 if (Body && (!FD || !FD->isDefaulted())) { 14279 // C++ constructors that have function-try-blocks can't have return 14280 // statements in the handlers of that block. (C++ [except.handle]p14) 14281 // Verify this. 14282 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14283 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14284 14285 // Verify that gotos and switch cases don't jump into scopes illegally. 14286 if (getCurFunction()->NeedsScopeChecking() && 14287 !PP.isCodeCompletionEnabled()) 14288 DiagnoseInvalidJumps(Body); 14289 14290 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14291 if (!Destructor->getParent()->isDependentType()) 14292 CheckDestructor(Destructor); 14293 14294 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14295 Destructor->getParent()); 14296 } 14297 14298 // If any errors have occurred, clear out any temporaries that may have 14299 // been leftover. This ensures that these temporaries won't be picked up for 14300 // deletion in some later function. 14301 if (getDiagnostics().hasErrorOccurred() || 14302 getDiagnostics().getSuppressAllDiagnostics()) { 14303 DiscardCleanupsInEvaluationContext(); 14304 } 14305 if (!getDiagnostics().hasUncompilableErrorOccurred() && 14306 !isa<FunctionTemplateDecl>(dcl)) { 14307 // Since the body is valid, issue any analysis-based warnings that are 14308 // enabled. 14309 ActivePolicy = &WP; 14310 } 14311 14312 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14313 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14314 FD->setInvalidDecl(); 14315 14316 if (FD && FD->hasAttr<NakedAttr>()) { 14317 for (const Stmt *S : Body->children()) { 14318 // Allow local register variables without initializer as they don't 14319 // require prologue. 14320 bool RegisterVariables = false; 14321 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14322 for (const auto *Decl : DS->decls()) { 14323 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14324 RegisterVariables = 14325 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14326 if (!RegisterVariables) 14327 break; 14328 } 14329 } 14330 } 14331 if (RegisterVariables) 14332 continue; 14333 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14334 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14335 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14336 FD->setInvalidDecl(); 14337 break; 14338 } 14339 } 14340 } 14341 14342 assert(ExprCleanupObjects.size() == 14343 ExprEvalContexts.back().NumCleanupObjects && 14344 "Leftover temporaries in function"); 14345 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14346 assert(MaybeODRUseExprs.empty() && 14347 "Leftover expressions for odr-use checking"); 14348 } 14349 14350 if (!IsInstantiation) 14351 PopDeclContext(); 14352 14353 PopFunctionScopeInfo(ActivePolicy, dcl); 14354 // If any errors have occurred, clear out any temporaries that may have 14355 // been leftover. This ensures that these temporaries won't be picked up for 14356 // deletion in some later function. 14357 if (getDiagnostics().hasErrorOccurred()) { 14358 DiscardCleanupsInEvaluationContext(); 14359 } 14360 14361 return dcl; 14362 } 14363 14364 /// When we finish delayed parsing of an attribute, we must attach it to the 14365 /// relevant Decl. 14366 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14367 ParsedAttributes &Attrs) { 14368 // Always attach attributes to the underlying decl. 14369 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14370 D = TD->getTemplatedDecl(); 14371 ProcessDeclAttributeList(S, D, Attrs); 14372 14373 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14374 if (Method->isStatic()) 14375 checkThisInStaticMemberFunctionAttributes(Method); 14376 } 14377 14378 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14379 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14380 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14381 IdentifierInfo &II, Scope *S) { 14382 // Find the scope in which the identifier is injected and the corresponding 14383 // DeclContext. 14384 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14385 // In that case, we inject the declaration into the translation unit scope 14386 // instead. 14387 Scope *BlockScope = S; 14388 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14389 BlockScope = BlockScope->getParent(); 14390 14391 Scope *ContextScope = BlockScope; 14392 while (!ContextScope->getEntity()) 14393 ContextScope = ContextScope->getParent(); 14394 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14395 14396 // Before we produce a declaration for an implicitly defined 14397 // function, see whether there was a locally-scoped declaration of 14398 // this name as a function or variable. If so, use that 14399 // (non-visible) declaration, and complain about it. 14400 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14401 if (ExternCPrev) { 14402 // We still need to inject the function into the enclosing block scope so 14403 // that later (non-call) uses can see it. 14404 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14405 14406 // C89 footnote 38: 14407 // If in fact it is not defined as having type "function returning int", 14408 // the behavior is undefined. 14409 if (!isa<FunctionDecl>(ExternCPrev) || 14410 !Context.typesAreCompatible( 14411 cast<FunctionDecl>(ExternCPrev)->getType(), 14412 Context.getFunctionNoProtoType(Context.IntTy))) { 14413 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14414 << ExternCPrev << !getLangOpts().C99; 14415 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14416 return ExternCPrev; 14417 } 14418 } 14419 14420 // Extension in C99. Legal in C90, but warn about it. 14421 unsigned diag_id; 14422 if (II.getName().startswith("__builtin_")) 14423 diag_id = diag::warn_builtin_unknown; 14424 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14425 else if (getLangOpts().OpenCL) 14426 diag_id = diag::err_opencl_implicit_function_decl; 14427 else if (getLangOpts().C99) 14428 diag_id = diag::ext_implicit_function_decl; 14429 else 14430 diag_id = diag::warn_implicit_function_decl; 14431 Diag(Loc, diag_id) << &II; 14432 14433 // If we found a prior declaration of this function, don't bother building 14434 // another one. We've already pushed that one into scope, so there's nothing 14435 // more to do. 14436 if (ExternCPrev) 14437 return ExternCPrev; 14438 14439 // Because typo correction is expensive, only do it if the implicit 14440 // function declaration is going to be treated as an error. 14441 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14442 TypoCorrection Corrected; 14443 DeclFilterCCC<FunctionDecl> CCC{}; 14444 if (S && (Corrected = 14445 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14446 S, nullptr, CCC, CTK_NonError))) 14447 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14448 /*ErrorRecovery*/false); 14449 } 14450 14451 // Set a Declarator for the implicit definition: int foo(); 14452 const char *Dummy; 14453 AttributeFactory attrFactory; 14454 DeclSpec DS(attrFactory); 14455 unsigned DiagID; 14456 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14457 Context.getPrintingPolicy()); 14458 (void)Error; // Silence warning. 14459 assert(!Error && "Error setting up implicit decl!"); 14460 SourceLocation NoLoc; 14461 Declarator D(DS, DeclaratorContext::BlockContext); 14462 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14463 /*IsAmbiguous=*/false, 14464 /*LParenLoc=*/NoLoc, 14465 /*Params=*/nullptr, 14466 /*NumParams=*/0, 14467 /*EllipsisLoc=*/NoLoc, 14468 /*RParenLoc=*/NoLoc, 14469 /*RefQualifierIsLvalueRef=*/true, 14470 /*RefQualifierLoc=*/NoLoc, 14471 /*MutableLoc=*/NoLoc, EST_None, 14472 /*ESpecRange=*/SourceRange(), 14473 /*Exceptions=*/nullptr, 14474 /*ExceptionRanges=*/nullptr, 14475 /*NumExceptions=*/0, 14476 /*NoexceptExpr=*/nullptr, 14477 /*ExceptionSpecTokens=*/nullptr, 14478 /*DeclsInPrototype=*/None, Loc, 14479 Loc, D), 14480 std::move(DS.getAttributes()), SourceLocation()); 14481 D.SetIdentifier(&II, Loc); 14482 14483 // Insert this function into the enclosing block scope. 14484 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14485 FD->setImplicit(); 14486 14487 AddKnownFunctionAttributes(FD); 14488 14489 return FD; 14490 } 14491 14492 /// If this function is a C++ replaceable global allocation function 14493 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14494 /// adds any function attributes that we know a priori based on the standard. 14495 /// 14496 /// We need to check for duplicate attributes both here and where user-written 14497 /// attributes are applied to declarations. 14498 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14499 FunctionDecl *FD) { 14500 if (FD->isInvalidDecl()) 14501 return; 14502 14503 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14504 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14505 return; 14506 14507 Optional<unsigned> AlignmentParam; 14508 bool IsNothrow = false; 14509 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14510 return; 14511 14512 // C++2a [basic.stc.dynamic.allocation]p4: 14513 // An allocation function that has a non-throwing exception specification 14514 // indicates failure by returning a null pointer value. Any other allocation 14515 // function never returns a null pointer value and indicates failure only by 14516 // throwing an exception [...] 14517 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14518 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14519 14520 // C++2a [basic.stc.dynamic.allocation]p2: 14521 // An allocation function attempts to allocate the requested amount of 14522 // storage. [...] If the request succeeds, the value returned by a 14523 // replaceable allocation function is a [...] pointer value p0 different 14524 // from any previously returned value p1 [...] 14525 // 14526 // However, this particular information is being added in codegen, 14527 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14528 14529 // C++2a [basic.stc.dynamic.allocation]p2: 14530 // An allocation function attempts to allocate the requested amount of 14531 // storage. If it is successful, it returns the address of the start of a 14532 // block of storage whose length in bytes is at least as large as the 14533 // requested size. 14534 if (!FD->hasAttr<AllocSizeAttr>()) { 14535 FD->addAttr(AllocSizeAttr::CreateImplicit( 14536 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14537 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14538 } 14539 14540 // C++2a [basic.stc.dynamic.allocation]p3: 14541 // For an allocation function [...], the pointer returned on a successful 14542 // call shall represent the address of storage that is aligned as follows: 14543 // (3.1) If the allocation function takes an argument of type 14544 // std::align_val_t, the storage will have the alignment 14545 // specified by the value of this argument. 14546 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14547 FD->addAttr(AllocAlignAttr::CreateImplicit( 14548 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14549 } 14550 14551 // FIXME: 14552 // C++2a [basic.stc.dynamic.allocation]p3: 14553 // For an allocation function [...], the pointer returned on a successful 14554 // call shall represent the address of storage that is aligned as follows: 14555 // (3.2) Otherwise, if the allocation function is named operator new[], 14556 // the storage is aligned for any object that does not have 14557 // new-extended alignment ([basic.align]) and is no larger than the 14558 // requested size. 14559 // (3.3) Otherwise, the storage is aligned for any object that does not 14560 // have new-extended alignment and is of the requested size. 14561 } 14562 14563 /// Adds any function attributes that we know a priori based on 14564 /// the declaration of this function. 14565 /// 14566 /// These attributes can apply both to implicitly-declared builtins 14567 /// (like __builtin___printf_chk) or to library-declared functions 14568 /// like NSLog or printf. 14569 /// 14570 /// We need to check for duplicate attributes both here and where user-written 14571 /// attributes are applied to declarations. 14572 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14573 if (FD->isInvalidDecl()) 14574 return; 14575 14576 // If this is a built-in function, map its builtin attributes to 14577 // actual attributes. 14578 if (unsigned BuiltinID = FD->getBuiltinID()) { 14579 // Handle printf-formatting attributes. 14580 unsigned FormatIdx; 14581 bool HasVAListArg; 14582 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14583 if (!FD->hasAttr<FormatAttr>()) { 14584 const char *fmt = "printf"; 14585 unsigned int NumParams = FD->getNumParams(); 14586 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14587 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14588 fmt = "NSString"; 14589 FD->addAttr(FormatAttr::CreateImplicit(Context, 14590 &Context.Idents.get(fmt), 14591 FormatIdx+1, 14592 HasVAListArg ? 0 : FormatIdx+2, 14593 FD->getLocation())); 14594 } 14595 } 14596 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14597 HasVAListArg)) { 14598 if (!FD->hasAttr<FormatAttr>()) 14599 FD->addAttr(FormatAttr::CreateImplicit(Context, 14600 &Context.Idents.get("scanf"), 14601 FormatIdx+1, 14602 HasVAListArg ? 0 : FormatIdx+2, 14603 FD->getLocation())); 14604 } 14605 14606 // Handle automatically recognized callbacks. 14607 SmallVector<int, 4> Encoding; 14608 if (!FD->hasAttr<CallbackAttr>() && 14609 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14610 FD->addAttr(CallbackAttr::CreateImplicit( 14611 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14612 14613 // Mark const if we don't care about errno and that is the only thing 14614 // preventing the function from being const. This allows IRgen to use LLVM 14615 // intrinsics for such functions. 14616 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14617 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14618 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14619 14620 // We make "fma" on some platforms const because we know it does not set 14621 // errno in those environments even though it could set errno based on the 14622 // C standard. 14623 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14624 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14625 !FD->hasAttr<ConstAttr>()) { 14626 switch (BuiltinID) { 14627 case Builtin::BI__builtin_fma: 14628 case Builtin::BI__builtin_fmaf: 14629 case Builtin::BI__builtin_fmal: 14630 case Builtin::BIfma: 14631 case Builtin::BIfmaf: 14632 case Builtin::BIfmal: 14633 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14634 break; 14635 default: 14636 break; 14637 } 14638 } 14639 14640 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14641 !FD->hasAttr<ReturnsTwiceAttr>()) 14642 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 14643 FD->getLocation())); 14644 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 14645 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14646 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 14647 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 14648 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 14649 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14650 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 14651 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 14652 // Add the appropriate attribute, depending on the CUDA compilation mode 14653 // and which target the builtin belongs to. For example, during host 14654 // compilation, aux builtins are __device__, while the rest are __host__. 14655 if (getLangOpts().CUDAIsDevice != 14656 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 14657 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 14658 else 14659 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 14660 } 14661 } 14662 14663 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 14664 14665 // If C++ exceptions are enabled but we are told extern "C" functions cannot 14666 // throw, add an implicit nothrow attribute to any extern "C" function we come 14667 // across. 14668 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 14669 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 14670 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 14671 if (!FPT || FPT->getExceptionSpecType() == EST_None) 14672 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14673 } 14674 14675 IdentifierInfo *Name = FD->getIdentifier(); 14676 if (!Name) 14677 return; 14678 if ((!getLangOpts().CPlusPlus && 14679 FD->getDeclContext()->isTranslationUnit()) || 14680 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 14681 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 14682 LinkageSpecDecl::lang_c)) { 14683 // Okay: this could be a libc/libm/Objective-C function we know 14684 // about. 14685 } else 14686 return; 14687 14688 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 14689 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 14690 // target-specific builtins, perhaps? 14691 if (!FD->hasAttr<FormatAttr>()) 14692 FD->addAttr(FormatAttr::CreateImplicit(Context, 14693 &Context.Idents.get("printf"), 2, 14694 Name->isStr("vasprintf") ? 0 : 3, 14695 FD->getLocation())); 14696 } 14697 14698 if (Name->isStr("__CFStringMakeConstantString")) { 14699 // We already have a __builtin___CFStringMakeConstantString, 14700 // but builds that use -fno-constant-cfstrings don't go through that. 14701 if (!FD->hasAttr<FormatArgAttr>()) 14702 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 14703 FD->getLocation())); 14704 } 14705 } 14706 14707 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 14708 TypeSourceInfo *TInfo) { 14709 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 14710 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 14711 14712 if (!TInfo) { 14713 assert(D.isInvalidType() && "no declarator info for valid type"); 14714 TInfo = Context.getTrivialTypeSourceInfo(T); 14715 } 14716 14717 // Scope manipulation handled by caller. 14718 TypedefDecl *NewTD = 14719 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 14720 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 14721 14722 // Bail out immediately if we have an invalid declaration. 14723 if (D.isInvalidType()) { 14724 NewTD->setInvalidDecl(); 14725 return NewTD; 14726 } 14727 14728 if (D.getDeclSpec().isModulePrivateSpecified()) { 14729 if (CurContext->isFunctionOrMethod()) 14730 Diag(NewTD->getLocation(), diag::err_module_private_local) 14731 << 2 << NewTD->getDeclName() 14732 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 14733 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 14734 else 14735 NewTD->setModulePrivate(); 14736 } 14737 14738 // C++ [dcl.typedef]p8: 14739 // If the typedef declaration defines an unnamed class (or 14740 // enum), the first typedef-name declared by the declaration 14741 // to be that class type (or enum type) is used to denote the 14742 // class type (or enum type) for linkage purposes only. 14743 // We need to check whether the type was declared in the declaration. 14744 switch (D.getDeclSpec().getTypeSpecType()) { 14745 case TST_enum: 14746 case TST_struct: 14747 case TST_interface: 14748 case TST_union: 14749 case TST_class: { 14750 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 14751 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 14752 break; 14753 } 14754 14755 default: 14756 break; 14757 } 14758 14759 return NewTD; 14760 } 14761 14762 /// Check that this is a valid underlying type for an enum declaration. 14763 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 14764 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 14765 QualType T = TI->getType(); 14766 14767 if (T->isDependentType()) 14768 return false; 14769 14770 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 14771 if (BT->isInteger()) 14772 return false; 14773 14774 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 14775 return true; 14776 } 14777 14778 /// Check whether this is a valid redeclaration of a previous enumeration. 14779 /// \return true if the redeclaration was invalid. 14780 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 14781 QualType EnumUnderlyingTy, bool IsFixed, 14782 const EnumDecl *Prev) { 14783 if (IsScoped != Prev->isScoped()) { 14784 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 14785 << Prev->isScoped(); 14786 Diag(Prev->getLocation(), diag::note_previous_declaration); 14787 return true; 14788 } 14789 14790 if (IsFixed && Prev->isFixed()) { 14791 if (!EnumUnderlyingTy->isDependentType() && 14792 !Prev->getIntegerType()->isDependentType() && 14793 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 14794 Prev->getIntegerType())) { 14795 // TODO: Highlight the underlying type of the redeclaration. 14796 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 14797 << EnumUnderlyingTy << Prev->getIntegerType(); 14798 Diag(Prev->getLocation(), diag::note_previous_declaration) 14799 << Prev->getIntegerTypeRange(); 14800 return true; 14801 } 14802 } else if (IsFixed != Prev->isFixed()) { 14803 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 14804 << Prev->isFixed(); 14805 Diag(Prev->getLocation(), diag::note_previous_declaration); 14806 return true; 14807 } 14808 14809 return false; 14810 } 14811 14812 /// Get diagnostic %select index for tag kind for 14813 /// redeclaration diagnostic message. 14814 /// WARNING: Indexes apply to particular diagnostics only! 14815 /// 14816 /// \returns diagnostic %select index. 14817 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 14818 switch (Tag) { 14819 case TTK_Struct: return 0; 14820 case TTK_Interface: return 1; 14821 case TTK_Class: return 2; 14822 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 14823 } 14824 } 14825 14826 /// Determine if tag kind is a class-key compatible with 14827 /// class for redeclaration (class, struct, or __interface). 14828 /// 14829 /// \returns true iff the tag kind is compatible. 14830 static bool isClassCompatTagKind(TagTypeKind Tag) 14831 { 14832 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 14833 } 14834 14835 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 14836 TagTypeKind TTK) { 14837 if (isa<TypedefDecl>(PrevDecl)) 14838 return NTK_Typedef; 14839 else if (isa<TypeAliasDecl>(PrevDecl)) 14840 return NTK_TypeAlias; 14841 else if (isa<ClassTemplateDecl>(PrevDecl)) 14842 return NTK_Template; 14843 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 14844 return NTK_TypeAliasTemplate; 14845 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 14846 return NTK_TemplateTemplateArgument; 14847 switch (TTK) { 14848 case TTK_Struct: 14849 case TTK_Interface: 14850 case TTK_Class: 14851 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 14852 case TTK_Union: 14853 return NTK_NonUnion; 14854 case TTK_Enum: 14855 return NTK_NonEnum; 14856 } 14857 llvm_unreachable("invalid TTK"); 14858 } 14859 14860 /// Determine whether a tag with a given kind is acceptable 14861 /// as a redeclaration of the given tag declaration. 14862 /// 14863 /// \returns true if the new tag kind is acceptable, false otherwise. 14864 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 14865 TagTypeKind NewTag, bool isDefinition, 14866 SourceLocation NewTagLoc, 14867 const IdentifierInfo *Name) { 14868 // C++ [dcl.type.elab]p3: 14869 // The class-key or enum keyword present in the 14870 // elaborated-type-specifier shall agree in kind with the 14871 // declaration to which the name in the elaborated-type-specifier 14872 // refers. This rule also applies to the form of 14873 // elaborated-type-specifier that declares a class-name or 14874 // friend class since it can be construed as referring to the 14875 // definition of the class. Thus, in any 14876 // elaborated-type-specifier, the enum keyword shall be used to 14877 // refer to an enumeration (7.2), the union class-key shall be 14878 // used to refer to a union (clause 9), and either the class or 14879 // struct class-key shall be used to refer to a class (clause 9) 14880 // declared using the class or struct class-key. 14881 TagTypeKind OldTag = Previous->getTagKind(); 14882 if (OldTag != NewTag && 14883 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 14884 return false; 14885 14886 // Tags are compatible, but we might still want to warn on mismatched tags. 14887 // Non-class tags can't be mismatched at this point. 14888 if (!isClassCompatTagKind(NewTag)) 14889 return true; 14890 14891 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 14892 // by our warning analysis. We don't want to warn about mismatches with (eg) 14893 // declarations in system headers that are designed to be specialized, but if 14894 // a user asks us to warn, we should warn if their code contains mismatched 14895 // declarations. 14896 auto IsIgnoredLoc = [&](SourceLocation Loc) { 14897 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 14898 Loc); 14899 }; 14900 if (IsIgnoredLoc(NewTagLoc)) 14901 return true; 14902 14903 auto IsIgnored = [&](const TagDecl *Tag) { 14904 return IsIgnoredLoc(Tag->getLocation()); 14905 }; 14906 while (IsIgnored(Previous)) { 14907 Previous = Previous->getPreviousDecl(); 14908 if (!Previous) 14909 return true; 14910 OldTag = Previous->getTagKind(); 14911 } 14912 14913 bool isTemplate = false; 14914 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 14915 isTemplate = Record->getDescribedClassTemplate(); 14916 14917 if (inTemplateInstantiation()) { 14918 if (OldTag != NewTag) { 14919 // In a template instantiation, do not offer fix-its for tag mismatches 14920 // since they usually mess up the template instead of fixing the problem. 14921 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 14922 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14923 << getRedeclDiagFromTagKind(OldTag); 14924 // FIXME: Note previous location? 14925 } 14926 return true; 14927 } 14928 14929 if (isDefinition) { 14930 // On definitions, check all previous tags and issue a fix-it for each 14931 // one that doesn't match the current tag. 14932 if (Previous->getDefinition()) { 14933 // Don't suggest fix-its for redefinitions. 14934 return true; 14935 } 14936 14937 bool previousMismatch = false; 14938 for (const TagDecl *I : Previous->redecls()) { 14939 if (I->getTagKind() != NewTag) { 14940 // Ignore previous declarations for which the warning was disabled. 14941 if (IsIgnored(I)) 14942 continue; 14943 14944 if (!previousMismatch) { 14945 previousMismatch = true; 14946 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 14947 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14948 << getRedeclDiagFromTagKind(I->getTagKind()); 14949 } 14950 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 14951 << getRedeclDiagFromTagKind(NewTag) 14952 << FixItHint::CreateReplacement(I->getInnerLocStart(), 14953 TypeWithKeyword::getTagTypeKindName(NewTag)); 14954 } 14955 } 14956 return true; 14957 } 14958 14959 // Identify the prevailing tag kind: this is the kind of the definition (if 14960 // there is a non-ignored definition), or otherwise the kind of the prior 14961 // (non-ignored) declaration. 14962 const TagDecl *PrevDef = Previous->getDefinition(); 14963 if (PrevDef && IsIgnored(PrevDef)) 14964 PrevDef = nullptr; 14965 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 14966 if (Redecl->getTagKind() != NewTag) { 14967 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 14968 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14969 << getRedeclDiagFromTagKind(OldTag); 14970 Diag(Redecl->getLocation(), diag::note_previous_use); 14971 14972 // If there is a previous definition, suggest a fix-it. 14973 if (PrevDef) { 14974 Diag(NewTagLoc, diag::note_struct_class_suggestion) 14975 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 14976 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 14977 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 14978 } 14979 } 14980 14981 return true; 14982 } 14983 14984 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 14985 /// from an outer enclosing namespace or file scope inside a friend declaration. 14986 /// This should provide the commented out code in the following snippet: 14987 /// namespace N { 14988 /// struct X; 14989 /// namespace M { 14990 /// struct Y { friend struct /*N::*/ X; }; 14991 /// } 14992 /// } 14993 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 14994 SourceLocation NameLoc) { 14995 // While the decl is in a namespace, do repeated lookup of that name and see 14996 // if we get the same namespace back. If we do not, continue until 14997 // translation unit scope, at which point we have a fully qualified NNS. 14998 SmallVector<IdentifierInfo *, 4> Namespaces; 14999 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15000 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15001 // This tag should be declared in a namespace, which can only be enclosed by 15002 // other namespaces. Bail if there's an anonymous namespace in the chain. 15003 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15004 if (!Namespace || Namespace->isAnonymousNamespace()) 15005 return FixItHint(); 15006 IdentifierInfo *II = Namespace->getIdentifier(); 15007 Namespaces.push_back(II); 15008 NamedDecl *Lookup = SemaRef.LookupSingleName( 15009 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15010 if (Lookup == Namespace) 15011 break; 15012 } 15013 15014 // Once we have all the namespaces, reverse them to go outermost first, and 15015 // build an NNS. 15016 SmallString<64> Insertion; 15017 llvm::raw_svector_ostream OS(Insertion); 15018 if (DC->isTranslationUnit()) 15019 OS << "::"; 15020 std::reverse(Namespaces.begin(), Namespaces.end()); 15021 for (auto *II : Namespaces) 15022 OS << II->getName() << "::"; 15023 return FixItHint::CreateInsertion(NameLoc, Insertion); 15024 } 15025 15026 /// Determine whether a tag originally declared in context \p OldDC can 15027 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15028 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15029 /// using-declaration). 15030 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15031 DeclContext *NewDC) { 15032 OldDC = OldDC->getRedeclContext(); 15033 NewDC = NewDC->getRedeclContext(); 15034 15035 if (OldDC->Equals(NewDC)) 15036 return true; 15037 15038 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15039 // encloses the other). 15040 if (S.getLangOpts().MSVCCompat && 15041 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15042 return true; 15043 15044 return false; 15045 } 15046 15047 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15048 /// former case, Name will be non-null. In the later case, Name will be null. 15049 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15050 /// reference/declaration/definition of a tag. 15051 /// 15052 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15053 /// trailing-type-specifier) other than one in an alias-declaration. 15054 /// 15055 /// \param SkipBody If non-null, will be set to indicate if the caller should 15056 /// skip the definition of this tag and treat it as if it were a declaration. 15057 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15058 SourceLocation KWLoc, CXXScopeSpec &SS, 15059 IdentifierInfo *Name, SourceLocation NameLoc, 15060 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15061 SourceLocation ModulePrivateLoc, 15062 MultiTemplateParamsArg TemplateParameterLists, 15063 bool &OwnedDecl, bool &IsDependent, 15064 SourceLocation ScopedEnumKWLoc, 15065 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15066 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15067 SkipBodyInfo *SkipBody) { 15068 // If this is not a definition, it must have a name. 15069 IdentifierInfo *OrigName = Name; 15070 assert((Name != nullptr || TUK == TUK_Definition) && 15071 "Nameless record must be a definition!"); 15072 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15073 15074 OwnedDecl = false; 15075 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15076 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15077 15078 // FIXME: Check member specializations more carefully. 15079 bool isMemberSpecialization = false; 15080 bool Invalid = false; 15081 15082 // We only need to do this matching if we have template parameters 15083 // or a scope specifier, which also conveniently avoids this work 15084 // for non-C++ cases. 15085 if (TemplateParameterLists.size() > 0 || 15086 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15087 if (TemplateParameterList *TemplateParams = 15088 MatchTemplateParametersToScopeSpecifier( 15089 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15090 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15091 if (Kind == TTK_Enum) { 15092 Diag(KWLoc, diag::err_enum_template); 15093 return nullptr; 15094 } 15095 15096 if (TemplateParams->size() > 0) { 15097 // This is a declaration or definition of a class template (which may 15098 // be a member of another template). 15099 15100 if (Invalid) 15101 return nullptr; 15102 15103 OwnedDecl = false; 15104 DeclResult Result = CheckClassTemplate( 15105 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15106 AS, ModulePrivateLoc, 15107 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15108 TemplateParameterLists.data(), SkipBody); 15109 return Result.get(); 15110 } else { 15111 // The "template<>" header is extraneous. 15112 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15113 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15114 isMemberSpecialization = true; 15115 } 15116 } 15117 } 15118 15119 // Figure out the underlying type if this a enum declaration. We need to do 15120 // this early, because it's needed to detect if this is an incompatible 15121 // redeclaration. 15122 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15123 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15124 15125 if (Kind == TTK_Enum) { 15126 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15127 // No underlying type explicitly specified, or we failed to parse the 15128 // type, default to int. 15129 EnumUnderlying = Context.IntTy.getTypePtr(); 15130 } else if (UnderlyingType.get()) { 15131 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15132 // integral type; any cv-qualification is ignored. 15133 TypeSourceInfo *TI = nullptr; 15134 GetTypeFromParser(UnderlyingType.get(), &TI); 15135 EnumUnderlying = TI; 15136 15137 if (CheckEnumUnderlyingType(TI)) 15138 // Recover by falling back to int. 15139 EnumUnderlying = Context.IntTy.getTypePtr(); 15140 15141 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15142 UPPC_FixedUnderlyingType)) 15143 EnumUnderlying = Context.IntTy.getTypePtr(); 15144 15145 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15146 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15147 // of 'int'. However, if this is an unfixed forward declaration, don't set 15148 // the underlying type unless the user enables -fms-compatibility. This 15149 // makes unfixed forward declared enums incomplete and is more conforming. 15150 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15151 EnumUnderlying = Context.IntTy.getTypePtr(); 15152 } 15153 } 15154 15155 DeclContext *SearchDC = CurContext; 15156 DeclContext *DC = CurContext; 15157 bool isStdBadAlloc = false; 15158 bool isStdAlignValT = false; 15159 15160 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15161 if (TUK == TUK_Friend || TUK == TUK_Reference) 15162 Redecl = NotForRedeclaration; 15163 15164 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15165 /// implemented asks for structural equivalence checking, the returned decl 15166 /// here is passed back to the parser, allowing the tag body to be parsed. 15167 auto createTagFromNewDecl = [&]() -> TagDecl * { 15168 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15169 // If there is an identifier, use the location of the identifier as the 15170 // location of the decl, otherwise use the location of the struct/union 15171 // keyword. 15172 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15173 TagDecl *New = nullptr; 15174 15175 if (Kind == TTK_Enum) { 15176 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15177 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15178 // If this is an undefined enum, bail. 15179 if (TUK != TUK_Definition && !Invalid) 15180 return nullptr; 15181 if (EnumUnderlying) { 15182 EnumDecl *ED = cast<EnumDecl>(New); 15183 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15184 ED->setIntegerTypeSourceInfo(TI); 15185 else 15186 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15187 ED->setPromotionType(ED->getIntegerType()); 15188 } 15189 } else { // struct/union 15190 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15191 nullptr); 15192 } 15193 15194 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15195 // Add alignment attributes if necessary; these attributes are checked 15196 // when the ASTContext lays out the structure. 15197 // 15198 // It is important for implementing the correct semantics that this 15199 // happen here (in ActOnTag). The #pragma pack stack is 15200 // maintained as a result of parser callbacks which can occur at 15201 // many points during the parsing of a struct declaration (because 15202 // the #pragma tokens are effectively skipped over during the 15203 // parsing of the struct). 15204 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15205 AddAlignmentAttributesForRecord(RD); 15206 AddMsStructLayoutForRecord(RD); 15207 } 15208 } 15209 New->setLexicalDeclContext(CurContext); 15210 return New; 15211 }; 15212 15213 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15214 if (Name && SS.isNotEmpty()) { 15215 // We have a nested-name tag ('struct foo::bar'). 15216 15217 // Check for invalid 'foo::'. 15218 if (SS.isInvalid()) { 15219 Name = nullptr; 15220 goto CreateNewDecl; 15221 } 15222 15223 // If this is a friend or a reference to a class in a dependent 15224 // context, don't try to make a decl for it. 15225 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15226 DC = computeDeclContext(SS, false); 15227 if (!DC) { 15228 IsDependent = true; 15229 return nullptr; 15230 } 15231 } else { 15232 DC = computeDeclContext(SS, true); 15233 if (!DC) { 15234 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15235 << SS.getRange(); 15236 return nullptr; 15237 } 15238 } 15239 15240 if (RequireCompleteDeclContext(SS, DC)) 15241 return nullptr; 15242 15243 SearchDC = DC; 15244 // Look-up name inside 'foo::'. 15245 LookupQualifiedName(Previous, DC); 15246 15247 if (Previous.isAmbiguous()) 15248 return nullptr; 15249 15250 if (Previous.empty()) { 15251 // Name lookup did not find anything. However, if the 15252 // nested-name-specifier refers to the current instantiation, 15253 // and that current instantiation has any dependent base 15254 // classes, we might find something at instantiation time: treat 15255 // this as a dependent elaborated-type-specifier. 15256 // But this only makes any sense for reference-like lookups. 15257 if (Previous.wasNotFoundInCurrentInstantiation() && 15258 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15259 IsDependent = true; 15260 return nullptr; 15261 } 15262 15263 // A tag 'foo::bar' must already exist. 15264 Diag(NameLoc, diag::err_not_tag_in_scope) 15265 << Kind << Name << DC << SS.getRange(); 15266 Name = nullptr; 15267 Invalid = true; 15268 goto CreateNewDecl; 15269 } 15270 } else if (Name) { 15271 // C++14 [class.mem]p14: 15272 // If T is the name of a class, then each of the following shall have a 15273 // name different from T: 15274 // -- every member of class T that is itself a type 15275 if (TUK != TUK_Reference && TUK != TUK_Friend && 15276 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15277 return nullptr; 15278 15279 // If this is a named struct, check to see if there was a previous forward 15280 // declaration or definition. 15281 // FIXME: We're looking into outer scopes here, even when we 15282 // shouldn't be. Doing so can result in ambiguities that we 15283 // shouldn't be diagnosing. 15284 LookupName(Previous, S); 15285 15286 // When declaring or defining a tag, ignore ambiguities introduced 15287 // by types using'ed into this scope. 15288 if (Previous.isAmbiguous() && 15289 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15290 LookupResult::Filter F = Previous.makeFilter(); 15291 while (F.hasNext()) { 15292 NamedDecl *ND = F.next(); 15293 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15294 SearchDC->getRedeclContext())) 15295 F.erase(); 15296 } 15297 F.done(); 15298 } 15299 15300 // C++11 [namespace.memdef]p3: 15301 // If the name in a friend declaration is neither qualified nor 15302 // a template-id and the declaration is a function or an 15303 // elaborated-type-specifier, the lookup to determine whether 15304 // the entity has been previously declared shall not consider 15305 // any scopes outside the innermost enclosing namespace. 15306 // 15307 // MSVC doesn't implement the above rule for types, so a friend tag 15308 // declaration may be a redeclaration of a type declared in an enclosing 15309 // scope. They do implement this rule for friend functions. 15310 // 15311 // Does it matter that this should be by scope instead of by 15312 // semantic context? 15313 if (!Previous.empty() && TUK == TUK_Friend) { 15314 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15315 LookupResult::Filter F = Previous.makeFilter(); 15316 bool FriendSawTagOutsideEnclosingNamespace = false; 15317 while (F.hasNext()) { 15318 NamedDecl *ND = F.next(); 15319 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15320 if (DC->isFileContext() && 15321 !EnclosingNS->Encloses(ND->getDeclContext())) { 15322 if (getLangOpts().MSVCCompat) 15323 FriendSawTagOutsideEnclosingNamespace = true; 15324 else 15325 F.erase(); 15326 } 15327 } 15328 F.done(); 15329 15330 // Diagnose this MSVC extension in the easy case where lookup would have 15331 // unambiguously found something outside the enclosing namespace. 15332 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15333 NamedDecl *ND = Previous.getFoundDecl(); 15334 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15335 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15336 } 15337 } 15338 15339 // Note: there used to be some attempt at recovery here. 15340 if (Previous.isAmbiguous()) 15341 return nullptr; 15342 15343 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15344 // FIXME: This makes sure that we ignore the contexts associated 15345 // with C structs, unions, and enums when looking for a matching 15346 // tag declaration or definition. See the similar lookup tweak 15347 // in Sema::LookupName; is there a better way to deal with this? 15348 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15349 SearchDC = SearchDC->getParent(); 15350 } 15351 } 15352 15353 if (Previous.isSingleResult() && 15354 Previous.getFoundDecl()->isTemplateParameter()) { 15355 // Maybe we will complain about the shadowed template parameter. 15356 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15357 // Just pretend that we didn't see the previous declaration. 15358 Previous.clear(); 15359 } 15360 15361 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15362 DC->Equals(getStdNamespace())) { 15363 if (Name->isStr("bad_alloc")) { 15364 // This is a declaration of or a reference to "std::bad_alloc". 15365 isStdBadAlloc = true; 15366 15367 // If std::bad_alloc has been implicitly declared (but made invisible to 15368 // name lookup), fill in this implicit declaration as the previous 15369 // declaration, so that the declarations get chained appropriately. 15370 if (Previous.empty() && StdBadAlloc) 15371 Previous.addDecl(getStdBadAlloc()); 15372 } else if (Name->isStr("align_val_t")) { 15373 isStdAlignValT = true; 15374 if (Previous.empty() && StdAlignValT) 15375 Previous.addDecl(getStdAlignValT()); 15376 } 15377 } 15378 15379 // If we didn't find a previous declaration, and this is a reference 15380 // (or friend reference), move to the correct scope. In C++, we 15381 // also need to do a redeclaration lookup there, just in case 15382 // there's a shadow friend decl. 15383 if (Name && Previous.empty() && 15384 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15385 if (Invalid) goto CreateNewDecl; 15386 assert(SS.isEmpty()); 15387 15388 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15389 // C++ [basic.scope.pdecl]p5: 15390 // -- for an elaborated-type-specifier of the form 15391 // 15392 // class-key identifier 15393 // 15394 // if the elaborated-type-specifier is used in the 15395 // decl-specifier-seq or parameter-declaration-clause of a 15396 // function defined in namespace scope, the identifier is 15397 // declared as a class-name in the namespace that contains 15398 // the declaration; otherwise, except as a friend 15399 // declaration, the identifier is declared in the smallest 15400 // non-class, non-function-prototype scope that contains the 15401 // declaration. 15402 // 15403 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15404 // C structs and unions. 15405 // 15406 // It is an error in C++ to declare (rather than define) an enum 15407 // type, including via an elaborated type specifier. We'll 15408 // diagnose that later; for now, declare the enum in the same 15409 // scope as we would have picked for any other tag type. 15410 // 15411 // GNU C also supports this behavior as part of its incomplete 15412 // enum types extension, while GNU C++ does not. 15413 // 15414 // Find the context where we'll be declaring the tag. 15415 // FIXME: We would like to maintain the current DeclContext as the 15416 // lexical context, 15417 SearchDC = getTagInjectionContext(SearchDC); 15418 15419 // Find the scope where we'll be declaring the tag. 15420 S = getTagInjectionScope(S, getLangOpts()); 15421 } else { 15422 assert(TUK == TUK_Friend); 15423 // C++ [namespace.memdef]p3: 15424 // If a friend declaration in a non-local class first declares a 15425 // class or function, the friend class or function is a member of 15426 // the innermost enclosing namespace. 15427 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15428 } 15429 15430 // In C++, we need to do a redeclaration lookup to properly 15431 // diagnose some problems. 15432 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15433 // hidden declaration so that we don't get ambiguity errors when using a 15434 // type declared by an elaborated-type-specifier. In C that is not correct 15435 // and we should instead merge compatible types found by lookup. 15436 if (getLangOpts().CPlusPlus) { 15437 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15438 LookupQualifiedName(Previous, SearchDC); 15439 } else { 15440 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15441 LookupName(Previous, S); 15442 } 15443 } 15444 15445 // If we have a known previous declaration to use, then use it. 15446 if (Previous.empty() && SkipBody && SkipBody->Previous) 15447 Previous.addDecl(SkipBody->Previous); 15448 15449 if (!Previous.empty()) { 15450 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15451 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15452 15453 // It's okay to have a tag decl in the same scope as a typedef 15454 // which hides a tag decl in the same scope. Finding this 15455 // insanity with a redeclaration lookup can only actually happen 15456 // in C++. 15457 // 15458 // This is also okay for elaborated-type-specifiers, which is 15459 // technically forbidden by the current standard but which is 15460 // okay according to the likely resolution of an open issue; 15461 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15462 if (getLangOpts().CPlusPlus) { 15463 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15464 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15465 TagDecl *Tag = TT->getDecl(); 15466 if (Tag->getDeclName() == Name && 15467 Tag->getDeclContext()->getRedeclContext() 15468 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15469 PrevDecl = Tag; 15470 Previous.clear(); 15471 Previous.addDecl(Tag); 15472 Previous.resolveKind(); 15473 } 15474 } 15475 } 15476 } 15477 15478 // If this is a redeclaration of a using shadow declaration, it must 15479 // declare a tag in the same context. In MSVC mode, we allow a 15480 // redefinition if either context is within the other. 15481 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15482 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15483 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15484 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15485 !(OldTag && isAcceptableTagRedeclContext( 15486 *this, OldTag->getDeclContext(), SearchDC))) { 15487 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15488 Diag(Shadow->getTargetDecl()->getLocation(), 15489 diag::note_using_decl_target); 15490 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15491 << 0; 15492 // Recover by ignoring the old declaration. 15493 Previous.clear(); 15494 goto CreateNewDecl; 15495 } 15496 } 15497 15498 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15499 // If this is a use of a previous tag, or if the tag is already declared 15500 // in the same scope (so that the definition/declaration completes or 15501 // rementions the tag), reuse the decl. 15502 if (TUK == TUK_Reference || TUK == TUK_Friend || 15503 isDeclInScope(DirectPrevDecl, SearchDC, S, 15504 SS.isNotEmpty() || isMemberSpecialization)) { 15505 // Make sure that this wasn't declared as an enum and now used as a 15506 // struct or something similar. 15507 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15508 TUK == TUK_Definition, KWLoc, 15509 Name)) { 15510 bool SafeToContinue 15511 = (PrevTagDecl->getTagKind() != TTK_Enum && 15512 Kind != TTK_Enum); 15513 if (SafeToContinue) 15514 Diag(KWLoc, diag::err_use_with_wrong_tag) 15515 << Name 15516 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15517 PrevTagDecl->getKindName()); 15518 else 15519 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15520 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15521 15522 if (SafeToContinue) 15523 Kind = PrevTagDecl->getTagKind(); 15524 else { 15525 // Recover by making this an anonymous redefinition. 15526 Name = nullptr; 15527 Previous.clear(); 15528 Invalid = true; 15529 } 15530 } 15531 15532 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15533 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15534 15535 // If this is an elaborated-type-specifier for a scoped enumeration, 15536 // the 'class' keyword is not necessary and not permitted. 15537 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15538 if (ScopedEnum) 15539 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 15540 << PrevEnum->isScoped() 15541 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 15542 return PrevTagDecl; 15543 } 15544 15545 QualType EnumUnderlyingTy; 15546 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15547 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15548 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15549 EnumUnderlyingTy = QualType(T, 0); 15550 15551 // All conflicts with previous declarations are recovered by 15552 // returning the previous declaration, unless this is a definition, 15553 // in which case we want the caller to bail out. 15554 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15555 ScopedEnum, EnumUnderlyingTy, 15556 IsFixed, PrevEnum)) 15557 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15558 } 15559 15560 // C++11 [class.mem]p1: 15561 // A member shall not be declared twice in the member-specification, 15562 // except that a nested class or member class template can be declared 15563 // and then later defined. 15564 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15565 S->isDeclScope(PrevDecl)) { 15566 Diag(NameLoc, diag::ext_member_redeclared); 15567 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15568 } 15569 15570 if (!Invalid) { 15571 // If this is a use, just return the declaration we found, unless 15572 // we have attributes. 15573 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15574 if (!Attrs.empty()) { 15575 // FIXME: Diagnose these attributes. For now, we create a new 15576 // declaration to hold them. 15577 } else if (TUK == TUK_Reference && 15578 (PrevTagDecl->getFriendObjectKind() == 15579 Decl::FOK_Undeclared || 15580 PrevDecl->getOwningModule() != getCurrentModule()) && 15581 SS.isEmpty()) { 15582 // This declaration is a reference to an existing entity, but 15583 // has different visibility from that entity: it either makes 15584 // a friend visible or it makes a type visible in a new module. 15585 // In either case, create a new declaration. We only do this if 15586 // the declaration would have meant the same thing if no prior 15587 // declaration were found, that is, if it was found in the same 15588 // scope where we would have injected a declaration. 15589 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15590 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15591 return PrevTagDecl; 15592 // This is in the injected scope, create a new declaration in 15593 // that scope. 15594 S = getTagInjectionScope(S, getLangOpts()); 15595 } else { 15596 return PrevTagDecl; 15597 } 15598 } 15599 15600 // Diagnose attempts to redefine a tag. 15601 if (TUK == TUK_Definition) { 15602 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15603 // If we're defining a specialization and the previous definition 15604 // is from an implicit instantiation, don't emit an error 15605 // here; we'll catch this in the general case below. 15606 bool IsExplicitSpecializationAfterInstantiation = false; 15607 if (isMemberSpecialization) { 15608 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15609 IsExplicitSpecializationAfterInstantiation = 15610 RD->getTemplateSpecializationKind() != 15611 TSK_ExplicitSpecialization; 15612 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15613 IsExplicitSpecializationAfterInstantiation = 15614 ED->getTemplateSpecializationKind() != 15615 TSK_ExplicitSpecialization; 15616 } 15617 15618 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15619 // not keep more that one definition around (merge them). However, 15620 // ensure the decl passes the structural compatibility check in 15621 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15622 NamedDecl *Hidden = nullptr; 15623 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15624 // There is a definition of this tag, but it is not visible. We 15625 // explicitly make use of C++'s one definition rule here, and 15626 // assume that this definition is identical to the hidden one 15627 // we already have. Make the existing definition visible and 15628 // use it in place of this one. 15629 if (!getLangOpts().CPlusPlus) { 15630 // Postpone making the old definition visible until after we 15631 // complete parsing the new one and do the structural 15632 // comparison. 15633 SkipBody->CheckSameAsPrevious = true; 15634 SkipBody->New = createTagFromNewDecl(); 15635 SkipBody->Previous = Def; 15636 return Def; 15637 } else { 15638 SkipBody->ShouldSkip = true; 15639 SkipBody->Previous = Def; 15640 makeMergedDefinitionVisible(Hidden); 15641 // Carry on and handle it like a normal definition. We'll 15642 // skip starting the definitiion later. 15643 } 15644 } else if (!IsExplicitSpecializationAfterInstantiation) { 15645 // A redeclaration in function prototype scope in C isn't 15646 // visible elsewhere, so merely issue a warning. 15647 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 15648 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 15649 else 15650 Diag(NameLoc, diag::err_redefinition) << Name; 15651 notePreviousDefinition(Def, 15652 NameLoc.isValid() ? NameLoc : KWLoc); 15653 // If this is a redefinition, recover by making this 15654 // struct be anonymous, which will make any later 15655 // references get the previous definition. 15656 Name = nullptr; 15657 Previous.clear(); 15658 Invalid = true; 15659 } 15660 } else { 15661 // If the type is currently being defined, complain 15662 // about a nested redefinition. 15663 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 15664 if (TD->isBeingDefined()) { 15665 Diag(NameLoc, diag::err_nested_redefinition) << Name; 15666 Diag(PrevTagDecl->getLocation(), 15667 diag::note_previous_definition); 15668 Name = nullptr; 15669 Previous.clear(); 15670 Invalid = true; 15671 } 15672 } 15673 15674 // Okay, this is definition of a previously declared or referenced 15675 // tag. We're going to create a new Decl for it. 15676 } 15677 15678 // Okay, we're going to make a redeclaration. If this is some kind 15679 // of reference, make sure we build the redeclaration in the same DC 15680 // as the original, and ignore the current access specifier. 15681 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15682 SearchDC = PrevTagDecl->getDeclContext(); 15683 AS = AS_none; 15684 } 15685 } 15686 // If we get here we have (another) forward declaration or we 15687 // have a definition. Just create a new decl. 15688 15689 } else { 15690 // If we get here, this is a definition of a new tag type in a nested 15691 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 15692 // new decl/type. We set PrevDecl to NULL so that the entities 15693 // have distinct types. 15694 Previous.clear(); 15695 } 15696 // If we get here, we're going to create a new Decl. If PrevDecl 15697 // is non-NULL, it's a definition of the tag declared by 15698 // PrevDecl. If it's NULL, we have a new definition. 15699 15700 // Otherwise, PrevDecl is not a tag, but was found with tag 15701 // lookup. This is only actually possible in C++, where a few 15702 // things like templates still live in the tag namespace. 15703 } else { 15704 // Use a better diagnostic if an elaborated-type-specifier 15705 // found the wrong kind of type on the first 15706 // (non-redeclaration) lookup. 15707 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 15708 !Previous.isForRedeclaration()) { 15709 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15710 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 15711 << Kind; 15712 Diag(PrevDecl->getLocation(), diag::note_declared_at); 15713 Invalid = true; 15714 15715 // Otherwise, only diagnose if the declaration is in scope. 15716 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 15717 SS.isNotEmpty() || isMemberSpecialization)) { 15718 // do nothing 15719 15720 // Diagnose implicit declarations introduced by elaborated types. 15721 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 15722 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15723 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 15724 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15725 Invalid = true; 15726 15727 // Otherwise it's a declaration. Call out a particularly common 15728 // case here. 15729 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15730 unsigned Kind = 0; 15731 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 15732 Diag(NameLoc, diag::err_tag_definition_of_typedef) 15733 << Name << Kind << TND->getUnderlyingType(); 15734 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15735 Invalid = true; 15736 15737 // Otherwise, diagnose. 15738 } else { 15739 // The tag name clashes with something else in the target scope, 15740 // issue an error and recover by making this tag be anonymous. 15741 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 15742 notePreviousDefinition(PrevDecl, NameLoc); 15743 Name = nullptr; 15744 Invalid = true; 15745 } 15746 15747 // The existing declaration isn't relevant to us; we're in a 15748 // new scope, so clear out the previous declaration. 15749 Previous.clear(); 15750 } 15751 } 15752 15753 CreateNewDecl: 15754 15755 TagDecl *PrevDecl = nullptr; 15756 if (Previous.isSingleResult()) 15757 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 15758 15759 // If there is an identifier, use the location of the identifier as the 15760 // location of the decl, otherwise use the location of the struct/union 15761 // keyword. 15762 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15763 15764 // Otherwise, create a new declaration. If there is a previous 15765 // declaration of the same entity, the two will be linked via 15766 // PrevDecl. 15767 TagDecl *New; 15768 15769 if (Kind == TTK_Enum) { 15770 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15771 // enum X { A, B, C } D; D should chain to X. 15772 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 15773 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 15774 ScopedEnumUsesClassTag, IsFixed); 15775 15776 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 15777 StdAlignValT = cast<EnumDecl>(New); 15778 15779 // If this is an undefined enum, warn. 15780 if (TUK != TUK_Definition && !Invalid) { 15781 TagDecl *Def; 15782 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 15783 // C++0x: 7.2p2: opaque-enum-declaration. 15784 // Conflicts are diagnosed above. Do nothing. 15785 } 15786 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 15787 Diag(Loc, diag::ext_forward_ref_enum_def) 15788 << New; 15789 Diag(Def->getLocation(), diag::note_previous_definition); 15790 } else { 15791 unsigned DiagID = diag::ext_forward_ref_enum; 15792 if (getLangOpts().MSVCCompat) 15793 DiagID = diag::ext_ms_forward_ref_enum; 15794 else if (getLangOpts().CPlusPlus) 15795 DiagID = diag::err_forward_ref_enum; 15796 Diag(Loc, DiagID); 15797 } 15798 } 15799 15800 if (EnumUnderlying) { 15801 EnumDecl *ED = cast<EnumDecl>(New); 15802 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15803 ED->setIntegerTypeSourceInfo(TI); 15804 else 15805 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 15806 ED->setPromotionType(ED->getIntegerType()); 15807 assert(ED->isComplete() && "enum with type should be complete"); 15808 } 15809 } else { 15810 // struct/union/class 15811 15812 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15813 // struct X { int A; } D; D should chain to X. 15814 if (getLangOpts().CPlusPlus) { 15815 // FIXME: Look for a way to use RecordDecl for simple structs. 15816 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15817 cast_or_null<CXXRecordDecl>(PrevDecl)); 15818 15819 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 15820 StdBadAlloc = cast<CXXRecordDecl>(New); 15821 } else 15822 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15823 cast_or_null<RecordDecl>(PrevDecl)); 15824 } 15825 15826 // C++11 [dcl.type]p3: 15827 // A type-specifier-seq shall not define a class or enumeration [...]. 15828 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 15829 TUK == TUK_Definition) { 15830 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 15831 << Context.getTagDeclType(New); 15832 Invalid = true; 15833 } 15834 15835 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 15836 DC->getDeclKind() == Decl::Enum) { 15837 Diag(New->getLocation(), diag::err_type_defined_in_enum) 15838 << Context.getTagDeclType(New); 15839 Invalid = true; 15840 } 15841 15842 // Maybe add qualifier info. 15843 if (SS.isNotEmpty()) { 15844 if (SS.isSet()) { 15845 // If this is either a declaration or a definition, check the 15846 // nested-name-specifier against the current context. 15847 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 15848 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 15849 isMemberSpecialization)) 15850 Invalid = true; 15851 15852 New->setQualifierInfo(SS.getWithLocInContext(Context)); 15853 if (TemplateParameterLists.size() > 0) { 15854 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 15855 } 15856 } 15857 else 15858 Invalid = true; 15859 } 15860 15861 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15862 // Add alignment attributes if necessary; these attributes are checked when 15863 // the ASTContext lays out the structure. 15864 // 15865 // It is important for implementing the correct semantics that this 15866 // happen here (in ActOnTag). The #pragma pack stack is 15867 // maintained as a result of parser callbacks which can occur at 15868 // many points during the parsing of a struct declaration (because 15869 // the #pragma tokens are effectively skipped over during the 15870 // parsing of the struct). 15871 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15872 AddAlignmentAttributesForRecord(RD); 15873 AddMsStructLayoutForRecord(RD); 15874 } 15875 } 15876 15877 if (ModulePrivateLoc.isValid()) { 15878 if (isMemberSpecialization) 15879 Diag(New->getLocation(), diag::err_module_private_specialization) 15880 << 2 15881 << FixItHint::CreateRemoval(ModulePrivateLoc); 15882 // __module_private__ does not apply to local classes. However, we only 15883 // diagnose this as an error when the declaration specifiers are 15884 // freestanding. Here, we just ignore the __module_private__. 15885 else if (!SearchDC->isFunctionOrMethod()) 15886 New->setModulePrivate(); 15887 } 15888 15889 // If this is a specialization of a member class (of a class template), 15890 // check the specialization. 15891 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 15892 Invalid = true; 15893 15894 // If we're declaring or defining a tag in function prototype scope in C, 15895 // note that this type can only be used within the function and add it to 15896 // the list of decls to inject into the function definition scope. 15897 if ((Name || Kind == TTK_Enum) && 15898 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 15899 if (getLangOpts().CPlusPlus) { 15900 // C++ [dcl.fct]p6: 15901 // Types shall not be defined in return or parameter types. 15902 if (TUK == TUK_Definition && !IsTypeSpecifier) { 15903 Diag(Loc, diag::err_type_defined_in_param_type) 15904 << Name; 15905 Invalid = true; 15906 } 15907 } else if (!PrevDecl) { 15908 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 15909 } 15910 } 15911 15912 if (Invalid) 15913 New->setInvalidDecl(); 15914 15915 // Set the lexical context. If the tag has a C++ scope specifier, the 15916 // lexical context will be different from the semantic context. 15917 New->setLexicalDeclContext(CurContext); 15918 15919 // Mark this as a friend decl if applicable. 15920 // In Microsoft mode, a friend declaration also acts as a forward 15921 // declaration so we always pass true to setObjectOfFriendDecl to make 15922 // the tag name visible. 15923 if (TUK == TUK_Friend) 15924 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 15925 15926 // Set the access specifier. 15927 if (!Invalid && SearchDC->isRecord()) 15928 SetMemberAccessSpecifier(New, PrevDecl, AS); 15929 15930 if (PrevDecl) 15931 CheckRedeclarationModuleOwnership(New, PrevDecl); 15932 15933 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 15934 New->startDefinition(); 15935 15936 ProcessDeclAttributeList(S, New, Attrs); 15937 AddPragmaAttributes(S, New); 15938 15939 // If this has an identifier, add it to the scope stack. 15940 if (TUK == TUK_Friend) { 15941 // We might be replacing an existing declaration in the lookup tables; 15942 // if so, borrow its access specifier. 15943 if (PrevDecl) 15944 New->setAccess(PrevDecl->getAccess()); 15945 15946 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 15947 DC->makeDeclVisibleInContext(New); 15948 if (Name) // can be null along some error paths 15949 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 15950 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 15951 } else if (Name) { 15952 S = getNonFieldDeclScope(S); 15953 PushOnScopeChains(New, S, true); 15954 } else { 15955 CurContext->addDecl(New); 15956 } 15957 15958 // If this is the C FILE type, notify the AST context. 15959 if (IdentifierInfo *II = New->getIdentifier()) 15960 if (!New->isInvalidDecl() && 15961 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 15962 II->isStr("FILE")) 15963 Context.setFILEDecl(New); 15964 15965 if (PrevDecl) 15966 mergeDeclAttributes(New, PrevDecl); 15967 15968 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 15969 inferGslOwnerPointerAttribute(CXXRD); 15970 15971 // If there's a #pragma GCC visibility in scope, set the visibility of this 15972 // record. 15973 AddPushedVisibilityAttribute(New); 15974 15975 if (isMemberSpecialization && !New->isInvalidDecl()) 15976 CompleteMemberSpecialization(New, Previous); 15977 15978 OwnedDecl = true; 15979 // In C++, don't return an invalid declaration. We can't recover well from 15980 // the cases where we make the type anonymous. 15981 if (Invalid && getLangOpts().CPlusPlus) { 15982 if (New->isBeingDefined()) 15983 if (auto RD = dyn_cast<RecordDecl>(New)) 15984 RD->completeDefinition(); 15985 return nullptr; 15986 } else if (SkipBody && SkipBody->ShouldSkip) { 15987 return SkipBody->Previous; 15988 } else { 15989 return New; 15990 } 15991 } 15992 15993 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 15994 AdjustDeclIfTemplate(TagD); 15995 TagDecl *Tag = cast<TagDecl>(TagD); 15996 15997 // Enter the tag context. 15998 PushDeclContext(S, Tag); 15999 16000 ActOnDocumentableDecl(TagD); 16001 16002 // If there's a #pragma GCC visibility in scope, set the visibility of this 16003 // record. 16004 AddPushedVisibilityAttribute(Tag); 16005 } 16006 16007 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16008 SkipBodyInfo &SkipBody) { 16009 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16010 return false; 16011 16012 // Make the previous decl visible. 16013 makeMergedDefinitionVisible(SkipBody.Previous); 16014 return true; 16015 } 16016 16017 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16018 assert(isa<ObjCContainerDecl>(IDecl) && 16019 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16020 DeclContext *OCD = cast<DeclContext>(IDecl); 16021 assert(getContainingDC(OCD) == CurContext && 16022 "The next DeclContext should be lexically contained in the current one."); 16023 CurContext = OCD; 16024 return IDecl; 16025 } 16026 16027 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16028 SourceLocation FinalLoc, 16029 bool IsFinalSpelledSealed, 16030 SourceLocation LBraceLoc) { 16031 AdjustDeclIfTemplate(TagD); 16032 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16033 16034 FieldCollector->StartClass(); 16035 16036 if (!Record->getIdentifier()) 16037 return; 16038 16039 if (FinalLoc.isValid()) 16040 Record->addAttr(FinalAttr::Create( 16041 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16042 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16043 16044 // C++ [class]p2: 16045 // [...] The class-name is also inserted into the scope of the 16046 // class itself; this is known as the injected-class-name. For 16047 // purposes of access checking, the injected-class-name is treated 16048 // as if it were a public member name. 16049 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16050 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16051 Record->getLocation(), Record->getIdentifier(), 16052 /*PrevDecl=*/nullptr, 16053 /*DelayTypeCreation=*/true); 16054 Context.getTypeDeclType(InjectedClassName, Record); 16055 InjectedClassName->setImplicit(); 16056 InjectedClassName->setAccess(AS_public); 16057 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16058 InjectedClassName->setDescribedClassTemplate(Template); 16059 PushOnScopeChains(InjectedClassName, S); 16060 assert(InjectedClassName->isInjectedClassName() && 16061 "Broken injected-class-name"); 16062 } 16063 16064 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16065 SourceRange BraceRange) { 16066 AdjustDeclIfTemplate(TagD); 16067 TagDecl *Tag = cast<TagDecl>(TagD); 16068 Tag->setBraceRange(BraceRange); 16069 16070 // Make sure we "complete" the definition even it is invalid. 16071 if (Tag->isBeingDefined()) { 16072 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16073 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16074 RD->completeDefinition(); 16075 } 16076 16077 if (isa<CXXRecordDecl>(Tag)) { 16078 FieldCollector->FinishClass(); 16079 } 16080 16081 // Exit this scope of this tag's definition. 16082 PopDeclContext(); 16083 16084 if (getCurLexicalContext()->isObjCContainer() && 16085 Tag->getDeclContext()->isFileContext()) 16086 Tag->setTopLevelDeclInObjCContainer(); 16087 16088 // Notify the consumer that we've defined a tag. 16089 if (!Tag->isInvalidDecl()) 16090 Consumer.HandleTagDeclDefinition(Tag); 16091 } 16092 16093 void Sema::ActOnObjCContainerFinishDefinition() { 16094 // Exit this scope of this interface definition. 16095 PopDeclContext(); 16096 } 16097 16098 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16099 assert(DC == CurContext && "Mismatch of container contexts"); 16100 OriginalLexicalContext = DC; 16101 ActOnObjCContainerFinishDefinition(); 16102 } 16103 16104 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16105 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16106 OriginalLexicalContext = nullptr; 16107 } 16108 16109 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16110 AdjustDeclIfTemplate(TagD); 16111 TagDecl *Tag = cast<TagDecl>(TagD); 16112 Tag->setInvalidDecl(); 16113 16114 // Make sure we "complete" the definition even it is invalid. 16115 if (Tag->isBeingDefined()) { 16116 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16117 RD->completeDefinition(); 16118 } 16119 16120 // We're undoing ActOnTagStartDefinition here, not 16121 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16122 // the FieldCollector. 16123 16124 PopDeclContext(); 16125 } 16126 16127 // Note that FieldName may be null for anonymous bitfields. 16128 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16129 IdentifierInfo *FieldName, 16130 QualType FieldTy, bool IsMsStruct, 16131 Expr *BitWidth, bool *ZeroWidth) { 16132 // Default to true; that shouldn't confuse checks for emptiness 16133 if (ZeroWidth) 16134 *ZeroWidth = true; 16135 16136 // C99 6.7.2.1p4 - verify the field type. 16137 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16138 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16139 // Handle incomplete types with specific error. 16140 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 16141 return ExprError(); 16142 if (FieldName) 16143 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16144 << FieldName << FieldTy << BitWidth->getSourceRange(); 16145 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16146 << FieldTy << BitWidth->getSourceRange(); 16147 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16148 UPPC_BitFieldWidth)) 16149 return ExprError(); 16150 16151 // If the bit-width is type- or value-dependent, don't try to check 16152 // it now. 16153 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16154 return BitWidth; 16155 16156 llvm::APSInt Value; 16157 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 16158 if (ICE.isInvalid()) 16159 return ICE; 16160 BitWidth = ICE.get(); 16161 16162 if (Value != 0 && ZeroWidth) 16163 *ZeroWidth = false; 16164 16165 // Zero-width bitfield is ok for anonymous field. 16166 if (Value == 0 && FieldName) 16167 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16168 16169 if (Value.isSigned() && Value.isNegative()) { 16170 if (FieldName) 16171 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16172 << FieldName << Value.toString(10); 16173 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16174 << Value.toString(10); 16175 } 16176 16177 if (!FieldTy->isDependentType()) { 16178 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16179 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16180 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16181 16182 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16183 // ABI. 16184 bool CStdConstraintViolation = 16185 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16186 bool MSBitfieldViolation = 16187 Value.ugt(TypeStorageSize) && 16188 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16189 if (CStdConstraintViolation || MSBitfieldViolation) { 16190 unsigned DiagWidth = 16191 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16192 if (FieldName) 16193 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16194 << FieldName << (unsigned)Value.getZExtValue() 16195 << !CStdConstraintViolation << DiagWidth; 16196 16197 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16198 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 16199 << DiagWidth; 16200 } 16201 16202 // Warn on types where the user might conceivably expect to get all 16203 // specified bits as value bits: that's all integral types other than 16204 // 'bool'. 16205 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 16206 if (FieldName) 16207 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16208 << FieldName << (unsigned)Value.getZExtValue() 16209 << (unsigned)TypeWidth; 16210 else 16211 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 16212 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 16213 } 16214 } 16215 16216 return BitWidth; 16217 } 16218 16219 /// ActOnField - Each field of a C struct/union is passed into this in order 16220 /// to create a FieldDecl object for it. 16221 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16222 Declarator &D, Expr *BitfieldWidth) { 16223 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16224 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16225 /*InitStyle=*/ICIS_NoInit, AS_public); 16226 return Res; 16227 } 16228 16229 /// HandleField - Analyze a field of a C struct or a C++ data member. 16230 /// 16231 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16232 SourceLocation DeclStart, 16233 Declarator &D, Expr *BitWidth, 16234 InClassInitStyle InitStyle, 16235 AccessSpecifier AS) { 16236 if (D.isDecompositionDeclarator()) { 16237 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16238 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16239 << Decomp.getSourceRange(); 16240 return nullptr; 16241 } 16242 16243 IdentifierInfo *II = D.getIdentifier(); 16244 SourceLocation Loc = DeclStart; 16245 if (II) Loc = D.getIdentifierLoc(); 16246 16247 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16248 QualType T = TInfo->getType(); 16249 if (getLangOpts().CPlusPlus) { 16250 CheckExtraCXXDefaultArguments(D); 16251 16252 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16253 UPPC_DataMemberType)) { 16254 D.setInvalidType(); 16255 T = Context.IntTy; 16256 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16257 } 16258 } 16259 16260 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16261 16262 if (D.getDeclSpec().isInlineSpecified()) 16263 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16264 << getLangOpts().CPlusPlus17; 16265 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16266 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16267 diag::err_invalid_thread) 16268 << DeclSpec::getSpecifierName(TSCS); 16269 16270 // Check to see if this name was declared as a member previously 16271 NamedDecl *PrevDecl = nullptr; 16272 LookupResult Previous(*this, II, Loc, LookupMemberName, 16273 ForVisibleRedeclaration); 16274 LookupName(Previous, S); 16275 switch (Previous.getResultKind()) { 16276 case LookupResult::Found: 16277 case LookupResult::FoundUnresolvedValue: 16278 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16279 break; 16280 16281 case LookupResult::FoundOverloaded: 16282 PrevDecl = Previous.getRepresentativeDecl(); 16283 break; 16284 16285 case LookupResult::NotFound: 16286 case LookupResult::NotFoundInCurrentInstantiation: 16287 case LookupResult::Ambiguous: 16288 break; 16289 } 16290 Previous.suppressDiagnostics(); 16291 16292 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16293 // Maybe we will complain about the shadowed template parameter. 16294 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16295 // Just pretend that we didn't see the previous declaration. 16296 PrevDecl = nullptr; 16297 } 16298 16299 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16300 PrevDecl = nullptr; 16301 16302 bool Mutable 16303 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16304 SourceLocation TSSL = D.getBeginLoc(); 16305 FieldDecl *NewFD 16306 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16307 TSSL, AS, PrevDecl, &D); 16308 16309 if (NewFD->isInvalidDecl()) 16310 Record->setInvalidDecl(); 16311 16312 if (D.getDeclSpec().isModulePrivateSpecified()) 16313 NewFD->setModulePrivate(); 16314 16315 if (NewFD->isInvalidDecl() && PrevDecl) { 16316 // Don't introduce NewFD into scope; there's already something 16317 // with the same name in the same scope. 16318 } else if (II) { 16319 PushOnScopeChains(NewFD, S); 16320 } else 16321 Record->addDecl(NewFD); 16322 16323 return NewFD; 16324 } 16325 16326 /// Build a new FieldDecl and check its well-formedness. 16327 /// 16328 /// This routine builds a new FieldDecl given the fields name, type, 16329 /// record, etc. \p PrevDecl should refer to any previous declaration 16330 /// with the same name and in the same scope as the field to be 16331 /// created. 16332 /// 16333 /// \returns a new FieldDecl. 16334 /// 16335 /// \todo The Declarator argument is a hack. It will be removed once 16336 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16337 TypeSourceInfo *TInfo, 16338 RecordDecl *Record, SourceLocation Loc, 16339 bool Mutable, Expr *BitWidth, 16340 InClassInitStyle InitStyle, 16341 SourceLocation TSSL, 16342 AccessSpecifier AS, NamedDecl *PrevDecl, 16343 Declarator *D) { 16344 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16345 bool InvalidDecl = false; 16346 if (D) InvalidDecl = D->isInvalidType(); 16347 16348 // If we receive a broken type, recover by assuming 'int' and 16349 // marking this declaration as invalid. 16350 if (T.isNull()) { 16351 InvalidDecl = true; 16352 T = Context.IntTy; 16353 } 16354 16355 QualType EltTy = Context.getBaseElementType(T); 16356 if (!EltTy->isDependentType()) { 16357 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 16358 // Fields of incomplete type force their record to be invalid. 16359 Record->setInvalidDecl(); 16360 InvalidDecl = true; 16361 } else { 16362 NamedDecl *Def; 16363 EltTy->isIncompleteType(&Def); 16364 if (Def && Def->isInvalidDecl()) { 16365 Record->setInvalidDecl(); 16366 InvalidDecl = true; 16367 } 16368 } 16369 } 16370 16371 // TR 18037 does not allow fields to be declared with address space 16372 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16373 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16374 Diag(Loc, diag::err_field_with_address_space); 16375 Record->setInvalidDecl(); 16376 InvalidDecl = true; 16377 } 16378 16379 if (LangOpts.OpenCL) { 16380 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16381 // used as structure or union field: image, sampler, event or block types. 16382 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16383 T->isBlockPointerType()) { 16384 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16385 Record->setInvalidDecl(); 16386 InvalidDecl = true; 16387 } 16388 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16389 if (BitWidth) { 16390 Diag(Loc, diag::err_opencl_bitfields); 16391 InvalidDecl = true; 16392 } 16393 } 16394 16395 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16396 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16397 T.hasQualifiers()) { 16398 InvalidDecl = true; 16399 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16400 } 16401 16402 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16403 // than a variably modified type. 16404 if (!InvalidDecl && T->isVariablyModifiedType()) { 16405 bool SizeIsNegative; 16406 llvm::APSInt Oversized; 16407 16408 TypeSourceInfo *FixedTInfo = 16409 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 16410 SizeIsNegative, 16411 Oversized); 16412 if (FixedTInfo) { 16413 Diag(Loc, diag::warn_illegal_constant_array_size); 16414 TInfo = FixedTInfo; 16415 T = FixedTInfo->getType(); 16416 } else { 16417 if (SizeIsNegative) 16418 Diag(Loc, diag::err_typecheck_negative_array_size); 16419 else if (Oversized.getBoolValue()) 16420 Diag(Loc, diag::err_array_too_large) 16421 << Oversized.toString(10); 16422 else 16423 Diag(Loc, diag::err_typecheck_field_variable_size); 16424 InvalidDecl = true; 16425 } 16426 } 16427 16428 // Fields can not have abstract class types 16429 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16430 diag::err_abstract_type_in_decl, 16431 AbstractFieldType)) 16432 InvalidDecl = true; 16433 16434 bool ZeroWidth = false; 16435 if (InvalidDecl) 16436 BitWidth = nullptr; 16437 // If this is declared as a bit-field, check the bit-field. 16438 if (BitWidth) { 16439 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16440 &ZeroWidth).get(); 16441 if (!BitWidth) { 16442 InvalidDecl = true; 16443 BitWidth = nullptr; 16444 ZeroWidth = false; 16445 } 16446 } 16447 16448 // Check that 'mutable' is consistent with the type of the declaration. 16449 if (!InvalidDecl && Mutable) { 16450 unsigned DiagID = 0; 16451 if (T->isReferenceType()) 16452 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16453 : diag::err_mutable_reference; 16454 else if (T.isConstQualified()) 16455 DiagID = diag::err_mutable_const; 16456 16457 if (DiagID) { 16458 SourceLocation ErrLoc = Loc; 16459 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16460 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16461 Diag(ErrLoc, DiagID); 16462 if (DiagID != diag::ext_mutable_reference) { 16463 Mutable = false; 16464 InvalidDecl = true; 16465 } 16466 } 16467 } 16468 16469 // C++11 [class.union]p8 (DR1460): 16470 // At most one variant member of a union may have a 16471 // brace-or-equal-initializer. 16472 if (InitStyle != ICIS_NoInit) 16473 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16474 16475 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16476 BitWidth, Mutable, InitStyle); 16477 if (InvalidDecl) 16478 NewFD->setInvalidDecl(); 16479 16480 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16481 Diag(Loc, diag::err_duplicate_member) << II; 16482 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16483 NewFD->setInvalidDecl(); 16484 } 16485 16486 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16487 if (Record->isUnion()) { 16488 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16489 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16490 if (RDecl->getDefinition()) { 16491 // C++ [class.union]p1: An object of a class with a non-trivial 16492 // constructor, a non-trivial copy constructor, a non-trivial 16493 // destructor, or a non-trivial copy assignment operator 16494 // cannot be a member of a union, nor can an array of such 16495 // objects. 16496 if (CheckNontrivialField(NewFD)) 16497 NewFD->setInvalidDecl(); 16498 } 16499 } 16500 16501 // C++ [class.union]p1: If a union contains a member of reference type, 16502 // the program is ill-formed, except when compiling with MSVC extensions 16503 // enabled. 16504 if (EltTy->isReferenceType()) { 16505 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16506 diag::ext_union_member_of_reference_type : 16507 diag::err_union_member_of_reference_type) 16508 << NewFD->getDeclName() << EltTy; 16509 if (!getLangOpts().MicrosoftExt) 16510 NewFD->setInvalidDecl(); 16511 } 16512 } 16513 } 16514 16515 // FIXME: We need to pass in the attributes given an AST 16516 // representation, not a parser representation. 16517 if (D) { 16518 // FIXME: The current scope is almost... but not entirely... correct here. 16519 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16520 16521 if (NewFD->hasAttrs()) 16522 CheckAlignasUnderalignment(NewFD); 16523 } 16524 16525 // In auto-retain/release, infer strong retension for fields of 16526 // retainable type. 16527 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16528 NewFD->setInvalidDecl(); 16529 16530 if (T.isObjCGCWeak()) 16531 Diag(Loc, diag::warn_attribute_weak_on_field); 16532 16533 NewFD->setAccess(AS); 16534 return NewFD; 16535 } 16536 16537 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16538 assert(FD); 16539 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16540 16541 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16542 return false; 16543 16544 QualType EltTy = Context.getBaseElementType(FD->getType()); 16545 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16546 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16547 if (RDecl->getDefinition()) { 16548 // We check for copy constructors before constructors 16549 // because otherwise we'll never get complaints about 16550 // copy constructors. 16551 16552 CXXSpecialMember member = CXXInvalid; 16553 // We're required to check for any non-trivial constructors. Since the 16554 // implicit default constructor is suppressed if there are any 16555 // user-declared constructors, we just need to check that there is a 16556 // trivial default constructor and a trivial copy constructor. (We don't 16557 // worry about move constructors here, since this is a C++98 check.) 16558 if (RDecl->hasNonTrivialCopyConstructor()) 16559 member = CXXCopyConstructor; 16560 else if (!RDecl->hasTrivialDefaultConstructor()) 16561 member = CXXDefaultConstructor; 16562 else if (RDecl->hasNonTrivialCopyAssignment()) 16563 member = CXXCopyAssignment; 16564 else if (RDecl->hasNonTrivialDestructor()) 16565 member = CXXDestructor; 16566 16567 if (member != CXXInvalid) { 16568 if (!getLangOpts().CPlusPlus11 && 16569 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16570 // Objective-C++ ARC: it is an error to have a non-trivial field of 16571 // a union. However, system headers in Objective-C programs 16572 // occasionally have Objective-C lifetime objects within unions, 16573 // and rather than cause the program to fail, we make those 16574 // members unavailable. 16575 SourceLocation Loc = FD->getLocation(); 16576 if (getSourceManager().isInSystemHeader(Loc)) { 16577 if (!FD->hasAttr<UnavailableAttr>()) 16578 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16579 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16580 return false; 16581 } 16582 } 16583 16584 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16585 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16586 diag::err_illegal_union_or_anon_struct_member) 16587 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16588 DiagnoseNontrivial(RDecl, member); 16589 return !getLangOpts().CPlusPlus11; 16590 } 16591 } 16592 } 16593 16594 return false; 16595 } 16596 16597 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16598 /// AST enum value. 16599 static ObjCIvarDecl::AccessControl 16600 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16601 switch (ivarVisibility) { 16602 default: llvm_unreachable("Unknown visitibility kind"); 16603 case tok::objc_private: return ObjCIvarDecl::Private; 16604 case tok::objc_public: return ObjCIvarDecl::Public; 16605 case tok::objc_protected: return ObjCIvarDecl::Protected; 16606 case tok::objc_package: return ObjCIvarDecl::Package; 16607 } 16608 } 16609 16610 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16611 /// in order to create an IvarDecl object for it. 16612 Decl *Sema::ActOnIvar(Scope *S, 16613 SourceLocation DeclStart, 16614 Declarator &D, Expr *BitfieldWidth, 16615 tok::ObjCKeywordKind Visibility) { 16616 16617 IdentifierInfo *II = D.getIdentifier(); 16618 Expr *BitWidth = (Expr*)BitfieldWidth; 16619 SourceLocation Loc = DeclStart; 16620 if (II) Loc = D.getIdentifierLoc(); 16621 16622 // FIXME: Unnamed fields can be handled in various different ways, for 16623 // example, unnamed unions inject all members into the struct namespace! 16624 16625 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16626 QualType T = TInfo->getType(); 16627 16628 if (BitWidth) { 16629 // 6.7.2.1p3, 6.7.2.1p4 16630 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16631 if (!BitWidth) 16632 D.setInvalidType(); 16633 } else { 16634 // Not a bitfield. 16635 16636 // validate II. 16637 16638 } 16639 if (T->isReferenceType()) { 16640 Diag(Loc, diag::err_ivar_reference_type); 16641 D.setInvalidType(); 16642 } 16643 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16644 // than a variably modified type. 16645 else if (T->isVariablyModifiedType()) { 16646 Diag(Loc, diag::err_typecheck_ivar_variable_size); 16647 D.setInvalidType(); 16648 } 16649 16650 // Get the visibility (access control) for this ivar. 16651 ObjCIvarDecl::AccessControl ac = 16652 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 16653 : ObjCIvarDecl::None; 16654 // Must set ivar's DeclContext to its enclosing interface. 16655 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 16656 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 16657 return nullptr; 16658 ObjCContainerDecl *EnclosingContext; 16659 if (ObjCImplementationDecl *IMPDecl = 16660 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16661 if (LangOpts.ObjCRuntime.isFragile()) { 16662 // Case of ivar declared in an implementation. Context is that of its class. 16663 EnclosingContext = IMPDecl->getClassInterface(); 16664 assert(EnclosingContext && "Implementation has no class interface!"); 16665 } 16666 else 16667 EnclosingContext = EnclosingDecl; 16668 } else { 16669 if (ObjCCategoryDecl *CDecl = 16670 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16671 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 16672 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 16673 return nullptr; 16674 } 16675 } 16676 EnclosingContext = EnclosingDecl; 16677 } 16678 16679 // Construct the decl. 16680 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 16681 DeclStart, Loc, II, T, 16682 TInfo, ac, (Expr *)BitfieldWidth); 16683 16684 if (II) { 16685 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 16686 ForVisibleRedeclaration); 16687 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 16688 && !isa<TagDecl>(PrevDecl)) { 16689 Diag(Loc, diag::err_duplicate_member) << II; 16690 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16691 NewID->setInvalidDecl(); 16692 } 16693 } 16694 16695 // Process attributes attached to the ivar. 16696 ProcessDeclAttributes(S, NewID, D); 16697 16698 if (D.isInvalidType()) 16699 NewID->setInvalidDecl(); 16700 16701 // In ARC, infer 'retaining' for ivars of retainable type. 16702 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 16703 NewID->setInvalidDecl(); 16704 16705 if (D.getDeclSpec().isModulePrivateSpecified()) 16706 NewID->setModulePrivate(); 16707 16708 if (II) { 16709 // FIXME: When interfaces are DeclContexts, we'll need to add 16710 // these to the interface. 16711 S->AddDecl(NewID); 16712 IdResolver.AddDecl(NewID); 16713 } 16714 16715 if (LangOpts.ObjCRuntime.isNonFragile() && 16716 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 16717 Diag(Loc, diag::warn_ivars_in_interface); 16718 16719 return NewID; 16720 } 16721 16722 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 16723 /// class and class extensions. For every class \@interface and class 16724 /// extension \@interface, if the last ivar is a bitfield of any type, 16725 /// then add an implicit `char :0` ivar to the end of that interface. 16726 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 16727 SmallVectorImpl<Decl *> &AllIvarDecls) { 16728 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 16729 return; 16730 16731 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 16732 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 16733 16734 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 16735 return; 16736 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 16737 if (!ID) { 16738 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 16739 if (!CD->IsClassExtension()) 16740 return; 16741 } 16742 // No need to add this to end of @implementation. 16743 else 16744 return; 16745 } 16746 // All conditions are met. Add a new bitfield to the tail end of ivars. 16747 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 16748 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 16749 16750 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 16751 DeclLoc, DeclLoc, nullptr, 16752 Context.CharTy, 16753 Context.getTrivialTypeSourceInfo(Context.CharTy, 16754 DeclLoc), 16755 ObjCIvarDecl::Private, BW, 16756 true); 16757 AllIvarDecls.push_back(Ivar); 16758 } 16759 16760 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 16761 ArrayRef<Decl *> Fields, SourceLocation LBrac, 16762 SourceLocation RBrac, 16763 const ParsedAttributesView &Attrs) { 16764 assert(EnclosingDecl && "missing record or interface decl"); 16765 16766 // If this is an Objective-C @implementation or category and we have 16767 // new fields here we should reset the layout of the interface since 16768 // it will now change. 16769 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 16770 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 16771 switch (DC->getKind()) { 16772 default: break; 16773 case Decl::ObjCCategory: 16774 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 16775 break; 16776 case Decl::ObjCImplementation: 16777 Context. 16778 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 16779 break; 16780 } 16781 } 16782 16783 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 16784 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 16785 16786 // Start counting up the number of named members; make sure to include 16787 // members of anonymous structs and unions in the total. 16788 unsigned NumNamedMembers = 0; 16789 if (Record) { 16790 for (const auto *I : Record->decls()) { 16791 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 16792 if (IFD->getDeclName()) 16793 ++NumNamedMembers; 16794 } 16795 } 16796 16797 // Verify that all the fields are okay. 16798 SmallVector<FieldDecl*, 32> RecFields; 16799 16800 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 16801 i != end; ++i) { 16802 FieldDecl *FD = cast<FieldDecl>(*i); 16803 16804 // Get the type for the field. 16805 const Type *FDTy = FD->getType().getTypePtr(); 16806 16807 if (!FD->isAnonymousStructOrUnion()) { 16808 // Remember all fields written by the user. 16809 RecFields.push_back(FD); 16810 } 16811 16812 // If the field is already invalid for some reason, don't emit more 16813 // diagnostics about it. 16814 if (FD->isInvalidDecl()) { 16815 EnclosingDecl->setInvalidDecl(); 16816 continue; 16817 } 16818 16819 // C99 6.7.2.1p2: 16820 // A structure or union shall not contain a member with 16821 // incomplete or function type (hence, a structure shall not 16822 // contain an instance of itself, but may contain a pointer to 16823 // an instance of itself), except that the last member of a 16824 // structure with more than one named member may have incomplete 16825 // array type; such a structure (and any union containing, 16826 // possibly recursively, a member that is such a structure) 16827 // shall not be a member of a structure or an element of an 16828 // array. 16829 bool IsLastField = (i + 1 == Fields.end()); 16830 if (FDTy->isFunctionType()) { 16831 // Field declared as a function. 16832 Diag(FD->getLocation(), diag::err_field_declared_as_function) 16833 << FD->getDeclName(); 16834 FD->setInvalidDecl(); 16835 EnclosingDecl->setInvalidDecl(); 16836 continue; 16837 } else if (FDTy->isIncompleteArrayType() && 16838 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 16839 if (Record) { 16840 // Flexible array member. 16841 // Microsoft and g++ is more permissive regarding flexible array. 16842 // It will accept flexible array in union and also 16843 // as the sole element of a struct/class. 16844 unsigned DiagID = 0; 16845 if (!Record->isUnion() && !IsLastField) { 16846 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 16847 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 16848 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 16849 FD->setInvalidDecl(); 16850 EnclosingDecl->setInvalidDecl(); 16851 continue; 16852 } else if (Record->isUnion()) 16853 DiagID = getLangOpts().MicrosoftExt 16854 ? diag::ext_flexible_array_union_ms 16855 : getLangOpts().CPlusPlus 16856 ? diag::ext_flexible_array_union_gnu 16857 : diag::err_flexible_array_union; 16858 else if (NumNamedMembers < 1) 16859 DiagID = getLangOpts().MicrosoftExt 16860 ? diag::ext_flexible_array_empty_aggregate_ms 16861 : getLangOpts().CPlusPlus 16862 ? diag::ext_flexible_array_empty_aggregate_gnu 16863 : diag::err_flexible_array_empty_aggregate; 16864 16865 if (DiagID) 16866 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 16867 << Record->getTagKind(); 16868 // While the layout of types that contain virtual bases is not specified 16869 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 16870 // virtual bases after the derived members. This would make a flexible 16871 // array member declared at the end of an object not adjacent to the end 16872 // of the type. 16873 if (CXXRecord && CXXRecord->getNumVBases() != 0) 16874 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 16875 << FD->getDeclName() << Record->getTagKind(); 16876 if (!getLangOpts().C99) 16877 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 16878 << FD->getDeclName() << Record->getTagKind(); 16879 16880 // If the element type has a non-trivial destructor, we would not 16881 // implicitly destroy the elements, so disallow it for now. 16882 // 16883 // FIXME: GCC allows this. We should probably either implicitly delete 16884 // the destructor of the containing class, or just allow this. 16885 QualType BaseElem = Context.getBaseElementType(FD->getType()); 16886 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 16887 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 16888 << FD->getDeclName() << FD->getType(); 16889 FD->setInvalidDecl(); 16890 EnclosingDecl->setInvalidDecl(); 16891 continue; 16892 } 16893 // Okay, we have a legal flexible array member at the end of the struct. 16894 Record->setHasFlexibleArrayMember(true); 16895 } else { 16896 // In ObjCContainerDecl ivars with incomplete array type are accepted, 16897 // unless they are followed by another ivar. That check is done 16898 // elsewhere, after synthesized ivars are known. 16899 } 16900 } else if (!FDTy->isDependentType() && 16901 RequireCompleteType(FD->getLocation(), FD->getType(), 16902 diag::err_field_incomplete)) { 16903 // Incomplete type 16904 FD->setInvalidDecl(); 16905 EnclosingDecl->setInvalidDecl(); 16906 continue; 16907 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 16908 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 16909 // A type which contains a flexible array member is considered to be a 16910 // flexible array member. 16911 Record->setHasFlexibleArrayMember(true); 16912 if (!Record->isUnion()) { 16913 // If this is a struct/class and this is not the last element, reject 16914 // it. Note that GCC supports variable sized arrays in the middle of 16915 // structures. 16916 if (!IsLastField) 16917 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 16918 << FD->getDeclName() << FD->getType(); 16919 else { 16920 // We support flexible arrays at the end of structs in 16921 // other structs as an extension. 16922 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 16923 << FD->getDeclName(); 16924 } 16925 } 16926 } 16927 if (isa<ObjCContainerDecl>(EnclosingDecl) && 16928 RequireNonAbstractType(FD->getLocation(), FD->getType(), 16929 diag::err_abstract_type_in_decl, 16930 AbstractIvarType)) { 16931 // Ivars can not have abstract class types 16932 FD->setInvalidDecl(); 16933 } 16934 if (Record && FDTTy->getDecl()->hasObjectMember()) 16935 Record->setHasObjectMember(true); 16936 if (Record && FDTTy->getDecl()->hasVolatileMember()) 16937 Record->setHasVolatileMember(true); 16938 } else if (FDTy->isObjCObjectType()) { 16939 /// A field cannot be an Objective-c object 16940 Diag(FD->getLocation(), diag::err_statically_allocated_object) 16941 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 16942 QualType T = Context.getObjCObjectPointerType(FD->getType()); 16943 FD->setType(T); 16944 } else if (Record && Record->isUnion() && 16945 FD->getType().hasNonTrivialObjCLifetime() && 16946 getSourceManager().isInSystemHeader(FD->getLocation()) && 16947 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 16948 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 16949 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 16950 // For backward compatibility, fields of C unions declared in system 16951 // headers that have non-trivial ObjC ownership qualifications are marked 16952 // as unavailable unless the qualifier is explicit and __strong. This can 16953 // break ABI compatibility between programs compiled with ARC and MRR, but 16954 // is a better option than rejecting programs using those unions under 16955 // ARC. 16956 FD->addAttr(UnavailableAttr::CreateImplicit( 16957 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 16958 FD->getLocation())); 16959 } else if (getLangOpts().ObjC && 16960 getLangOpts().getGC() != LangOptions::NonGC && 16961 Record && !Record->hasObjectMember()) { 16962 if (FD->getType()->isObjCObjectPointerType() || 16963 FD->getType().isObjCGCStrong()) 16964 Record->setHasObjectMember(true); 16965 else if (Context.getAsArrayType(FD->getType())) { 16966 QualType BaseType = Context.getBaseElementType(FD->getType()); 16967 if (BaseType->isRecordType() && 16968 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 16969 Record->setHasObjectMember(true); 16970 else if (BaseType->isObjCObjectPointerType() || 16971 BaseType.isObjCGCStrong()) 16972 Record->setHasObjectMember(true); 16973 } 16974 } 16975 16976 if (Record && !getLangOpts().CPlusPlus && 16977 !shouldIgnoreForRecordTriviality(FD)) { 16978 QualType FT = FD->getType(); 16979 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 16980 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 16981 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 16982 Record->isUnion()) 16983 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 16984 } 16985 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 16986 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 16987 Record->setNonTrivialToPrimitiveCopy(true); 16988 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 16989 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 16990 } 16991 if (FT.isDestructedType()) { 16992 Record->setNonTrivialToPrimitiveDestroy(true); 16993 Record->setParamDestroyedInCallee(true); 16994 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 16995 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 16996 } 16997 16998 if (const auto *RT = FT->getAs<RecordType>()) { 16999 if (RT->getDecl()->getArgPassingRestrictions() == 17000 RecordDecl::APK_CanNeverPassInRegs) 17001 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17002 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17003 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17004 } 17005 17006 if (Record && FD->getType().isVolatileQualified()) 17007 Record->setHasVolatileMember(true); 17008 // Keep track of the number of named members. 17009 if (FD->getIdentifier()) 17010 ++NumNamedMembers; 17011 } 17012 17013 // Okay, we successfully defined 'Record'. 17014 if (Record) { 17015 bool Completed = false; 17016 if (CXXRecord) { 17017 if (!CXXRecord->isInvalidDecl()) { 17018 // Set access bits correctly on the directly-declared conversions. 17019 for (CXXRecordDecl::conversion_iterator 17020 I = CXXRecord->conversion_begin(), 17021 E = CXXRecord->conversion_end(); I != E; ++I) 17022 I.setAccess((*I)->getAccess()); 17023 } 17024 17025 if (!CXXRecord->isDependentType()) { 17026 // Add any implicitly-declared members to this class. 17027 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17028 17029 if (!CXXRecord->isInvalidDecl()) { 17030 // If we have virtual base classes, we may end up finding multiple 17031 // final overriders for a given virtual function. Check for this 17032 // problem now. 17033 if (CXXRecord->getNumVBases()) { 17034 CXXFinalOverriderMap FinalOverriders; 17035 CXXRecord->getFinalOverriders(FinalOverriders); 17036 17037 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17038 MEnd = FinalOverriders.end(); 17039 M != MEnd; ++M) { 17040 for (OverridingMethods::iterator SO = M->second.begin(), 17041 SOEnd = M->second.end(); 17042 SO != SOEnd; ++SO) { 17043 assert(SO->second.size() > 0 && 17044 "Virtual function without overriding functions?"); 17045 if (SO->second.size() == 1) 17046 continue; 17047 17048 // C++ [class.virtual]p2: 17049 // In a derived class, if a virtual member function of a base 17050 // class subobject has more than one final overrider the 17051 // program is ill-formed. 17052 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17053 << (const NamedDecl *)M->first << Record; 17054 Diag(M->first->getLocation(), 17055 diag::note_overridden_virtual_function); 17056 for (OverridingMethods::overriding_iterator 17057 OM = SO->second.begin(), 17058 OMEnd = SO->second.end(); 17059 OM != OMEnd; ++OM) 17060 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17061 << (const NamedDecl *)M->first << OM->Method->getParent(); 17062 17063 Record->setInvalidDecl(); 17064 } 17065 } 17066 CXXRecord->completeDefinition(&FinalOverriders); 17067 Completed = true; 17068 } 17069 } 17070 } 17071 } 17072 17073 if (!Completed) 17074 Record->completeDefinition(); 17075 17076 // Handle attributes before checking the layout. 17077 ProcessDeclAttributeList(S, Record, Attrs); 17078 17079 // We may have deferred checking for a deleted destructor. Check now. 17080 if (CXXRecord) { 17081 auto *Dtor = CXXRecord->getDestructor(); 17082 if (Dtor && Dtor->isImplicit() && 17083 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17084 CXXRecord->setImplicitDestructorIsDeleted(); 17085 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17086 } 17087 } 17088 17089 if (Record->hasAttrs()) { 17090 CheckAlignasUnderalignment(Record); 17091 17092 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17093 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17094 IA->getRange(), IA->getBestCase(), 17095 IA->getInheritanceModel()); 17096 } 17097 17098 // Check if the structure/union declaration is a type that can have zero 17099 // size in C. For C this is a language extension, for C++ it may cause 17100 // compatibility problems. 17101 bool CheckForZeroSize; 17102 if (!getLangOpts().CPlusPlus) { 17103 CheckForZeroSize = true; 17104 } else { 17105 // For C++ filter out types that cannot be referenced in C code. 17106 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17107 CheckForZeroSize = 17108 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17109 !CXXRecord->isDependentType() && 17110 CXXRecord->isCLike(); 17111 } 17112 if (CheckForZeroSize) { 17113 bool ZeroSize = true; 17114 bool IsEmpty = true; 17115 unsigned NonBitFields = 0; 17116 for (RecordDecl::field_iterator I = Record->field_begin(), 17117 E = Record->field_end(); 17118 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17119 IsEmpty = false; 17120 if (I->isUnnamedBitfield()) { 17121 if (!I->isZeroLengthBitField(Context)) 17122 ZeroSize = false; 17123 } else { 17124 ++NonBitFields; 17125 QualType FieldType = I->getType(); 17126 if (FieldType->isIncompleteType() || 17127 !Context.getTypeSizeInChars(FieldType).isZero()) 17128 ZeroSize = false; 17129 } 17130 } 17131 17132 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17133 // allowed in C++, but warn if its declaration is inside 17134 // extern "C" block. 17135 if (ZeroSize) { 17136 Diag(RecLoc, getLangOpts().CPlusPlus ? 17137 diag::warn_zero_size_struct_union_in_extern_c : 17138 diag::warn_zero_size_struct_union_compat) 17139 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17140 } 17141 17142 // Structs without named members are extension in C (C99 6.7.2.1p7), 17143 // but are accepted by GCC. 17144 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17145 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17146 diag::ext_no_named_members_in_struct_union) 17147 << Record->isUnion(); 17148 } 17149 } 17150 } else { 17151 ObjCIvarDecl **ClsFields = 17152 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17153 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17154 ID->setEndOfDefinitionLoc(RBrac); 17155 // Add ivar's to class's DeclContext. 17156 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17157 ClsFields[i]->setLexicalDeclContext(ID); 17158 ID->addDecl(ClsFields[i]); 17159 } 17160 // Must enforce the rule that ivars in the base classes may not be 17161 // duplicates. 17162 if (ID->getSuperClass()) 17163 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17164 } else if (ObjCImplementationDecl *IMPDecl = 17165 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17166 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17167 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17168 // Ivar declared in @implementation never belongs to the implementation. 17169 // Only it is in implementation's lexical context. 17170 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17171 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17172 IMPDecl->setIvarLBraceLoc(LBrac); 17173 IMPDecl->setIvarRBraceLoc(RBrac); 17174 } else if (ObjCCategoryDecl *CDecl = 17175 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17176 // case of ivars in class extension; all other cases have been 17177 // reported as errors elsewhere. 17178 // FIXME. Class extension does not have a LocEnd field. 17179 // CDecl->setLocEnd(RBrac); 17180 // Add ivar's to class extension's DeclContext. 17181 // Diagnose redeclaration of private ivars. 17182 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17183 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17184 if (IDecl) { 17185 if (const ObjCIvarDecl *ClsIvar = 17186 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17187 Diag(ClsFields[i]->getLocation(), 17188 diag::err_duplicate_ivar_declaration); 17189 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17190 continue; 17191 } 17192 for (const auto *Ext : IDecl->known_extensions()) { 17193 if (const ObjCIvarDecl *ClsExtIvar 17194 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17195 Diag(ClsFields[i]->getLocation(), 17196 diag::err_duplicate_ivar_declaration); 17197 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17198 continue; 17199 } 17200 } 17201 } 17202 ClsFields[i]->setLexicalDeclContext(CDecl); 17203 CDecl->addDecl(ClsFields[i]); 17204 } 17205 CDecl->setIvarLBraceLoc(LBrac); 17206 CDecl->setIvarRBraceLoc(RBrac); 17207 } 17208 } 17209 } 17210 17211 /// Determine whether the given integral value is representable within 17212 /// the given type T. 17213 static bool isRepresentableIntegerValue(ASTContext &Context, 17214 llvm::APSInt &Value, 17215 QualType T) { 17216 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17217 "Integral type required!"); 17218 unsigned BitWidth = Context.getIntWidth(T); 17219 17220 if (Value.isUnsigned() || Value.isNonNegative()) { 17221 if (T->isSignedIntegerOrEnumerationType()) 17222 --BitWidth; 17223 return Value.getActiveBits() <= BitWidth; 17224 } 17225 return Value.getMinSignedBits() <= BitWidth; 17226 } 17227 17228 // Given an integral type, return the next larger integral type 17229 // (or a NULL type of no such type exists). 17230 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17231 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17232 // enum checking below. 17233 assert((T->isIntegralType(Context) || 17234 T->isEnumeralType()) && "Integral type required!"); 17235 const unsigned NumTypes = 4; 17236 QualType SignedIntegralTypes[NumTypes] = { 17237 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17238 }; 17239 QualType UnsignedIntegralTypes[NumTypes] = { 17240 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17241 Context.UnsignedLongLongTy 17242 }; 17243 17244 unsigned BitWidth = Context.getTypeSize(T); 17245 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17246 : UnsignedIntegralTypes; 17247 for (unsigned I = 0; I != NumTypes; ++I) 17248 if (Context.getTypeSize(Types[I]) > BitWidth) 17249 return Types[I]; 17250 17251 return QualType(); 17252 } 17253 17254 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17255 EnumConstantDecl *LastEnumConst, 17256 SourceLocation IdLoc, 17257 IdentifierInfo *Id, 17258 Expr *Val) { 17259 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17260 llvm::APSInt EnumVal(IntWidth); 17261 QualType EltTy; 17262 17263 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17264 Val = nullptr; 17265 17266 if (Val) 17267 Val = DefaultLvalueConversion(Val).get(); 17268 17269 if (Val) { 17270 if (Enum->isDependentType() || Val->isTypeDependent()) 17271 EltTy = Context.DependentTy; 17272 else { 17273 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17274 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17275 // constant-expression in the enumerator-definition shall be a converted 17276 // constant expression of the underlying type. 17277 EltTy = Enum->getIntegerType(); 17278 ExprResult Converted = 17279 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17280 CCEK_Enumerator); 17281 if (Converted.isInvalid()) 17282 Val = nullptr; 17283 else 17284 Val = Converted.get(); 17285 } else if (!Val->isValueDependent() && 17286 !(Val = VerifyIntegerConstantExpression(Val, 17287 &EnumVal).get())) { 17288 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17289 } else { 17290 if (Enum->isComplete()) { 17291 EltTy = Enum->getIntegerType(); 17292 17293 // In Obj-C and Microsoft mode, require the enumeration value to be 17294 // representable in the underlying type of the enumeration. In C++11, 17295 // we perform a non-narrowing conversion as part of converted constant 17296 // expression checking. 17297 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17298 if (Context.getTargetInfo() 17299 .getTriple() 17300 .isWindowsMSVCEnvironment()) { 17301 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17302 } else { 17303 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17304 } 17305 } 17306 17307 // Cast to the underlying type. 17308 Val = ImpCastExprToType(Val, EltTy, 17309 EltTy->isBooleanType() ? CK_IntegralToBoolean 17310 : CK_IntegralCast) 17311 .get(); 17312 } else if (getLangOpts().CPlusPlus) { 17313 // C++11 [dcl.enum]p5: 17314 // If the underlying type is not fixed, the type of each enumerator 17315 // is the type of its initializing value: 17316 // - If an initializer is specified for an enumerator, the 17317 // initializing value has the same type as the expression. 17318 EltTy = Val->getType(); 17319 } else { 17320 // C99 6.7.2.2p2: 17321 // The expression that defines the value of an enumeration constant 17322 // shall be an integer constant expression that has a value 17323 // representable as an int. 17324 17325 // Complain if the value is not representable in an int. 17326 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17327 Diag(IdLoc, diag::ext_enum_value_not_int) 17328 << EnumVal.toString(10) << Val->getSourceRange() 17329 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17330 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17331 // Force the type of the expression to 'int'. 17332 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17333 } 17334 EltTy = Val->getType(); 17335 } 17336 } 17337 } 17338 } 17339 17340 if (!Val) { 17341 if (Enum->isDependentType()) 17342 EltTy = Context.DependentTy; 17343 else if (!LastEnumConst) { 17344 // C++0x [dcl.enum]p5: 17345 // If the underlying type is not fixed, the type of each enumerator 17346 // is the type of its initializing value: 17347 // - If no initializer is specified for the first enumerator, the 17348 // initializing value has an unspecified integral type. 17349 // 17350 // GCC uses 'int' for its unspecified integral type, as does 17351 // C99 6.7.2.2p3. 17352 if (Enum->isFixed()) { 17353 EltTy = Enum->getIntegerType(); 17354 } 17355 else { 17356 EltTy = Context.IntTy; 17357 } 17358 } else { 17359 // Assign the last value + 1. 17360 EnumVal = LastEnumConst->getInitVal(); 17361 ++EnumVal; 17362 EltTy = LastEnumConst->getType(); 17363 17364 // Check for overflow on increment. 17365 if (EnumVal < LastEnumConst->getInitVal()) { 17366 // C++0x [dcl.enum]p5: 17367 // If the underlying type is not fixed, the type of each enumerator 17368 // is the type of its initializing value: 17369 // 17370 // - Otherwise the type of the initializing value is the same as 17371 // the type of the initializing value of the preceding enumerator 17372 // unless the incremented value is not representable in that type, 17373 // in which case the type is an unspecified integral type 17374 // sufficient to contain the incremented value. If no such type 17375 // exists, the program is ill-formed. 17376 QualType T = getNextLargerIntegralType(Context, EltTy); 17377 if (T.isNull() || Enum->isFixed()) { 17378 // There is no integral type larger enough to represent this 17379 // value. Complain, then allow the value to wrap around. 17380 EnumVal = LastEnumConst->getInitVal(); 17381 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17382 ++EnumVal; 17383 if (Enum->isFixed()) 17384 // When the underlying type is fixed, this is ill-formed. 17385 Diag(IdLoc, diag::err_enumerator_wrapped) 17386 << EnumVal.toString(10) 17387 << EltTy; 17388 else 17389 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17390 << EnumVal.toString(10); 17391 } else { 17392 EltTy = T; 17393 } 17394 17395 // Retrieve the last enumerator's value, extent that type to the 17396 // type that is supposed to be large enough to represent the incremented 17397 // value, then increment. 17398 EnumVal = LastEnumConst->getInitVal(); 17399 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17400 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17401 ++EnumVal; 17402 17403 // If we're not in C++, diagnose the overflow of enumerator values, 17404 // which in C99 means that the enumerator value is not representable in 17405 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17406 // permits enumerator values that are representable in some larger 17407 // integral type. 17408 if (!getLangOpts().CPlusPlus && !T.isNull()) 17409 Diag(IdLoc, diag::warn_enum_value_overflow); 17410 } else if (!getLangOpts().CPlusPlus && 17411 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17412 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17413 Diag(IdLoc, diag::ext_enum_value_not_int) 17414 << EnumVal.toString(10) << 1; 17415 } 17416 } 17417 } 17418 17419 if (!EltTy->isDependentType()) { 17420 // Make the enumerator value match the signedness and size of the 17421 // enumerator's type. 17422 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17423 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17424 } 17425 17426 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17427 Val, EnumVal); 17428 } 17429 17430 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17431 SourceLocation IILoc) { 17432 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17433 !getLangOpts().CPlusPlus) 17434 return SkipBodyInfo(); 17435 17436 // We have an anonymous enum definition. Look up the first enumerator to 17437 // determine if we should merge the definition with an existing one and 17438 // skip the body. 17439 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17440 forRedeclarationInCurContext()); 17441 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17442 if (!PrevECD) 17443 return SkipBodyInfo(); 17444 17445 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17446 NamedDecl *Hidden; 17447 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17448 SkipBodyInfo Skip; 17449 Skip.Previous = Hidden; 17450 return Skip; 17451 } 17452 17453 return SkipBodyInfo(); 17454 } 17455 17456 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17457 SourceLocation IdLoc, IdentifierInfo *Id, 17458 const ParsedAttributesView &Attrs, 17459 SourceLocation EqualLoc, Expr *Val) { 17460 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17461 EnumConstantDecl *LastEnumConst = 17462 cast_or_null<EnumConstantDecl>(lastEnumConst); 17463 17464 // The scope passed in may not be a decl scope. Zip up the scope tree until 17465 // we find one that is. 17466 S = getNonFieldDeclScope(S); 17467 17468 // Verify that there isn't already something declared with this name in this 17469 // scope. 17470 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17471 LookupName(R, S); 17472 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17473 17474 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17475 // Maybe we will complain about the shadowed template parameter. 17476 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17477 // Just pretend that we didn't see the previous declaration. 17478 PrevDecl = nullptr; 17479 } 17480 17481 // C++ [class.mem]p15: 17482 // If T is the name of a class, then each of the following shall have a name 17483 // different from T: 17484 // - every enumerator of every member of class T that is an unscoped 17485 // enumerated type 17486 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17487 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17488 DeclarationNameInfo(Id, IdLoc)); 17489 17490 EnumConstantDecl *New = 17491 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17492 if (!New) 17493 return nullptr; 17494 17495 if (PrevDecl) { 17496 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17497 // Check for other kinds of shadowing not already handled. 17498 CheckShadow(New, PrevDecl, R); 17499 } 17500 17501 // When in C++, we may get a TagDecl with the same name; in this case the 17502 // enum constant will 'hide' the tag. 17503 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17504 "Received TagDecl when not in C++!"); 17505 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17506 if (isa<EnumConstantDecl>(PrevDecl)) 17507 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17508 else 17509 Diag(IdLoc, diag::err_redefinition) << Id; 17510 notePreviousDefinition(PrevDecl, IdLoc); 17511 return nullptr; 17512 } 17513 } 17514 17515 // Process attributes. 17516 ProcessDeclAttributeList(S, New, Attrs); 17517 AddPragmaAttributes(S, New); 17518 17519 // Register this decl in the current scope stack. 17520 New->setAccess(TheEnumDecl->getAccess()); 17521 PushOnScopeChains(New, S); 17522 17523 ActOnDocumentableDecl(New); 17524 17525 return New; 17526 } 17527 17528 // Returns true when the enum initial expression does not trigger the 17529 // duplicate enum warning. A few common cases are exempted as follows: 17530 // Element2 = Element1 17531 // Element2 = Element1 + 1 17532 // Element2 = Element1 - 1 17533 // Where Element2 and Element1 are from the same enum. 17534 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17535 Expr *InitExpr = ECD->getInitExpr(); 17536 if (!InitExpr) 17537 return true; 17538 InitExpr = InitExpr->IgnoreImpCasts(); 17539 17540 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17541 if (!BO->isAdditiveOp()) 17542 return true; 17543 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17544 if (!IL) 17545 return true; 17546 if (IL->getValue() != 1) 17547 return true; 17548 17549 InitExpr = BO->getLHS(); 17550 } 17551 17552 // This checks if the elements are from the same enum. 17553 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17554 if (!DRE) 17555 return true; 17556 17557 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17558 if (!EnumConstant) 17559 return true; 17560 17561 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17562 Enum) 17563 return true; 17564 17565 return false; 17566 } 17567 17568 // Emits a warning when an element is implicitly set a value that 17569 // a previous element has already been set to. 17570 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17571 EnumDecl *Enum, QualType EnumType) { 17572 // Avoid anonymous enums 17573 if (!Enum->getIdentifier()) 17574 return; 17575 17576 // Only check for small enums. 17577 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17578 return; 17579 17580 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17581 return; 17582 17583 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17584 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17585 17586 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17587 17588 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 17589 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17590 17591 // Use int64_t as a key to avoid needing special handling for map keys. 17592 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17593 llvm::APSInt Val = D->getInitVal(); 17594 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17595 }; 17596 17597 DuplicatesVector DupVector; 17598 ValueToVectorMap EnumMap; 17599 17600 // Populate the EnumMap with all values represented by enum constants without 17601 // an initializer. 17602 for (auto *Element : Elements) { 17603 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17604 17605 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17606 // this constant. Skip this enum since it may be ill-formed. 17607 if (!ECD) { 17608 return; 17609 } 17610 17611 // Constants with initalizers are handled in the next loop. 17612 if (ECD->getInitExpr()) 17613 continue; 17614 17615 // Duplicate values are handled in the next loop. 17616 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17617 } 17618 17619 if (EnumMap.size() == 0) 17620 return; 17621 17622 // Create vectors for any values that has duplicates. 17623 for (auto *Element : Elements) { 17624 // The last loop returned if any constant was null. 17625 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17626 if (!ValidDuplicateEnum(ECD, Enum)) 17627 continue; 17628 17629 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17630 if (Iter == EnumMap.end()) 17631 continue; 17632 17633 DeclOrVector& Entry = Iter->second; 17634 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17635 // Ensure constants are different. 17636 if (D == ECD) 17637 continue; 17638 17639 // Create new vector and push values onto it. 17640 auto Vec = std::make_unique<ECDVector>(); 17641 Vec->push_back(D); 17642 Vec->push_back(ECD); 17643 17644 // Update entry to point to the duplicates vector. 17645 Entry = Vec.get(); 17646 17647 // Store the vector somewhere we can consult later for quick emission of 17648 // diagnostics. 17649 DupVector.emplace_back(std::move(Vec)); 17650 continue; 17651 } 17652 17653 ECDVector *Vec = Entry.get<ECDVector*>(); 17654 // Make sure constants are not added more than once. 17655 if (*Vec->begin() == ECD) 17656 continue; 17657 17658 Vec->push_back(ECD); 17659 } 17660 17661 // Emit diagnostics. 17662 for (const auto &Vec : DupVector) { 17663 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 17664 17665 // Emit warning for one enum constant. 17666 auto *FirstECD = Vec->front(); 17667 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 17668 << FirstECD << FirstECD->getInitVal().toString(10) 17669 << FirstECD->getSourceRange(); 17670 17671 // Emit one note for each of the remaining enum constants with 17672 // the same value. 17673 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 17674 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 17675 << ECD << ECD->getInitVal().toString(10) 17676 << ECD->getSourceRange(); 17677 } 17678 } 17679 17680 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 17681 bool AllowMask) const { 17682 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 17683 assert(ED->isCompleteDefinition() && "expected enum definition"); 17684 17685 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 17686 llvm::APInt &FlagBits = R.first->second; 17687 17688 if (R.second) { 17689 for (auto *E : ED->enumerators()) { 17690 const auto &EVal = E->getInitVal(); 17691 // Only single-bit enumerators introduce new flag values. 17692 if (EVal.isPowerOf2()) 17693 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 17694 } 17695 } 17696 17697 // A value is in a flag enum if either its bits are a subset of the enum's 17698 // flag bits (the first condition) or we are allowing masks and the same is 17699 // true of its complement (the second condition). When masks are allowed, we 17700 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 17701 // 17702 // While it's true that any value could be used as a mask, the assumption is 17703 // that a mask will have all of the insignificant bits set. Anything else is 17704 // likely a logic error. 17705 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 17706 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 17707 } 17708 17709 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 17710 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 17711 const ParsedAttributesView &Attrs) { 17712 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 17713 QualType EnumType = Context.getTypeDeclType(Enum); 17714 17715 ProcessDeclAttributeList(S, Enum, Attrs); 17716 17717 if (Enum->isDependentType()) { 17718 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17719 EnumConstantDecl *ECD = 17720 cast_or_null<EnumConstantDecl>(Elements[i]); 17721 if (!ECD) continue; 17722 17723 ECD->setType(EnumType); 17724 } 17725 17726 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 17727 return; 17728 } 17729 17730 // TODO: If the result value doesn't fit in an int, it must be a long or long 17731 // long value. ISO C does not support this, but GCC does as an extension, 17732 // emit a warning. 17733 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17734 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 17735 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 17736 17737 // Verify that all the values are okay, compute the size of the values, and 17738 // reverse the list. 17739 unsigned NumNegativeBits = 0; 17740 unsigned NumPositiveBits = 0; 17741 17742 // Keep track of whether all elements have type int. 17743 bool AllElementsInt = true; 17744 17745 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17746 EnumConstantDecl *ECD = 17747 cast_or_null<EnumConstantDecl>(Elements[i]); 17748 if (!ECD) continue; // Already issued a diagnostic. 17749 17750 const llvm::APSInt &InitVal = ECD->getInitVal(); 17751 17752 // Keep track of the size of positive and negative values. 17753 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 17754 NumPositiveBits = std::max(NumPositiveBits, 17755 (unsigned)InitVal.getActiveBits()); 17756 else 17757 NumNegativeBits = std::max(NumNegativeBits, 17758 (unsigned)InitVal.getMinSignedBits()); 17759 17760 // Keep track of whether every enum element has type int (very common). 17761 if (AllElementsInt) 17762 AllElementsInt = ECD->getType() == Context.IntTy; 17763 } 17764 17765 // Figure out the type that should be used for this enum. 17766 QualType BestType; 17767 unsigned BestWidth; 17768 17769 // C++0x N3000 [conv.prom]p3: 17770 // An rvalue of an unscoped enumeration type whose underlying 17771 // type is not fixed can be converted to an rvalue of the first 17772 // of the following types that can represent all the values of 17773 // the enumeration: int, unsigned int, long int, unsigned long 17774 // int, long long int, or unsigned long long int. 17775 // C99 6.4.4.3p2: 17776 // An identifier declared as an enumeration constant has type int. 17777 // The C99 rule is modified by a gcc extension 17778 QualType BestPromotionType; 17779 17780 bool Packed = Enum->hasAttr<PackedAttr>(); 17781 // -fshort-enums is the equivalent to specifying the packed attribute on all 17782 // enum definitions. 17783 if (LangOpts.ShortEnums) 17784 Packed = true; 17785 17786 // If the enum already has a type because it is fixed or dictated by the 17787 // target, promote that type instead of analyzing the enumerators. 17788 if (Enum->isComplete()) { 17789 BestType = Enum->getIntegerType(); 17790 if (BestType->isPromotableIntegerType()) 17791 BestPromotionType = Context.getPromotedIntegerType(BestType); 17792 else 17793 BestPromotionType = BestType; 17794 17795 BestWidth = Context.getIntWidth(BestType); 17796 } 17797 else if (NumNegativeBits) { 17798 // If there is a negative value, figure out the smallest integer type (of 17799 // int/long/longlong) that fits. 17800 // If it's packed, check also if it fits a char or a short. 17801 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 17802 BestType = Context.SignedCharTy; 17803 BestWidth = CharWidth; 17804 } else if (Packed && NumNegativeBits <= ShortWidth && 17805 NumPositiveBits < ShortWidth) { 17806 BestType = Context.ShortTy; 17807 BestWidth = ShortWidth; 17808 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 17809 BestType = Context.IntTy; 17810 BestWidth = IntWidth; 17811 } else { 17812 BestWidth = Context.getTargetInfo().getLongWidth(); 17813 17814 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 17815 BestType = Context.LongTy; 17816 } else { 17817 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17818 17819 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 17820 Diag(Enum->getLocation(), diag::ext_enum_too_large); 17821 BestType = Context.LongLongTy; 17822 } 17823 } 17824 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 17825 } else { 17826 // If there is no negative value, figure out the smallest type that fits 17827 // all of the enumerator values. 17828 // If it's packed, check also if it fits a char or a short. 17829 if (Packed && NumPositiveBits <= CharWidth) { 17830 BestType = Context.UnsignedCharTy; 17831 BestPromotionType = Context.IntTy; 17832 BestWidth = CharWidth; 17833 } else if (Packed && NumPositiveBits <= ShortWidth) { 17834 BestType = Context.UnsignedShortTy; 17835 BestPromotionType = Context.IntTy; 17836 BestWidth = ShortWidth; 17837 } else if (NumPositiveBits <= IntWidth) { 17838 BestType = Context.UnsignedIntTy; 17839 BestWidth = IntWidth; 17840 BestPromotionType 17841 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17842 ? Context.UnsignedIntTy : Context.IntTy; 17843 } else if (NumPositiveBits <= 17844 (BestWidth = Context.getTargetInfo().getLongWidth())) { 17845 BestType = Context.UnsignedLongTy; 17846 BestPromotionType 17847 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17848 ? Context.UnsignedLongTy : Context.LongTy; 17849 } else { 17850 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17851 assert(NumPositiveBits <= BestWidth && 17852 "How could an initializer get larger than ULL?"); 17853 BestType = Context.UnsignedLongLongTy; 17854 BestPromotionType 17855 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17856 ? Context.UnsignedLongLongTy : Context.LongLongTy; 17857 } 17858 } 17859 17860 // Loop over all of the enumerator constants, changing their types to match 17861 // the type of the enum if needed. 17862 for (auto *D : Elements) { 17863 auto *ECD = cast_or_null<EnumConstantDecl>(D); 17864 if (!ECD) continue; // Already issued a diagnostic. 17865 17866 // Standard C says the enumerators have int type, but we allow, as an 17867 // extension, the enumerators to be larger than int size. If each 17868 // enumerator value fits in an int, type it as an int, otherwise type it the 17869 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 17870 // that X has type 'int', not 'unsigned'. 17871 17872 // Determine whether the value fits into an int. 17873 llvm::APSInt InitVal = ECD->getInitVal(); 17874 17875 // If it fits into an integer type, force it. Otherwise force it to match 17876 // the enum decl type. 17877 QualType NewTy; 17878 unsigned NewWidth; 17879 bool NewSign; 17880 if (!getLangOpts().CPlusPlus && 17881 !Enum->isFixed() && 17882 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 17883 NewTy = Context.IntTy; 17884 NewWidth = IntWidth; 17885 NewSign = true; 17886 } else if (ECD->getType() == BestType) { 17887 // Already the right type! 17888 if (getLangOpts().CPlusPlus) 17889 // C++ [dcl.enum]p4: Following the closing brace of an 17890 // enum-specifier, each enumerator has the type of its 17891 // enumeration. 17892 ECD->setType(EnumType); 17893 continue; 17894 } else { 17895 NewTy = BestType; 17896 NewWidth = BestWidth; 17897 NewSign = BestType->isSignedIntegerOrEnumerationType(); 17898 } 17899 17900 // Adjust the APSInt value. 17901 InitVal = InitVal.extOrTrunc(NewWidth); 17902 InitVal.setIsSigned(NewSign); 17903 ECD->setInitVal(InitVal); 17904 17905 // Adjust the Expr initializer and type. 17906 if (ECD->getInitExpr() && 17907 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 17908 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 17909 CK_IntegralCast, 17910 ECD->getInitExpr(), 17911 /*base paths*/ nullptr, 17912 VK_RValue)); 17913 if (getLangOpts().CPlusPlus) 17914 // C++ [dcl.enum]p4: Following the closing brace of an 17915 // enum-specifier, each enumerator has the type of its 17916 // enumeration. 17917 ECD->setType(EnumType); 17918 else 17919 ECD->setType(NewTy); 17920 } 17921 17922 Enum->completeDefinition(BestType, BestPromotionType, 17923 NumPositiveBits, NumNegativeBits); 17924 17925 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 17926 17927 if (Enum->isClosedFlag()) { 17928 for (Decl *D : Elements) { 17929 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 17930 if (!ECD) continue; // Already issued a diagnostic. 17931 17932 llvm::APSInt InitVal = ECD->getInitVal(); 17933 if (InitVal != 0 && !InitVal.isPowerOf2() && 17934 !IsValueInFlagEnum(Enum, InitVal, true)) 17935 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 17936 << ECD << Enum; 17937 } 17938 } 17939 17940 // Now that the enum type is defined, ensure it's not been underaligned. 17941 if (Enum->hasAttrs()) 17942 CheckAlignasUnderalignment(Enum); 17943 } 17944 17945 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 17946 SourceLocation StartLoc, 17947 SourceLocation EndLoc) { 17948 StringLiteral *AsmString = cast<StringLiteral>(expr); 17949 17950 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 17951 AsmString, StartLoc, 17952 EndLoc); 17953 CurContext->addDecl(New); 17954 return New; 17955 } 17956 17957 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 17958 IdentifierInfo* AliasName, 17959 SourceLocation PragmaLoc, 17960 SourceLocation NameLoc, 17961 SourceLocation AliasNameLoc) { 17962 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 17963 LookupOrdinaryName); 17964 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 17965 AttributeCommonInfo::AS_Pragma); 17966 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 17967 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 17968 17969 // If a declaration that: 17970 // 1) declares a function or a variable 17971 // 2) has external linkage 17972 // already exists, add a label attribute to it. 17973 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17974 if (isDeclExternC(PrevDecl)) 17975 PrevDecl->addAttr(Attr); 17976 else 17977 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 17978 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 17979 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 17980 } else 17981 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 17982 } 17983 17984 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 17985 SourceLocation PragmaLoc, 17986 SourceLocation NameLoc) { 17987 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 17988 17989 if (PrevDecl) { 17990 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 17991 } else { 17992 (void)WeakUndeclaredIdentifiers.insert( 17993 std::pair<IdentifierInfo*,WeakInfo> 17994 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 17995 } 17996 } 17997 17998 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 17999 IdentifierInfo* AliasName, 18000 SourceLocation PragmaLoc, 18001 SourceLocation NameLoc, 18002 SourceLocation AliasNameLoc) { 18003 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18004 LookupOrdinaryName); 18005 WeakInfo W = WeakInfo(Name, NameLoc); 18006 18007 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18008 if (!PrevDecl->hasAttr<AliasAttr>()) 18009 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18010 DeclApplyPragmaWeak(TUScope, ND, W); 18011 } else { 18012 (void)WeakUndeclaredIdentifiers.insert( 18013 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18014 } 18015 } 18016 18017 Decl *Sema::getObjCDeclContext() const { 18018 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18019 } 18020 18021 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) { 18022 // Templates are emitted when they're instantiated. 18023 if (FD->isDependentContext()) 18024 return FunctionEmissionStatus::TemplateDiscarded; 18025 18026 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; 18027 if (LangOpts.OpenMPIsDevice) { 18028 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18029 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18030 if (DevTy.hasValue()) { 18031 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18032 OMPES = FunctionEmissionStatus::OMPDiscarded; 18033 else if (DeviceKnownEmittedFns.count(FD) > 0) 18034 OMPES = FunctionEmissionStatus::Emitted; 18035 } 18036 } else if (LangOpts.OpenMP) { 18037 // In OpenMP 4.5 all the functions are host functions. 18038 if (LangOpts.OpenMP <= 45) { 18039 OMPES = FunctionEmissionStatus::Emitted; 18040 } else { 18041 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18042 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18043 // In OpenMP 5.0 or above, DevTy may be changed later by 18044 // #pragma omp declare target to(*) device_type(*). Therefore DevTy 18045 // having no value does not imply host. The emission status will be 18046 // checked again at the end of compilation unit. 18047 if (DevTy.hasValue()) { 18048 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 18049 OMPES = FunctionEmissionStatus::OMPDiscarded; 18050 } else if (DeviceKnownEmittedFns.count(FD) > 0) { 18051 OMPES = FunctionEmissionStatus::Emitted; 18052 } 18053 } 18054 } 18055 } 18056 if (OMPES == FunctionEmissionStatus::OMPDiscarded || 18057 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) 18058 return OMPES; 18059 18060 if (LangOpts.CUDA) { 18061 // When compiling for device, host functions are never emitted. Similarly, 18062 // when compiling for host, device and global functions are never emitted. 18063 // (Technically, we do emit a host-side stub for global functions, but this 18064 // doesn't count for our purposes here.) 18065 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18066 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18067 return FunctionEmissionStatus::CUDADiscarded; 18068 if (!LangOpts.CUDAIsDevice && 18069 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18070 return FunctionEmissionStatus::CUDADiscarded; 18071 18072 // Check whether this function is externally visible -- if so, it's 18073 // known-emitted. 18074 // 18075 // We have to check the GVA linkage of the function's *definition* -- if we 18076 // only have a declaration, we don't know whether or not the function will 18077 // be emitted, because (say) the definition could include "inline". 18078 FunctionDecl *Def = FD->getDefinition(); 18079 18080 if (Def && 18081 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) 18082 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) 18083 return FunctionEmissionStatus::Emitted; 18084 } 18085 18086 // Otherwise, the function is known-emitted if it's in our set of 18087 // known-emitted functions. 18088 return (DeviceKnownEmittedFns.count(FD) > 0) 18089 ? FunctionEmissionStatus::Emitted 18090 : FunctionEmissionStatus::Unknown; 18091 } 18092 18093 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18094 // Host-side references to a __global__ function refer to the stub, so the 18095 // function itself is never emitted and therefore should not be marked. 18096 // If we have host fn calls kernel fn calls host+device, the HD function 18097 // does not get instantiated on the host. We model this by omitting at the 18098 // call to the kernel from the callgraph. This ensures that, when compiling 18099 // for host, only HD functions actually called from the host get marked as 18100 // known-emitted. 18101 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18102 IdentifyCUDATarget(Callee) == CFT_Global; 18103 } 18104