1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TypeLocBuilder.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/CommentDiagnostic.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/NonTrivialTypeVisitor.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 36 #include "clang/Sema/CXXFieldCollector.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaInternal.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/ADT/SmallString.h" 47 #include "llvm/ADT/Triple.h" 48 #include <algorithm> 49 #include <cstring> 50 #include <functional> 51 #include <unordered_map> 52 53 using namespace clang; 54 using namespace sema; 55 56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 57 if (OwnedType) { 58 Decl *Group[2] = { OwnedType, Ptr }; 59 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 60 } 61 62 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 63 } 64 65 namespace { 66 67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 68 public: 69 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 70 bool AllowTemplates = false, 71 bool AllowNonTemplates = true) 72 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 73 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 74 WantExpressionKeywords = false; 75 WantCXXNamedCasts = false; 76 WantRemainingKeywords = false; 77 } 78 79 bool ValidateCandidate(const TypoCorrection &candidate) override { 80 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 81 if (!AllowInvalidDecl && ND->isInvalidDecl()) 82 return false; 83 84 if (getAsTypeTemplateDecl(ND)) 85 return AllowTemplates; 86 87 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 88 if (!IsType) 89 return false; 90 91 if (AllowNonTemplates) 92 return true; 93 94 // An injected-class-name of a class template (specialization) is valid 95 // as a template or as a non-template. 96 if (AllowTemplates) { 97 auto *RD = dyn_cast<CXXRecordDecl>(ND); 98 if (!RD || !RD->isInjectedClassName()) 99 return false; 100 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 101 return RD->getDescribedClassTemplate() || 102 isa<ClassTemplateSpecializationDecl>(RD); 103 } 104 105 return false; 106 } 107 108 return !WantClassName && candidate.isKeyword(); 109 } 110 111 std::unique_ptr<CorrectionCandidateCallback> clone() override { 112 return std::make_unique<TypeNameValidatorCCC>(*this); 113 } 114 115 private: 116 bool AllowInvalidDecl; 117 bool WantClassName; 118 bool AllowTemplates; 119 bool AllowNonTemplates; 120 }; 121 122 } // end anonymous namespace 123 124 /// Determine whether the token kind starts a simple-type-specifier. 125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 126 switch (Kind) { 127 // FIXME: Take into account the current language when deciding whether a 128 // token kind is a valid type specifier 129 case tok::kw_short: 130 case tok::kw_long: 131 case tok::kw___int64: 132 case tok::kw___int128: 133 case tok::kw_signed: 134 case tok::kw_unsigned: 135 case tok::kw_void: 136 case tok::kw_char: 137 case tok::kw_int: 138 case tok::kw_half: 139 case tok::kw_float: 140 case tok::kw_double: 141 case tok::kw___bf16: 142 case tok::kw__Float16: 143 case tok::kw___float128: 144 case tok::kw_wchar_t: 145 case tok::kw_bool: 146 case tok::kw___underlying_type: 147 case tok::kw___auto_type: 148 return true; 149 150 case tok::annot_typename: 151 case tok::kw_char16_t: 152 case tok::kw_char32_t: 153 case tok::kw_typeof: 154 case tok::annot_decltype: 155 case tok::kw_decltype: 156 return getLangOpts().CPlusPlus; 157 158 case tok::kw_char8_t: 159 return getLangOpts().Char8; 160 161 default: 162 break; 163 } 164 165 return false; 166 } 167 168 namespace { 169 enum class UnqualifiedTypeNameLookupResult { 170 NotFound, 171 FoundNonType, 172 FoundType 173 }; 174 } // end anonymous namespace 175 176 /// Tries to perform unqualified lookup of the type decls in bases for 177 /// dependent class. 178 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 179 /// type decl, \a FoundType if only type decls are found. 180 static UnqualifiedTypeNameLookupResult 181 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 182 SourceLocation NameLoc, 183 const CXXRecordDecl *RD) { 184 if (!RD->hasDefinition()) 185 return UnqualifiedTypeNameLookupResult::NotFound; 186 // Look for type decls in base classes. 187 UnqualifiedTypeNameLookupResult FoundTypeDecl = 188 UnqualifiedTypeNameLookupResult::NotFound; 189 for (const auto &Base : RD->bases()) { 190 const CXXRecordDecl *BaseRD = nullptr; 191 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 192 BaseRD = BaseTT->getAsCXXRecordDecl(); 193 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 194 // Look for type decls in dependent base classes that have known primary 195 // templates. 196 if (!TST || !TST->isDependentType()) 197 continue; 198 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 199 if (!TD) 200 continue; 201 if (auto *BasePrimaryTemplate = 202 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 204 BaseRD = BasePrimaryTemplate; 205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 206 if (const ClassTemplatePartialSpecializationDecl *PS = 207 CTD->findPartialSpecialization(Base.getType())) 208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 209 BaseRD = PS; 210 } 211 } 212 } 213 if (BaseRD) { 214 for (NamedDecl *ND : BaseRD->lookup(&II)) { 215 if (!isa<TypeDecl>(ND)) 216 return UnqualifiedTypeNameLookupResult::FoundNonType; 217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 218 } 219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 221 case UnqualifiedTypeNameLookupResult::FoundNonType: 222 return UnqualifiedTypeNameLookupResult::FoundNonType; 223 case UnqualifiedTypeNameLookupResult::FoundType: 224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 225 break; 226 case UnqualifiedTypeNameLookupResult::NotFound: 227 break; 228 } 229 } 230 } 231 } 232 233 return FoundTypeDecl; 234 } 235 236 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 237 const IdentifierInfo &II, 238 SourceLocation NameLoc) { 239 // Lookup in the parent class template context, if any. 240 const CXXRecordDecl *RD = nullptr; 241 UnqualifiedTypeNameLookupResult FoundTypeDecl = 242 UnqualifiedTypeNameLookupResult::NotFound; 243 for (DeclContext *DC = S.CurContext; 244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 245 DC = DC->getParent()) { 246 // Look for type decls in dependent base classes that have known primary 247 // templates. 248 RD = dyn_cast<CXXRecordDecl>(DC); 249 if (RD && RD->getDescribedClassTemplate()) 250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 251 } 252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 253 return nullptr; 254 255 // We found some types in dependent base classes. Recover as if the user 256 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 257 // lookup during template instantiation. 258 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 259 260 ASTContext &Context = S.Context; 261 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 262 cast<Type>(Context.getRecordType(RD))); 263 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 264 265 CXXScopeSpec SS; 266 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 267 268 TypeLocBuilder Builder; 269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 270 DepTL.setNameLoc(NameLoc); 271 DepTL.setElaboratedKeywordLoc(SourceLocation()); 272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 273 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 274 } 275 276 /// If the identifier refers to a type name within this scope, 277 /// return the declaration of that type. 278 /// 279 /// This routine performs ordinary name lookup of the identifier II 280 /// within the given scope, with optional C++ scope specifier SS, to 281 /// determine whether the name refers to a type. If so, returns an 282 /// opaque pointer (actually a QualType) corresponding to that 283 /// type. Otherwise, returns NULL. 284 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 285 Scope *S, CXXScopeSpec *SS, 286 bool isClassName, bool HasTrailingDot, 287 ParsedType ObjectTypePtr, 288 bool IsCtorOrDtorName, 289 bool WantNontrivialTypeSourceInfo, 290 bool IsClassTemplateDeductionContext, 291 IdentifierInfo **CorrectedII) { 292 // FIXME: Consider allowing this outside C++1z mode as an extension. 293 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 294 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 295 !isClassName && !HasTrailingDot; 296 297 // Determine where we will perform name lookup. 298 DeclContext *LookupCtx = nullptr; 299 if (ObjectTypePtr) { 300 QualType ObjectType = ObjectTypePtr.get(); 301 if (ObjectType->isRecordType()) 302 LookupCtx = computeDeclContext(ObjectType); 303 } else if (SS && SS->isNotEmpty()) { 304 LookupCtx = computeDeclContext(*SS, false); 305 306 if (!LookupCtx) { 307 if (isDependentScopeSpecifier(*SS)) { 308 // C++ [temp.res]p3: 309 // A qualified-id that refers to a type and in which the 310 // nested-name-specifier depends on a template-parameter (14.6.2) 311 // shall be prefixed by the keyword typename to indicate that the 312 // qualified-id denotes a type, forming an 313 // elaborated-type-specifier (7.1.5.3). 314 // 315 // We therefore do not perform any name lookup if the result would 316 // refer to a member of an unknown specialization. 317 if (!isClassName && !IsCtorOrDtorName) 318 return nullptr; 319 320 // We know from the grammar that this name refers to a type, 321 // so build a dependent node to describe the type. 322 if (WantNontrivialTypeSourceInfo) 323 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 324 325 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 326 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 327 II, NameLoc); 328 return ParsedType::make(T); 329 } 330 331 return nullptr; 332 } 333 334 if (!LookupCtx->isDependentContext() && 335 RequireCompleteDeclContext(*SS, LookupCtx)) 336 return nullptr; 337 } 338 339 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 340 // lookup for class-names. 341 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 342 LookupOrdinaryName; 343 LookupResult Result(*this, &II, NameLoc, Kind); 344 if (LookupCtx) { 345 // Perform "qualified" name lookup into the declaration context we 346 // computed, which is either the type of the base of a member access 347 // expression or the declaration context associated with a prior 348 // nested-name-specifier. 349 LookupQualifiedName(Result, LookupCtx); 350 351 if (ObjectTypePtr && Result.empty()) { 352 // C++ [basic.lookup.classref]p3: 353 // If the unqualified-id is ~type-name, the type-name is looked up 354 // in the context of the entire postfix-expression. If the type T of 355 // the object expression is of a class type C, the type-name is also 356 // looked up in the scope of class C. At least one of the lookups shall 357 // find a name that refers to (possibly cv-qualified) T. 358 LookupName(Result, S); 359 } 360 } else { 361 // Perform unqualified name lookup. 362 LookupName(Result, S); 363 364 // For unqualified lookup in a class template in MSVC mode, look into 365 // dependent base classes where the primary class template is known. 366 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 367 if (ParsedType TypeInBase = 368 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 369 return TypeInBase; 370 } 371 } 372 373 NamedDecl *IIDecl = nullptr; 374 switch (Result.getResultKind()) { 375 case LookupResult::NotFound: 376 case LookupResult::NotFoundInCurrentInstantiation: 377 if (CorrectedII) { 378 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 379 AllowDeducedTemplate); 380 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 381 S, SS, CCC, CTK_ErrorRecovery); 382 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 383 TemplateTy Template; 384 bool MemberOfUnknownSpecialization; 385 UnqualifiedId TemplateName; 386 TemplateName.setIdentifier(NewII, NameLoc); 387 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 388 CXXScopeSpec NewSS, *NewSSPtr = SS; 389 if (SS && NNS) { 390 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 391 NewSSPtr = &NewSS; 392 } 393 if (Correction && (NNS || NewII != &II) && 394 // Ignore a correction to a template type as the to-be-corrected 395 // identifier is not a template (typo correction for template names 396 // is handled elsewhere). 397 !(getLangOpts().CPlusPlus && NewSSPtr && 398 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 399 Template, MemberOfUnknownSpecialization))) { 400 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 401 isClassName, HasTrailingDot, ObjectTypePtr, 402 IsCtorOrDtorName, 403 WantNontrivialTypeSourceInfo, 404 IsClassTemplateDeductionContext); 405 if (Ty) { 406 diagnoseTypo(Correction, 407 PDiag(diag::err_unknown_type_or_class_name_suggest) 408 << Result.getLookupName() << isClassName); 409 if (SS && NNS) 410 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 411 *CorrectedII = NewII; 412 return Ty; 413 } 414 } 415 } 416 // If typo correction failed or was not performed, fall through 417 LLVM_FALLTHROUGH; 418 case LookupResult::FoundOverloaded: 419 case LookupResult::FoundUnresolvedValue: 420 Result.suppressDiagnostics(); 421 return nullptr; 422 423 case LookupResult::Ambiguous: 424 // Recover from type-hiding ambiguities by hiding the type. We'll 425 // do the lookup again when looking for an object, and we can 426 // diagnose the error then. If we don't do this, then the error 427 // about hiding the type will be immediately followed by an error 428 // that only makes sense if the identifier was treated like a type. 429 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 430 Result.suppressDiagnostics(); 431 return nullptr; 432 } 433 434 // Look to see if we have a type anywhere in the list of results. 435 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 436 Res != ResEnd; ++Res) { 437 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 438 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 439 if (!IIDecl || 440 (*Res)->getLocation().getRawEncoding() < 441 IIDecl->getLocation().getRawEncoding()) 442 IIDecl = *Res; 443 } 444 } 445 446 if (!IIDecl) { 447 // None of the entities we found is a type, so there is no way 448 // to even assume that the result is a type. In this case, don't 449 // complain about the ambiguity. The parser will either try to 450 // perform this lookup again (e.g., as an object name), which 451 // will produce the ambiguity, or will complain that it expected 452 // a type name. 453 Result.suppressDiagnostics(); 454 return nullptr; 455 } 456 457 // We found a type within the ambiguous lookup; diagnose the 458 // ambiguity and then return that type. This might be the right 459 // answer, or it might not be, but it suppresses any attempt to 460 // perform the name lookup again. 461 break; 462 463 case LookupResult::Found: 464 IIDecl = Result.getFoundDecl(); 465 break; 466 } 467 468 assert(IIDecl && "Didn't find decl"); 469 470 QualType T; 471 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 472 // C++ [class.qual]p2: A lookup that would find the injected-class-name 473 // instead names the constructors of the class, except when naming a class. 474 // This is ill-formed when we're not actually forming a ctor or dtor name. 475 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 476 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 477 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 478 FoundRD->isInjectedClassName() && 479 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 480 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 481 << &II << /*Type*/1; 482 483 DiagnoseUseOfDecl(IIDecl, NameLoc); 484 485 T = Context.getTypeDeclType(TD); 486 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 487 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 488 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 489 if (!HasTrailingDot) 490 T = Context.getObjCInterfaceType(IDecl); 491 } else if (AllowDeducedTemplate) { 492 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 493 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 494 QualType(), false); 495 } 496 497 if (T.isNull()) { 498 // If it's not plausibly a type, suppress diagnostics. 499 Result.suppressDiagnostics(); 500 return nullptr; 501 } 502 503 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 504 // constructor or destructor name (in such a case, the scope specifier 505 // will be attached to the enclosing Expr or Decl node). 506 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 507 !isa<ObjCInterfaceDecl>(IIDecl)) { 508 if (WantNontrivialTypeSourceInfo) { 509 // Construct a type with type-source information. 510 TypeLocBuilder Builder; 511 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 512 513 T = getElaboratedType(ETK_None, *SS, T); 514 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 515 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 516 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 517 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 518 } else { 519 T = getElaboratedType(ETK_None, *SS, T); 520 } 521 } 522 523 return ParsedType::make(T); 524 } 525 526 // Builds a fake NNS for the given decl context. 527 static NestedNameSpecifier * 528 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 529 for (;; DC = DC->getLookupParent()) { 530 DC = DC->getPrimaryContext(); 531 auto *ND = dyn_cast<NamespaceDecl>(DC); 532 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 533 return NestedNameSpecifier::Create(Context, nullptr, ND); 534 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 535 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 536 RD->getTypeForDecl()); 537 else if (isa<TranslationUnitDecl>(DC)) 538 return NestedNameSpecifier::GlobalSpecifier(Context); 539 } 540 llvm_unreachable("something isn't in TU scope?"); 541 } 542 543 /// Find the parent class with dependent bases of the innermost enclosing method 544 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 545 /// up allowing unqualified dependent type names at class-level, which MSVC 546 /// correctly rejects. 547 static const CXXRecordDecl * 548 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 549 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 550 DC = DC->getPrimaryContext(); 551 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 552 if (MD->getParent()->hasAnyDependentBases()) 553 return MD->getParent(); 554 } 555 return nullptr; 556 } 557 558 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 559 SourceLocation NameLoc, 560 bool IsTemplateTypeArg) { 561 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 562 563 NestedNameSpecifier *NNS = nullptr; 564 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 565 // If we weren't able to parse a default template argument, delay lookup 566 // until instantiation time by making a non-dependent DependentTypeName. We 567 // pretend we saw a NestedNameSpecifier referring to the current scope, and 568 // lookup is retried. 569 // FIXME: This hurts our diagnostic quality, since we get errors like "no 570 // type named 'Foo' in 'current_namespace'" when the user didn't write any 571 // name specifiers. 572 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 573 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 574 } else if (const CXXRecordDecl *RD = 575 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 576 // Build a DependentNameType that will perform lookup into RD at 577 // instantiation time. 578 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 579 RD->getTypeForDecl()); 580 581 // Diagnose that this identifier was undeclared, and retry the lookup during 582 // template instantiation. 583 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 584 << RD; 585 } else { 586 // This is not a situation that we should recover from. 587 return ParsedType(); 588 } 589 590 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 591 592 // Build type location information. We synthesized the qualifier, so we have 593 // to build a fake NestedNameSpecifierLoc. 594 NestedNameSpecifierLocBuilder NNSLocBuilder; 595 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 596 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 597 598 TypeLocBuilder Builder; 599 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 600 DepTL.setNameLoc(NameLoc); 601 DepTL.setElaboratedKeywordLoc(SourceLocation()); 602 DepTL.setQualifierLoc(QualifierLoc); 603 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 604 } 605 606 /// isTagName() - This method is called *for error recovery purposes only* 607 /// to determine if the specified name is a valid tag name ("struct foo"). If 608 /// so, this returns the TST for the tag corresponding to it (TST_enum, 609 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 610 /// cases in C where the user forgot to specify the tag. 611 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 612 // Do a tag name lookup in this scope. 613 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 614 LookupName(R, S, false); 615 R.suppressDiagnostics(); 616 if (R.getResultKind() == LookupResult::Found) 617 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 618 switch (TD->getTagKind()) { 619 case TTK_Struct: return DeclSpec::TST_struct; 620 case TTK_Interface: return DeclSpec::TST_interface; 621 case TTK_Union: return DeclSpec::TST_union; 622 case TTK_Class: return DeclSpec::TST_class; 623 case TTK_Enum: return DeclSpec::TST_enum; 624 } 625 } 626 627 return DeclSpec::TST_unspecified; 628 } 629 630 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 631 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 632 /// then downgrade the missing typename error to a warning. 633 /// This is needed for MSVC compatibility; Example: 634 /// @code 635 /// template<class T> class A { 636 /// public: 637 /// typedef int TYPE; 638 /// }; 639 /// template<class T> class B : public A<T> { 640 /// public: 641 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 642 /// }; 643 /// @endcode 644 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 645 if (CurContext->isRecord()) { 646 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 647 return true; 648 649 const Type *Ty = SS->getScopeRep()->getAsType(); 650 651 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 652 for (const auto &Base : RD->bases()) 653 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 654 return true; 655 return S->isFunctionPrototypeScope(); 656 } 657 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 658 } 659 660 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 661 SourceLocation IILoc, 662 Scope *S, 663 CXXScopeSpec *SS, 664 ParsedType &SuggestedType, 665 bool IsTemplateName) { 666 // Don't report typename errors for editor placeholders. 667 if (II->isEditorPlaceholder()) 668 return; 669 // We don't have anything to suggest (yet). 670 SuggestedType = nullptr; 671 672 // There may have been a typo in the name of the type. Look up typo 673 // results, in case we have something that we can suggest. 674 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 675 /*AllowTemplates=*/IsTemplateName, 676 /*AllowNonTemplates=*/!IsTemplateName); 677 if (TypoCorrection Corrected = 678 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 679 CCC, CTK_ErrorRecovery)) { 680 // FIXME: Support error recovery for the template-name case. 681 bool CanRecover = !IsTemplateName; 682 if (Corrected.isKeyword()) { 683 // We corrected to a keyword. 684 diagnoseTypo(Corrected, 685 PDiag(IsTemplateName ? diag::err_no_template_suggest 686 : diag::err_unknown_typename_suggest) 687 << II); 688 II = Corrected.getCorrectionAsIdentifierInfo(); 689 } else { 690 // We found a similarly-named type or interface; suggest that. 691 if (!SS || !SS->isSet()) { 692 diagnoseTypo(Corrected, 693 PDiag(IsTemplateName ? diag::err_no_template_suggest 694 : diag::err_unknown_typename_suggest) 695 << II, CanRecover); 696 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 697 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 698 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 699 II->getName().equals(CorrectedStr); 700 diagnoseTypo(Corrected, 701 PDiag(IsTemplateName 702 ? diag::err_no_member_template_suggest 703 : diag::err_unknown_nested_typename_suggest) 704 << II << DC << DroppedSpecifier << SS->getRange(), 705 CanRecover); 706 } else { 707 llvm_unreachable("could not have corrected a typo here"); 708 } 709 710 if (!CanRecover) 711 return; 712 713 CXXScopeSpec tmpSS; 714 if (Corrected.getCorrectionSpecifier()) 715 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 716 SourceRange(IILoc)); 717 // FIXME: Support class template argument deduction here. 718 SuggestedType = 719 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 720 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 721 /*IsCtorOrDtorName=*/false, 722 /*WantNontrivialTypeSourceInfo=*/true); 723 } 724 return; 725 } 726 727 if (getLangOpts().CPlusPlus && !IsTemplateName) { 728 // See if II is a class template that the user forgot to pass arguments to. 729 UnqualifiedId Name; 730 Name.setIdentifier(II, IILoc); 731 CXXScopeSpec EmptySS; 732 TemplateTy TemplateResult; 733 bool MemberOfUnknownSpecialization; 734 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 735 Name, nullptr, true, TemplateResult, 736 MemberOfUnknownSpecialization) == TNK_Type_template) { 737 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 738 return; 739 } 740 } 741 742 // FIXME: Should we move the logic that tries to recover from a missing tag 743 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 744 745 if (!SS || (!SS->isSet() && !SS->isInvalid())) 746 Diag(IILoc, IsTemplateName ? diag::err_no_template 747 : diag::err_unknown_typename) 748 << II; 749 else if (DeclContext *DC = computeDeclContext(*SS, false)) 750 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 751 : diag::err_typename_nested_not_found) 752 << II << DC << SS->getRange(); 753 else if (isDependentScopeSpecifier(*SS)) { 754 unsigned DiagID = diag::err_typename_missing; 755 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 756 DiagID = diag::ext_typename_missing; 757 758 Diag(SS->getRange().getBegin(), DiagID) 759 << SS->getScopeRep() << II->getName() 760 << SourceRange(SS->getRange().getBegin(), IILoc) 761 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 762 SuggestedType = ActOnTypenameType(S, SourceLocation(), 763 *SS, *II, IILoc).get(); 764 } else { 765 assert(SS && SS->isInvalid() && 766 "Invalid scope specifier has already been diagnosed"); 767 } 768 } 769 770 /// Determine whether the given result set contains either a type name 771 /// or 772 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 773 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 774 NextToken.is(tok::less); 775 776 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 777 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 778 return true; 779 780 if (CheckTemplate && isa<TemplateDecl>(*I)) 781 return true; 782 } 783 784 return false; 785 } 786 787 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 788 Scope *S, CXXScopeSpec &SS, 789 IdentifierInfo *&Name, 790 SourceLocation NameLoc) { 791 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 792 SemaRef.LookupParsedName(R, S, &SS); 793 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 794 StringRef FixItTagName; 795 switch (Tag->getTagKind()) { 796 case TTK_Class: 797 FixItTagName = "class "; 798 break; 799 800 case TTK_Enum: 801 FixItTagName = "enum "; 802 break; 803 804 case TTK_Struct: 805 FixItTagName = "struct "; 806 break; 807 808 case TTK_Interface: 809 FixItTagName = "__interface "; 810 break; 811 812 case TTK_Union: 813 FixItTagName = "union "; 814 break; 815 } 816 817 StringRef TagName = FixItTagName.drop_back(); 818 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 819 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 820 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 821 822 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 823 I != IEnd; ++I) 824 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 825 << Name << TagName; 826 827 // Replace lookup results with just the tag decl. 828 Result.clear(Sema::LookupTagName); 829 SemaRef.LookupParsedName(Result, S, &SS); 830 return true; 831 } 832 833 return false; 834 } 835 836 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 837 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 838 QualType T, SourceLocation NameLoc) { 839 ASTContext &Context = S.Context; 840 841 TypeLocBuilder Builder; 842 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 843 844 T = S.getElaboratedType(ETK_None, SS, T); 845 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 846 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 847 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 848 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 849 } 850 851 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 852 IdentifierInfo *&Name, 853 SourceLocation NameLoc, 854 const Token &NextToken, 855 CorrectionCandidateCallback *CCC) { 856 DeclarationNameInfo NameInfo(Name, NameLoc); 857 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 858 859 assert(NextToken.isNot(tok::coloncolon) && 860 "parse nested name specifiers before calling ClassifyName"); 861 if (getLangOpts().CPlusPlus && SS.isSet() && 862 isCurrentClassName(*Name, S, &SS)) { 863 // Per [class.qual]p2, this names the constructors of SS, not the 864 // injected-class-name. We don't have a classification for that. 865 // There's not much point caching this result, since the parser 866 // will reject it later. 867 return NameClassification::Unknown(); 868 } 869 870 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 871 LookupParsedName(Result, S, &SS, !CurMethod); 872 873 if (SS.isInvalid()) 874 return NameClassification::Error(); 875 876 // For unqualified lookup in a class template in MSVC mode, look into 877 // dependent base classes where the primary class template is known. 878 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 879 if (ParsedType TypeInBase = 880 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 881 return TypeInBase; 882 } 883 884 // Perform lookup for Objective-C instance variables (including automatically 885 // synthesized instance variables), if we're in an Objective-C method. 886 // FIXME: This lookup really, really needs to be folded in to the normal 887 // unqualified lookup mechanism. 888 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 889 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 890 if (Ivar.isInvalid()) 891 return NameClassification::Error(); 892 if (Ivar.isUsable()) 893 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 894 895 // We defer builtin creation until after ivar lookup inside ObjC methods. 896 if (Result.empty()) 897 LookupBuiltin(Result); 898 } 899 900 bool SecondTry = false; 901 bool IsFilteredTemplateName = false; 902 903 Corrected: 904 switch (Result.getResultKind()) { 905 case LookupResult::NotFound: 906 // If an unqualified-id is followed by a '(', then we have a function 907 // call. 908 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 909 // In C++, this is an ADL-only call. 910 // FIXME: Reference? 911 if (getLangOpts().CPlusPlus) 912 return NameClassification::UndeclaredNonType(); 913 914 // C90 6.3.2.2: 915 // If the expression that precedes the parenthesized argument list in a 916 // function call consists solely of an identifier, and if no 917 // declaration is visible for this identifier, the identifier is 918 // implicitly declared exactly as if, in the innermost block containing 919 // the function call, the declaration 920 // 921 // extern int identifier (); 922 // 923 // appeared. 924 // 925 // We also allow this in C99 as an extension. 926 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 927 return NameClassification::NonType(D); 928 } 929 930 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 931 // In C++20 onwards, this could be an ADL-only call to a function 932 // template, and we're required to assume that this is a template name. 933 // 934 // FIXME: Find a way to still do typo correction in this case. 935 TemplateName Template = 936 Context.getAssumedTemplateName(NameInfo.getName()); 937 return NameClassification::UndeclaredTemplate(Template); 938 } 939 940 // In C, we first see whether there is a tag type by the same name, in 941 // which case it's likely that the user just forgot to write "enum", 942 // "struct", or "union". 943 if (!getLangOpts().CPlusPlus && !SecondTry && 944 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 945 break; 946 } 947 948 // Perform typo correction to determine if there is another name that is 949 // close to this name. 950 if (!SecondTry && CCC) { 951 SecondTry = true; 952 if (TypoCorrection Corrected = 953 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 954 &SS, *CCC, CTK_ErrorRecovery)) { 955 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 956 unsigned QualifiedDiag = diag::err_no_member_suggest; 957 958 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 959 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 960 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 961 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 962 UnqualifiedDiag = diag::err_no_template_suggest; 963 QualifiedDiag = diag::err_no_member_template_suggest; 964 } else if (UnderlyingFirstDecl && 965 (isa<TypeDecl>(UnderlyingFirstDecl) || 966 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 967 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 968 UnqualifiedDiag = diag::err_unknown_typename_suggest; 969 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 970 } 971 972 if (SS.isEmpty()) { 973 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 974 } else {// FIXME: is this even reachable? Test it. 975 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 976 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 977 Name->getName().equals(CorrectedStr); 978 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 979 << Name << computeDeclContext(SS, false) 980 << DroppedSpecifier << SS.getRange()); 981 } 982 983 // Update the name, so that the caller has the new name. 984 Name = Corrected.getCorrectionAsIdentifierInfo(); 985 986 // Typo correction corrected to a keyword. 987 if (Corrected.isKeyword()) 988 return Name; 989 990 // Also update the LookupResult... 991 // FIXME: This should probably go away at some point 992 Result.clear(); 993 Result.setLookupName(Corrected.getCorrection()); 994 if (FirstDecl) 995 Result.addDecl(FirstDecl); 996 997 // If we found an Objective-C instance variable, let 998 // LookupInObjCMethod build the appropriate expression to 999 // reference the ivar. 1000 // FIXME: This is a gross hack. 1001 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1002 DeclResult R = 1003 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1004 if (R.isInvalid()) 1005 return NameClassification::Error(); 1006 if (R.isUsable()) 1007 return NameClassification::NonType(Ivar); 1008 } 1009 1010 goto Corrected; 1011 } 1012 } 1013 1014 // We failed to correct; just fall through and let the parser deal with it. 1015 Result.suppressDiagnostics(); 1016 return NameClassification::Unknown(); 1017 1018 case LookupResult::NotFoundInCurrentInstantiation: { 1019 // We performed name lookup into the current instantiation, and there were 1020 // dependent bases, so we treat this result the same way as any other 1021 // dependent nested-name-specifier. 1022 1023 // C++ [temp.res]p2: 1024 // A name used in a template declaration or definition and that is 1025 // dependent on a template-parameter is assumed not to name a type 1026 // unless the applicable name lookup finds a type name or the name is 1027 // qualified by the keyword typename. 1028 // 1029 // FIXME: If the next token is '<', we might want to ask the parser to 1030 // perform some heroics to see if we actually have a 1031 // template-argument-list, which would indicate a missing 'template' 1032 // keyword here. 1033 return NameClassification::DependentNonType(); 1034 } 1035 1036 case LookupResult::Found: 1037 case LookupResult::FoundOverloaded: 1038 case LookupResult::FoundUnresolvedValue: 1039 break; 1040 1041 case LookupResult::Ambiguous: 1042 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1043 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1044 /*AllowDependent=*/false)) { 1045 // C++ [temp.local]p3: 1046 // A lookup that finds an injected-class-name (10.2) can result in an 1047 // ambiguity in certain cases (for example, if it is found in more than 1048 // one base class). If all of the injected-class-names that are found 1049 // refer to specializations of the same class template, and if the name 1050 // is followed by a template-argument-list, the reference refers to the 1051 // class template itself and not a specialization thereof, and is not 1052 // ambiguous. 1053 // 1054 // This filtering can make an ambiguous result into an unambiguous one, 1055 // so try again after filtering out template names. 1056 FilterAcceptableTemplateNames(Result); 1057 if (!Result.isAmbiguous()) { 1058 IsFilteredTemplateName = true; 1059 break; 1060 } 1061 } 1062 1063 // Diagnose the ambiguity and return an error. 1064 return NameClassification::Error(); 1065 } 1066 1067 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1068 (IsFilteredTemplateName || 1069 hasAnyAcceptableTemplateNames( 1070 Result, /*AllowFunctionTemplates=*/true, 1071 /*AllowDependent=*/false, 1072 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1073 getLangOpts().CPlusPlus20))) { 1074 // C++ [temp.names]p3: 1075 // After name lookup (3.4) finds that a name is a template-name or that 1076 // an operator-function-id or a literal- operator-id refers to a set of 1077 // overloaded functions any member of which is a function template if 1078 // this is followed by a <, the < is always taken as the delimiter of a 1079 // template-argument-list and never as the less-than operator. 1080 // C++2a [temp.names]p2: 1081 // A name is also considered to refer to a template if it is an 1082 // unqualified-id followed by a < and name lookup finds either one 1083 // or more functions or finds nothing. 1084 if (!IsFilteredTemplateName) 1085 FilterAcceptableTemplateNames(Result); 1086 1087 bool IsFunctionTemplate; 1088 bool IsVarTemplate; 1089 TemplateName Template; 1090 if (Result.end() - Result.begin() > 1) { 1091 IsFunctionTemplate = true; 1092 Template = Context.getOverloadedTemplateName(Result.begin(), 1093 Result.end()); 1094 } else if (!Result.empty()) { 1095 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1096 *Result.begin(), /*AllowFunctionTemplates=*/true, 1097 /*AllowDependent=*/false)); 1098 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1099 IsVarTemplate = isa<VarTemplateDecl>(TD); 1100 1101 if (SS.isNotEmpty()) 1102 Template = 1103 Context.getQualifiedTemplateName(SS.getScopeRep(), 1104 /*TemplateKeyword=*/false, TD); 1105 else 1106 Template = TemplateName(TD); 1107 } else { 1108 // All results were non-template functions. This is a function template 1109 // name. 1110 IsFunctionTemplate = true; 1111 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1112 } 1113 1114 if (IsFunctionTemplate) { 1115 // Function templates always go through overload resolution, at which 1116 // point we'll perform the various checks (e.g., accessibility) we need 1117 // to based on which function we selected. 1118 Result.suppressDiagnostics(); 1119 1120 return NameClassification::FunctionTemplate(Template); 1121 } 1122 1123 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1124 : NameClassification::TypeTemplate(Template); 1125 } 1126 1127 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1128 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1129 DiagnoseUseOfDecl(Type, NameLoc); 1130 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1131 QualType T = Context.getTypeDeclType(Type); 1132 if (SS.isNotEmpty()) 1133 return buildNestedType(*this, SS, T, NameLoc); 1134 return ParsedType::make(T); 1135 } 1136 1137 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1138 if (!Class) { 1139 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1140 if (ObjCCompatibleAliasDecl *Alias = 1141 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1142 Class = Alias->getClassInterface(); 1143 } 1144 1145 if (Class) { 1146 DiagnoseUseOfDecl(Class, NameLoc); 1147 1148 if (NextToken.is(tok::period)) { 1149 // Interface. <something> is parsed as a property reference expression. 1150 // Just return "unknown" as a fall-through for now. 1151 Result.suppressDiagnostics(); 1152 return NameClassification::Unknown(); 1153 } 1154 1155 QualType T = Context.getObjCInterfaceType(Class); 1156 return ParsedType::make(T); 1157 } 1158 1159 if (isa<ConceptDecl>(FirstDecl)) 1160 return NameClassification::Concept( 1161 TemplateName(cast<TemplateDecl>(FirstDecl))); 1162 1163 // We can have a type template here if we're classifying a template argument. 1164 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1165 !isa<VarTemplateDecl>(FirstDecl)) 1166 return NameClassification::TypeTemplate( 1167 TemplateName(cast<TemplateDecl>(FirstDecl))); 1168 1169 // Check for a tag type hidden by a non-type decl in a few cases where it 1170 // seems likely a type is wanted instead of the non-type that was found. 1171 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1172 if ((NextToken.is(tok::identifier) || 1173 (NextIsOp && 1174 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1175 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1176 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1177 DiagnoseUseOfDecl(Type, NameLoc); 1178 QualType T = Context.getTypeDeclType(Type); 1179 if (SS.isNotEmpty()) 1180 return buildNestedType(*this, SS, T, NameLoc); 1181 return ParsedType::make(T); 1182 } 1183 1184 // FIXME: This is context-dependent. We need to defer building the member 1185 // expression until the classification is consumed. 1186 if (FirstDecl->isCXXClassMember()) 1187 return NameClassification::ContextIndependentExpr( 1188 BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr, 1189 S)); 1190 1191 // If we already know which single declaration is referenced, just annotate 1192 // that declaration directly. 1193 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1194 if (Result.isSingleResult() && !ADL) 1195 return NameClassification::NonType(Result.getRepresentativeDecl()); 1196 1197 // Build an UnresolvedLookupExpr. Note that this doesn't depend on the 1198 // context in which we performed classification, so it's safe to do now. 1199 return NameClassification::ContextIndependentExpr( 1200 BuildDeclarationNameExpr(SS, Result, ADL)); 1201 } 1202 1203 ExprResult 1204 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1205 SourceLocation NameLoc) { 1206 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1207 CXXScopeSpec SS; 1208 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1209 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1210 } 1211 1212 ExprResult 1213 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1214 IdentifierInfo *Name, 1215 SourceLocation NameLoc, 1216 bool IsAddressOfOperand) { 1217 DeclarationNameInfo NameInfo(Name, NameLoc); 1218 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1219 NameInfo, IsAddressOfOperand, 1220 /*TemplateArgs=*/nullptr); 1221 } 1222 1223 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1224 NamedDecl *Found, 1225 SourceLocation NameLoc, 1226 const Token &NextToken) { 1227 if (getCurMethodDecl() && SS.isEmpty()) 1228 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1229 return BuildIvarRefExpr(S, NameLoc, Ivar); 1230 1231 // Reconstruct the lookup result. 1232 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1233 Result.addDecl(Found); 1234 Result.resolveKind(); 1235 1236 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1237 return BuildDeclarationNameExpr(SS, Result, ADL); 1238 } 1239 1240 Sema::TemplateNameKindForDiagnostics 1241 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1242 auto *TD = Name.getAsTemplateDecl(); 1243 if (!TD) 1244 return TemplateNameKindForDiagnostics::DependentTemplate; 1245 if (isa<ClassTemplateDecl>(TD)) 1246 return TemplateNameKindForDiagnostics::ClassTemplate; 1247 if (isa<FunctionTemplateDecl>(TD)) 1248 return TemplateNameKindForDiagnostics::FunctionTemplate; 1249 if (isa<VarTemplateDecl>(TD)) 1250 return TemplateNameKindForDiagnostics::VarTemplate; 1251 if (isa<TypeAliasTemplateDecl>(TD)) 1252 return TemplateNameKindForDiagnostics::AliasTemplate; 1253 if (isa<TemplateTemplateParmDecl>(TD)) 1254 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1255 if (isa<ConceptDecl>(TD)) 1256 return TemplateNameKindForDiagnostics::Concept; 1257 return TemplateNameKindForDiagnostics::DependentTemplate; 1258 } 1259 1260 // Determines the context to return to after temporarily entering a 1261 // context. This depends in an unnecessarily complicated way on the 1262 // exact ordering of callbacks from the parser. 1263 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1264 1265 // Functions defined inline within classes aren't parsed until we've 1266 // finished parsing the top-level class, so the top-level class is 1267 // the context we'll need to return to. 1268 // A Lambda call operator whose parent is a class must not be treated 1269 // as an inline member function. A Lambda can be used legally 1270 // either as an in-class member initializer or a default argument. These 1271 // are parsed once the class has been marked complete and so the containing 1272 // context would be the nested class (when the lambda is defined in one); 1273 // If the class is not complete, then the lambda is being used in an 1274 // ill-formed fashion (such as to specify the width of a bit-field, or 1275 // in an array-bound) - in which case we still want to return the 1276 // lexically containing DC (which could be a nested class). 1277 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1278 DC = DC->getLexicalParent(); 1279 1280 // A function not defined within a class will always return to its 1281 // lexical context. 1282 if (!isa<CXXRecordDecl>(DC)) 1283 return DC; 1284 1285 // A C++ inline method/friend is parsed *after* the topmost class 1286 // it was declared in is fully parsed ("complete"); the topmost 1287 // class is the context we need to return to. 1288 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1289 DC = RD; 1290 1291 // Return the declaration context of the topmost class the inline method is 1292 // declared in. 1293 return DC; 1294 } 1295 1296 return DC->getLexicalParent(); 1297 } 1298 1299 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1300 assert(getContainingDC(DC) == CurContext && 1301 "The next DeclContext should be lexically contained in the current one."); 1302 CurContext = DC; 1303 S->setEntity(DC); 1304 } 1305 1306 void Sema::PopDeclContext() { 1307 assert(CurContext && "DeclContext imbalance!"); 1308 1309 CurContext = getContainingDC(CurContext); 1310 assert(CurContext && "Popped translation unit!"); 1311 } 1312 1313 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1314 Decl *D) { 1315 // Unlike PushDeclContext, the context to which we return is not necessarily 1316 // the containing DC of TD, because the new context will be some pre-existing 1317 // TagDecl definition instead of a fresh one. 1318 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1319 CurContext = cast<TagDecl>(D)->getDefinition(); 1320 assert(CurContext && "skipping definition of undefined tag"); 1321 // Start lookups from the parent of the current context; we don't want to look 1322 // into the pre-existing complete definition. 1323 S->setEntity(CurContext->getLookupParent()); 1324 return Result; 1325 } 1326 1327 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1328 CurContext = static_cast<decltype(CurContext)>(Context); 1329 } 1330 1331 /// EnterDeclaratorContext - Used when we must lookup names in the context 1332 /// of a declarator's nested name specifier. 1333 /// 1334 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1335 // C++0x [basic.lookup.unqual]p13: 1336 // A name used in the definition of a static data member of class 1337 // X (after the qualified-id of the static member) is looked up as 1338 // if the name was used in a member function of X. 1339 // C++0x [basic.lookup.unqual]p14: 1340 // If a variable member of a namespace is defined outside of the 1341 // scope of its namespace then any name used in the definition of 1342 // the variable member (after the declarator-id) is looked up as 1343 // if the definition of the variable member occurred in its 1344 // namespace. 1345 // Both of these imply that we should push a scope whose context 1346 // is the semantic context of the declaration. We can't use 1347 // PushDeclContext here because that context is not necessarily 1348 // lexically contained in the current context. Fortunately, 1349 // the containing scope should have the appropriate information. 1350 1351 assert(!S->getEntity() && "scope already has entity"); 1352 1353 #ifndef NDEBUG 1354 Scope *Ancestor = S->getParent(); 1355 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1356 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1357 #endif 1358 1359 CurContext = DC; 1360 S->setEntity(DC); 1361 } 1362 1363 void Sema::ExitDeclaratorContext(Scope *S) { 1364 assert(S->getEntity() == CurContext && "Context imbalance!"); 1365 1366 // Switch back to the lexical context. The safety of this is 1367 // enforced by an assert in EnterDeclaratorContext. 1368 Scope *Ancestor = S->getParent(); 1369 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1370 CurContext = Ancestor->getEntity(); 1371 1372 // We don't need to do anything with the scope, which is going to 1373 // disappear. 1374 } 1375 1376 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1377 // We assume that the caller has already called 1378 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1379 FunctionDecl *FD = D->getAsFunction(); 1380 if (!FD) 1381 return; 1382 1383 // Same implementation as PushDeclContext, but enters the context 1384 // from the lexical parent, rather than the top-level class. 1385 assert(CurContext == FD->getLexicalParent() && 1386 "The next DeclContext should be lexically contained in the current one."); 1387 CurContext = FD; 1388 S->setEntity(CurContext); 1389 1390 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1391 ParmVarDecl *Param = FD->getParamDecl(P); 1392 // If the parameter has an identifier, then add it to the scope 1393 if (Param->getIdentifier()) { 1394 S->AddDecl(Param); 1395 IdResolver.AddDecl(Param); 1396 } 1397 } 1398 } 1399 1400 void Sema::ActOnExitFunctionContext() { 1401 // Same implementation as PopDeclContext, but returns to the lexical parent, 1402 // rather than the top-level class. 1403 assert(CurContext && "DeclContext imbalance!"); 1404 CurContext = CurContext->getLexicalParent(); 1405 assert(CurContext && "Popped translation unit!"); 1406 } 1407 1408 /// Determine whether we allow overloading of the function 1409 /// PrevDecl with another declaration. 1410 /// 1411 /// This routine determines whether overloading is possible, not 1412 /// whether some new function is actually an overload. It will return 1413 /// true in C++ (where we can always provide overloads) or, as an 1414 /// extension, in C when the previous function is already an 1415 /// overloaded function declaration or has the "overloadable" 1416 /// attribute. 1417 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1418 ASTContext &Context, 1419 const FunctionDecl *New) { 1420 if (Context.getLangOpts().CPlusPlus) 1421 return true; 1422 1423 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1424 return true; 1425 1426 return Previous.getResultKind() == LookupResult::Found && 1427 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1428 New->hasAttr<OverloadableAttr>()); 1429 } 1430 1431 /// Add this decl to the scope shadowed decl chains. 1432 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1433 // Move up the scope chain until we find the nearest enclosing 1434 // non-transparent context. The declaration will be introduced into this 1435 // scope. 1436 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1437 S = S->getParent(); 1438 1439 // Add scoped declarations into their context, so that they can be 1440 // found later. Declarations without a context won't be inserted 1441 // into any context. 1442 if (AddToContext) 1443 CurContext->addDecl(D); 1444 1445 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1446 // are function-local declarations. 1447 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1448 !D->getDeclContext()->getRedeclContext()->Equals( 1449 D->getLexicalDeclContext()->getRedeclContext()) && 1450 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1451 return; 1452 1453 // Template instantiations should also not be pushed into scope. 1454 if (isa<FunctionDecl>(D) && 1455 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1456 return; 1457 1458 // If this replaces anything in the current scope, 1459 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1460 IEnd = IdResolver.end(); 1461 for (; I != IEnd; ++I) { 1462 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1463 S->RemoveDecl(*I); 1464 IdResolver.RemoveDecl(*I); 1465 1466 // Should only need to replace one decl. 1467 break; 1468 } 1469 } 1470 1471 S->AddDecl(D); 1472 1473 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1474 // Implicitly-generated labels may end up getting generated in an order that 1475 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1476 // the label at the appropriate place in the identifier chain. 1477 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1478 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1479 if (IDC == CurContext) { 1480 if (!S->isDeclScope(*I)) 1481 continue; 1482 } else if (IDC->Encloses(CurContext)) 1483 break; 1484 } 1485 1486 IdResolver.InsertDeclAfter(I, D); 1487 } else { 1488 IdResolver.AddDecl(D); 1489 } 1490 } 1491 1492 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1493 bool AllowInlineNamespace) { 1494 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1495 } 1496 1497 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1498 DeclContext *TargetDC = DC->getPrimaryContext(); 1499 do { 1500 if (DeclContext *ScopeDC = S->getEntity()) 1501 if (ScopeDC->getPrimaryContext() == TargetDC) 1502 return S; 1503 } while ((S = S->getParent())); 1504 1505 return nullptr; 1506 } 1507 1508 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1509 DeclContext*, 1510 ASTContext&); 1511 1512 /// Filters out lookup results that don't fall within the given scope 1513 /// as determined by isDeclInScope. 1514 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1515 bool ConsiderLinkage, 1516 bool AllowInlineNamespace) { 1517 LookupResult::Filter F = R.makeFilter(); 1518 while (F.hasNext()) { 1519 NamedDecl *D = F.next(); 1520 1521 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1522 continue; 1523 1524 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1525 continue; 1526 1527 F.erase(); 1528 } 1529 1530 F.done(); 1531 } 1532 1533 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1534 /// have compatible owning modules. 1535 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1536 // FIXME: The Modules TS is not clear about how friend declarations are 1537 // to be treated. It's not meaningful to have different owning modules for 1538 // linkage in redeclarations of the same entity, so for now allow the 1539 // redeclaration and change the owning modules to match. 1540 if (New->getFriendObjectKind() && 1541 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1542 New->setLocalOwningModule(Old->getOwningModule()); 1543 makeMergedDefinitionVisible(New); 1544 return false; 1545 } 1546 1547 Module *NewM = New->getOwningModule(); 1548 Module *OldM = Old->getOwningModule(); 1549 1550 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1551 NewM = NewM->Parent; 1552 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1553 OldM = OldM->Parent; 1554 1555 if (NewM == OldM) 1556 return false; 1557 1558 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1559 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1560 if (NewIsModuleInterface || OldIsModuleInterface) { 1561 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1562 // if a declaration of D [...] appears in the purview of a module, all 1563 // other such declarations shall appear in the purview of the same module 1564 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1565 << New 1566 << NewIsModuleInterface 1567 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1568 << OldIsModuleInterface 1569 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1570 Diag(Old->getLocation(), diag::note_previous_declaration); 1571 New->setInvalidDecl(); 1572 return true; 1573 } 1574 1575 return false; 1576 } 1577 1578 static bool isUsingDecl(NamedDecl *D) { 1579 return isa<UsingShadowDecl>(D) || 1580 isa<UnresolvedUsingTypenameDecl>(D) || 1581 isa<UnresolvedUsingValueDecl>(D); 1582 } 1583 1584 /// Removes using shadow declarations from the lookup results. 1585 static void RemoveUsingDecls(LookupResult &R) { 1586 LookupResult::Filter F = R.makeFilter(); 1587 while (F.hasNext()) 1588 if (isUsingDecl(F.next())) 1589 F.erase(); 1590 1591 F.done(); 1592 } 1593 1594 /// Check for this common pattern: 1595 /// @code 1596 /// class S { 1597 /// S(const S&); // DO NOT IMPLEMENT 1598 /// void operator=(const S&); // DO NOT IMPLEMENT 1599 /// }; 1600 /// @endcode 1601 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1602 // FIXME: Should check for private access too but access is set after we get 1603 // the decl here. 1604 if (D->doesThisDeclarationHaveABody()) 1605 return false; 1606 1607 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1608 return CD->isCopyConstructor(); 1609 return D->isCopyAssignmentOperator(); 1610 } 1611 1612 // We need this to handle 1613 // 1614 // typedef struct { 1615 // void *foo() { return 0; } 1616 // } A; 1617 // 1618 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1619 // for example. If 'A', foo will have external linkage. If we have '*A', 1620 // foo will have no linkage. Since we can't know until we get to the end 1621 // of the typedef, this function finds out if D might have non-external linkage. 1622 // Callers should verify at the end of the TU if it D has external linkage or 1623 // not. 1624 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1625 const DeclContext *DC = D->getDeclContext(); 1626 while (!DC->isTranslationUnit()) { 1627 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1628 if (!RD->hasNameForLinkage()) 1629 return true; 1630 } 1631 DC = DC->getParent(); 1632 } 1633 1634 return !D->isExternallyVisible(); 1635 } 1636 1637 // FIXME: This needs to be refactored; some other isInMainFile users want 1638 // these semantics. 1639 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1640 if (S.TUKind != TU_Complete) 1641 return false; 1642 return S.SourceMgr.isInMainFile(Loc); 1643 } 1644 1645 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1646 assert(D); 1647 1648 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1649 return false; 1650 1651 // Ignore all entities declared within templates, and out-of-line definitions 1652 // of members of class templates. 1653 if (D->getDeclContext()->isDependentContext() || 1654 D->getLexicalDeclContext()->isDependentContext()) 1655 return false; 1656 1657 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1658 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1659 return false; 1660 // A non-out-of-line declaration of a member specialization was implicitly 1661 // instantiated; it's the out-of-line declaration that we're interested in. 1662 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1663 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1664 return false; 1665 1666 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1667 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1668 return false; 1669 } else { 1670 // 'static inline' functions are defined in headers; don't warn. 1671 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1672 return false; 1673 } 1674 1675 if (FD->doesThisDeclarationHaveABody() && 1676 Context.DeclMustBeEmitted(FD)) 1677 return false; 1678 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1679 // Constants and utility variables are defined in headers with internal 1680 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1681 // like "inline".) 1682 if (!isMainFileLoc(*this, VD->getLocation())) 1683 return false; 1684 1685 if (Context.DeclMustBeEmitted(VD)) 1686 return false; 1687 1688 if (VD->isStaticDataMember() && 1689 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1690 return false; 1691 if (VD->isStaticDataMember() && 1692 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1693 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1694 return false; 1695 1696 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1697 return false; 1698 } else { 1699 return false; 1700 } 1701 1702 // Only warn for unused decls internal to the translation unit. 1703 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1704 // for inline functions defined in the main source file, for instance. 1705 return mightHaveNonExternalLinkage(D); 1706 } 1707 1708 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1709 if (!D) 1710 return; 1711 1712 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1713 const FunctionDecl *First = FD->getFirstDecl(); 1714 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1715 return; // First should already be in the vector. 1716 } 1717 1718 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1719 const VarDecl *First = VD->getFirstDecl(); 1720 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1721 return; // First should already be in the vector. 1722 } 1723 1724 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1725 UnusedFileScopedDecls.push_back(D); 1726 } 1727 1728 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1729 if (D->isInvalidDecl()) 1730 return false; 1731 1732 bool Referenced = false; 1733 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1734 // For a decomposition declaration, warn if none of the bindings are 1735 // referenced, instead of if the variable itself is referenced (which 1736 // it is, by the bindings' expressions). 1737 for (auto *BD : DD->bindings()) { 1738 if (BD->isReferenced()) { 1739 Referenced = true; 1740 break; 1741 } 1742 } 1743 } else if (!D->getDeclName()) { 1744 return false; 1745 } else if (D->isReferenced() || D->isUsed()) { 1746 Referenced = true; 1747 } 1748 1749 if (Referenced || D->hasAttr<UnusedAttr>() || 1750 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1751 return false; 1752 1753 if (isa<LabelDecl>(D)) 1754 return true; 1755 1756 // Except for labels, we only care about unused decls that are local to 1757 // functions. 1758 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1759 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1760 // For dependent types, the diagnostic is deferred. 1761 WithinFunction = 1762 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1763 if (!WithinFunction) 1764 return false; 1765 1766 if (isa<TypedefNameDecl>(D)) 1767 return true; 1768 1769 // White-list anything that isn't a local variable. 1770 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1771 return false; 1772 1773 // Types of valid local variables should be complete, so this should succeed. 1774 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1775 1776 // White-list anything with an __attribute__((unused)) type. 1777 const auto *Ty = VD->getType().getTypePtr(); 1778 1779 // Only look at the outermost level of typedef. 1780 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1781 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1782 return false; 1783 } 1784 1785 // If we failed to complete the type for some reason, or if the type is 1786 // dependent, don't diagnose the variable. 1787 if (Ty->isIncompleteType() || Ty->isDependentType()) 1788 return false; 1789 1790 // Look at the element type to ensure that the warning behaviour is 1791 // consistent for both scalars and arrays. 1792 Ty = Ty->getBaseElementTypeUnsafe(); 1793 1794 if (const TagType *TT = Ty->getAs<TagType>()) { 1795 const TagDecl *Tag = TT->getDecl(); 1796 if (Tag->hasAttr<UnusedAttr>()) 1797 return false; 1798 1799 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1800 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1801 return false; 1802 1803 if (const Expr *Init = VD->getInit()) { 1804 if (const ExprWithCleanups *Cleanups = 1805 dyn_cast<ExprWithCleanups>(Init)) 1806 Init = Cleanups->getSubExpr(); 1807 const CXXConstructExpr *Construct = 1808 dyn_cast<CXXConstructExpr>(Init); 1809 if (Construct && !Construct->isElidable()) { 1810 CXXConstructorDecl *CD = Construct->getConstructor(); 1811 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1812 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1813 return false; 1814 } 1815 1816 // Suppress the warning if we don't know how this is constructed, and 1817 // it could possibly be non-trivial constructor. 1818 if (Init->isTypeDependent()) 1819 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1820 if (!Ctor->isTrivial()) 1821 return false; 1822 } 1823 } 1824 } 1825 1826 // TODO: __attribute__((unused)) templates? 1827 } 1828 1829 return true; 1830 } 1831 1832 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1833 FixItHint &Hint) { 1834 if (isa<LabelDecl>(D)) { 1835 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1836 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1837 true); 1838 if (AfterColon.isInvalid()) 1839 return; 1840 Hint = FixItHint::CreateRemoval( 1841 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1842 } 1843 } 1844 1845 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1846 if (D->getTypeForDecl()->isDependentType()) 1847 return; 1848 1849 for (auto *TmpD : D->decls()) { 1850 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1851 DiagnoseUnusedDecl(T); 1852 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1853 DiagnoseUnusedNestedTypedefs(R); 1854 } 1855 } 1856 1857 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1858 /// unless they are marked attr(unused). 1859 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1860 if (!ShouldDiagnoseUnusedDecl(D)) 1861 return; 1862 1863 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1864 // typedefs can be referenced later on, so the diagnostics are emitted 1865 // at end-of-translation-unit. 1866 UnusedLocalTypedefNameCandidates.insert(TD); 1867 return; 1868 } 1869 1870 FixItHint Hint; 1871 GenerateFixForUnusedDecl(D, Context, Hint); 1872 1873 unsigned DiagID; 1874 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1875 DiagID = diag::warn_unused_exception_param; 1876 else if (isa<LabelDecl>(D)) 1877 DiagID = diag::warn_unused_label; 1878 else 1879 DiagID = diag::warn_unused_variable; 1880 1881 Diag(D->getLocation(), DiagID) << D << Hint; 1882 } 1883 1884 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1885 // Verify that we have no forward references left. If so, there was a goto 1886 // or address of a label taken, but no definition of it. Label fwd 1887 // definitions are indicated with a null substmt which is also not a resolved 1888 // MS inline assembly label name. 1889 bool Diagnose = false; 1890 if (L->isMSAsmLabel()) 1891 Diagnose = !L->isResolvedMSAsmLabel(); 1892 else 1893 Diagnose = L->getStmt() == nullptr; 1894 if (Diagnose) 1895 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1896 } 1897 1898 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1899 S->mergeNRVOIntoParent(); 1900 1901 if (S->decl_empty()) return; 1902 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1903 "Scope shouldn't contain decls!"); 1904 1905 for (auto *TmpD : S->decls()) { 1906 assert(TmpD && "This decl didn't get pushed??"); 1907 1908 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1909 NamedDecl *D = cast<NamedDecl>(TmpD); 1910 1911 // Diagnose unused variables in this scope. 1912 if (!S->hasUnrecoverableErrorOccurred()) { 1913 DiagnoseUnusedDecl(D); 1914 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1915 DiagnoseUnusedNestedTypedefs(RD); 1916 } 1917 1918 if (!D->getDeclName()) continue; 1919 1920 // If this was a forward reference to a label, verify it was defined. 1921 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1922 CheckPoppedLabel(LD, *this); 1923 1924 // Remove this name from our lexical scope, and warn on it if we haven't 1925 // already. 1926 IdResolver.RemoveDecl(D); 1927 auto ShadowI = ShadowingDecls.find(D); 1928 if (ShadowI != ShadowingDecls.end()) { 1929 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1930 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1931 << D << FD << FD->getParent(); 1932 Diag(FD->getLocation(), diag::note_previous_declaration); 1933 } 1934 ShadowingDecls.erase(ShadowI); 1935 } 1936 } 1937 } 1938 1939 /// Look for an Objective-C class in the translation unit. 1940 /// 1941 /// \param Id The name of the Objective-C class we're looking for. If 1942 /// typo-correction fixes this name, the Id will be updated 1943 /// to the fixed name. 1944 /// 1945 /// \param IdLoc The location of the name in the translation unit. 1946 /// 1947 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1948 /// if there is no class with the given name. 1949 /// 1950 /// \returns The declaration of the named Objective-C class, or NULL if the 1951 /// class could not be found. 1952 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1953 SourceLocation IdLoc, 1954 bool DoTypoCorrection) { 1955 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1956 // creation from this context. 1957 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1958 1959 if (!IDecl && DoTypoCorrection) { 1960 // Perform typo correction at the given location, but only if we 1961 // find an Objective-C class name. 1962 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1963 if (TypoCorrection C = 1964 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1965 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1966 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1967 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1968 Id = IDecl->getIdentifier(); 1969 } 1970 } 1971 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1972 // This routine must always return a class definition, if any. 1973 if (Def && Def->getDefinition()) 1974 Def = Def->getDefinition(); 1975 return Def; 1976 } 1977 1978 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1979 /// from S, where a non-field would be declared. This routine copes 1980 /// with the difference between C and C++ scoping rules in structs and 1981 /// unions. For example, the following code is well-formed in C but 1982 /// ill-formed in C++: 1983 /// @code 1984 /// struct S6 { 1985 /// enum { BAR } e; 1986 /// }; 1987 /// 1988 /// void test_S6() { 1989 /// struct S6 a; 1990 /// a.e = BAR; 1991 /// } 1992 /// @endcode 1993 /// For the declaration of BAR, this routine will return a different 1994 /// scope. The scope S will be the scope of the unnamed enumeration 1995 /// within S6. In C++, this routine will return the scope associated 1996 /// with S6, because the enumeration's scope is a transparent 1997 /// context but structures can contain non-field names. In C, this 1998 /// routine will return the translation unit scope, since the 1999 /// enumeration's scope is a transparent context and structures cannot 2000 /// contain non-field names. 2001 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2002 while (((S->getFlags() & Scope::DeclScope) == 0) || 2003 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2004 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2005 S = S->getParent(); 2006 return S; 2007 } 2008 2009 /// Looks up the declaration of "struct objc_super" and 2010 /// saves it for later use in building builtin declaration of 2011 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 2012 /// pre-existing declaration exists no action takes place. 2013 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 2014 IdentifierInfo *II) { 2015 if (!II->isStr("objc_msgSendSuper")) 2016 return; 2017 ASTContext &Context = ThisSema.Context; 2018 2019 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 2020 SourceLocation(), Sema::LookupTagName); 2021 ThisSema.LookupName(Result, S); 2022 if (Result.getResultKind() == LookupResult::Found) 2023 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 2024 Context.setObjCSuperType(Context.getTagDeclType(TD)); 2025 } 2026 2027 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2028 ASTContext::GetBuiltinTypeError Error) { 2029 switch (Error) { 2030 case ASTContext::GE_None: 2031 return ""; 2032 case ASTContext::GE_Missing_type: 2033 return BuiltinInfo.getHeaderName(ID); 2034 case ASTContext::GE_Missing_stdio: 2035 return "stdio.h"; 2036 case ASTContext::GE_Missing_setjmp: 2037 return "setjmp.h"; 2038 case ASTContext::GE_Missing_ucontext: 2039 return "ucontext.h"; 2040 } 2041 llvm_unreachable("unhandled error kind"); 2042 } 2043 2044 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2045 /// file scope. lazily create a decl for it. ForRedeclaration is true 2046 /// if we're creating this built-in in anticipation of redeclaring the 2047 /// built-in. 2048 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2049 Scope *S, bool ForRedeclaration, 2050 SourceLocation Loc) { 2051 LookupPredefedObjCSuperType(*this, S, II); 2052 2053 ASTContext::GetBuiltinTypeError Error; 2054 QualType R = Context.GetBuiltinType(ID, Error); 2055 if (Error) { 2056 if (!ForRedeclaration) 2057 return nullptr; 2058 2059 // If we have a builtin without an associated type we should not emit a 2060 // warning when we were not able to find a type for it. 2061 if (Error == ASTContext::GE_Missing_type) 2062 return nullptr; 2063 2064 // If we could not find a type for setjmp it is because the jmp_buf type was 2065 // not defined prior to the setjmp declaration. 2066 if (Error == ASTContext::GE_Missing_setjmp) { 2067 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2068 << Context.BuiltinInfo.getName(ID); 2069 return nullptr; 2070 } 2071 2072 // Generally, we emit a warning that the declaration requires the 2073 // appropriate header. 2074 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2075 << getHeaderName(Context.BuiltinInfo, ID, Error) 2076 << Context.BuiltinInfo.getName(ID); 2077 return nullptr; 2078 } 2079 2080 if (!ForRedeclaration && 2081 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2082 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2083 Diag(Loc, diag::ext_implicit_lib_function_decl) 2084 << Context.BuiltinInfo.getName(ID) << R; 2085 if (Context.BuiltinInfo.getHeaderName(ID) && 2086 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 2087 Diag(Loc, diag::note_include_header_or_declare) 2088 << Context.BuiltinInfo.getHeaderName(ID) 2089 << Context.BuiltinInfo.getName(ID); 2090 } 2091 2092 if (R.isNull()) 2093 return nullptr; 2094 2095 DeclContext *Parent = Context.getTranslationUnitDecl(); 2096 if (getLangOpts().CPlusPlus) { 2097 LinkageSpecDecl *CLinkageDecl = 2098 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 2099 LinkageSpecDecl::lang_c, false); 2100 CLinkageDecl->setImplicit(); 2101 Parent->addDecl(CLinkageDecl); 2102 Parent = CLinkageDecl; 2103 } 2104 2105 FunctionDecl *New = FunctionDecl::Create(Context, 2106 Parent, 2107 Loc, Loc, II, R, /*TInfo=*/nullptr, 2108 SC_Extern, 2109 false, 2110 R->isFunctionProtoType()); 2111 New->setImplicit(); 2112 2113 // Create Decl objects for each parameter, adding them to the 2114 // FunctionDecl. 2115 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 2116 SmallVector<ParmVarDecl*, 16> Params; 2117 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2118 ParmVarDecl *parm = 2119 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2120 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2121 SC_None, nullptr); 2122 parm->setScopeInfo(0, i); 2123 Params.push_back(parm); 2124 } 2125 New->setParams(Params); 2126 } 2127 2128 AddKnownFunctionAttributes(New); 2129 RegisterLocallyScopedExternCDecl(New, S); 2130 2131 // TUScope is the translation-unit scope to insert this function into. 2132 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2133 // relate Scopes to DeclContexts, and probably eliminate CurContext 2134 // entirely, but we're not there yet. 2135 DeclContext *SavedContext = CurContext; 2136 CurContext = Parent; 2137 PushOnScopeChains(New, TUScope); 2138 CurContext = SavedContext; 2139 return New; 2140 } 2141 2142 /// Typedef declarations don't have linkage, but they still denote the same 2143 /// entity if their types are the same. 2144 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2145 /// isSameEntity. 2146 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2147 TypedefNameDecl *Decl, 2148 LookupResult &Previous) { 2149 // This is only interesting when modules are enabled. 2150 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2151 return; 2152 2153 // Empty sets are uninteresting. 2154 if (Previous.empty()) 2155 return; 2156 2157 LookupResult::Filter Filter = Previous.makeFilter(); 2158 while (Filter.hasNext()) { 2159 NamedDecl *Old = Filter.next(); 2160 2161 // Non-hidden declarations are never ignored. 2162 if (S.isVisible(Old)) 2163 continue; 2164 2165 // Declarations of the same entity are not ignored, even if they have 2166 // different linkages. 2167 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2168 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2169 Decl->getUnderlyingType())) 2170 continue; 2171 2172 // If both declarations give a tag declaration a typedef name for linkage 2173 // purposes, then they declare the same entity. 2174 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2175 Decl->getAnonDeclWithTypedefName()) 2176 continue; 2177 } 2178 2179 Filter.erase(); 2180 } 2181 2182 Filter.done(); 2183 } 2184 2185 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2186 QualType OldType; 2187 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2188 OldType = OldTypedef->getUnderlyingType(); 2189 else 2190 OldType = Context.getTypeDeclType(Old); 2191 QualType NewType = New->getUnderlyingType(); 2192 2193 if (NewType->isVariablyModifiedType()) { 2194 // Must not redefine a typedef with a variably-modified type. 2195 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2196 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2197 << Kind << NewType; 2198 if (Old->getLocation().isValid()) 2199 notePreviousDefinition(Old, New->getLocation()); 2200 New->setInvalidDecl(); 2201 return true; 2202 } 2203 2204 if (OldType != NewType && 2205 !OldType->isDependentType() && 2206 !NewType->isDependentType() && 2207 !Context.hasSameType(OldType, NewType)) { 2208 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2209 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2210 << Kind << NewType << OldType; 2211 if (Old->getLocation().isValid()) 2212 notePreviousDefinition(Old, New->getLocation()); 2213 New->setInvalidDecl(); 2214 return true; 2215 } 2216 return false; 2217 } 2218 2219 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2220 /// same name and scope as a previous declaration 'Old'. Figure out 2221 /// how to resolve this situation, merging decls or emitting 2222 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2223 /// 2224 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2225 LookupResult &OldDecls) { 2226 // If the new decl is known invalid already, don't bother doing any 2227 // merging checks. 2228 if (New->isInvalidDecl()) return; 2229 2230 // Allow multiple definitions for ObjC built-in typedefs. 2231 // FIXME: Verify the underlying types are equivalent! 2232 if (getLangOpts().ObjC) { 2233 const IdentifierInfo *TypeID = New->getIdentifier(); 2234 switch (TypeID->getLength()) { 2235 default: break; 2236 case 2: 2237 { 2238 if (!TypeID->isStr("id")) 2239 break; 2240 QualType T = New->getUnderlyingType(); 2241 if (!T->isPointerType()) 2242 break; 2243 if (!T->isVoidPointerType()) { 2244 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2245 if (!PT->isStructureType()) 2246 break; 2247 } 2248 Context.setObjCIdRedefinitionType(T); 2249 // Install the built-in type for 'id', ignoring the current definition. 2250 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2251 return; 2252 } 2253 case 5: 2254 if (!TypeID->isStr("Class")) 2255 break; 2256 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2257 // Install the built-in type for 'Class', ignoring the current definition. 2258 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2259 return; 2260 case 3: 2261 if (!TypeID->isStr("SEL")) 2262 break; 2263 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2264 // Install the built-in type for 'SEL', ignoring the current definition. 2265 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2266 return; 2267 } 2268 // Fall through - the typedef name was not a builtin type. 2269 } 2270 2271 // Verify the old decl was also a type. 2272 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2273 if (!Old) { 2274 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2275 << New->getDeclName(); 2276 2277 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2278 if (OldD->getLocation().isValid()) 2279 notePreviousDefinition(OldD, New->getLocation()); 2280 2281 return New->setInvalidDecl(); 2282 } 2283 2284 // If the old declaration is invalid, just give up here. 2285 if (Old->isInvalidDecl()) 2286 return New->setInvalidDecl(); 2287 2288 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2289 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2290 auto *NewTag = New->getAnonDeclWithTypedefName(); 2291 NamedDecl *Hidden = nullptr; 2292 if (OldTag && NewTag && 2293 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2294 !hasVisibleDefinition(OldTag, &Hidden)) { 2295 // There is a definition of this tag, but it is not visible. Use it 2296 // instead of our tag. 2297 New->setTypeForDecl(OldTD->getTypeForDecl()); 2298 if (OldTD->isModed()) 2299 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2300 OldTD->getUnderlyingType()); 2301 else 2302 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2303 2304 // Make the old tag definition visible. 2305 makeMergedDefinitionVisible(Hidden); 2306 2307 // If this was an unscoped enumeration, yank all of its enumerators 2308 // out of the scope. 2309 if (isa<EnumDecl>(NewTag)) { 2310 Scope *EnumScope = getNonFieldDeclScope(S); 2311 for (auto *D : NewTag->decls()) { 2312 auto *ED = cast<EnumConstantDecl>(D); 2313 assert(EnumScope->isDeclScope(ED)); 2314 EnumScope->RemoveDecl(ED); 2315 IdResolver.RemoveDecl(ED); 2316 ED->getLexicalDeclContext()->removeDecl(ED); 2317 } 2318 } 2319 } 2320 } 2321 2322 // If the typedef types are not identical, reject them in all languages and 2323 // with any extensions enabled. 2324 if (isIncompatibleTypedef(Old, New)) 2325 return; 2326 2327 // The types match. Link up the redeclaration chain and merge attributes if 2328 // the old declaration was a typedef. 2329 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2330 New->setPreviousDecl(Typedef); 2331 mergeDeclAttributes(New, Old); 2332 } 2333 2334 if (getLangOpts().MicrosoftExt) 2335 return; 2336 2337 if (getLangOpts().CPlusPlus) { 2338 // C++ [dcl.typedef]p2: 2339 // In a given non-class scope, a typedef specifier can be used to 2340 // redefine the name of any type declared in that scope to refer 2341 // to the type to which it already refers. 2342 if (!isa<CXXRecordDecl>(CurContext)) 2343 return; 2344 2345 // C++0x [dcl.typedef]p4: 2346 // In a given class scope, a typedef specifier can be used to redefine 2347 // any class-name declared in that scope that is not also a typedef-name 2348 // to refer to the type to which it already refers. 2349 // 2350 // This wording came in via DR424, which was a correction to the 2351 // wording in DR56, which accidentally banned code like: 2352 // 2353 // struct S { 2354 // typedef struct A { } A; 2355 // }; 2356 // 2357 // in the C++03 standard. We implement the C++0x semantics, which 2358 // allow the above but disallow 2359 // 2360 // struct S { 2361 // typedef int I; 2362 // typedef int I; 2363 // }; 2364 // 2365 // since that was the intent of DR56. 2366 if (!isa<TypedefNameDecl>(Old)) 2367 return; 2368 2369 Diag(New->getLocation(), diag::err_redefinition) 2370 << New->getDeclName(); 2371 notePreviousDefinition(Old, New->getLocation()); 2372 return New->setInvalidDecl(); 2373 } 2374 2375 // Modules always permit redefinition of typedefs, as does C11. 2376 if (getLangOpts().Modules || getLangOpts().C11) 2377 return; 2378 2379 // If we have a redefinition of a typedef in C, emit a warning. This warning 2380 // is normally mapped to an error, but can be controlled with 2381 // -Wtypedef-redefinition. If either the original or the redefinition is 2382 // in a system header, don't emit this for compatibility with GCC. 2383 if (getDiagnostics().getSuppressSystemWarnings() && 2384 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2385 (Old->isImplicit() || 2386 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2387 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2388 return; 2389 2390 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2391 << New->getDeclName(); 2392 notePreviousDefinition(Old, New->getLocation()); 2393 } 2394 2395 /// DeclhasAttr - returns true if decl Declaration already has the target 2396 /// attribute. 2397 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2398 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2399 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2400 for (const auto *i : D->attrs()) 2401 if (i->getKind() == A->getKind()) { 2402 if (Ann) { 2403 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2404 return true; 2405 continue; 2406 } 2407 // FIXME: Don't hardcode this check 2408 if (OA && isa<OwnershipAttr>(i)) 2409 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2410 return true; 2411 } 2412 2413 return false; 2414 } 2415 2416 static bool isAttributeTargetADefinition(Decl *D) { 2417 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2418 return VD->isThisDeclarationADefinition(); 2419 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2420 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2421 return true; 2422 } 2423 2424 /// Merge alignment attributes from \p Old to \p New, taking into account the 2425 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2426 /// 2427 /// \return \c true if any attributes were added to \p New. 2428 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2429 // Look for alignas attributes on Old, and pick out whichever attribute 2430 // specifies the strictest alignment requirement. 2431 AlignedAttr *OldAlignasAttr = nullptr; 2432 AlignedAttr *OldStrictestAlignAttr = nullptr; 2433 unsigned OldAlign = 0; 2434 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2435 // FIXME: We have no way of representing inherited dependent alignments 2436 // in a case like: 2437 // template<int A, int B> struct alignas(A) X; 2438 // template<int A, int B> struct alignas(B) X {}; 2439 // For now, we just ignore any alignas attributes which are not on the 2440 // definition in such a case. 2441 if (I->isAlignmentDependent()) 2442 return false; 2443 2444 if (I->isAlignas()) 2445 OldAlignasAttr = I; 2446 2447 unsigned Align = I->getAlignment(S.Context); 2448 if (Align > OldAlign) { 2449 OldAlign = Align; 2450 OldStrictestAlignAttr = I; 2451 } 2452 } 2453 2454 // Look for alignas attributes on New. 2455 AlignedAttr *NewAlignasAttr = nullptr; 2456 unsigned NewAlign = 0; 2457 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2458 if (I->isAlignmentDependent()) 2459 return false; 2460 2461 if (I->isAlignas()) 2462 NewAlignasAttr = I; 2463 2464 unsigned Align = I->getAlignment(S.Context); 2465 if (Align > NewAlign) 2466 NewAlign = Align; 2467 } 2468 2469 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2470 // Both declarations have 'alignas' attributes. We require them to match. 2471 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2472 // fall short. (If two declarations both have alignas, they must both match 2473 // every definition, and so must match each other if there is a definition.) 2474 2475 // If either declaration only contains 'alignas(0)' specifiers, then it 2476 // specifies the natural alignment for the type. 2477 if (OldAlign == 0 || NewAlign == 0) { 2478 QualType Ty; 2479 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2480 Ty = VD->getType(); 2481 else 2482 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2483 2484 if (OldAlign == 0) 2485 OldAlign = S.Context.getTypeAlign(Ty); 2486 if (NewAlign == 0) 2487 NewAlign = S.Context.getTypeAlign(Ty); 2488 } 2489 2490 if (OldAlign != NewAlign) { 2491 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2492 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2493 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2494 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2495 } 2496 } 2497 2498 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2499 // C++11 [dcl.align]p6: 2500 // if any declaration of an entity has an alignment-specifier, 2501 // every defining declaration of that entity shall specify an 2502 // equivalent alignment. 2503 // C11 6.7.5/7: 2504 // If the definition of an object does not have an alignment 2505 // specifier, any other declaration of that object shall also 2506 // have no alignment specifier. 2507 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2508 << OldAlignasAttr; 2509 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2510 << OldAlignasAttr; 2511 } 2512 2513 bool AnyAdded = false; 2514 2515 // Ensure we have an attribute representing the strictest alignment. 2516 if (OldAlign > NewAlign) { 2517 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2518 Clone->setInherited(true); 2519 New->addAttr(Clone); 2520 AnyAdded = true; 2521 } 2522 2523 // Ensure we have an alignas attribute if the old declaration had one. 2524 if (OldAlignasAttr && !NewAlignasAttr && 2525 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2526 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2527 Clone->setInherited(true); 2528 New->addAttr(Clone); 2529 AnyAdded = true; 2530 } 2531 2532 return AnyAdded; 2533 } 2534 2535 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2536 const InheritableAttr *Attr, 2537 Sema::AvailabilityMergeKind AMK) { 2538 // This function copies an attribute Attr from a previous declaration to the 2539 // new declaration D if the new declaration doesn't itself have that attribute 2540 // yet or if that attribute allows duplicates. 2541 // If you're adding a new attribute that requires logic different from 2542 // "use explicit attribute on decl if present, else use attribute from 2543 // previous decl", for example if the attribute needs to be consistent 2544 // between redeclarations, you need to call a custom merge function here. 2545 InheritableAttr *NewAttr = nullptr; 2546 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2547 NewAttr = S.mergeAvailabilityAttr( 2548 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2549 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2550 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2551 AA->getPriority()); 2552 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2553 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2554 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2555 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2556 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2557 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2558 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2559 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2560 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2561 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2562 FA->getFirstArg()); 2563 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2564 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2565 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2566 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2567 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2568 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2569 IA->getInheritanceModel()); 2570 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2571 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2572 &S.Context.Idents.get(AA->getSpelling())); 2573 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2574 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2575 isa<CUDAGlobalAttr>(Attr))) { 2576 // CUDA target attributes are part of function signature for 2577 // overloading purposes and must not be merged. 2578 return false; 2579 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2580 NewAttr = S.mergeMinSizeAttr(D, *MA); 2581 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2582 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2583 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2584 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2585 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2586 NewAttr = S.mergeCommonAttr(D, *CommonA); 2587 else if (isa<AlignedAttr>(Attr)) 2588 // AlignedAttrs are handled separately, because we need to handle all 2589 // such attributes on a declaration at the same time. 2590 NewAttr = nullptr; 2591 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2592 (AMK == Sema::AMK_Override || 2593 AMK == Sema::AMK_ProtocolImplementation)) 2594 NewAttr = nullptr; 2595 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2596 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2597 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2598 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2599 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2600 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2601 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2602 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2603 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2604 NewAttr = S.mergeImportNameAttr(D, *INA); 2605 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2606 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2607 2608 if (NewAttr) { 2609 NewAttr->setInherited(true); 2610 D->addAttr(NewAttr); 2611 if (isa<MSInheritanceAttr>(NewAttr)) 2612 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2613 return true; 2614 } 2615 2616 return false; 2617 } 2618 2619 static const NamedDecl *getDefinition(const Decl *D) { 2620 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2621 return TD->getDefinition(); 2622 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2623 const VarDecl *Def = VD->getDefinition(); 2624 if (Def) 2625 return Def; 2626 return VD->getActingDefinition(); 2627 } 2628 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2629 return FD->getDefinition(); 2630 return nullptr; 2631 } 2632 2633 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2634 for (const auto *Attribute : D->attrs()) 2635 if (Attribute->getKind() == Kind) 2636 return true; 2637 return false; 2638 } 2639 2640 /// checkNewAttributesAfterDef - If we already have a definition, check that 2641 /// there are no new attributes in this declaration. 2642 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2643 if (!New->hasAttrs()) 2644 return; 2645 2646 const NamedDecl *Def = getDefinition(Old); 2647 if (!Def || Def == New) 2648 return; 2649 2650 AttrVec &NewAttributes = New->getAttrs(); 2651 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2652 const Attr *NewAttribute = NewAttributes[I]; 2653 2654 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2655 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2656 Sema::SkipBodyInfo SkipBody; 2657 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2658 2659 // If we're skipping this definition, drop the "alias" attribute. 2660 if (SkipBody.ShouldSkip) { 2661 NewAttributes.erase(NewAttributes.begin() + I); 2662 --E; 2663 continue; 2664 } 2665 } else { 2666 VarDecl *VD = cast<VarDecl>(New); 2667 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2668 VarDecl::TentativeDefinition 2669 ? diag::err_alias_after_tentative 2670 : diag::err_redefinition; 2671 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2672 if (Diag == diag::err_redefinition) 2673 S.notePreviousDefinition(Def, VD->getLocation()); 2674 else 2675 S.Diag(Def->getLocation(), diag::note_previous_definition); 2676 VD->setInvalidDecl(); 2677 } 2678 ++I; 2679 continue; 2680 } 2681 2682 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2683 // Tentative definitions are only interesting for the alias check above. 2684 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2685 ++I; 2686 continue; 2687 } 2688 } 2689 2690 if (hasAttribute(Def, NewAttribute->getKind())) { 2691 ++I; 2692 continue; // regular attr merging will take care of validating this. 2693 } 2694 2695 if (isa<C11NoReturnAttr>(NewAttribute)) { 2696 // C's _Noreturn is allowed to be added to a function after it is defined. 2697 ++I; 2698 continue; 2699 } else if (isa<UuidAttr>(NewAttribute)) { 2700 // msvc will allow a subsequent definition to add an uuid to a class 2701 ++I; 2702 continue; 2703 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2704 if (AA->isAlignas()) { 2705 // C++11 [dcl.align]p6: 2706 // if any declaration of an entity has an alignment-specifier, 2707 // every defining declaration of that entity shall specify an 2708 // equivalent alignment. 2709 // C11 6.7.5/7: 2710 // If the definition of an object does not have an alignment 2711 // specifier, any other declaration of that object shall also 2712 // have no alignment specifier. 2713 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2714 << AA; 2715 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2716 << AA; 2717 NewAttributes.erase(NewAttributes.begin() + I); 2718 --E; 2719 continue; 2720 } 2721 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2722 // If there is a C definition followed by a redeclaration with this 2723 // attribute then there are two different definitions. In C++, prefer the 2724 // standard diagnostics. 2725 if (!S.getLangOpts().CPlusPlus) { 2726 S.Diag(NewAttribute->getLocation(), 2727 diag::err_loader_uninitialized_redeclaration); 2728 S.Diag(Def->getLocation(), diag::note_previous_definition); 2729 NewAttributes.erase(NewAttributes.begin() + I); 2730 --E; 2731 continue; 2732 } 2733 } else if (isa<SelectAnyAttr>(NewAttribute) && 2734 cast<VarDecl>(New)->isInline() && 2735 !cast<VarDecl>(New)->isInlineSpecified()) { 2736 // Don't warn about applying selectany to implicitly inline variables. 2737 // Older compilers and language modes would require the use of selectany 2738 // to make such variables inline, and it would have no effect if we 2739 // honored it. 2740 ++I; 2741 continue; 2742 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2743 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2744 // declarations after defintions. 2745 ++I; 2746 continue; 2747 } 2748 2749 S.Diag(NewAttribute->getLocation(), 2750 diag::warn_attribute_precede_definition); 2751 S.Diag(Def->getLocation(), diag::note_previous_definition); 2752 NewAttributes.erase(NewAttributes.begin() + I); 2753 --E; 2754 } 2755 } 2756 2757 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2758 const ConstInitAttr *CIAttr, 2759 bool AttrBeforeInit) { 2760 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2761 2762 // Figure out a good way to write this specifier on the old declaration. 2763 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2764 // enough of the attribute list spelling information to extract that without 2765 // heroics. 2766 std::string SuitableSpelling; 2767 if (S.getLangOpts().CPlusPlus20) 2768 SuitableSpelling = std::string( 2769 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2770 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2771 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2772 InsertLoc, {tok::l_square, tok::l_square, 2773 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2774 S.PP.getIdentifierInfo("require_constant_initialization"), 2775 tok::r_square, tok::r_square})); 2776 if (SuitableSpelling.empty()) 2777 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2778 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2779 S.PP.getIdentifierInfo("require_constant_initialization"), 2780 tok::r_paren, tok::r_paren})); 2781 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2782 SuitableSpelling = "constinit"; 2783 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2784 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2785 if (SuitableSpelling.empty()) 2786 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2787 SuitableSpelling += " "; 2788 2789 if (AttrBeforeInit) { 2790 // extern constinit int a; 2791 // int a = 0; // error (missing 'constinit'), accepted as extension 2792 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2793 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2794 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2795 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2796 } else { 2797 // int a = 0; 2798 // constinit extern int a; // error (missing 'constinit') 2799 S.Diag(CIAttr->getLocation(), 2800 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2801 : diag::warn_require_const_init_added_too_late) 2802 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2803 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2804 << CIAttr->isConstinit() 2805 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2806 } 2807 } 2808 2809 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2810 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2811 AvailabilityMergeKind AMK) { 2812 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2813 UsedAttr *NewAttr = OldAttr->clone(Context); 2814 NewAttr->setInherited(true); 2815 New->addAttr(NewAttr); 2816 } 2817 2818 if (!Old->hasAttrs() && !New->hasAttrs()) 2819 return; 2820 2821 // [dcl.constinit]p1: 2822 // If the [constinit] specifier is applied to any declaration of a 2823 // variable, it shall be applied to the initializing declaration. 2824 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2825 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2826 if (bool(OldConstInit) != bool(NewConstInit)) { 2827 const auto *OldVD = cast<VarDecl>(Old); 2828 auto *NewVD = cast<VarDecl>(New); 2829 2830 // Find the initializing declaration. Note that we might not have linked 2831 // the new declaration into the redeclaration chain yet. 2832 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2833 if (!InitDecl && 2834 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2835 InitDecl = NewVD; 2836 2837 if (InitDecl == NewVD) { 2838 // This is the initializing declaration. If it would inherit 'constinit', 2839 // that's ill-formed. (Note that we do not apply this to the attribute 2840 // form). 2841 if (OldConstInit && OldConstInit->isConstinit()) 2842 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2843 /*AttrBeforeInit=*/true); 2844 } else if (NewConstInit) { 2845 // This is the first time we've been told that this declaration should 2846 // have a constant initializer. If we already saw the initializing 2847 // declaration, this is too late. 2848 if (InitDecl && InitDecl != NewVD) { 2849 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2850 /*AttrBeforeInit=*/false); 2851 NewVD->dropAttr<ConstInitAttr>(); 2852 } 2853 } 2854 } 2855 2856 // Attributes declared post-definition are currently ignored. 2857 checkNewAttributesAfterDef(*this, New, Old); 2858 2859 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2860 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2861 if (!OldA->isEquivalent(NewA)) { 2862 // This redeclaration changes __asm__ label. 2863 Diag(New->getLocation(), diag::err_different_asm_label); 2864 Diag(OldA->getLocation(), diag::note_previous_declaration); 2865 } 2866 } else if (Old->isUsed()) { 2867 // This redeclaration adds an __asm__ label to a declaration that has 2868 // already been ODR-used. 2869 Diag(New->getLocation(), diag::err_late_asm_label_name) 2870 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2871 } 2872 } 2873 2874 // Re-declaration cannot add abi_tag's. 2875 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2876 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2877 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2878 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2879 NewTag) == OldAbiTagAttr->tags_end()) { 2880 Diag(NewAbiTagAttr->getLocation(), 2881 diag::err_new_abi_tag_on_redeclaration) 2882 << NewTag; 2883 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2884 } 2885 } 2886 } else { 2887 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2888 Diag(Old->getLocation(), diag::note_previous_declaration); 2889 } 2890 } 2891 2892 // This redeclaration adds a section attribute. 2893 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2894 if (auto *VD = dyn_cast<VarDecl>(New)) { 2895 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2896 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2897 Diag(Old->getLocation(), diag::note_previous_declaration); 2898 } 2899 } 2900 } 2901 2902 // Redeclaration adds code-seg attribute. 2903 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2904 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2905 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2906 Diag(New->getLocation(), diag::warn_mismatched_section) 2907 << 0 /*codeseg*/; 2908 Diag(Old->getLocation(), diag::note_previous_declaration); 2909 } 2910 2911 if (!Old->hasAttrs()) 2912 return; 2913 2914 bool foundAny = New->hasAttrs(); 2915 2916 // Ensure that any moving of objects within the allocated map is done before 2917 // we process them. 2918 if (!foundAny) New->setAttrs(AttrVec()); 2919 2920 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2921 // Ignore deprecated/unavailable/availability attributes if requested. 2922 AvailabilityMergeKind LocalAMK = AMK_None; 2923 if (isa<DeprecatedAttr>(I) || 2924 isa<UnavailableAttr>(I) || 2925 isa<AvailabilityAttr>(I)) { 2926 switch (AMK) { 2927 case AMK_None: 2928 continue; 2929 2930 case AMK_Redeclaration: 2931 case AMK_Override: 2932 case AMK_ProtocolImplementation: 2933 LocalAMK = AMK; 2934 break; 2935 } 2936 } 2937 2938 // Already handled. 2939 if (isa<UsedAttr>(I)) 2940 continue; 2941 2942 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2943 foundAny = true; 2944 } 2945 2946 if (mergeAlignedAttrs(*this, New, Old)) 2947 foundAny = true; 2948 2949 if (!foundAny) New->dropAttrs(); 2950 } 2951 2952 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2953 /// to the new one. 2954 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2955 const ParmVarDecl *oldDecl, 2956 Sema &S) { 2957 // C++11 [dcl.attr.depend]p2: 2958 // The first declaration of a function shall specify the 2959 // carries_dependency attribute for its declarator-id if any declaration 2960 // of the function specifies the carries_dependency attribute. 2961 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2962 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2963 S.Diag(CDA->getLocation(), 2964 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2965 // Find the first declaration of the parameter. 2966 // FIXME: Should we build redeclaration chains for function parameters? 2967 const FunctionDecl *FirstFD = 2968 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2969 const ParmVarDecl *FirstVD = 2970 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2971 S.Diag(FirstVD->getLocation(), 2972 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2973 } 2974 2975 if (!oldDecl->hasAttrs()) 2976 return; 2977 2978 bool foundAny = newDecl->hasAttrs(); 2979 2980 // Ensure that any moving of objects within the allocated map is 2981 // done before we process them. 2982 if (!foundAny) newDecl->setAttrs(AttrVec()); 2983 2984 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2985 if (!DeclHasAttr(newDecl, I)) { 2986 InheritableAttr *newAttr = 2987 cast<InheritableParamAttr>(I->clone(S.Context)); 2988 newAttr->setInherited(true); 2989 newDecl->addAttr(newAttr); 2990 foundAny = true; 2991 } 2992 } 2993 2994 if (!foundAny) newDecl->dropAttrs(); 2995 } 2996 2997 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2998 const ParmVarDecl *OldParam, 2999 Sema &S) { 3000 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3001 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3002 if (*Oldnullability != *Newnullability) { 3003 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3004 << DiagNullabilityKind( 3005 *Newnullability, 3006 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3007 != 0)) 3008 << DiagNullabilityKind( 3009 *Oldnullability, 3010 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3011 != 0)); 3012 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3013 } 3014 } else { 3015 QualType NewT = NewParam->getType(); 3016 NewT = S.Context.getAttributedType( 3017 AttributedType::getNullabilityAttrKind(*Oldnullability), 3018 NewT, NewT); 3019 NewParam->setType(NewT); 3020 } 3021 } 3022 } 3023 3024 namespace { 3025 3026 /// Used in MergeFunctionDecl to keep track of function parameters in 3027 /// C. 3028 struct GNUCompatibleParamWarning { 3029 ParmVarDecl *OldParm; 3030 ParmVarDecl *NewParm; 3031 QualType PromotedType; 3032 }; 3033 3034 } // end anonymous namespace 3035 3036 // Determine whether the previous declaration was a definition, implicit 3037 // declaration, or a declaration. 3038 template <typename T> 3039 static std::pair<diag::kind, SourceLocation> 3040 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3041 diag::kind PrevDiag; 3042 SourceLocation OldLocation = Old->getLocation(); 3043 if (Old->isThisDeclarationADefinition()) 3044 PrevDiag = diag::note_previous_definition; 3045 else if (Old->isImplicit()) { 3046 PrevDiag = diag::note_previous_implicit_declaration; 3047 if (OldLocation.isInvalid()) 3048 OldLocation = New->getLocation(); 3049 } else 3050 PrevDiag = diag::note_previous_declaration; 3051 return std::make_pair(PrevDiag, OldLocation); 3052 } 3053 3054 /// canRedefineFunction - checks if a function can be redefined. Currently, 3055 /// only extern inline functions can be redefined, and even then only in 3056 /// GNU89 mode. 3057 static bool canRedefineFunction(const FunctionDecl *FD, 3058 const LangOptions& LangOpts) { 3059 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3060 !LangOpts.CPlusPlus && 3061 FD->isInlineSpecified() && 3062 FD->getStorageClass() == SC_Extern); 3063 } 3064 3065 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3066 const AttributedType *AT = T->getAs<AttributedType>(); 3067 while (AT && !AT->isCallingConv()) 3068 AT = AT->getModifiedType()->getAs<AttributedType>(); 3069 return AT; 3070 } 3071 3072 template <typename T> 3073 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3074 const DeclContext *DC = Old->getDeclContext(); 3075 if (DC->isRecord()) 3076 return false; 3077 3078 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3079 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3080 return true; 3081 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3082 return true; 3083 return false; 3084 } 3085 3086 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3087 static bool isExternC(VarTemplateDecl *) { return false; } 3088 3089 /// Check whether a redeclaration of an entity introduced by a 3090 /// using-declaration is valid, given that we know it's not an overload 3091 /// (nor a hidden tag declaration). 3092 template<typename ExpectedDecl> 3093 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3094 ExpectedDecl *New) { 3095 // C++11 [basic.scope.declarative]p4: 3096 // Given a set of declarations in a single declarative region, each of 3097 // which specifies the same unqualified name, 3098 // -- they shall all refer to the same entity, or all refer to functions 3099 // and function templates; or 3100 // -- exactly one declaration shall declare a class name or enumeration 3101 // name that is not a typedef name and the other declarations shall all 3102 // refer to the same variable or enumerator, or all refer to functions 3103 // and function templates; in this case the class name or enumeration 3104 // name is hidden (3.3.10). 3105 3106 // C++11 [namespace.udecl]p14: 3107 // If a function declaration in namespace scope or block scope has the 3108 // same name and the same parameter-type-list as a function introduced 3109 // by a using-declaration, and the declarations do not declare the same 3110 // function, the program is ill-formed. 3111 3112 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3113 if (Old && 3114 !Old->getDeclContext()->getRedeclContext()->Equals( 3115 New->getDeclContext()->getRedeclContext()) && 3116 !(isExternC(Old) && isExternC(New))) 3117 Old = nullptr; 3118 3119 if (!Old) { 3120 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3121 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3122 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3123 return true; 3124 } 3125 return false; 3126 } 3127 3128 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3129 const FunctionDecl *B) { 3130 assert(A->getNumParams() == B->getNumParams()); 3131 3132 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3133 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3134 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3135 if (AttrA == AttrB) 3136 return true; 3137 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3138 AttrA->isDynamic() == AttrB->isDynamic(); 3139 }; 3140 3141 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3142 } 3143 3144 /// If necessary, adjust the semantic declaration context for a qualified 3145 /// declaration to name the correct inline namespace within the qualifier. 3146 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3147 DeclaratorDecl *OldD) { 3148 // The only case where we need to update the DeclContext is when 3149 // redeclaration lookup for a qualified name finds a declaration 3150 // in an inline namespace within the context named by the qualifier: 3151 // 3152 // inline namespace N { int f(); } 3153 // int ::f(); // Sema DC needs adjusting from :: to N::. 3154 // 3155 // For unqualified declarations, the semantic context *can* change 3156 // along the redeclaration chain (for local extern declarations, 3157 // extern "C" declarations, and friend declarations in particular). 3158 if (!NewD->getQualifier()) 3159 return; 3160 3161 // NewD is probably already in the right context. 3162 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3163 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3164 if (NamedDC->Equals(SemaDC)) 3165 return; 3166 3167 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3168 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3169 "unexpected context for redeclaration"); 3170 3171 auto *LexDC = NewD->getLexicalDeclContext(); 3172 auto FixSemaDC = [=](NamedDecl *D) { 3173 if (!D) 3174 return; 3175 D->setDeclContext(SemaDC); 3176 D->setLexicalDeclContext(LexDC); 3177 }; 3178 3179 FixSemaDC(NewD); 3180 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3181 FixSemaDC(FD->getDescribedFunctionTemplate()); 3182 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3183 FixSemaDC(VD->getDescribedVarTemplate()); 3184 } 3185 3186 /// MergeFunctionDecl - We just parsed a function 'New' from 3187 /// declarator D which has the same name and scope as a previous 3188 /// declaration 'Old'. Figure out how to resolve this situation, 3189 /// merging decls or emitting diagnostics as appropriate. 3190 /// 3191 /// In C++, New and Old must be declarations that are not 3192 /// overloaded. Use IsOverload to determine whether New and Old are 3193 /// overloaded, and to select the Old declaration that New should be 3194 /// merged with. 3195 /// 3196 /// Returns true if there was an error, false otherwise. 3197 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3198 Scope *S, bool MergeTypeWithOld) { 3199 // Verify the old decl was also a function. 3200 FunctionDecl *Old = OldD->getAsFunction(); 3201 if (!Old) { 3202 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3203 if (New->getFriendObjectKind()) { 3204 Diag(New->getLocation(), diag::err_using_decl_friend); 3205 Diag(Shadow->getTargetDecl()->getLocation(), 3206 diag::note_using_decl_target); 3207 Diag(Shadow->getUsingDecl()->getLocation(), 3208 diag::note_using_decl) << 0; 3209 return true; 3210 } 3211 3212 // Check whether the two declarations might declare the same function. 3213 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3214 return true; 3215 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3216 } else { 3217 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3218 << New->getDeclName(); 3219 notePreviousDefinition(OldD, New->getLocation()); 3220 return true; 3221 } 3222 } 3223 3224 // If the old declaration is invalid, just give up here. 3225 if (Old->isInvalidDecl()) 3226 return true; 3227 3228 // Disallow redeclaration of some builtins. 3229 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3230 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3231 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3232 << Old << Old->getType(); 3233 return true; 3234 } 3235 3236 diag::kind PrevDiag; 3237 SourceLocation OldLocation; 3238 std::tie(PrevDiag, OldLocation) = 3239 getNoteDiagForInvalidRedeclaration(Old, New); 3240 3241 // Don't complain about this if we're in GNU89 mode and the old function 3242 // is an extern inline function. 3243 // Don't complain about specializations. They are not supposed to have 3244 // storage classes. 3245 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3246 New->getStorageClass() == SC_Static && 3247 Old->hasExternalFormalLinkage() && 3248 !New->getTemplateSpecializationInfo() && 3249 !canRedefineFunction(Old, getLangOpts())) { 3250 if (getLangOpts().MicrosoftExt) { 3251 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3252 Diag(OldLocation, PrevDiag); 3253 } else { 3254 Diag(New->getLocation(), diag::err_static_non_static) << New; 3255 Diag(OldLocation, PrevDiag); 3256 return true; 3257 } 3258 } 3259 3260 if (New->hasAttr<InternalLinkageAttr>() && 3261 !Old->hasAttr<InternalLinkageAttr>()) { 3262 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3263 << New->getDeclName(); 3264 notePreviousDefinition(Old, New->getLocation()); 3265 New->dropAttr<InternalLinkageAttr>(); 3266 } 3267 3268 if (CheckRedeclarationModuleOwnership(New, Old)) 3269 return true; 3270 3271 if (!getLangOpts().CPlusPlus) { 3272 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3273 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3274 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3275 << New << OldOvl; 3276 3277 // Try our best to find a decl that actually has the overloadable 3278 // attribute for the note. In most cases (e.g. programs with only one 3279 // broken declaration/definition), this won't matter. 3280 // 3281 // FIXME: We could do this if we juggled some extra state in 3282 // OverloadableAttr, rather than just removing it. 3283 const Decl *DiagOld = Old; 3284 if (OldOvl) { 3285 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3286 const auto *A = D->getAttr<OverloadableAttr>(); 3287 return A && !A->isImplicit(); 3288 }); 3289 // If we've implicitly added *all* of the overloadable attrs to this 3290 // chain, emitting a "previous redecl" note is pointless. 3291 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3292 } 3293 3294 if (DiagOld) 3295 Diag(DiagOld->getLocation(), 3296 diag::note_attribute_overloadable_prev_overload) 3297 << OldOvl; 3298 3299 if (OldOvl) 3300 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3301 else 3302 New->dropAttr<OverloadableAttr>(); 3303 } 3304 } 3305 3306 // If a function is first declared with a calling convention, but is later 3307 // declared or defined without one, all following decls assume the calling 3308 // convention of the first. 3309 // 3310 // It's OK if a function is first declared without a calling convention, 3311 // but is later declared or defined with the default calling convention. 3312 // 3313 // To test if either decl has an explicit calling convention, we look for 3314 // AttributedType sugar nodes on the type as written. If they are missing or 3315 // were canonicalized away, we assume the calling convention was implicit. 3316 // 3317 // Note also that we DO NOT return at this point, because we still have 3318 // other tests to run. 3319 QualType OldQType = Context.getCanonicalType(Old->getType()); 3320 QualType NewQType = Context.getCanonicalType(New->getType()); 3321 const FunctionType *OldType = cast<FunctionType>(OldQType); 3322 const FunctionType *NewType = cast<FunctionType>(NewQType); 3323 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3324 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3325 bool RequiresAdjustment = false; 3326 3327 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3328 FunctionDecl *First = Old->getFirstDecl(); 3329 const FunctionType *FT = 3330 First->getType().getCanonicalType()->castAs<FunctionType>(); 3331 FunctionType::ExtInfo FI = FT->getExtInfo(); 3332 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3333 if (!NewCCExplicit) { 3334 // Inherit the CC from the previous declaration if it was specified 3335 // there but not here. 3336 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3337 RequiresAdjustment = true; 3338 } else if (New->getBuiltinID()) { 3339 // Calling Conventions on a Builtin aren't really useful and setting a 3340 // default calling convention and cdecl'ing some builtin redeclarations is 3341 // common, so warn and ignore the calling convention on the redeclaration. 3342 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3343 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3344 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3345 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3346 RequiresAdjustment = true; 3347 } else { 3348 // Calling conventions aren't compatible, so complain. 3349 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3350 Diag(New->getLocation(), diag::err_cconv_change) 3351 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3352 << !FirstCCExplicit 3353 << (!FirstCCExplicit ? "" : 3354 FunctionType::getNameForCallConv(FI.getCC())); 3355 3356 // Put the note on the first decl, since it is the one that matters. 3357 Diag(First->getLocation(), diag::note_previous_declaration); 3358 return true; 3359 } 3360 } 3361 3362 // FIXME: diagnose the other way around? 3363 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3364 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3365 RequiresAdjustment = true; 3366 } 3367 3368 // Merge regparm attribute. 3369 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3370 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3371 if (NewTypeInfo.getHasRegParm()) { 3372 Diag(New->getLocation(), diag::err_regparm_mismatch) 3373 << NewType->getRegParmType() 3374 << OldType->getRegParmType(); 3375 Diag(OldLocation, diag::note_previous_declaration); 3376 return true; 3377 } 3378 3379 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3380 RequiresAdjustment = true; 3381 } 3382 3383 // Merge ns_returns_retained attribute. 3384 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3385 if (NewTypeInfo.getProducesResult()) { 3386 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3387 << "'ns_returns_retained'"; 3388 Diag(OldLocation, diag::note_previous_declaration); 3389 return true; 3390 } 3391 3392 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3393 RequiresAdjustment = true; 3394 } 3395 3396 if (OldTypeInfo.getNoCallerSavedRegs() != 3397 NewTypeInfo.getNoCallerSavedRegs()) { 3398 if (NewTypeInfo.getNoCallerSavedRegs()) { 3399 AnyX86NoCallerSavedRegistersAttr *Attr = 3400 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3401 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3402 Diag(OldLocation, diag::note_previous_declaration); 3403 return true; 3404 } 3405 3406 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3407 RequiresAdjustment = true; 3408 } 3409 3410 if (RequiresAdjustment) { 3411 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3412 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3413 New->setType(QualType(AdjustedType, 0)); 3414 NewQType = Context.getCanonicalType(New->getType()); 3415 } 3416 3417 // If this redeclaration makes the function inline, we may need to add it to 3418 // UndefinedButUsed. 3419 if (!Old->isInlined() && New->isInlined() && 3420 !New->hasAttr<GNUInlineAttr>() && 3421 !getLangOpts().GNUInline && 3422 Old->isUsed(false) && 3423 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3424 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3425 SourceLocation())); 3426 3427 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3428 // about it. 3429 if (New->hasAttr<GNUInlineAttr>() && 3430 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3431 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3432 } 3433 3434 // If pass_object_size params don't match up perfectly, this isn't a valid 3435 // redeclaration. 3436 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3437 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3438 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3439 << New->getDeclName(); 3440 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3441 return true; 3442 } 3443 3444 if (getLangOpts().CPlusPlus) { 3445 // C++1z [over.load]p2 3446 // Certain function declarations cannot be overloaded: 3447 // -- Function declarations that differ only in the return type, 3448 // the exception specification, or both cannot be overloaded. 3449 3450 // Check the exception specifications match. This may recompute the type of 3451 // both Old and New if it resolved exception specifications, so grab the 3452 // types again after this. Because this updates the type, we do this before 3453 // any of the other checks below, which may update the "de facto" NewQType 3454 // but do not necessarily update the type of New. 3455 if (CheckEquivalentExceptionSpec(Old, New)) 3456 return true; 3457 OldQType = Context.getCanonicalType(Old->getType()); 3458 NewQType = Context.getCanonicalType(New->getType()); 3459 3460 // Go back to the type source info to compare the declared return types, 3461 // per C++1y [dcl.type.auto]p13: 3462 // Redeclarations or specializations of a function or function template 3463 // with a declared return type that uses a placeholder type shall also 3464 // use that placeholder, not a deduced type. 3465 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3466 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3467 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3468 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3469 OldDeclaredReturnType)) { 3470 QualType ResQT; 3471 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3472 OldDeclaredReturnType->isObjCObjectPointerType()) 3473 // FIXME: This does the wrong thing for a deduced return type. 3474 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3475 if (ResQT.isNull()) { 3476 if (New->isCXXClassMember() && New->isOutOfLine()) 3477 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3478 << New << New->getReturnTypeSourceRange(); 3479 else 3480 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3481 << New->getReturnTypeSourceRange(); 3482 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3483 << Old->getReturnTypeSourceRange(); 3484 return true; 3485 } 3486 else 3487 NewQType = ResQT; 3488 } 3489 3490 QualType OldReturnType = OldType->getReturnType(); 3491 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3492 if (OldReturnType != NewReturnType) { 3493 // If this function has a deduced return type and has already been 3494 // defined, copy the deduced value from the old declaration. 3495 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3496 if (OldAT && OldAT->isDeduced()) { 3497 New->setType( 3498 SubstAutoType(New->getType(), 3499 OldAT->isDependentType() ? Context.DependentTy 3500 : OldAT->getDeducedType())); 3501 NewQType = Context.getCanonicalType( 3502 SubstAutoType(NewQType, 3503 OldAT->isDependentType() ? Context.DependentTy 3504 : OldAT->getDeducedType())); 3505 } 3506 } 3507 3508 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3509 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3510 if (OldMethod && NewMethod) { 3511 // Preserve triviality. 3512 NewMethod->setTrivial(OldMethod->isTrivial()); 3513 3514 // MSVC allows explicit template specialization at class scope: 3515 // 2 CXXMethodDecls referring to the same function will be injected. 3516 // We don't want a redeclaration error. 3517 bool IsClassScopeExplicitSpecialization = 3518 OldMethod->isFunctionTemplateSpecialization() && 3519 NewMethod->isFunctionTemplateSpecialization(); 3520 bool isFriend = NewMethod->getFriendObjectKind(); 3521 3522 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3523 !IsClassScopeExplicitSpecialization) { 3524 // -- Member function declarations with the same name and the 3525 // same parameter types cannot be overloaded if any of them 3526 // is a static member function declaration. 3527 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3528 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3529 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3530 return true; 3531 } 3532 3533 // C++ [class.mem]p1: 3534 // [...] A member shall not be declared twice in the 3535 // member-specification, except that a nested class or member 3536 // class template can be declared and then later defined. 3537 if (!inTemplateInstantiation()) { 3538 unsigned NewDiag; 3539 if (isa<CXXConstructorDecl>(OldMethod)) 3540 NewDiag = diag::err_constructor_redeclared; 3541 else if (isa<CXXDestructorDecl>(NewMethod)) 3542 NewDiag = diag::err_destructor_redeclared; 3543 else if (isa<CXXConversionDecl>(NewMethod)) 3544 NewDiag = diag::err_conv_function_redeclared; 3545 else 3546 NewDiag = diag::err_member_redeclared; 3547 3548 Diag(New->getLocation(), NewDiag); 3549 } else { 3550 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3551 << New << New->getType(); 3552 } 3553 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3554 return true; 3555 3556 // Complain if this is an explicit declaration of a special 3557 // member that was initially declared implicitly. 3558 // 3559 // As an exception, it's okay to befriend such methods in order 3560 // to permit the implicit constructor/destructor/operator calls. 3561 } else if (OldMethod->isImplicit()) { 3562 if (isFriend) { 3563 NewMethod->setImplicit(); 3564 } else { 3565 Diag(NewMethod->getLocation(), 3566 diag::err_definition_of_implicitly_declared_member) 3567 << New << getSpecialMember(OldMethod); 3568 return true; 3569 } 3570 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3571 Diag(NewMethod->getLocation(), 3572 diag::err_definition_of_explicitly_defaulted_member) 3573 << getSpecialMember(OldMethod); 3574 return true; 3575 } 3576 } 3577 3578 // C++11 [dcl.attr.noreturn]p1: 3579 // The first declaration of a function shall specify the noreturn 3580 // attribute if any declaration of that function specifies the noreturn 3581 // attribute. 3582 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3583 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3584 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3585 Diag(Old->getFirstDecl()->getLocation(), 3586 diag::note_noreturn_missing_first_decl); 3587 } 3588 3589 // C++11 [dcl.attr.depend]p2: 3590 // The first declaration of a function shall specify the 3591 // carries_dependency attribute for its declarator-id if any declaration 3592 // of the function specifies the carries_dependency attribute. 3593 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3594 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3595 Diag(CDA->getLocation(), 3596 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3597 Diag(Old->getFirstDecl()->getLocation(), 3598 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3599 } 3600 3601 // (C++98 8.3.5p3): 3602 // All declarations for a function shall agree exactly in both the 3603 // return type and the parameter-type-list. 3604 // We also want to respect all the extended bits except noreturn. 3605 3606 // noreturn should now match unless the old type info didn't have it. 3607 QualType OldQTypeForComparison = OldQType; 3608 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3609 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3610 const FunctionType *OldTypeForComparison 3611 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3612 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3613 assert(OldQTypeForComparison.isCanonical()); 3614 } 3615 3616 if (haveIncompatibleLanguageLinkages(Old, New)) { 3617 // As a special case, retain the language linkage from previous 3618 // declarations of a friend function as an extension. 3619 // 3620 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3621 // and is useful because there's otherwise no way to specify language 3622 // linkage within class scope. 3623 // 3624 // Check cautiously as the friend object kind isn't yet complete. 3625 if (New->getFriendObjectKind() != Decl::FOK_None) { 3626 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3627 Diag(OldLocation, PrevDiag); 3628 } else { 3629 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3630 Diag(OldLocation, PrevDiag); 3631 return true; 3632 } 3633 } 3634 3635 // If the function types are compatible, merge the declarations. Ignore the 3636 // exception specifier because it was already checked above in 3637 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3638 // about incompatible types under -fms-compatibility. 3639 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3640 NewQType)) 3641 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3642 3643 // If the types are imprecise (due to dependent constructs in friends or 3644 // local extern declarations), it's OK if they differ. We'll check again 3645 // during instantiation. 3646 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3647 return false; 3648 3649 // Fall through for conflicting redeclarations and redefinitions. 3650 } 3651 3652 // C: Function types need to be compatible, not identical. This handles 3653 // duplicate function decls like "void f(int); void f(enum X);" properly. 3654 if (!getLangOpts().CPlusPlus && 3655 Context.typesAreCompatible(OldQType, NewQType)) { 3656 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3657 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3658 const FunctionProtoType *OldProto = nullptr; 3659 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3660 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3661 // The old declaration provided a function prototype, but the 3662 // new declaration does not. Merge in the prototype. 3663 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3664 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3665 NewQType = 3666 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3667 OldProto->getExtProtoInfo()); 3668 New->setType(NewQType); 3669 New->setHasInheritedPrototype(); 3670 3671 // Synthesize parameters with the same types. 3672 SmallVector<ParmVarDecl*, 16> Params; 3673 for (const auto &ParamType : OldProto->param_types()) { 3674 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3675 SourceLocation(), nullptr, 3676 ParamType, /*TInfo=*/nullptr, 3677 SC_None, nullptr); 3678 Param->setScopeInfo(0, Params.size()); 3679 Param->setImplicit(); 3680 Params.push_back(Param); 3681 } 3682 3683 New->setParams(Params); 3684 } 3685 3686 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3687 } 3688 3689 // Check if the function types are compatible when pointer size address 3690 // spaces are ignored. 3691 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3692 return false; 3693 3694 // GNU C permits a K&R definition to follow a prototype declaration 3695 // if the declared types of the parameters in the K&R definition 3696 // match the types in the prototype declaration, even when the 3697 // promoted types of the parameters from the K&R definition differ 3698 // from the types in the prototype. GCC then keeps the types from 3699 // the prototype. 3700 // 3701 // If a variadic prototype is followed by a non-variadic K&R definition, 3702 // the K&R definition becomes variadic. This is sort of an edge case, but 3703 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3704 // C99 6.9.1p8. 3705 if (!getLangOpts().CPlusPlus && 3706 Old->hasPrototype() && !New->hasPrototype() && 3707 New->getType()->getAs<FunctionProtoType>() && 3708 Old->getNumParams() == New->getNumParams()) { 3709 SmallVector<QualType, 16> ArgTypes; 3710 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3711 const FunctionProtoType *OldProto 3712 = Old->getType()->getAs<FunctionProtoType>(); 3713 const FunctionProtoType *NewProto 3714 = New->getType()->getAs<FunctionProtoType>(); 3715 3716 // Determine whether this is the GNU C extension. 3717 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3718 NewProto->getReturnType()); 3719 bool LooseCompatible = !MergedReturn.isNull(); 3720 for (unsigned Idx = 0, End = Old->getNumParams(); 3721 LooseCompatible && Idx != End; ++Idx) { 3722 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3723 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3724 if (Context.typesAreCompatible(OldParm->getType(), 3725 NewProto->getParamType(Idx))) { 3726 ArgTypes.push_back(NewParm->getType()); 3727 } else if (Context.typesAreCompatible(OldParm->getType(), 3728 NewParm->getType(), 3729 /*CompareUnqualified=*/true)) { 3730 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3731 NewProto->getParamType(Idx) }; 3732 Warnings.push_back(Warn); 3733 ArgTypes.push_back(NewParm->getType()); 3734 } else 3735 LooseCompatible = false; 3736 } 3737 3738 if (LooseCompatible) { 3739 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3740 Diag(Warnings[Warn].NewParm->getLocation(), 3741 diag::ext_param_promoted_not_compatible_with_prototype) 3742 << Warnings[Warn].PromotedType 3743 << Warnings[Warn].OldParm->getType(); 3744 if (Warnings[Warn].OldParm->getLocation().isValid()) 3745 Diag(Warnings[Warn].OldParm->getLocation(), 3746 diag::note_previous_declaration); 3747 } 3748 3749 if (MergeTypeWithOld) 3750 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3751 OldProto->getExtProtoInfo())); 3752 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3753 } 3754 3755 // Fall through to diagnose conflicting types. 3756 } 3757 3758 // A function that has already been declared has been redeclared or 3759 // defined with a different type; show an appropriate diagnostic. 3760 3761 // If the previous declaration was an implicitly-generated builtin 3762 // declaration, then at the very least we should use a specialized note. 3763 unsigned BuiltinID; 3764 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3765 // If it's actually a library-defined builtin function like 'malloc' 3766 // or 'printf', just warn about the incompatible redeclaration. 3767 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3768 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3769 Diag(OldLocation, diag::note_previous_builtin_declaration) 3770 << Old << Old->getType(); 3771 3772 // If this is a global redeclaration, just forget hereafter 3773 // about the "builtin-ness" of the function. 3774 // 3775 // Doing this for local extern declarations is problematic. If 3776 // the builtin declaration remains visible, a second invalid 3777 // local declaration will produce a hard error; if it doesn't 3778 // remain visible, a single bogus local redeclaration (which is 3779 // actually only a warning) could break all the downstream code. 3780 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3781 New->getIdentifier()->revertBuiltin(); 3782 3783 return false; 3784 } 3785 3786 PrevDiag = diag::note_previous_builtin_declaration; 3787 } 3788 3789 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3790 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3791 return true; 3792 } 3793 3794 /// Completes the merge of two function declarations that are 3795 /// known to be compatible. 3796 /// 3797 /// This routine handles the merging of attributes and other 3798 /// properties of function declarations from the old declaration to 3799 /// the new declaration, once we know that New is in fact a 3800 /// redeclaration of Old. 3801 /// 3802 /// \returns false 3803 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3804 Scope *S, bool MergeTypeWithOld) { 3805 // Merge the attributes 3806 mergeDeclAttributes(New, Old); 3807 3808 // Merge "pure" flag. 3809 if (Old->isPure()) 3810 New->setPure(); 3811 3812 // Merge "used" flag. 3813 if (Old->getMostRecentDecl()->isUsed(false)) 3814 New->setIsUsed(); 3815 3816 // Merge attributes from the parameters. These can mismatch with K&R 3817 // declarations. 3818 if (New->getNumParams() == Old->getNumParams()) 3819 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3820 ParmVarDecl *NewParam = New->getParamDecl(i); 3821 ParmVarDecl *OldParam = Old->getParamDecl(i); 3822 mergeParamDeclAttributes(NewParam, OldParam, *this); 3823 mergeParamDeclTypes(NewParam, OldParam, *this); 3824 } 3825 3826 if (getLangOpts().CPlusPlus) 3827 return MergeCXXFunctionDecl(New, Old, S); 3828 3829 // Merge the function types so the we get the composite types for the return 3830 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3831 // was visible. 3832 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3833 if (!Merged.isNull() && MergeTypeWithOld) 3834 New->setType(Merged); 3835 3836 return false; 3837 } 3838 3839 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3840 ObjCMethodDecl *oldMethod) { 3841 // Merge the attributes, including deprecated/unavailable 3842 AvailabilityMergeKind MergeKind = 3843 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3844 ? AMK_ProtocolImplementation 3845 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3846 : AMK_Override; 3847 3848 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3849 3850 // Merge attributes from the parameters. 3851 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3852 oe = oldMethod->param_end(); 3853 for (ObjCMethodDecl::param_iterator 3854 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3855 ni != ne && oi != oe; ++ni, ++oi) 3856 mergeParamDeclAttributes(*ni, *oi, *this); 3857 3858 CheckObjCMethodOverride(newMethod, oldMethod); 3859 } 3860 3861 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3862 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3863 3864 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3865 ? diag::err_redefinition_different_type 3866 : diag::err_redeclaration_different_type) 3867 << New->getDeclName() << New->getType() << Old->getType(); 3868 3869 diag::kind PrevDiag; 3870 SourceLocation OldLocation; 3871 std::tie(PrevDiag, OldLocation) 3872 = getNoteDiagForInvalidRedeclaration(Old, New); 3873 S.Diag(OldLocation, PrevDiag); 3874 New->setInvalidDecl(); 3875 } 3876 3877 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3878 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3879 /// emitting diagnostics as appropriate. 3880 /// 3881 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3882 /// to here in AddInitializerToDecl. We can't check them before the initializer 3883 /// is attached. 3884 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3885 bool MergeTypeWithOld) { 3886 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3887 return; 3888 3889 QualType MergedT; 3890 if (getLangOpts().CPlusPlus) { 3891 if (New->getType()->isUndeducedType()) { 3892 // We don't know what the new type is until the initializer is attached. 3893 return; 3894 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3895 // These could still be something that needs exception specs checked. 3896 return MergeVarDeclExceptionSpecs(New, Old); 3897 } 3898 // C++ [basic.link]p10: 3899 // [...] the types specified by all declarations referring to a given 3900 // object or function shall be identical, except that declarations for an 3901 // array object can specify array types that differ by the presence or 3902 // absence of a major array bound (8.3.4). 3903 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3904 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3905 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3906 3907 // We are merging a variable declaration New into Old. If it has an array 3908 // bound, and that bound differs from Old's bound, we should diagnose the 3909 // mismatch. 3910 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3911 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3912 PrevVD = PrevVD->getPreviousDecl()) { 3913 QualType PrevVDTy = PrevVD->getType(); 3914 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3915 continue; 3916 3917 if (!Context.hasSameType(New->getType(), PrevVDTy)) 3918 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3919 } 3920 } 3921 3922 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3923 if (Context.hasSameType(OldArray->getElementType(), 3924 NewArray->getElementType())) 3925 MergedT = New->getType(); 3926 } 3927 // FIXME: Check visibility. New is hidden but has a complete type. If New 3928 // has no array bound, it should not inherit one from Old, if Old is not 3929 // visible. 3930 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3931 if (Context.hasSameType(OldArray->getElementType(), 3932 NewArray->getElementType())) 3933 MergedT = Old->getType(); 3934 } 3935 } 3936 else if (New->getType()->isObjCObjectPointerType() && 3937 Old->getType()->isObjCObjectPointerType()) { 3938 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3939 Old->getType()); 3940 } 3941 } else { 3942 // C 6.2.7p2: 3943 // All declarations that refer to the same object or function shall have 3944 // compatible type. 3945 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3946 } 3947 if (MergedT.isNull()) { 3948 // It's OK if we couldn't merge types if either type is dependent, for a 3949 // block-scope variable. In other cases (static data members of class 3950 // templates, variable templates, ...), we require the types to be 3951 // equivalent. 3952 // FIXME: The C++ standard doesn't say anything about this. 3953 if ((New->getType()->isDependentType() || 3954 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3955 // If the old type was dependent, we can't merge with it, so the new type 3956 // becomes dependent for now. We'll reproduce the original type when we 3957 // instantiate the TypeSourceInfo for the variable. 3958 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3959 New->setType(Context.DependentTy); 3960 return; 3961 } 3962 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3963 } 3964 3965 // Don't actually update the type on the new declaration if the old 3966 // declaration was an extern declaration in a different scope. 3967 if (MergeTypeWithOld) 3968 New->setType(MergedT); 3969 } 3970 3971 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3972 LookupResult &Previous) { 3973 // C11 6.2.7p4: 3974 // For an identifier with internal or external linkage declared 3975 // in a scope in which a prior declaration of that identifier is 3976 // visible, if the prior declaration specifies internal or 3977 // external linkage, the type of the identifier at the later 3978 // declaration becomes the composite type. 3979 // 3980 // If the variable isn't visible, we do not merge with its type. 3981 if (Previous.isShadowed()) 3982 return false; 3983 3984 if (S.getLangOpts().CPlusPlus) { 3985 // C++11 [dcl.array]p3: 3986 // If there is a preceding declaration of the entity in the same 3987 // scope in which the bound was specified, an omitted array bound 3988 // is taken to be the same as in that earlier declaration. 3989 return NewVD->isPreviousDeclInSameBlockScope() || 3990 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3991 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3992 } else { 3993 // If the old declaration was function-local, don't merge with its 3994 // type unless we're in the same function. 3995 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3996 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3997 } 3998 } 3999 4000 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4001 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4002 /// situation, merging decls or emitting diagnostics as appropriate. 4003 /// 4004 /// Tentative definition rules (C99 6.9.2p2) are checked by 4005 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4006 /// definitions here, since the initializer hasn't been attached. 4007 /// 4008 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4009 // If the new decl is already invalid, don't do any other checking. 4010 if (New->isInvalidDecl()) 4011 return; 4012 4013 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4014 return; 4015 4016 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4017 4018 // Verify the old decl was also a variable or variable template. 4019 VarDecl *Old = nullptr; 4020 VarTemplateDecl *OldTemplate = nullptr; 4021 if (Previous.isSingleResult()) { 4022 if (NewTemplate) { 4023 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4024 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4025 4026 if (auto *Shadow = 4027 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4028 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4029 return New->setInvalidDecl(); 4030 } else { 4031 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4032 4033 if (auto *Shadow = 4034 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4035 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4036 return New->setInvalidDecl(); 4037 } 4038 } 4039 if (!Old) { 4040 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4041 << New->getDeclName(); 4042 notePreviousDefinition(Previous.getRepresentativeDecl(), 4043 New->getLocation()); 4044 return New->setInvalidDecl(); 4045 } 4046 4047 // Ensure the template parameters are compatible. 4048 if (NewTemplate && 4049 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4050 OldTemplate->getTemplateParameters(), 4051 /*Complain=*/true, TPL_TemplateMatch)) 4052 return New->setInvalidDecl(); 4053 4054 // C++ [class.mem]p1: 4055 // A member shall not be declared twice in the member-specification [...] 4056 // 4057 // Here, we need only consider static data members. 4058 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4059 Diag(New->getLocation(), diag::err_duplicate_member) 4060 << New->getIdentifier(); 4061 Diag(Old->getLocation(), diag::note_previous_declaration); 4062 New->setInvalidDecl(); 4063 } 4064 4065 mergeDeclAttributes(New, Old); 4066 // Warn if an already-declared variable is made a weak_import in a subsequent 4067 // declaration 4068 if (New->hasAttr<WeakImportAttr>() && 4069 Old->getStorageClass() == SC_None && 4070 !Old->hasAttr<WeakImportAttr>()) { 4071 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4072 notePreviousDefinition(Old, New->getLocation()); 4073 // Remove weak_import attribute on new declaration. 4074 New->dropAttr<WeakImportAttr>(); 4075 } 4076 4077 if (New->hasAttr<InternalLinkageAttr>() && 4078 !Old->hasAttr<InternalLinkageAttr>()) { 4079 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4080 << New->getDeclName(); 4081 notePreviousDefinition(Old, New->getLocation()); 4082 New->dropAttr<InternalLinkageAttr>(); 4083 } 4084 4085 // Merge the types. 4086 VarDecl *MostRecent = Old->getMostRecentDecl(); 4087 if (MostRecent != Old) { 4088 MergeVarDeclTypes(New, MostRecent, 4089 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4090 if (New->isInvalidDecl()) 4091 return; 4092 } 4093 4094 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4095 if (New->isInvalidDecl()) 4096 return; 4097 4098 diag::kind PrevDiag; 4099 SourceLocation OldLocation; 4100 std::tie(PrevDiag, OldLocation) = 4101 getNoteDiagForInvalidRedeclaration(Old, New); 4102 4103 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4104 if (New->getStorageClass() == SC_Static && 4105 !New->isStaticDataMember() && 4106 Old->hasExternalFormalLinkage()) { 4107 if (getLangOpts().MicrosoftExt) { 4108 Diag(New->getLocation(), diag::ext_static_non_static) 4109 << New->getDeclName(); 4110 Diag(OldLocation, PrevDiag); 4111 } else { 4112 Diag(New->getLocation(), diag::err_static_non_static) 4113 << New->getDeclName(); 4114 Diag(OldLocation, PrevDiag); 4115 return New->setInvalidDecl(); 4116 } 4117 } 4118 // C99 6.2.2p4: 4119 // For an identifier declared with the storage-class specifier 4120 // extern in a scope in which a prior declaration of that 4121 // identifier is visible,23) if the prior declaration specifies 4122 // internal or external linkage, the linkage of the identifier at 4123 // the later declaration is the same as the linkage specified at 4124 // the prior declaration. If no prior declaration is visible, or 4125 // if the prior declaration specifies no linkage, then the 4126 // identifier has external linkage. 4127 if (New->hasExternalStorage() && Old->hasLinkage()) 4128 /* Okay */; 4129 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4130 !New->isStaticDataMember() && 4131 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4132 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4133 Diag(OldLocation, PrevDiag); 4134 return New->setInvalidDecl(); 4135 } 4136 4137 // Check if extern is followed by non-extern and vice-versa. 4138 if (New->hasExternalStorage() && 4139 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4140 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4141 Diag(OldLocation, PrevDiag); 4142 return New->setInvalidDecl(); 4143 } 4144 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4145 !New->hasExternalStorage()) { 4146 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4147 Diag(OldLocation, PrevDiag); 4148 return New->setInvalidDecl(); 4149 } 4150 4151 if (CheckRedeclarationModuleOwnership(New, Old)) 4152 return; 4153 4154 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4155 4156 // FIXME: The test for external storage here seems wrong? We still 4157 // need to check for mismatches. 4158 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4159 // Don't complain about out-of-line definitions of static members. 4160 !(Old->getLexicalDeclContext()->isRecord() && 4161 !New->getLexicalDeclContext()->isRecord())) { 4162 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4163 Diag(OldLocation, PrevDiag); 4164 return New->setInvalidDecl(); 4165 } 4166 4167 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4168 if (VarDecl *Def = Old->getDefinition()) { 4169 // C++1z [dcl.fcn.spec]p4: 4170 // If the definition of a variable appears in a translation unit before 4171 // its first declaration as inline, the program is ill-formed. 4172 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4173 Diag(Def->getLocation(), diag::note_previous_definition); 4174 } 4175 } 4176 4177 // If this redeclaration makes the variable inline, we may need to add it to 4178 // UndefinedButUsed. 4179 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4180 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4181 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4182 SourceLocation())); 4183 4184 if (New->getTLSKind() != Old->getTLSKind()) { 4185 if (!Old->getTLSKind()) { 4186 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4187 Diag(OldLocation, PrevDiag); 4188 } else if (!New->getTLSKind()) { 4189 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4190 Diag(OldLocation, PrevDiag); 4191 } else { 4192 // Do not allow redeclaration to change the variable between requiring 4193 // static and dynamic initialization. 4194 // FIXME: GCC allows this, but uses the TLS keyword on the first 4195 // declaration to determine the kind. Do we need to be compatible here? 4196 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4197 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4198 Diag(OldLocation, PrevDiag); 4199 } 4200 } 4201 4202 // C++ doesn't have tentative definitions, so go right ahead and check here. 4203 if (getLangOpts().CPlusPlus && 4204 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4205 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4206 Old->getCanonicalDecl()->isConstexpr()) { 4207 // This definition won't be a definition any more once it's been merged. 4208 Diag(New->getLocation(), 4209 diag::warn_deprecated_redundant_constexpr_static_def); 4210 } else if (VarDecl *Def = Old->getDefinition()) { 4211 if (checkVarDeclRedefinition(Def, New)) 4212 return; 4213 } 4214 } 4215 4216 if (haveIncompatibleLanguageLinkages(Old, New)) { 4217 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4218 Diag(OldLocation, PrevDiag); 4219 New->setInvalidDecl(); 4220 return; 4221 } 4222 4223 // Merge "used" flag. 4224 if (Old->getMostRecentDecl()->isUsed(false)) 4225 New->setIsUsed(); 4226 4227 // Keep a chain of previous declarations. 4228 New->setPreviousDecl(Old); 4229 if (NewTemplate) 4230 NewTemplate->setPreviousDecl(OldTemplate); 4231 adjustDeclContextForDeclaratorDecl(New, Old); 4232 4233 // Inherit access appropriately. 4234 New->setAccess(Old->getAccess()); 4235 if (NewTemplate) 4236 NewTemplate->setAccess(New->getAccess()); 4237 4238 if (Old->isInline()) 4239 New->setImplicitlyInline(); 4240 } 4241 4242 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4243 SourceManager &SrcMgr = getSourceManager(); 4244 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4245 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4246 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4247 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4248 auto &HSI = PP.getHeaderSearchInfo(); 4249 StringRef HdrFilename = 4250 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4251 4252 auto noteFromModuleOrInclude = [&](Module *Mod, 4253 SourceLocation IncLoc) -> bool { 4254 // Redefinition errors with modules are common with non modular mapped 4255 // headers, example: a non-modular header H in module A that also gets 4256 // included directly in a TU. Pointing twice to the same header/definition 4257 // is confusing, try to get better diagnostics when modules is on. 4258 if (IncLoc.isValid()) { 4259 if (Mod) { 4260 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4261 << HdrFilename.str() << Mod->getFullModuleName(); 4262 if (!Mod->DefinitionLoc.isInvalid()) 4263 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4264 << Mod->getFullModuleName(); 4265 } else { 4266 Diag(IncLoc, diag::note_redefinition_include_same_file) 4267 << HdrFilename.str(); 4268 } 4269 return true; 4270 } 4271 4272 return false; 4273 }; 4274 4275 // Is it the same file and same offset? Provide more information on why 4276 // this leads to a redefinition error. 4277 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4278 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4279 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4280 bool EmittedDiag = 4281 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4282 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4283 4284 // If the header has no guards, emit a note suggesting one. 4285 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4286 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4287 4288 if (EmittedDiag) 4289 return; 4290 } 4291 4292 // Redefinition coming from different files or couldn't do better above. 4293 if (Old->getLocation().isValid()) 4294 Diag(Old->getLocation(), diag::note_previous_definition); 4295 } 4296 4297 /// We've just determined that \p Old and \p New both appear to be definitions 4298 /// of the same variable. Either diagnose or fix the problem. 4299 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4300 if (!hasVisibleDefinition(Old) && 4301 (New->getFormalLinkage() == InternalLinkage || 4302 New->isInline() || 4303 New->getDescribedVarTemplate() || 4304 New->getNumTemplateParameterLists() || 4305 New->getDeclContext()->isDependentContext())) { 4306 // The previous definition is hidden, and multiple definitions are 4307 // permitted (in separate TUs). Demote this to a declaration. 4308 New->demoteThisDefinitionToDeclaration(); 4309 4310 // Make the canonical definition visible. 4311 if (auto *OldTD = Old->getDescribedVarTemplate()) 4312 makeMergedDefinitionVisible(OldTD); 4313 makeMergedDefinitionVisible(Old); 4314 return false; 4315 } else { 4316 Diag(New->getLocation(), diag::err_redefinition) << New; 4317 notePreviousDefinition(Old, New->getLocation()); 4318 New->setInvalidDecl(); 4319 return true; 4320 } 4321 } 4322 4323 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4324 /// no declarator (e.g. "struct foo;") is parsed. 4325 Decl * 4326 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4327 RecordDecl *&AnonRecord) { 4328 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4329 AnonRecord); 4330 } 4331 4332 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4333 // disambiguate entities defined in different scopes. 4334 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4335 // compatibility. 4336 // We will pick our mangling number depending on which version of MSVC is being 4337 // targeted. 4338 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4339 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4340 ? S->getMSCurManglingNumber() 4341 : S->getMSLastManglingNumber(); 4342 } 4343 4344 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4345 if (!Context.getLangOpts().CPlusPlus) 4346 return; 4347 4348 if (isa<CXXRecordDecl>(Tag->getParent())) { 4349 // If this tag is the direct child of a class, number it if 4350 // it is anonymous. 4351 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4352 return; 4353 MangleNumberingContext &MCtx = 4354 Context.getManglingNumberContext(Tag->getParent()); 4355 Context.setManglingNumber( 4356 Tag, MCtx.getManglingNumber( 4357 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4358 return; 4359 } 4360 4361 // If this tag isn't a direct child of a class, number it if it is local. 4362 MangleNumberingContext *MCtx; 4363 Decl *ManglingContextDecl; 4364 std::tie(MCtx, ManglingContextDecl) = 4365 getCurrentMangleNumberContext(Tag->getDeclContext()); 4366 if (MCtx) { 4367 Context.setManglingNumber( 4368 Tag, MCtx->getManglingNumber( 4369 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4370 } 4371 } 4372 4373 namespace { 4374 struct NonCLikeKind { 4375 enum { 4376 None, 4377 BaseClass, 4378 DefaultMemberInit, 4379 Lambda, 4380 Friend, 4381 OtherMember, 4382 Invalid, 4383 } Kind = None; 4384 SourceRange Range; 4385 4386 explicit operator bool() { return Kind != None; } 4387 }; 4388 } 4389 4390 /// Determine whether a class is C-like, according to the rules of C++ 4391 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4392 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4393 if (RD->isInvalidDecl()) 4394 return {NonCLikeKind::Invalid, {}}; 4395 4396 // C++ [dcl.typedef]p9: [P1766R1] 4397 // An unnamed class with a typedef name for linkage purposes shall not 4398 // 4399 // -- have any base classes 4400 if (RD->getNumBases()) 4401 return {NonCLikeKind::BaseClass, 4402 SourceRange(RD->bases_begin()->getBeginLoc(), 4403 RD->bases_end()[-1].getEndLoc())}; 4404 bool Invalid = false; 4405 for (Decl *D : RD->decls()) { 4406 // Don't complain about things we already diagnosed. 4407 if (D->isInvalidDecl()) { 4408 Invalid = true; 4409 continue; 4410 } 4411 4412 // -- have any [...] default member initializers 4413 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4414 if (FD->hasInClassInitializer()) { 4415 auto *Init = FD->getInClassInitializer(); 4416 return {NonCLikeKind::DefaultMemberInit, 4417 Init ? Init->getSourceRange() : D->getSourceRange()}; 4418 } 4419 continue; 4420 } 4421 4422 // FIXME: We don't allow friend declarations. This violates the wording of 4423 // P1766, but not the intent. 4424 if (isa<FriendDecl>(D)) 4425 return {NonCLikeKind::Friend, D->getSourceRange()}; 4426 4427 // -- declare any members other than non-static data members, member 4428 // enumerations, or member classes, 4429 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4430 isa<EnumDecl>(D)) 4431 continue; 4432 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4433 if (!MemberRD) { 4434 if (D->isImplicit()) 4435 continue; 4436 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4437 } 4438 4439 // -- contain a lambda-expression, 4440 if (MemberRD->isLambda()) 4441 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4442 4443 // and all member classes shall also satisfy these requirements 4444 // (recursively). 4445 if (MemberRD->isThisDeclarationADefinition()) { 4446 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4447 return Kind; 4448 } 4449 } 4450 4451 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4452 } 4453 4454 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4455 TypedefNameDecl *NewTD) { 4456 if (TagFromDeclSpec->isInvalidDecl()) 4457 return; 4458 4459 // Do nothing if the tag already has a name for linkage purposes. 4460 if (TagFromDeclSpec->hasNameForLinkage()) 4461 return; 4462 4463 // A well-formed anonymous tag must always be a TUK_Definition. 4464 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4465 4466 // The type must match the tag exactly; no qualifiers allowed. 4467 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4468 Context.getTagDeclType(TagFromDeclSpec))) { 4469 if (getLangOpts().CPlusPlus) 4470 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4471 return; 4472 } 4473 4474 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4475 // An unnamed class with a typedef name for linkage purposes shall [be 4476 // C-like]. 4477 // 4478 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4479 // shouldn't happen, but there are constructs that the language rule doesn't 4480 // disallow for which we can't reasonably avoid computing linkage early. 4481 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4482 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4483 : NonCLikeKind(); 4484 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4485 if (NonCLike || ChangesLinkage) { 4486 if (NonCLike.Kind == NonCLikeKind::Invalid) 4487 return; 4488 4489 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4490 if (ChangesLinkage) { 4491 // If the linkage changes, we can't accept this as an extension. 4492 if (NonCLike.Kind == NonCLikeKind::None) 4493 DiagID = diag::err_typedef_changes_linkage; 4494 else 4495 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4496 } 4497 4498 SourceLocation FixitLoc = 4499 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4500 llvm::SmallString<40> TextToInsert; 4501 TextToInsert += ' '; 4502 TextToInsert += NewTD->getIdentifier()->getName(); 4503 4504 Diag(FixitLoc, DiagID) 4505 << isa<TypeAliasDecl>(NewTD) 4506 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4507 if (NonCLike.Kind != NonCLikeKind::None) { 4508 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4509 << NonCLike.Kind - 1 << NonCLike.Range; 4510 } 4511 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4512 << NewTD << isa<TypeAliasDecl>(NewTD); 4513 4514 if (ChangesLinkage) 4515 return; 4516 } 4517 4518 // Otherwise, set this as the anon-decl typedef for the tag. 4519 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4520 } 4521 4522 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4523 switch (T) { 4524 case DeclSpec::TST_class: 4525 return 0; 4526 case DeclSpec::TST_struct: 4527 return 1; 4528 case DeclSpec::TST_interface: 4529 return 2; 4530 case DeclSpec::TST_union: 4531 return 3; 4532 case DeclSpec::TST_enum: 4533 return 4; 4534 default: 4535 llvm_unreachable("unexpected type specifier"); 4536 } 4537 } 4538 4539 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4540 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4541 /// parameters to cope with template friend declarations. 4542 Decl * 4543 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4544 MultiTemplateParamsArg TemplateParams, 4545 bool IsExplicitInstantiation, 4546 RecordDecl *&AnonRecord) { 4547 Decl *TagD = nullptr; 4548 TagDecl *Tag = nullptr; 4549 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4550 DS.getTypeSpecType() == DeclSpec::TST_struct || 4551 DS.getTypeSpecType() == DeclSpec::TST_interface || 4552 DS.getTypeSpecType() == DeclSpec::TST_union || 4553 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4554 TagD = DS.getRepAsDecl(); 4555 4556 if (!TagD) // We probably had an error 4557 return nullptr; 4558 4559 // Note that the above type specs guarantee that the 4560 // type rep is a Decl, whereas in many of the others 4561 // it's a Type. 4562 if (isa<TagDecl>(TagD)) 4563 Tag = cast<TagDecl>(TagD); 4564 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4565 Tag = CTD->getTemplatedDecl(); 4566 } 4567 4568 if (Tag) { 4569 handleTagNumbering(Tag, S); 4570 Tag->setFreeStanding(); 4571 if (Tag->isInvalidDecl()) 4572 return Tag; 4573 } 4574 4575 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4576 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4577 // or incomplete types shall not be restrict-qualified." 4578 if (TypeQuals & DeclSpec::TQ_restrict) 4579 Diag(DS.getRestrictSpecLoc(), 4580 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4581 << DS.getSourceRange(); 4582 } 4583 4584 if (DS.isInlineSpecified()) 4585 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4586 << getLangOpts().CPlusPlus17; 4587 4588 if (DS.hasConstexprSpecifier()) { 4589 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4590 // and definitions of functions and variables. 4591 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4592 // the declaration of a function or function template 4593 if (Tag) 4594 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4595 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4596 << DS.getConstexprSpecifier(); 4597 else 4598 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4599 << DS.getConstexprSpecifier(); 4600 // Don't emit warnings after this error. 4601 return TagD; 4602 } 4603 4604 DiagnoseFunctionSpecifiers(DS); 4605 4606 if (DS.isFriendSpecified()) { 4607 // If we're dealing with a decl but not a TagDecl, assume that 4608 // whatever routines created it handled the friendship aspect. 4609 if (TagD && !Tag) 4610 return nullptr; 4611 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4612 } 4613 4614 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4615 bool IsExplicitSpecialization = 4616 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4617 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4618 !IsExplicitInstantiation && !IsExplicitSpecialization && 4619 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4620 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4621 // nested-name-specifier unless it is an explicit instantiation 4622 // or an explicit specialization. 4623 // 4624 // FIXME: We allow class template partial specializations here too, per the 4625 // obvious intent of DR1819. 4626 // 4627 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4628 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4629 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4630 return nullptr; 4631 } 4632 4633 // Track whether this decl-specifier declares anything. 4634 bool DeclaresAnything = true; 4635 4636 // Handle anonymous struct definitions. 4637 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4638 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4639 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4640 if (getLangOpts().CPlusPlus || 4641 Record->getDeclContext()->isRecord()) { 4642 // If CurContext is a DeclContext that can contain statements, 4643 // RecursiveASTVisitor won't visit the decls that 4644 // BuildAnonymousStructOrUnion() will put into CurContext. 4645 // Also store them here so that they can be part of the 4646 // DeclStmt that gets created in this case. 4647 // FIXME: Also return the IndirectFieldDecls created by 4648 // BuildAnonymousStructOr union, for the same reason? 4649 if (CurContext->isFunctionOrMethod()) 4650 AnonRecord = Record; 4651 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4652 Context.getPrintingPolicy()); 4653 } 4654 4655 DeclaresAnything = false; 4656 } 4657 } 4658 4659 // C11 6.7.2.1p2: 4660 // A struct-declaration that does not declare an anonymous structure or 4661 // anonymous union shall contain a struct-declarator-list. 4662 // 4663 // This rule also existed in C89 and C99; the grammar for struct-declaration 4664 // did not permit a struct-declaration without a struct-declarator-list. 4665 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4666 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4667 // Check for Microsoft C extension: anonymous struct/union member. 4668 // Handle 2 kinds of anonymous struct/union: 4669 // struct STRUCT; 4670 // union UNION; 4671 // and 4672 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4673 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4674 if ((Tag && Tag->getDeclName()) || 4675 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4676 RecordDecl *Record = nullptr; 4677 if (Tag) 4678 Record = dyn_cast<RecordDecl>(Tag); 4679 else if (const RecordType *RT = 4680 DS.getRepAsType().get()->getAsStructureType()) 4681 Record = RT->getDecl(); 4682 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4683 Record = UT->getDecl(); 4684 4685 if (Record && getLangOpts().MicrosoftExt) { 4686 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4687 << Record->isUnion() << DS.getSourceRange(); 4688 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4689 } 4690 4691 DeclaresAnything = false; 4692 } 4693 } 4694 4695 // Skip all the checks below if we have a type error. 4696 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4697 (TagD && TagD->isInvalidDecl())) 4698 return TagD; 4699 4700 if (getLangOpts().CPlusPlus && 4701 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4702 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4703 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4704 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4705 DeclaresAnything = false; 4706 4707 if (!DS.isMissingDeclaratorOk()) { 4708 // Customize diagnostic for a typedef missing a name. 4709 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4710 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4711 << DS.getSourceRange(); 4712 else 4713 DeclaresAnything = false; 4714 } 4715 4716 if (DS.isModulePrivateSpecified() && 4717 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4718 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4719 << Tag->getTagKind() 4720 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4721 4722 ActOnDocumentableDecl(TagD); 4723 4724 // C 6.7/2: 4725 // A declaration [...] shall declare at least a declarator [...], a tag, 4726 // or the members of an enumeration. 4727 // C++ [dcl.dcl]p3: 4728 // [If there are no declarators], and except for the declaration of an 4729 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4730 // names into the program, or shall redeclare a name introduced by a 4731 // previous declaration. 4732 if (!DeclaresAnything) { 4733 // In C, we allow this as a (popular) extension / bug. Don't bother 4734 // producing further diagnostics for redundant qualifiers after this. 4735 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4736 return TagD; 4737 } 4738 4739 // C++ [dcl.stc]p1: 4740 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4741 // init-declarator-list of the declaration shall not be empty. 4742 // C++ [dcl.fct.spec]p1: 4743 // If a cv-qualifier appears in a decl-specifier-seq, the 4744 // init-declarator-list of the declaration shall not be empty. 4745 // 4746 // Spurious qualifiers here appear to be valid in C. 4747 unsigned DiagID = diag::warn_standalone_specifier; 4748 if (getLangOpts().CPlusPlus) 4749 DiagID = diag::ext_standalone_specifier; 4750 4751 // Note that a linkage-specification sets a storage class, but 4752 // 'extern "C" struct foo;' is actually valid and not theoretically 4753 // useless. 4754 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4755 if (SCS == DeclSpec::SCS_mutable) 4756 // Since mutable is not a viable storage class specifier in C, there is 4757 // no reason to treat it as an extension. Instead, diagnose as an error. 4758 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4759 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4760 Diag(DS.getStorageClassSpecLoc(), DiagID) 4761 << DeclSpec::getSpecifierName(SCS); 4762 } 4763 4764 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4765 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4766 << DeclSpec::getSpecifierName(TSCS); 4767 if (DS.getTypeQualifiers()) { 4768 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4769 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4770 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4771 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4772 // Restrict is covered above. 4773 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4774 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4775 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4776 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4777 } 4778 4779 // Warn about ignored type attributes, for example: 4780 // __attribute__((aligned)) struct A; 4781 // Attributes should be placed after tag to apply to type declaration. 4782 if (!DS.getAttributes().empty()) { 4783 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4784 if (TypeSpecType == DeclSpec::TST_class || 4785 TypeSpecType == DeclSpec::TST_struct || 4786 TypeSpecType == DeclSpec::TST_interface || 4787 TypeSpecType == DeclSpec::TST_union || 4788 TypeSpecType == DeclSpec::TST_enum) { 4789 for (const ParsedAttr &AL : DS.getAttributes()) 4790 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4791 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4792 } 4793 } 4794 4795 return TagD; 4796 } 4797 4798 /// We are trying to inject an anonymous member into the given scope; 4799 /// check if there's an existing declaration that can't be overloaded. 4800 /// 4801 /// \return true if this is a forbidden redeclaration 4802 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4803 Scope *S, 4804 DeclContext *Owner, 4805 DeclarationName Name, 4806 SourceLocation NameLoc, 4807 bool IsUnion) { 4808 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4809 Sema::ForVisibleRedeclaration); 4810 if (!SemaRef.LookupName(R, S)) return false; 4811 4812 // Pick a representative declaration. 4813 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4814 assert(PrevDecl && "Expected a non-null Decl"); 4815 4816 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4817 return false; 4818 4819 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4820 << IsUnion << Name; 4821 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4822 4823 return true; 4824 } 4825 4826 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4827 /// anonymous struct or union AnonRecord into the owning context Owner 4828 /// and scope S. This routine will be invoked just after we realize 4829 /// that an unnamed union or struct is actually an anonymous union or 4830 /// struct, e.g., 4831 /// 4832 /// @code 4833 /// union { 4834 /// int i; 4835 /// float f; 4836 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4837 /// // f into the surrounding scope.x 4838 /// @endcode 4839 /// 4840 /// This routine is recursive, injecting the names of nested anonymous 4841 /// structs/unions into the owning context and scope as well. 4842 static bool 4843 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4844 RecordDecl *AnonRecord, AccessSpecifier AS, 4845 SmallVectorImpl<NamedDecl *> &Chaining) { 4846 bool Invalid = false; 4847 4848 // Look every FieldDecl and IndirectFieldDecl with a name. 4849 for (auto *D : AnonRecord->decls()) { 4850 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4851 cast<NamedDecl>(D)->getDeclName()) { 4852 ValueDecl *VD = cast<ValueDecl>(D); 4853 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4854 VD->getLocation(), 4855 AnonRecord->isUnion())) { 4856 // C++ [class.union]p2: 4857 // The names of the members of an anonymous union shall be 4858 // distinct from the names of any other entity in the 4859 // scope in which the anonymous union is declared. 4860 Invalid = true; 4861 } else { 4862 // C++ [class.union]p2: 4863 // For the purpose of name lookup, after the anonymous union 4864 // definition, the members of the anonymous union are 4865 // considered to have been defined in the scope in which the 4866 // anonymous union is declared. 4867 unsigned OldChainingSize = Chaining.size(); 4868 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4869 Chaining.append(IF->chain_begin(), IF->chain_end()); 4870 else 4871 Chaining.push_back(VD); 4872 4873 assert(Chaining.size() >= 2); 4874 NamedDecl **NamedChain = 4875 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4876 for (unsigned i = 0; i < Chaining.size(); i++) 4877 NamedChain[i] = Chaining[i]; 4878 4879 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4880 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4881 VD->getType(), {NamedChain, Chaining.size()}); 4882 4883 for (const auto *Attr : VD->attrs()) 4884 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4885 4886 IndirectField->setAccess(AS); 4887 IndirectField->setImplicit(); 4888 SemaRef.PushOnScopeChains(IndirectField, S); 4889 4890 // That includes picking up the appropriate access specifier. 4891 if (AS != AS_none) IndirectField->setAccess(AS); 4892 4893 Chaining.resize(OldChainingSize); 4894 } 4895 } 4896 } 4897 4898 return Invalid; 4899 } 4900 4901 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4902 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4903 /// illegal input values are mapped to SC_None. 4904 static StorageClass 4905 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4906 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4907 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4908 "Parser allowed 'typedef' as storage class VarDecl."); 4909 switch (StorageClassSpec) { 4910 case DeclSpec::SCS_unspecified: return SC_None; 4911 case DeclSpec::SCS_extern: 4912 if (DS.isExternInLinkageSpec()) 4913 return SC_None; 4914 return SC_Extern; 4915 case DeclSpec::SCS_static: return SC_Static; 4916 case DeclSpec::SCS_auto: return SC_Auto; 4917 case DeclSpec::SCS_register: return SC_Register; 4918 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4919 // Illegal SCSs map to None: error reporting is up to the caller. 4920 case DeclSpec::SCS_mutable: // Fall through. 4921 case DeclSpec::SCS_typedef: return SC_None; 4922 } 4923 llvm_unreachable("unknown storage class specifier"); 4924 } 4925 4926 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4927 assert(Record->hasInClassInitializer()); 4928 4929 for (const auto *I : Record->decls()) { 4930 const auto *FD = dyn_cast<FieldDecl>(I); 4931 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4932 FD = IFD->getAnonField(); 4933 if (FD && FD->hasInClassInitializer()) 4934 return FD->getLocation(); 4935 } 4936 4937 llvm_unreachable("couldn't find in-class initializer"); 4938 } 4939 4940 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4941 SourceLocation DefaultInitLoc) { 4942 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4943 return; 4944 4945 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4946 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4947 } 4948 4949 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4950 CXXRecordDecl *AnonUnion) { 4951 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4952 return; 4953 4954 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4955 } 4956 4957 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4958 /// anonymous structure or union. Anonymous unions are a C++ feature 4959 /// (C++ [class.union]) and a C11 feature; anonymous structures 4960 /// are a C11 feature and GNU C++ extension. 4961 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4962 AccessSpecifier AS, 4963 RecordDecl *Record, 4964 const PrintingPolicy &Policy) { 4965 DeclContext *Owner = Record->getDeclContext(); 4966 4967 // Diagnose whether this anonymous struct/union is an extension. 4968 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4969 Diag(Record->getLocation(), diag::ext_anonymous_union); 4970 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4971 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4972 else if (!Record->isUnion() && !getLangOpts().C11) 4973 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4974 4975 // C and C++ require different kinds of checks for anonymous 4976 // structs/unions. 4977 bool Invalid = false; 4978 if (getLangOpts().CPlusPlus) { 4979 const char *PrevSpec = nullptr; 4980 if (Record->isUnion()) { 4981 // C++ [class.union]p6: 4982 // C++17 [class.union.anon]p2: 4983 // Anonymous unions declared in a named namespace or in the 4984 // global namespace shall be declared static. 4985 unsigned DiagID; 4986 DeclContext *OwnerScope = Owner->getRedeclContext(); 4987 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4988 (OwnerScope->isTranslationUnit() || 4989 (OwnerScope->isNamespace() && 4990 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 4991 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4992 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4993 4994 // Recover by adding 'static'. 4995 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4996 PrevSpec, DiagID, Policy); 4997 } 4998 // C++ [class.union]p6: 4999 // A storage class is not allowed in a declaration of an 5000 // anonymous union in a class scope. 5001 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5002 isa<RecordDecl>(Owner)) { 5003 Diag(DS.getStorageClassSpecLoc(), 5004 diag::err_anonymous_union_with_storage_spec) 5005 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5006 5007 // Recover by removing the storage specifier. 5008 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5009 SourceLocation(), 5010 PrevSpec, DiagID, Context.getPrintingPolicy()); 5011 } 5012 } 5013 5014 // Ignore const/volatile/restrict qualifiers. 5015 if (DS.getTypeQualifiers()) { 5016 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5017 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5018 << Record->isUnion() << "const" 5019 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5020 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5021 Diag(DS.getVolatileSpecLoc(), 5022 diag::ext_anonymous_struct_union_qualified) 5023 << Record->isUnion() << "volatile" 5024 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5025 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5026 Diag(DS.getRestrictSpecLoc(), 5027 diag::ext_anonymous_struct_union_qualified) 5028 << Record->isUnion() << "restrict" 5029 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5030 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5031 Diag(DS.getAtomicSpecLoc(), 5032 diag::ext_anonymous_struct_union_qualified) 5033 << Record->isUnion() << "_Atomic" 5034 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5035 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5036 Diag(DS.getUnalignedSpecLoc(), 5037 diag::ext_anonymous_struct_union_qualified) 5038 << Record->isUnion() << "__unaligned" 5039 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5040 5041 DS.ClearTypeQualifiers(); 5042 } 5043 5044 // C++ [class.union]p2: 5045 // The member-specification of an anonymous union shall only 5046 // define non-static data members. [Note: nested types and 5047 // functions cannot be declared within an anonymous union. ] 5048 for (auto *Mem : Record->decls()) { 5049 // Ignore invalid declarations; we already diagnosed them. 5050 if (Mem->isInvalidDecl()) 5051 continue; 5052 5053 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5054 // C++ [class.union]p3: 5055 // An anonymous union shall not have private or protected 5056 // members (clause 11). 5057 assert(FD->getAccess() != AS_none); 5058 if (FD->getAccess() != AS_public) { 5059 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5060 << Record->isUnion() << (FD->getAccess() == AS_protected); 5061 Invalid = true; 5062 } 5063 5064 // C++ [class.union]p1 5065 // An object of a class with a non-trivial constructor, a non-trivial 5066 // copy constructor, a non-trivial destructor, or a non-trivial copy 5067 // assignment operator cannot be a member of a union, nor can an 5068 // array of such objects. 5069 if (CheckNontrivialField(FD)) 5070 Invalid = true; 5071 } else if (Mem->isImplicit()) { 5072 // Any implicit members are fine. 5073 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5074 // This is a type that showed up in an 5075 // elaborated-type-specifier inside the anonymous struct or 5076 // union, but which actually declares a type outside of the 5077 // anonymous struct or union. It's okay. 5078 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5079 if (!MemRecord->isAnonymousStructOrUnion() && 5080 MemRecord->getDeclName()) { 5081 // Visual C++ allows type definition in anonymous struct or union. 5082 if (getLangOpts().MicrosoftExt) 5083 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5084 << Record->isUnion(); 5085 else { 5086 // This is a nested type declaration. 5087 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5088 << Record->isUnion(); 5089 Invalid = true; 5090 } 5091 } else { 5092 // This is an anonymous type definition within another anonymous type. 5093 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5094 // not part of standard C++. 5095 Diag(MemRecord->getLocation(), 5096 diag::ext_anonymous_record_with_anonymous_type) 5097 << Record->isUnion(); 5098 } 5099 } else if (isa<AccessSpecDecl>(Mem)) { 5100 // Any access specifier is fine. 5101 } else if (isa<StaticAssertDecl>(Mem)) { 5102 // In C++1z, static_assert declarations are also fine. 5103 } else { 5104 // We have something that isn't a non-static data 5105 // member. Complain about it. 5106 unsigned DK = diag::err_anonymous_record_bad_member; 5107 if (isa<TypeDecl>(Mem)) 5108 DK = diag::err_anonymous_record_with_type; 5109 else if (isa<FunctionDecl>(Mem)) 5110 DK = diag::err_anonymous_record_with_function; 5111 else if (isa<VarDecl>(Mem)) 5112 DK = diag::err_anonymous_record_with_static; 5113 5114 // Visual C++ allows type definition in anonymous struct or union. 5115 if (getLangOpts().MicrosoftExt && 5116 DK == diag::err_anonymous_record_with_type) 5117 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5118 << Record->isUnion(); 5119 else { 5120 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5121 Invalid = true; 5122 } 5123 } 5124 } 5125 5126 // C++11 [class.union]p8 (DR1460): 5127 // At most one variant member of a union may have a 5128 // brace-or-equal-initializer. 5129 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5130 Owner->isRecord()) 5131 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5132 cast<CXXRecordDecl>(Record)); 5133 } 5134 5135 if (!Record->isUnion() && !Owner->isRecord()) { 5136 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5137 << getLangOpts().CPlusPlus; 5138 Invalid = true; 5139 } 5140 5141 // C++ [dcl.dcl]p3: 5142 // [If there are no declarators], and except for the declaration of an 5143 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5144 // names into the program 5145 // C++ [class.mem]p2: 5146 // each such member-declaration shall either declare at least one member 5147 // name of the class or declare at least one unnamed bit-field 5148 // 5149 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5150 if (getLangOpts().CPlusPlus && Record->field_empty()) 5151 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5152 5153 // Mock up a declarator. 5154 Declarator Dc(DS, DeclaratorContext::MemberContext); 5155 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5156 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5157 5158 // Create a declaration for this anonymous struct/union. 5159 NamedDecl *Anon = nullptr; 5160 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5161 Anon = FieldDecl::Create( 5162 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5163 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5164 /*BitWidth=*/nullptr, /*Mutable=*/false, 5165 /*InitStyle=*/ICIS_NoInit); 5166 Anon->setAccess(AS); 5167 ProcessDeclAttributes(S, Anon, Dc); 5168 5169 if (getLangOpts().CPlusPlus) 5170 FieldCollector->Add(cast<FieldDecl>(Anon)); 5171 } else { 5172 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5173 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5174 if (SCSpec == DeclSpec::SCS_mutable) { 5175 // mutable can only appear on non-static class members, so it's always 5176 // an error here 5177 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5178 Invalid = true; 5179 SC = SC_None; 5180 } 5181 5182 assert(DS.getAttributes().empty() && "No attribute expected"); 5183 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5184 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5185 Context.getTypeDeclType(Record), TInfo, SC); 5186 5187 // Default-initialize the implicit variable. This initialization will be 5188 // trivial in almost all cases, except if a union member has an in-class 5189 // initializer: 5190 // union { int n = 0; }; 5191 ActOnUninitializedDecl(Anon); 5192 } 5193 Anon->setImplicit(); 5194 5195 // Mark this as an anonymous struct/union type. 5196 Record->setAnonymousStructOrUnion(true); 5197 5198 // Add the anonymous struct/union object to the current 5199 // context. We'll be referencing this object when we refer to one of 5200 // its members. 5201 Owner->addDecl(Anon); 5202 5203 // Inject the members of the anonymous struct/union into the owning 5204 // context and into the identifier resolver chain for name lookup 5205 // purposes. 5206 SmallVector<NamedDecl*, 2> Chain; 5207 Chain.push_back(Anon); 5208 5209 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5210 Invalid = true; 5211 5212 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5213 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5214 MangleNumberingContext *MCtx; 5215 Decl *ManglingContextDecl; 5216 std::tie(MCtx, ManglingContextDecl) = 5217 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5218 if (MCtx) { 5219 Context.setManglingNumber( 5220 NewVD, MCtx->getManglingNumber( 5221 NewVD, getMSManglingNumber(getLangOpts(), S))); 5222 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5223 } 5224 } 5225 } 5226 5227 if (Invalid) 5228 Anon->setInvalidDecl(); 5229 5230 return Anon; 5231 } 5232 5233 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5234 /// Microsoft C anonymous structure. 5235 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5236 /// Example: 5237 /// 5238 /// struct A { int a; }; 5239 /// struct B { struct A; int b; }; 5240 /// 5241 /// void foo() { 5242 /// B var; 5243 /// var.a = 3; 5244 /// } 5245 /// 5246 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5247 RecordDecl *Record) { 5248 assert(Record && "expected a record!"); 5249 5250 // Mock up a declarator. 5251 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 5252 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5253 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5254 5255 auto *ParentDecl = cast<RecordDecl>(CurContext); 5256 QualType RecTy = Context.getTypeDeclType(Record); 5257 5258 // Create a declaration for this anonymous struct. 5259 NamedDecl *Anon = 5260 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5261 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5262 /*BitWidth=*/nullptr, /*Mutable=*/false, 5263 /*InitStyle=*/ICIS_NoInit); 5264 Anon->setImplicit(); 5265 5266 // Add the anonymous struct object to the current context. 5267 CurContext->addDecl(Anon); 5268 5269 // Inject the members of the anonymous struct into the current 5270 // context and into the identifier resolver chain for name lookup 5271 // purposes. 5272 SmallVector<NamedDecl*, 2> Chain; 5273 Chain.push_back(Anon); 5274 5275 RecordDecl *RecordDef = Record->getDefinition(); 5276 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5277 diag::err_field_incomplete_or_sizeless) || 5278 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5279 AS_none, Chain)) { 5280 Anon->setInvalidDecl(); 5281 ParentDecl->setInvalidDecl(); 5282 } 5283 5284 return Anon; 5285 } 5286 5287 /// GetNameForDeclarator - Determine the full declaration name for the 5288 /// given Declarator. 5289 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5290 return GetNameFromUnqualifiedId(D.getName()); 5291 } 5292 5293 /// Retrieves the declaration name from a parsed unqualified-id. 5294 DeclarationNameInfo 5295 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5296 DeclarationNameInfo NameInfo; 5297 NameInfo.setLoc(Name.StartLocation); 5298 5299 switch (Name.getKind()) { 5300 5301 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5302 case UnqualifiedIdKind::IK_Identifier: 5303 NameInfo.setName(Name.Identifier); 5304 return NameInfo; 5305 5306 case UnqualifiedIdKind::IK_DeductionGuideName: { 5307 // C++ [temp.deduct.guide]p3: 5308 // The simple-template-id shall name a class template specialization. 5309 // The template-name shall be the same identifier as the template-name 5310 // of the simple-template-id. 5311 // These together intend to imply that the template-name shall name a 5312 // class template. 5313 // FIXME: template<typename T> struct X {}; 5314 // template<typename T> using Y = X<T>; 5315 // Y(int) -> Y<int>; 5316 // satisfies these rules but does not name a class template. 5317 TemplateName TN = Name.TemplateName.get().get(); 5318 auto *Template = TN.getAsTemplateDecl(); 5319 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5320 Diag(Name.StartLocation, 5321 diag::err_deduction_guide_name_not_class_template) 5322 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5323 if (Template) 5324 Diag(Template->getLocation(), diag::note_template_decl_here); 5325 return DeclarationNameInfo(); 5326 } 5327 5328 NameInfo.setName( 5329 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5330 return NameInfo; 5331 } 5332 5333 case UnqualifiedIdKind::IK_OperatorFunctionId: 5334 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5335 Name.OperatorFunctionId.Operator)); 5336 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 5337 = Name.OperatorFunctionId.SymbolLocations[0]; 5338 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5339 = Name.EndLocation.getRawEncoding(); 5340 return NameInfo; 5341 5342 case UnqualifiedIdKind::IK_LiteralOperatorId: 5343 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5344 Name.Identifier)); 5345 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5346 return NameInfo; 5347 5348 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5349 TypeSourceInfo *TInfo; 5350 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5351 if (Ty.isNull()) 5352 return DeclarationNameInfo(); 5353 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5354 Context.getCanonicalType(Ty))); 5355 NameInfo.setNamedTypeInfo(TInfo); 5356 return NameInfo; 5357 } 5358 5359 case UnqualifiedIdKind::IK_ConstructorName: { 5360 TypeSourceInfo *TInfo; 5361 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5362 if (Ty.isNull()) 5363 return DeclarationNameInfo(); 5364 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5365 Context.getCanonicalType(Ty))); 5366 NameInfo.setNamedTypeInfo(TInfo); 5367 return NameInfo; 5368 } 5369 5370 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5371 // In well-formed code, we can only have a constructor 5372 // template-id that refers to the current context, so go there 5373 // to find the actual type being constructed. 5374 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5375 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5376 return DeclarationNameInfo(); 5377 5378 // Determine the type of the class being constructed. 5379 QualType CurClassType = Context.getTypeDeclType(CurClass); 5380 5381 // FIXME: Check two things: that the template-id names the same type as 5382 // CurClassType, and that the template-id does not occur when the name 5383 // was qualified. 5384 5385 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5386 Context.getCanonicalType(CurClassType))); 5387 // FIXME: should we retrieve TypeSourceInfo? 5388 NameInfo.setNamedTypeInfo(nullptr); 5389 return NameInfo; 5390 } 5391 5392 case UnqualifiedIdKind::IK_DestructorName: { 5393 TypeSourceInfo *TInfo; 5394 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5395 if (Ty.isNull()) 5396 return DeclarationNameInfo(); 5397 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5398 Context.getCanonicalType(Ty))); 5399 NameInfo.setNamedTypeInfo(TInfo); 5400 return NameInfo; 5401 } 5402 5403 case UnqualifiedIdKind::IK_TemplateId: { 5404 TemplateName TName = Name.TemplateId->Template.get(); 5405 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5406 return Context.getNameForTemplate(TName, TNameLoc); 5407 } 5408 5409 } // switch (Name.getKind()) 5410 5411 llvm_unreachable("Unknown name kind"); 5412 } 5413 5414 static QualType getCoreType(QualType Ty) { 5415 do { 5416 if (Ty->isPointerType() || Ty->isReferenceType()) 5417 Ty = Ty->getPointeeType(); 5418 else if (Ty->isArrayType()) 5419 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5420 else 5421 return Ty.withoutLocalFastQualifiers(); 5422 } while (true); 5423 } 5424 5425 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5426 /// and Definition have "nearly" matching parameters. This heuristic is 5427 /// used to improve diagnostics in the case where an out-of-line function 5428 /// definition doesn't match any declaration within the class or namespace. 5429 /// Also sets Params to the list of indices to the parameters that differ 5430 /// between the declaration and the definition. If hasSimilarParameters 5431 /// returns true and Params is empty, then all of the parameters match. 5432 static bool hasSimilarParameters(ASTContext &Context, 5433 FunctionDecl *Declaration, 5434 FunctionDecl *Definition, 5435 SmallVectorImpl<unsigned> &Params) { 5436 Params.clear(); 5437 if (Declaration->param_size() != Definition->param_size()) 5438 return false; 5439 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5440 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5441 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5442 5443 // The parameter types are identical 5444 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5445 continue; 5446 5447 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5448 QualType DefParamBaseTy = getCoreType(DefParamTy); 5449 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5450 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5451 5452 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5453 (DeclTyName && DeclTyName == DefTyName)) 5454 Params.push_back(Idx); 5455 else // The two parameters aren't even close 5456 return false; 5457 } 5458 5459 return true; 5460 } 5461 5462 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5463 /// declarator needs to be rebuilt in the current instantiation. 5464 /// Any bits of declarator which appear before the name are valid for 5465 /// consideration here. That's specifically the type in the decl spec 5466 /// and the base type in any member-pointer chunks. 5467 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5468 DeclarationName Name) { 5469 // The types we specifically need to rebuild are: 5470 // - typenames, typeofs, and decltypes 5471 // - types which will become injected class names 5472 // Of course, we also need to rebuild any type referencing such a 5473 // type. It's safest to just say "dependent", but we call out a 5474 // few cases here. 5475 5476 DeclSpec &DS = D.getMutableDeclSpec(); 5477 switch (DS.getTypeSpecType()) { 5478 case DeclSpec::TST_typename: 5479 case DeclSpec::TST_typeofType: 5480 case DeclSpec::TST_underlyingType: 5481 case DeclSpec::TST_atomic: { 5482 // Grab the type from the parser. 5483 TypeSourceInfo *TSI = nullptr; 5484 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5485 if (T.isNull() || !T->isDependentType()) break; 5486 5487 // Make sure there's a type source info. This isn't really much 5488 // of a waste; most dependent types should have type source info 5489 // attached already. 5490 if (!TSI) 5491 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5492 5493 // Rebuild the type in the current instantiation. 5494 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5495 if (!TSI) return true; 5496 5497 // Store the new type back in the decl spec. 5498 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5499 DS.UpdateTypeRep(LocType); 5500 break; 5501 } 5502 5503 case DeclSpec::TST_decltype: 5504 case DeclSpec::TST_typeofExpr: { 5505 Expr *E = DS.getRepAsExpr(); 5506 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5507 if (Result.isInvalid()) return true; 5508 DS.UpdateExprRep(Result.get()); 5509 break; 5510 } 5511 5512 default: 5513 // Nothing to do for these decl specs. 5514 break; 5515 } 5516 5517 // It doesn't matter what order we do this in. 5518 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5519 DeclaratorChunk &Chunk = D.getTypeObject(I); 5520 5521 // The only type information in the declarator which can come 5522 // before the declaration name is the base type of a member 5523 // pointer. 5524 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5525 continue; 5526 5527 // Rebuild the scope specifier in-place. 5528 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5529 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5530 return true; 5531 } 5532 5533 return false; 5534 } 5535 5536 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5537 D.setFunctionDefinitionKind(FDK_Declaration); 5538 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5539 5540 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5541 Dcl && Dcl->getDeclContext()->isFileContext()) 5542 Dcl->setTopLevelDeclInObjCContainer(); 5543 5544 if (getLangOpts().OpenCL) 5545 setCurrentOpenCLExtensionForDecl(Dcl); 5546 5547 return Dcl; 5548 } 5549 5550 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5551 /// If T is the name of a class, then each of the following shall have a 5552 /// name different from T: 5553 /// - every static data member of class T; 5554 /// - every member function of class T 5555 /// - every member of class T that is itself a type; 5556 /// \returns true if the declaration name violates these rules. 5557 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5558 DeclarationNameInfo NameInfo) { 5559 DeclarationName Name = NameInfo.getName(); 5560 5561 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5562 while (Record && Record->isAnonymousStructOrUnion()) 5563 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5564 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5565 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5566 return true; 5567 } 5568 5569 return false; 5570 } 5571 5572 /// Diagnose a declaration whose declarator-id has the given 5573 /// nested-name-specifier. 5574 /// 5575 /// \param SS The nested-name-specifier of the declarator-id. 5576 /// 5577 /// \param DC The declaration context to which the nested-name-specifier 5578 /// resolves. 5579 /// 5580 /// \param Name The name of the entity being declared. 5581 /// 5582 /// \param Loc The location of the name of the entity being declared. 5583 /// 5584 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5585 /// we're declaring an explicit / partial specialization / instantiation. 5586 /// 5587 /// \returns true if we cannot safely recover from this error, false otherwise. 5588 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5589 DeclarationName Name, 5590 SourceLocation Loc, bool IsTemplateId) { 5591 DeclContext *Cur = CurContext; 5592 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5593 Cur = Cur->getParent(); 5594 5595 // If the user provided a superfluous scope specifier that refers back to the 5596 // class in which the entity is already declared, diagnose and ignore it. 5597 // 5598 // class X { 5599 // void X::f(); 5600 // }; 5601 // 5602 // Note, it was once ill-formed to give redundant qualification in all 5603 // contexts, but that rule was removed by DR482. 5604 if (Cur->Equals(DC)) { 5605 if (Cur->isRecord()) { 5606 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5607 : diag::err_member_extra_qualification) 5608 << Name << FixItHint::CreateRemoval(SS.getRange()); 5609 SS.clear(); 5610 } else { 5611 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5612 } 5613 return false; 5614 } 5615 5616 // Check whether the qualifying scope encloses the scope of the original 5617 // declaration. For a template-id, we perform the checks in 5618 // CheckTemplateSpecializationScope. 5619 if (!Cur->Encloses(DC) && !IsTemplateId) { 5620 if (Cur->isRecord()) 5621 Diag(Loc, diag::err_member_qualification) 5622 << Name << SS.getRange(); 5623 else if (isa<TranslationUnitDecl>(DC)) 5624 Diag(Loc, diag::err_invalid_declarator_global_scope) 5625 << Name << SS.getRange(); 5626 else if (isa<FunctionDecl>(Cur)) 5627 Diag(Loc, diag::err_invalid_declarator_in_function) 5628 << Name << SS.getRange(); 5629 else if (isa<BlockDecl>(Cur)) 5630 Diag(Loc, diag::err_invalid_declarator_in_block) 5631 << Name << SS.getRange(); 5632 else 5633 Diag(Loc, diag::err_invalid_declarator_scope) 5634 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5635 5636 return true; 5637 } 5638 5639 if (Cur->isRecord()) { 5640 // Cannot qualify members within a class. 5641 Diag(Loc, diag::err_member_qualification) 5642 << Name << SS.getRange(); 5643 SS.clear(); 5644 5645 // C++ constructors and destructors with incorrect scopes can break 5646 // our AST invariants by having the wrong underlying types. If 5647 // that's the case, then drop this declaration entirely. 5648 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5649 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5650 !Context.hasSameType(Name.getCXXNameType(), 5651 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5652 return true; 5653 5654 return false; 5655 } 5656 5657 // C++11 [dcl.meaning]p1: 5658 // [...] "The nested-name-specifier of the qualified declarator-id shall 5659 // not begin with a decltype-specifer" 5660 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5661 while (SpecLoc.getPrefix()) 5662 SpecLoc = SpecLoc.getPrefix(); 5663 if (dyn_cast_or_null<DecltypeType>( 5664 SpecLoc.getNestedNameSpecifier()->getAsType())) 5665 Diag(Loc, diag::err_decltype_in_declarator) 5666 << SpecLoc.getTypeLoc().getSourceRange(); 5667 5668 return false; 5669 } 5670 5671 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5672 MultiTemplateParamsArg TemplateParamLists) { 5673 // TODO: consider using NameInfo for diagnostic. 5674 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5675 DeclarationName Name = NameInfo.getName(); 5676 5677 // All of these full declarators require an identifier. If it doesn't have 5678 // one, the ParsedFreeStandingDeclSpec action should be used. 5679 if (D.isDecompositionDeclarator()) { 5680 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5681 } else if (!Name) { 5682 if (!D.isInvalidType()) // Reject this if we think it is valid. 5683 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5684 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5685 return nullptr; 5686 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5687 return nullptr; 5688 5689 // The scope passed in may not be a decl scope. Zip up the scope tree until 5690 // we find one that is. 5691 while ((S->getFlags() & Scope::DeclScope) == 0 || 5692 (S->getFlags() & Scope::TemplateParamScope) != 0) 5693 S = S->getParent(); 5694 5695 DeclContext *DC = CurContext; 5696 if (D.getCXXScopeSpec().isInvalid()) 5697 D.setInvalidType(); 5698 else if (D.getCXXScopeSpec().isSet()) { 5699 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5700 UPPC_DeclarationQualifier)) 5701 return nullptr; 5702 5703 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5704 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5705 if (!DC || isa<EnumDecl>(DC)) { 5706 // If we could not compute the declaration context, it's because the 5707 // declaration context is dependent but does not refer to a class, 5708 // class template, or class template partial specialization. Complain 5709 // and return early, to avoid the coming semantic disaster. 5710 Diag(D.getIdentifierLoc(), 5711 diag::err_template_qualified_declarator_no_match) 5712 << D.getCXXScopeSpec().getScopeRep() 5713 << D.getCXXScopeSpec().getRange(); 5714 return nullptr; 5715 } 5716 bool IsDependentContext = DC->isDependentContext(); 5717 5718 if (!IsDependentContext && 5719 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5720 return nullptr; 5721 5722 // If a class is incomplete, do not parse entities inside it. 5723 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5724 Diag(D.getIdentifierLoc(), 5725 diag::err_member_def_undefined_record) 5726 << Name << DC << D.getCXXScopeSpec().getRange(); 5727 return nullptr; 5728 } 5729 if (!D.getDeclSpec().isFriendSpecified()) { 5730 if (diagnoseQualifiedDeclaration( 5731 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5732 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5733 if (DC->isRecord()) 5734 return nullptr; 5735 5736 D.setInvalidType(); 5737 } 5738 } 5739 5740 // Check whether we need to rebuild the type of the given 5741 // declaration in the current instantiation. 5742 if (EnteringContext && IsDependentContext && 5743 TemplateParamLists.size() != 0) { 5744 ContextRAII SavedContext(*this, DC); 5745 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5746 D.setInvalidType(); 5747 } 5748 } 5749 5750 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5751 QualType R = TInfo->getType(); 5752 5753 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5754 UPPC_DeclarationType)) 5755 D.setInvalidType(); 5756 5757 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5758 forRedeclarationInCurContext()); 5759 5760 // See if this is a redefinition of a variable in the same scope. 5761 if (!D.getCXXScopeSpec().isSet()) { 5762 bool IsLinkageLookup = false; 5763 bool CreateBuiltins = false; 5764 5765 // If the declaration we're planning to build will be a function 5766 // or object with linkage, then look for another declaration with 5767 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5768 // 5769 // If the declaration we're planning to build will be declared with 5770 // external linkage in the translation unit, create any builtin with 5771 // the same name. 5772 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5773 /* Do nothing*/; 5774 else if (CurContext->isFunctionOrMethod() && 5775 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5776 R->isFunctionType())) { 5777 IsLinkageLookup = true; 5778 CreateBuiltins = 5779 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5780 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5781 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5782 CreateBuiltins = true; 5783 5784 if (IsLinkageLookup) { 5785 Previous.clear(LookupRedeclarationWithLinkage); 5786 Previous.setRedeclarationKind(ForExternalRedeclaration); 5787 } 5788 5789 LookupName(Previous, S, CreateBuiltins); 5790 } else { // Something like "int foo::x;" 5791 LookupQualifiedName(Previous, DC); 5792 5793 // C++ [dcl.meaning]p1: 5794 // When the declarator-id is qualified, the declaration shall refer to a 5795 // previously declared member of the class or namespace to which the 5796 // qualifier refers (or, in the case of a namespace, of an element of the 5797 // inline namespace set of that namespace (7.3.1)) or to a specialization 5798 // thereof; [...] 5799 // 5800 // Note that we already checked the context above, and that we do not have 5801 // enough information to make sure that Previous contains the declaration 5802 // we want to match. For example, given: 5803 // 5804 // class X { 5805 // void f(); 5806 // void f(float); 5807 // }; 5808 // 5809 // void X::f(int) { } // ill-formed 5810 // 5811 // In this case, Previous will point to the overload set 5812 // containing the two f's declared in X, but neither of them 5813 // matches. 5814 5815 // C++ [dcl.meaning]p1: 5816 // [...] the member shall not merely have been introduced by a 5817 // using-declaration in the scope of the class or namespace nominated by 5818 // the nested-name-specifier of the declarator-id. 5819 RemoveUsingDecls(Previous); 5820 } 5821 5822 if (Previous.isSingleResult() && 5823 Previous.getFoundDecl()->isTemplateParameter()) { 5824 // Maybe we will complain about the shadowed template parameter. 5825 if (!D.isInvalidType()) 5826 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5827 Previous.getFoundDecl()); 5828 5829 // Just pretend that we didn't see the previous declaration. 5830 Previous.clear(); 5831 } 5832 5833 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5834 // Forget that the previous declaration is the injected-class-name. 5835 Previous.clear(); 5836 5837 // In C++, the previous declaration we find might be a tag type 5838 // (class or enum). In this case, the new declaration will hide the 5839 // tag type. Note that this applies to functions, function templates, and 5840 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5841 if (Previous.isSingleTagDecl() && 5842 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5843 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5844 Previous.clear(); 5845 5846 // Check that there are no default arguments other than in the parameters 5847 // of a function declaration (C++ only). 5848 if (getLangOpts().CPlusPlus) 5849 CheckExtraCXXDefaultArguments(D); 5850 5851 NamedDecl *New; 5852 5853 bool AddToScope = true; 5854 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5855 if (TemplateParamLists.size()) { 5856 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5857 return nullptr; 5858 } 5859 5860 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5861 } else if (R->isFunctionType()) { 5862 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5863 TemplateParamLists, 5864 AddToScope); 5865 } else { 5866 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5867 AddToScope); 5868 } 5869 5870 if (!New) 5871 return nullptr; 5872 5873 // If this has an identifier and is not a function template specialization, 5874 // add it to the scope stack. 5875 if (New->getDeclName() && AddToScope) 5876 PushOnScopeChains(New, S); 5877 5878 if (isInOpenMPDeclareTargetContext()) 5879 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5880 5881 return New; 5882 } 5883 5884 /// Helper method to turn variable array types into constant array 5885 /// types in certain situations which would otherwise be errors (for 5886 /// GCC compatibility). 5887 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5888 ASTContext &Context, 5889 bool &SizeIsNegative, 5890 llvm::APSInt &Oversized) { 5891 // This method tries to turn a variable array into a constant 5892 // array even when the size isn't an ICE. This is necessary 5893 // for compatibility with code that depends on gcc's buggy 5894 // constant expression folding, like struct {char x[(int)(char*)2];} 5895 SizeIsNegative = false; 5896 Oversized = 0; 5897 5898 if (T->isDependentType()) 5899 return QualType(); 5900 5901 QualifierCollector Qs; 5902 const Type *Ty = Qs.strip(T); 5903 5904 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5905 QualType Pointee = PTy->getPointeeType(); 5906 QualType FixedType = 5907 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5908 Oversized); 5909 if (FixedType.isNull()) return FixedType; 5910 FixedType = Context.getPointerType(FixedType); 5911 return Qs.apply(Context, FixedType); 5912 } 5913 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5914 QualType Inner = PTy->getInnerType(); 5915 QualType FixedType = 5916 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5917 Oversized); 5918 if (FixedType.isNull()) return FixedType; 5919 FixedType = Context.getParenType(FixedType); 5920 return Qs.apply(Context, FixedType); 5921 } 5922 5923 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5924 if (!VLATy) 5925 return QualType(); 5926 // FIXME: We should probably handle this case 5927 if (VLATy->getElementType()->isVariablyModifiedType()) 5928 return QualType(); 5929 5930 Expr::EvalResult Result; 5931 if (!VLATy->getSizeExpr() || 5932 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5933 return QualType(); 5934 5935 llvm::APSInt Res = Result.Val.getInt(); 5936 5937 // Check whether the array size is negative. 5938 if (Res.isSigned() && Res.isNegative()) { 5939 SizeIsNegative = true; 5940 return QualType(); 5941 } 5942 5943 // Check whether the array is too large to be addressed. 5944 unsigned ActiveSizeBits 5945 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5946 Res); 5947 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5948 Oversized = Res; 5949 return QualType(); 5950 } 5951 5952 return Context.getConstantArrayType( 5953 VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 5954 } 5955 5956 static void 5957 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5958 SrcTL = SrcTL.getUnqualifiedLoc(); 5959 DstTL = DstTL.getUnqualifiedLoc(); 5960 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5961 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5962 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5963 DstPTL.getPointeeLoc()); 5964 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5965 return; 5966 } 5967 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5968 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5969 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5970 DstPTL.getInnerLoc()); 5971 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5972 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5973 return; 5974 } 5975 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5976 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5977 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5978 TypeLoc DstElemTL = DstATL.getElementLoc(); 5979 DstElemTL.initializeFullCopy(SrcElemTL); 5980 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5981 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5982 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5983 } 5984 5985 /// Helper method to turn variable array types into constant array 5986 /// types in certain situations which would otherwise be errors (for 5987 /// GCC compatibility). 5988 static TypeSourceInfo* 5989 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5990 ASTContext &Context, 5991 bool &SizeIsNegative, 5992 llvm::APSInt &Oversized) { 5993 QualType FixedTy 5994 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5995 SizeIsNegative, Oversized); 5996 if (FixedTy.isNull()) 5997 return nullptr; 5998 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5999 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6000 FixedTInfo->getTypeLoc()); 6001 return FixedTInfo; 6002 } 6003 6004 /// Register the given locally-scoped extern "C" declaration so 6005 /// that it can be found later for redeclarations. We include any extern "C" 6006 /// declaration that is not visible in the translation unit here, not just 6007 /// function-scope declarations. 6008 void 6009 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6010 if (!getLangOpts().CPlusPlus && 6011 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6012 // Don't need to track declarations in the TU in C. 6013 return; 6014 6015 // Note that we have a locally-scoped external with this name. 6016 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6017 } 6018 6019 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6020 // FIXME: We can have multiple results via __attribute__((overloadable)). 6021 auto Result = Context.getExternCContextDecl()->lookup(Name); 6022 return Result.empty() ? nullptr : *Result.begin(); 6023 } 6024 6025 /// Diagnose function specifiers on a declaration of an identifier that 6026 /// does not identify a function. 6027 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6028 // FIXME: We should probably indicate the identifier in question to avoid 6029 // confusion for constructs like "virtual int a(), b;" 6030 if (DS.isVirtualSpecified()) 6031 Diag(DS.getVirtualSpecLoc(), 6032 diag::err_virtual_non_function); 6033 6034 if (DS.hasExplicitSpecifier()) 6035 Diag(DS.getExplicitSpecLoc(), 6036 diag::err_explicit_non_function); 6037 6038 if (DS.isNoreturnSpecified()) 6039 Diag(DS.getNoreturnSpecLoc(), 6040 diag::err_noreturn_non_function); 6041 } 6042 6043 NamedDecl* 6044 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6045 TypeSourceInfo *TInfo, LookupResult &Previous) { 6046 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6047 if (D.getCXXScopeSpec().isSet()) { 6048 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6049 << D.getCXXScopeSpec().getRange(); 6050 D.setInvalidType(); 6051 // Pretend we didn't see the scope specifier. 6052 DC = CurContext; 6053 Previous.clear(); 6054 } 6055 6056 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6057 6058 if (D.getDeclSpec().isInlineSpecified()) 6059 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6060 << getLangOpts().CPlusPlus17; 6061 if (D.getDeclSpec().hasConstexprSpecifier()) 6062 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6063 << 1 << D.getDeclSpec().getConstexprSpecifier(); 6064 6065 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6066 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6067 Diag(D.getName().StartLocation, 6068 diag::err_deduction_guide_invalid_specifier) 6069 << "typedef"; 6070 else 6071 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6072 << D.getName().getSourceRange(); 6073 return nullptr; 6074 } 6075 6076 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6077 if (!NewTD) return nullptr; 6078 6079 // Handle attributes prior to checking for duplicates in MergeVarDecl 6080 ProcessDeclAttributes(S, NewTD, D); 6081 6082 CheckTypedefForVariablyModifiedType(S, NewTD); 6083 6084 bool Redeclaration = D.isRedeclaration(); 6085 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6086 D.setRedeclaration(Redeclaration); 6087 return ND; 6088 } 6089 6090 void 6091 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6092 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6093 // then it shall have block scope. 6094 // Note that variably modified types must be fixed before merging the decl so 6095 // that redeclarations will match. 6096 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6097 QualType T = TInfo->getType(); 6098 if (T->isVariablyModifiedType()) { 6099 setFunctionHasBranchProtectedScope(); 6100 6101 if (S->getFnParent() == nullptr) { 6102 bool SizeIsNegative; 6103 llvm::APSInt Oversized; 6104 TypeSourceInfo *FixedTInfo = 6105 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6106 SizeIsNegative, 6107 Oversized); 6108 if (FixedTInfo) { 6109 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 6110 NewTD->setTypeSourceInfo(FixedTInfo); 6111 } else { 6112 if (SizeIsNegative) 6113 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6114 else if (T->isVariableArrayType()) 6115 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6116 else if (Oversized.getBoolValue()) 6117 Diag(NewTD->getLocation(), diag::err_array_too_large) 6118 << Oversized.toString(10); 6119 else 6120 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6121 NewTD->setInvalidDecl(); 6122 } 6123 } 6124 } 6125 } 6126 6127 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6128 /// declares a typedef-name, either using the 'typedef' type specifier or via 6129 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6130 NamedDecl* 6131 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6132 LookupResult &Previous, bool &Redeclaration) { 6133 6134 // Find the shadowed declaration before filtering for scope. 6135 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6136 6137 // Merge the decl with the existing one if appropriate. If the decl is 6138 // in an outer scope, it isn't the same thing. 6139 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6140 /*AllowInlineNamespace*/false); 6141 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6142 if (!Previous.empty()) { 6143 Redeclaration = true; 6144 MergeTypedefNameDecl(S, NewTD, Previous); 6145 } else { 6146 inferGslPointerAttribute(NewTD); 6147 } 6148 6149 if (ShadowedDecl && !Redeclaration) 6150 CheckShadow(NewTD, ShadowedDecl, Previous); 6151 6152 // If this is the C FILE type, notify the AST context. 6153 if (IdentifierInfo *II = NewTD->getIdentifier()) 6154 if (!NewTD->isInvalidDecl() && 6155 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6156 if (II->isStr("FILE")) 6157 Context.setFILEDecl(NewTD); 6158 else if (II->isStr("jmp_buf")) 6159 Context.setjmp_bufDecl(NewTD); 6160 else if (II->isStr("sigjmp_buf")) 6161 Context.setsigjmp_bufDecl(NewTD); 6162 else if (II->isStr("ucontext_t")) 6163 Context.setucontext_tDecl(NewTD); 6164 } 6165 6166 return NewTD; 6167 } 6168 6169 /// Determines whether the given declaration is an out-of-scope 6170 /// previous declaration. 6171 /// 6172 /// This routine should be invoked when name lookup has found a 6173 /// previous declaration (PrevDecl) that is not in the scope where a 6174 /// new declaration by the same name is being introduced. If the new 6175 /// declaration occurs in a local scope, previous declarations with 6176 /// linkage may still be considered previous declarations (C99 6177 /// 6.2.2p4-5, C++ [basic.link]p6). 6178 /// 6179 /// \param PrevDecl the previous declaration found by name 6180 /// lookup 6181 /// 6182 /// \param DC the context in which the new declaration is being 6183 /// declared. 6184 /// 6185 /// \returns true if PrevDecl is an out-of-scope previous declaration 6186 /// for a new delcaration with the same name. 6187 static bool 6188 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6189 ASTContext &Context) { 6190 if (!PrevDecl) 6191 return false; 6192 6193 if (!PrevDecl->hasLinkage()) 6194 return false; 6195 6196 if (Context.getLangOpts().CPlusPlus) { 6197 // C++ [basic.link]p6: 6198 // If there is a visible declaration of an entity with linkage 6199 // having the same name and type, ignoring entities declared 6200 // outside the innermost enclosing namespace scope, the block 6201 // scope declaration declares that same entity and receives the 6202 // linkage of the previous declaration. 6203 DeclContext *OuterContext = DC->getRedeclContext(); 6204 if (!OuterContext->isFunctionOrMethod()) 6205 // This rule only applies to block-scope declarations. 6206 return false; 6207 6208 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6209 if (PrevOuterContext->isRecord()) 6210 // We found a member function: ignore it. 6211 return false; 6212 6213 // Find the innermost enclosing namespace for the new and 6214 // previous declarations. 6215 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6216 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6217 6218 // The previous declaration is in a different namespace, so it 6219 // isn't the same function. 6220 if (!OuterContext->Equals(PrevOuterContext)) 6221 return false; 6222 } 6223 6224 return true; 6225 } 6226 6227 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6228 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6229 if (!SS.isSet()) return; 6230 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6231 } 6232 6233 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6234 QualType type = decl->getType(); 6235 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6236 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6237 // Various kinds of declaration aren't allowed to be __autoreleasing. 6238 unsigned kind = -1U; 6239 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6240 if (var->hasAttr<BlocksAttr>()) 6241 kind = 0; // __block 6242 else if (!var->hasLocalStorage()) 6243 kind = 1; // global 6244 } else if (isa<ObjCIvarDecl>(decl)) { 6245 kind = 3; // ivar 6246 } else if (isa<FieldDecl>(decl)) { 6247 kind = 2; // field 6248 } 6249 6250 if (kind != -1U) { 6251 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6252 << kind; 6253 } 6254 } else if (lifetime == Qualifiers::OCL_None) { 6255 // Try to infer lifetime. 6256 if (!type->isObjCLifetimeType()) 6257 return false; 6258 6259 lifetime = type->getObjCARCImplicitLifetime(); 6260 type = Context.getLifetimeQualifiedType(type, lifetime); 6261 decl->setType(type); 6262 } 6263 6264 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6265 // Thread-local variables cannot have lifetime. 6266 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6267 var->getTLSKind()) { 6268 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6269 << var->getType(); 6270 return true; 6271 } 6272 } 6273 6274 return false; 6275 } 6276 6277 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6278 if (Decl->getType().hasAddressSpace()) 6279 return; 6280 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6281 QualType Type = Var->getType(); 6282 if (Type->isSamplerT() || Type->isVoidType()) 6283 return; 6284 LangAS ImplAS = LangAS::opencl_private; 6285 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6286 Var->hasGlobalStorage()) 6287 ImplAS = LangAS::opencl_global; 6288 // If the original type from a decayed type is an array type and that array 6289 // type has no address space yet, deduce it now. 6290 if (auto DT = dyn_cast<DecayedType>(Type)) { 6291 auto OrigTy = DT->getOriginalType(); 6292 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6293 // Add the address space to the original array type and then propagate 6294 // that to the element type through `getAsArrayType`. 6295 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6296 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6297 // Re-generate the decayed type. 6298 Type = Context.getDecayedType(OrigTy); 6299 } 6300 } 6301 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6302 // Apply any qualifiers (including address space) from the array type to 6303 // the element type. This implements C99 6.7.3p8: "If the specification of 6304 // an array type includes any type qualifiers, the element type is so 6305 // qualified, not the array type." 6306 if (Type->isArrayType()) 6307 Type = QualType(Context.getAsArrayType(Type), 0); 6308 Decl->setType(Type); 6309 } 6310 } 6311 6312 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6313 // Ensure that an auto decl is deduced otherwise the checks below might cache 6314 // the wrong linkage. 6315 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6316 6317 // 'weak' only applies to declarations with external linkage. 6318 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6319 if (!ND.isExternallyVisible()) { 6320 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6321 ND.dropAttr<WeakAttr>(); 6322 } 6323 } 6324 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6325 if (ND.isExternallyVisible()) { 6326 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6327 ND.dropAttr<WeakRefAttr>(); 6328 ND.dropAttr<AliasAttr>(); 6329 } 6330 } 6331 6332 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6333 if (VD->hasInit()) { 6334 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6335 assert(VD->isThisDeclarationADefinition() && 6336 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6337 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6338 VD->dropAttr<AliasAttr>(); 6339 } 6340 } 6341 } 6342 6343 // 'selectany' only applies to externally visible variable declarations. 6344 // It does not apply to functions. 6345 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6346 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6347 S.Diag(Attr->getLocation(), 6348 diag::err_attribute_selectany_non_extern_data); 6349 ND.dropAttr<SelectAnyAttr>(); 6350 } 6351 } 6352 6353 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6354 auto *VD = dyn_cast<VarDecl>(&ND); 6355 bool IsAnonymousNS = false; 6356 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6357 if (VD) { 6358 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6359 while (NS && !IsAnonymousNS) { 6360 IsAnonymousNS = NS->isAnonymousNamespace(); 6361 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6362 } 6363 } 6364 // dll attributes require external linkage. Static locals may have external 6365 // linkage but still cannot be explicitly imported or exported. 6366 // In Microsoft mode, a variable defined in anonymous namespace must have 6367 // external linkage in order to be exported. 6368 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6369 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6370 (!AnonNSInMicrosoftMode && 6371 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6372 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6373 << &ND << Attr; 6374 ND.setInvalidDecl(); 6375 } 6376 } 6377 6378 // Virtual functions cannot be marked as 'notail'. 6379 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6380 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6381 if (MD->isVirtual()) { 6382 S.Diag(ND.getLocation(), 6383 diag::err_invalid_attribute_on_virtual_function) 6384 << Attr; 6385 ND.dropAttr<NotTailCalledAttr>(); 6386 } 6387 6388 // Check the attributes on the function type, if any. 6389 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6390 // Don't declare this variable in the second operand of the for-statement; 6391 // GCC miscompiles that by ending its lifetime before evaluating the 6392 // third operand. See gcc.gnu.org/PR86769. 6393 AttributedTypeLoc ATL; 6394 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6395 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6396 TL = ATL.getModifiedLoc()) { 6397 // The [[lifetimebound]] attribute can be applied to the implicit object 6398 // parameter of a non-static member function (other than a ctor or dtor) 6399 // by applying it to the function type. 6400 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6401 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6402 if (!MD || MD->isStatic()) { 6403 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6404 << !MD << A->getRange(); 6405 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6406 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6407 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6408 } 6409 } 6410 } 6411 } 6412 } 6413 6414 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6415 NamedDecl *NewDecl, 6416 bool IsSpecialization, 6417 bool IsDefinition) { 6418 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6419 return; 6420 6421 bool IsTemplate = false; 6422 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6423 OldDecl = OldTD->getTemplatedDecl(); 6424 IsTemplate = true; 6425 if (!IsSpecialization) 6426 IsDefinition = false; 6427 } 6428 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6429 NewDecl = NewTD->getTemplatedDecl(); 6430 IsTemplate = true; 6431 } 6432 6433 if (!OldDecl || !NewDecl) 6434 return; 6435 6436 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6437 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6438 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6439 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6440 6441 // dllimport and dllexport are inheritable attributes so we have to exclude 6442 // inherited attribute instances. 6443 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6444 (NewExportAttr && !NewExportAttr->isInherited()); 6445 6446 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6447 // the only exception being explicit specializations. 6448 // Implicitly generated declarations are also excluded for now because there 6449 // is no other way to switch these to use dllimport or dllexport. 6450 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6451 6452 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6453 // Allow with a warning for free functions and global variables. 6454 bool JustWarn = false; 6455 if (!OldDecl->isCXXClassMember()) { 6456 auto *VD = dyn_cast<VarDecl>(OldDecl); 6457 if (VD && !VD->getDescribedVarTemplate()) 6458 JustWarn = true; 6459 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6460 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6461 JustWarn = true; 6462 } 6463 6464 // We cannot change a declaration that's been used because IR has already 6465 // been emitted. Dllimported functions will still work though (modulo 6466 // address equality) as they can use the thunk. 6467 if (OldDecl->isUsed()) 6468 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6469 JustWarn = false; 6470 6471 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6472 : diag::err_attribute_dll_redeclaration; 6473 S.Diag(NewDecl->getLocation(), DiagID) 6474 << NewDecl 6475 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6476 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6477 if (!JustWarn) { 6478 NewDecl->setInvalidDecl(); 6479 return; 6480 } 6481 } 6482 6483 // A redeclaration is not allowed to drop a dllimport attribute, the only 6484 // exceptions being inline function definitions (except for function 6485 // templates), local extern declarations, qualified friend declarations or 6486 // special MSVC extension: in the last case, the declaration is treated as if 6487 // it were marked dllexport. 6488 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6489 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6490 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6491 // Ignore static data because out-of-line definitions are diagnosed 6492 // separately. 6493 IsStaticDataMember = VD->isStaticDataMember(); 6494 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6495 VarDecl::DeclarationOnly; 6496 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6497 IsInline = FD->isInlined(); 6498 IsQualifiedFriend = FD->getQualifier() && 6499 FD->getFriendObjectKind() == Decl::FOK_Declared; 6500 } 6501 6502 if (OldImportAttr && !HasNewAttr && 6503 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6504 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6505 if (IsMicrosoft && IsDefinition) { 6506 S.Diag(NewDecl->getLocation(), 6507 diag::warn_redeclaration_without_import_attribute) 6508 << NewDecl; 6509 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6510 NewDecl->dropAttr<DLLImportAttr>(); 6511 NewDecl->addAttr( 6512 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6513 } else { 6514 S.Diag(NewDecl->getLocation(), 6515 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6516 << NewDecl << OldImportAttr; 6517 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6518 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6519 OldDecl->dropAttr<DLLImportAttr>(); 6520 NewDecl->dropAttr<DLLImportAttr>(); 6521 } 6522 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6523 // In MinGW, seeing a function declared inline drops the dllimport 6524 // attribute. 6525 OldDecl->dropAttr<DLLImportAttr>(); 6526 NewDecl->dropAttr<DLLImportAttr>(); 6527 S.Diag(NewDecl->getLocation(), 6528 diag::warn_dllimport_dropped_from_inline_function) 6529 << NewDecl << OldImportAttr; 6530 } 6531 6532 // A specialization of a class template member function is processed here 6533 // since it's a redeclaration. If the parent class is dllexport, the 6534 // specialization inherits that attribute. This doesn't happen automatically 6535 // since the parent class isn't instantiated until later. 6536 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6537 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6538 !NewImportAttr && !NewExportAttr) { 6539 if (const DLLExportAttr *ParentExportAttr = 6540 MD->getParent()->getAttr<DLLExportAttr>()) { 6541 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6542 NewAttr->setInherited(true); 6543 NewDecl->addAttr(NewAttr); 6544 } 6545 } 6546 } 6547 } 6548 6549 /// Given that we are within the definition of the given function, 6550 /// will that definition behave like C99's 'inline', where the 6551 /// definition is discarded except for optimization purposes? 6552 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6553 // Try to avoid calling GetGVALinkageForFunction. 6554 6555 // All cases of this require the 'inline' keyword. 6556 if (!FD->isInlined()) return false; 6557 6558 // This is only possible in C++ with the gnu_inline attribute. 6559 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6560 return false; 6561 6562 // Okay, go ahead and call the relatively-more-expensive function. 6563 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6564 } 6565 6566 /// Determine whether a variable is extern "C" prior to attaching 6567 /// an initializer. We can't just call isExternC() here, because that 6568 /// will also compute and cache whether the declaration is externally 6569 /// visible, which might change when we attach the initializer. 6570 /// 6571 /// This can only be used if the declaration is known to not be a 6572 /// redeclaration of an internal linkage declaration. 6573 /// 6574 /// For instance: 6575 /// 6576 /// auto x = []{}; 6577 /// 6578 /// Attaching the initializer here makes this declaration not externally 6579 /// visible, because its type has internal linkage. 6580 /// 6581 /// FIXME: This is a hack. 6582 template<typename T> 6583 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6584 if (S.getLangOpts().CPlusPlus) { 6585 // In C++, the overloadable attribute negates the effects of extern "C". 6586 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6587 return false; 6588 6589 // So do CUDA's host/device attributes. 6590 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6591 D->template hasAttr<CUDAHostAttr>())) 6592 return false; 6593 } 6594 return D->isExternC(); 6595 } 6596 6597 static bool shouldConsiderLinkage(const VarDecl *VD) { 6598 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6599 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6600 isa<OMPDeclareMapperDecl>(DC)) 6601 return VD->hasExternalStorage(); 6602 if (DC->isFileContext()) 6603 return true; 6604 if (DC->isRecord()) 6605 return false; 6606 if (isa<RequiresExprBodyDecl>(DC)) 6607 return false; 6608 llvm_unreachable("Unexpected context"); 6609 } 6610 6611 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6612 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6613 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6614 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6615 return true; 6616 if (DC->isRecord()) 6617 return false; 6618 llvm_unreachable("Unexpected context"); 6619 } 6620 6621 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6622 ParsedAttr::Kind Kind) { 6623 // Check decl attributes on the DeclSpec. 6624 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6625 return true; 6626 6627 // Walk the declarator structure, checking decl attributes that were in a type 6628 // position to the decl itself. 6629 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6630 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6631 return true; 6632 } 6633 6634 // Finally, check attributes on the decl itself. 6635 return PD.getAttributes().hasAttribute(Kind); 6636 } 6637 6638 /// Adjust the \c DeclContext for a function or variable that might be a 6639 /// function-local external declaration. 6640 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6641 if (!DC->isFunctionOrMethod()) 6642 return false; 6643 6644 // If this is a local extern function or variable declared within a function 6645 // template, don't add it into the enclosing namespace scope until it is 6646 // instantiated; it might have a dependent type right now. 6647 if (DC->isDependentContext()) 6648 return true; 6649 6650 // C++11 [basic.link]p7: 6651 // When a block scope declaration of an entity with linkage is not found to 6652 // refer to some other declaration, then that entity is a member of the 6653 // innermost enclosing namespace. 6654 // 6655 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6656 // semantically-enclosing namespace, not a lexically-enclosing one. 6657 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6658 DC = DC->getParent(); 6659 return true; 6660 } 6661 6662 /// Returns true if given declaration has external C language linkage. 6663 static bool isDeclExternC(const Decl *D) { 6664 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6665 return FD->isExternC(); 6666 if (const auto *VD = dyn_cast<VarDecl>(D)) 6667 return VD->isExternC(); 6668 6669 llvm_unreachable("Unknown type of decl!"); 6670 } 6671 /// Returns true if there hasn't been any invalid type diagnosed. 6672 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, 6673 DeclContext *DC, QualType R) { 6674 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6675 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6676 // argument. 6677 if (R->isImageType() || R->isPipeType()) { 6678 Se.Diag(D.getIdentifierLoc(), 6679 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6680 << R; 6681 D.setInvalidType(); 6682 return false; 6683 } 6684 6685 // OpenCL v1.2 s6.9.r: 6686 // The event type cannot be used to declare a program scope variable. 6687 // OpenCL v2.0 s6.9.q: 6688 // The clk_event_t and reserve_id_t types cannot be declared in program 6689 // scope. 6690 if (NULL == S->getParent()) { 6691 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6692 Se.Diag(D.getIdentifierLoc(), 6693 diag::err_invalid_type_for_program_scope_var) 6694 << R; 6695 D.setInvalidType(); 6696 return false; 6697 } 6698 } 6699 6700 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6701 QualType NR = R; 6702 while (NR->isPointerType()) { 6703 if (NR->isFunctionPointerType()) { 6704 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6705 D.setInvalidType(); 6706 return false; 6707 } 6708 NR = NR->getPointeeType(); 6709 } 6710 6711 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6712 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6713 // half array type (unless the cl_khr_fp16 extension is enabled). 6714 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6715 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6716 D.setInvalidType(); 6717 return false; 6718 } 6719 } 6720 6721 // OpenCL v1.2 s6.9.r: 6722 // The event type cannot be used with the __local, __constant and __global 6723 // address space qualifiers. 6724 if (R->isEventT()) { 6725 if (R.getAddressSpace() != LangAS::opencl_private) { 6726 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6727 D.setInvalidType(); 6728 return false; 6729 } 6730 } 6731 6732 // C++ for OpenCL does not allow the thread_local storage qualifier. 6733 // OpenCL C does not support thread_local either, and 6734 // also reject all other thread storage class specifiers. 6735 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6736 if (TSC != TSCS_unspecified) { 6737 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; 6738 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6739 diag::err_opencl_unknown_type_specifier) 6740 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() 6741 << DeclSpec::getSpecifierName(TSC) << 1; 6742 D.setInvalidType(); 6743 return false; 6744 } 6745 6746 if (R->isSamplerT()) { 6747 // OpenCL v1.2 s6.9.b p4: 6748 // The sampler type cannot be used with the __local and __global address 6749 // space qualifiers. 6750 if (R.getAddressSpace() == LangAS::opencl_local || 6751 R.getAddressSpace() == LangAS::opencl_global) { 6752 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6753 D.setInvalidType(); 6754 } 6755 6756 // OpenCL v1.2 s6.12.14.1: 6757 // A global sampler must be declared with either the constant address 6758 // space qualifier or with the const qualifier. 6759 if (DC->isTranslationUnit() && 6760 !(R.getAddressSpace() == LangAS::opencl_constant || 6761 R.isConstQualified())) { 6762 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6763 D.setInvalidType(); 6764 } 6765 if (D.isInvalidType()) 6766 return false; 6767 } 6768 return true; 6769 } 6770 6771 NamedDecl *Sema::ActOnVariableDeclarator( 6772 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6773 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6774 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6775 QualType R = TInfo->getType(); 6776 DeclarationName Name = GetNameForDeclarator(D).getName(); 6777 6778 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6779 6780 if (D.isDecompositionDeclarator()) { 6781 // Take the name of the first declarator as our name for diagnostic 6782 // purposes. 6783 auto &Decomp = D.getDecompositionDeclarator(); 6784 if (!Decomp.bindings().empty()) { 6785 II = Decomp.bindings()[0].Name; 6786 Name = II; 6787 } 6788 } else if (!II) { 6789 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6790 return nullptr; 6791 } 6792 6793 6794 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6795 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6796 6797 // dllimport globals without explicit storage class are treated as extern. We 6798 // have to change the storage class this early to get the right DeclContext. 6799 if (SC == SC_None && !DC->isRecord() && 6800 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6801 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6802 SC = SC_Extern; 6803 6804 DeclContext *OriginalDC = DC; 6805 bool IsLocalExternDecl = SC == SC_Extern && 6806 adjustContextForLocalExternDecl(DC); 6807 6808 if (SCSpec == DeclSpec::SCS_mutable) { 6809 // mutable can only appear on non-static class members, so it's always 6810 // an error here 6811 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6812 D.setInvalidType(); 6813 SC = SC_None; 6814 } 6815 6816 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6817 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6818 D.getDeclSpec().getStorageClassSpecLoc())) { 6819 // In C++11, the 'register' storage class specifier is deprecated. 6820 // Suppress the warning in system macros, it's used in macros in some 6821 // popular C system headers, such as in glibc's htonl() macro. 6822 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6823 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6824 : diag::warn_deprecated_register) 6825 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6826 } 6827 6828 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6829 6830 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6831 // C99 6.9p2: The storage-class specifiers auto and register shall not 6832 // appear in the declaration specifiers in an external declaration. 6833 // Global Register+Asm is a GNU extension we support. 6834 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6835 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6836 D.setInvalidType(); 6837 } 6838 } 6839 6840 bool IsMemberSpecialization = false; 6841 bool IsVariableTemplateSpecialization = false; 6842 bool IsPartialSpecialization = false; 6843 bool IsVariableTemplate = false; 6844 VarDecl *NewVD = nullptr; 6845 VarTemplateDecl *NewTemplate = nullptr; 6846 TemplateParameterList *TemplateParams = nullptr; 6847 if (!getLangOpts().CPlusPlus) { 6848 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6849 II, R, TInfo, SC); 6850 6851 if (R->getContainedDeducedType()) 6852 ParsingInitForAutoVars.insert(NewVD); 6853 6854 if (D.isInvalidType()) 6855 NewVD->setInvalidDecl(); 6856 6857 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6858 NewVD->hasLocalStorage()) 6859 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6860 NTCUC_AutoVar, NTCUK_Destruct); 6861 } else { 6862 bool Invalid = false; 6863 6864 if (DC->isRecord() && !CurContext->isRecord()) { 6865 // This is an out-of-line definition of a static data member. 6866 switch (SC) { 6867 case SC_None: 6868 break; 6869 case SC_Static: 6870 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6871 diag::err_static_out_of_line) 6872 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6873 break; 6874 case SC_Auto: 6875 case SC_Register: 6876 case SC_Extern: 6877 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6878 // to names of variables declared in a block or to function parameters. 6879 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6880 // of class members 6881 6882 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6883 diag::err_storage_class_for_static_member) 6884 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6885 break; 6886 case SC_PrivateExtern: 6887 llvm_unreachable("C storage class in c++!"); 6888 } 6889 } 6890 6891 if (SC == SC_Static && CurContext->isRecord()) { 6892 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6893 // Walk up the enclosing DeclContexts to check for any that are 6894 // incompatible with static data members. 6895 const DeclContext *FunctionOrMethod = nullptr; 6896 const CXXRecordDecl *AnonStruct = nullptr; 6897 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 6898 if (Ctxt->isFunctionOrMethod()) { 6899 FunctionOrMethod = Ctxt; 6900 break; 6901 } 6902 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 6903 if (ParentDecl && !ParentDecl->getDeclName()) { 6904 AnonStruct = ParentDecl; 6905 break; 6906 } 6907 } 6908 if (FunctionOrMethod) { 6909 // C++ [class.static.data]p5: A local class shall not have static data 6910 // members. 6911 Diag(D.getIdentifierLoc(), 6912 diag::err_static_data_member_not_allowed_in_local_class) 6913 << Name << RD->getDeclName() << RD->getTagKind(); 6914 } else if (AnonStruct) { 6915 // C++ [class.static.data]p4: Unnamed classes and classes contained 6916 // directly or indirectly within unnamed classes shall not contain 6917 // static data members. 6918 Diag(D.getIdentifierLoc(), 6919 diag::err_static_data_member_not_allowed_in_anon_struct) 6920 << Name << AnonStruct->getTagKind(); 6921 Invalid = true; 6922 } else if (RD->isUnion()) { 6923 // C++98 [class.union]p1: If a union contains a static data member, 6924 // the program is ill-formed. C++11 drops this restriction. 6925 Diag(D.getIdentifierLoc(), 6926 getLangOpts().CPlusPlus11 6927 ? diag::warn_cxx98_compat_static_data_member_in_union 6928 : diag::ext_static_data_member_in_union) << Name; 6929 } 6930 } 6931 } 6932 6933 // Match up the template parameter lists with the scope specifier, then 6934 // determine whether we have a template or a template specialization. 6935 bool InvalidScope = false; 6936 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6937 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6938 D.getCXXScopeSpec(), 6939 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6940 ? D.getName().TemplateId 6941 : nullptr, 6942 TemplateParamLists, 6943 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 6944 Invalid |= InvalidScope; 6945 6946 if (TemplateParams) { 6947 if (!TemplateParams->size() && 6948 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6949 // There is an extraneous 'template<>' for this variable. Complain 6950 // about it, but allow the declaration of the variable. 6951 Diag(TemplateParams->getTemplateLoc(), 6952 diag::err_template_variable_noparams) 6953 << II 6954 << SourceRange(TemplateParams->getTemplateLoc(), 6955 TemplateParams->getRAngleLoc()); 6956 TemplateParams = nullptr; 6957 } else { 6958 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6959 // This is an explicit specialization or a partial specialization. 6960 // FIXME: Check that we can declare a specialization here. 6961 IsVariableTemplateSpecialization = true; 6962 IsPartialSpecialization = TemplateParams->size() > 0; 6963 } else { // if (TemplateParams->size() > 0) 6964 // This is a template declaration. 6965 IsVariableTemplate = true; 6966 6967 // Check that we can declare a template here. 6968 if (CheckTemplateDeclScope(S, TemplateParams)) 6969 return nullptr; 6970 6971 // Only C++1y supports variable templates (N3651). 6972 Diag(D.getIdentifierLoc(), 6973 getLangOpts().CPlusPlus14 6974 ? diag::warn_cxx11_compat_variable_template 6975 : diag::ext_variable_template); 6976 } 6977 } 6978 } else { 6979 assert((Invalid || 6980 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6981 "should have a 'template<>' for this decl"); 6982 } 6983 6984 if (IsVariableTemplateSpecialization) { 6985 SourceLocation TemplateKWLoc = 6986 TemplateParamLists.size() > 0 6987 ? TemplateParamLists[0]->getTemplateLoc() 6988 : SourceLocation(); 6989 DeclResult Res = ActOnVarTemplateSpecialization( 6990 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6991 IsPartialSpecialization); 6992 if (Res.isInvalid()) 6993 return nullptr; 6994 NewVD = cast<VarDecl>(Res.get()); 6995 AddToScope = false; 6996 } else if (D.isDecompositionDeclarator()) { 6997 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 6998 D.getIdentifierLoc(), R, TInfo, SC, 6999 Bindings); 7000 } else 7001 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7002 D.getIdentifierLoc(), II, R, TInfo, SC); 7003 7004 // If this is supposed to be a variable template, create it as such. 7005 if (IsVariableTemplate) { 7006 NewTemplate = 7007 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7008 TemplateParams, NewVD); 7009 NewVD->setDescribedVarTemplate(NewTemplate); 7010 } 7011 7012 // If this decl has an auto type in need of deduction, make a note of the 7013 // Decl so we can diagnose uses of it in its own initializer. 7014 if (R->getContainedDeducedType()) 7015 ParsingInitForAutoVars.insert(NewVD); 7016 7017 if (D.isInvalidType() || Invalid) { 7018 NewVD->setInvalidDecl(); 7019 if (NewTemplate) 7020 NewTemplate->setInvalidDecl(); 7021 } 7022 7023 SetNestedNameSpecifier(*this, NewVD, D); 7024 7025 // If we have any template parameter lists that don't directly belong to 7026 // the variable (matching the scope specifier), store them. 7027 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7028 if (TemplateParamLists.size() > VDTemplateParamLists) 7029 NewVD->setTemplateParameterListsInfo( 7030 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7031 } 7032 7033 if (D.getDeclSpec().isInlineSpecified()) { 7034 if (!getLangOpts().CPlusPlus) { 7035 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7036 << 0; 7037 } else if (CurContext->isFunctionOrMethod()) { 7038 // 'inline' is not allowed on block scope variable declaration. 7039 Diag(D.getDeclSpec().getInlineSpecLoc(), 7040 diag::err_inline_declaration_block_scope) << Name 7041 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7042 } else { 7043 Diag(D.getDeclSpec().getInlineSpecLoc(), 7044 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7045 : diag::ext_inline_variable); 7046 NewVD->setInlineSpecified(); 7047 } 7048 } 7049 7050 // Set the lexical context. If the declarator has a C++ scope specifier, the 7051 // lexical context will be different from the semantic context. 7052 NewVD->setLexicalDeclContext(CurContext); 7053 if (NewTemplate) 7054 NewTemplate->setLexicalDeclContext(CurContext); 7055 7056 if (IsLocalExternDecl) { 7057 if (D.isDecompositionDeclarator()) 7058 for (auto *B : Bindings) 7059 B->setLocalExternDecl(); 7060 else 7061 NewVD->setLocalExternDecl(); 7062 } 7063 7064 bool EmitTLSUnsupportedError = false; 7065 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7066 // C++11 [dcl.stc]p4: 7067 // When thread_local is applied to a variable of block scope the 7068 // storage-class-specifier static is implied if it does not appear 7069 // explicitly. 7070 // Core issue: 'static' is not implied if the variable is declared 7071 // 'extern'. 7072 if (NewVD->hasLocalStorage() && 7073 (SCSpec != DeclSpec::SCS_unspecified || 7074 TSCS != DeclSpec::TSCS_thread_local || 7075 !DC->isFunctionOrMethod())) 7076 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7077 diag::err_thread_non_global) 7078 << DeclSpec::getSpecifierName(TSCS); 7079 else if (!Context.getTargetInfo().isTLSSupported()) { 7080 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7081 getLangOpts().SYCLIsDevice) { 7082 // Postpone error emission until we've collected attributes required to 7083 // figure out whether it's a host or device variable and whether the 7084 // error should be ignored. 7085 EmitTLSUnsupportedError = true; 7086 // We still need to mark the variable as TLS so it shows up in AST with 7087 // proper storage class for other tools to use even if we're not going 7088 // to emit any code for it. 7089 NewVD->setTSCSpec(TSCS); 7090 } else 7091 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7092 diag::err_thread_unsupported); 7093 } else 7094 NewVD->setTSCSpec(TSCS); 7095 } 7096 7097 switch (D.getDeclSpec().getConstexprSpecifier()) { 7098 case CSK_unspecified: 7099 break; 7100 7101 case CSK_consteval: 7102 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7103 diag::err_constexpr_wrong_decl_kind) 7104 << D.getDeclSpec().getConstexprSpecifier(); 7105 LLVM_FALLTHROUGH; 7106 7107 case CSK_constexpr: 7108 NewVD->setConstexpr(true); 7109 MaybeAddCUDAConstantAttr(NewVD); 7110 // C++1z [dcl.spec.constexpr]p1: 7111 // A static data member declared with the constexpr specifier is 7112 // implicitly an inline variable. 7113 if (NewVD->isStaticDataMember() && 7114 (getLangOpts().CPlusPlus17 || 7115 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7116 NewVD->setImplicitlyInline(); 7117 break; 7118 7119 case CSK_constinit: 7120 if (!NewVD->hasGlobalStorage()) 7121 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7122 diag::err_constinit_local_variable); 7123 else 7124 NewVD->addAttr(ConstInitAttr::Create( 7125 Context, D.getDeclSpec().getConstexprSpecLoc(), 7126 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7127 break; 7128 } 7129 7130 // C99 6.7.4p3 7131 // An inline definition of a function with external linkage shall 7132 // not contain a definition of a modifiable object with static or 7133 // thread storage duration... 7134 // We only apply this when the function is required to be defined 7135 // elsewhere, i.e. when the function is not 'extern inline'. Note 7136 // that a local variable with thread storage duration still has to 7137 // be marked 'static'. Also note that it's possible to get these 7138 // semantics in C++ using __attribute__((gnu_inline)). 7139 if (SC == SC_Static && S->getFnParent() != nullptr && 7140 !NewVD->getType().isConstQualified()) { 7141 FunctionDecl *CurFD = getCurFunctionDecl(); 7142 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7143 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7144 diag::warn_static_local_in_extern_inline); 7145 MaybeSuggestAddingStaticToDecl(CurFD); 7146 } 7147 } 7148 7149 if (D.getDeclSpec().isModulePrivateSpecified()) { 7150 if (IsVariableTemplateSpecialization) 7151 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7152 << (IsPartialSpecialization ? 1 : 0) 7153 << FixItHint::CreateRemoval( 7154 D.getDeclSpec().getModulePrivateSpecLoc()); 7155 else if (IsMemberSpecialization) 7156 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7157 << 2 7158 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7159 else if (NewVD->hasLocalStorage()) 7160 Diag(NewVD->getLocation(), diag::err_module_private_local) 7161 << 0 << NewVD->getDeclName() 7162 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7163 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7164 else { 7165 NewVD->setModulePrivate(); 7166 if (NewTemplate) 7167 NewTemplate->setModulePrivate(); 7168 for (auto *B : Bindings) 7169 B->setModulePrivate(); 7170 } 7171 } 7172 7173 if (getLangOpts().OpenCL) { 7174 7175 deduceOpenCLAddressSpace(NewVD); 7176 7177 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); 7178 } 7179 7180 // Handle attributes prior to checking for duplicates in MergeVarDecl 7181 ProcessDeclAttributes(S, NewVD, D); 7182 7183 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7184 getLangOpts().SYCLIsDevice) { 7185 if (EmitTLSUnsupportedError && 7186 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7187 (getLangOpts().OpenMPIsDevice && 7188 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7189 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7190 diag::err_thread_unsupported); 7191 7192 if (EmitTLSUnsupportedError && 7193 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7194 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7195 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7196 // storage [duration]." 7197 if (SC == SC_None && S->getFnParent() != nullptr && 7198 (NewVD->hasAttr<CUDASharedAttr>() || 7199 NewVD->hasAttr<CUDAConstantAttr>())) { 7200 NewVD->setStorageClass(SC_Static); 7201 } 7202 } 7203 7204 // Ensure that dllimport globals without explicit storage class are treated as 7205 // extern. The storage class is set above using parsed attributes. Now we can 7206 // check the VarDecl itself. 7207 assert(!NewVD->hasAttr<DLLImportAttr>() || 7208 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7209 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7210 7211 // In auto-retain/release, infer strong retension for variables of 7212 // retainable type. 7213 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7214 NewVD->setInvalidDecl(); 7215 7216 // Handle GNU asm-label extension (encoded as an attribute). 7217 if (Expr *E = (Expr*)D.getAsmLabel()) { 7218 // The parser guarantees this is a string. 7219 StringLiteral *SE = cast<StringLiteral>(E); 7220 StringRef Label = SE->getString(); 7221 if (S->getFnParent() != nullptr) { 7222 switch (SC) { 7223 case SC_None: 7224 case SC_Auto: 7225 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7226 break; 7227 case SC_Register: 7228 // Local Named register 7229 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7230 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7231 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7232 break; 7233 case SC_Static: 7234 case SC_Extern: 7235 case SC_PrivateExtern: 7236 break; 7237 } 7238 } else if (SC == SC_Register) { 7239 // Global Named register 7240 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7241 const auto &TI = Context.getTargetInfo(); 7242 bool HasSizeMismatch; 7243 7244 if (!TI.isValidGCCRegisterName(Label)) 7245 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7246 else if (!TI.validateGlobalRegisterVariable(Label, 7247 Context.getTypeSize(R), 7248 HasSizeMismatch)) 7249 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7250 else if (HasSizeMismatch) 7251 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7252 } 7253 7254 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7255 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7256 NewVD->setInvalidDecl(true); 7257 } 7258 } 7259 7260 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7261 /*IsLiteralLabel=*/true, 7262 SE->getStrTokenLoc(0))); 7263 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7264 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7265 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7266 if (I != ExtnameUndeclaredIdentifiers.end()) { 7267 if (isDeclExternC(NewVD)) { 7268 NewVD->addAttr(I->second); 7269 ExtnameUndeclaredIdentifiers.erase(I); 7270 } else 7271 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7272 << /*Variable*/1 << NewVD; 7273 } 7274 } 7275 7276 // Find the shadowed declaration before filtering for scope. 7277 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7278 ? getShadowedDeclaration(NewVD, Previous) 7279 : nullptr; 7280 7281 // Don't consider existing declarations that are in a different 7282 // scope and are out-of-semantic-context declarations (if the new 7283 // declaration has linkage). 7284 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7285 D.getCXXScopeSpec().isNotEmpty() || 7286 IsMemberSpecialization || 7287 IsVariableTemplateSpecialization); 7288 7289 // Check whether the previous declaration is in the same block scope. This 7290 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7291 if (getLangOpts().CPlusPlus && 7292 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7293 NewVD->setPreviousDeclInSameBlockScope( 7294 Previous.isSingleResult() && !Previous.isShadowed() && 7295 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7296 7297 if (!getLangOpts().CPlusPlus) { 7298 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7299 } else { 7300 // If this is an explicit specialization of a static data member, check it. 7301 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7302 CheckMemberSpecialization(NewVD, Previous)) 7303 NewVD->setInvalidDecl(); 7304 7305 // Merge the decl with the existing one if appropriate. 7306 if (!Previous.empty()) { 7307 if (Previous.isSingleResult() && 7308 isa<FieldDecl>(Previous.getFoundDecl()) && 7309 D.getCXXScopeSpec().isSet()) { 7310 // The user tried to define a non-static data member 7311 // out-of-line (C++ [dcl.meaning]p1). 7312 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7313 << D.getCXXScopeSpec().getRange(); 7314 Previous.clear(); 7315 NewVD->setInvalidDecl(); 7316 } 7317 } else if (D.getCXXScopeSpec().isSet()) { 7318 // No previous declaration in the qualifying scope. 7319 Diag(D.getIdentifierLoc(), diag::err_no_member) 7320 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7321 << D.getCXXScopeSpec().getRange(); 7322 NewVD->setInvalidDecl(); 7323 } 7324 7325 if (!IsVariableTemplateSpecialization) 7326 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7327 7328 if (NewTemplate) { 7329 VarTemplateDecl *PrevVarTemplate = 7330 NewVD->getPreviousDecl() 7331 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7332 : nullptr; 7333 7334 // Check the template parameter list of this declaration, possibly 7335 // merging in the template parameter list from the previous variable 7336 // template declaration. 7337 if (CheckTemplateParameterList( 7338 TemplateParams, 7339 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7340 : nullptr, 7341 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7342 DC->isDependentContext()) 7343 ? TPC_ClassTemplateMember 7344 : TPC_VarTemplate)) 7345 NewVD->setInvalidDecl(); 7346 7347 // If we are providing an explicit specialization of a static variable 7348 // template, make a note of that. 7349 if (PrevVarTemplate && 7350 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7351 PrevVarTemplate->setMemberSpecialization(); 7352 } 7353 } 7354 7355 // Diagnose shadowed variables iff this isn't a redeclaration. 7356 if (ShadowedDecl && !D.isRedeclaration()) 7357 CheckShadow(NewVD, ShadowedDecl, Previous); 7358 7359 ProcessPragmaWeak(S, NewVD); 7360 7361 // If this is the first declaration of an extern C variable, update 7362 // the map of such variables. 7363 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7364 isIncompleteDeclExternC(*this, NewVD)) 7365 RegisterLocallyScopedExternCDecl(NewVD, S); 7366 7367 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7368 MangleNumberingContext *MCtx; 7369 Decl *ManglingContextDecl; 7370 std::tie(MCtx, ManglingContextDecl) = 7371 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7372 if (MCtx) { 7373 Context.setManglingNumber( 7374 NewVD, MCtx->getManglingNumber( 7375 NewVD, getMSManglingNumber(getLangOpts(), S))); 7376 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7377 } 7378 } 7379 7380 // Special handling of variable named 'main'. 7381 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7382 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7383 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7384 7385 // C++ [basic.start.main]p3 7386 // A program that declares a variable main at global scope is ill-formed. 7387 if (getLangOpts().CPlusPlus) 7388 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7389 7390 // In C, and external-linkage variable named main results in undefined 7391 // behavior. 7392 else if (NewVD->hasExternalFormalLinkage()) 7393 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7394 } 7395 7396 if (D.isRedeclaration() && !Previous.empty()) { 7397 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7398 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7399 D.isFunctionDefinition()); 7400 } 7401 7402 if (NewTemplate) { 7403 if (NewVD->isInvalidDecl()) 7404 NewTemplate->setInvalidDecl(); 7405 ActOnDocumentableDecl(NewTemplate); 7406 return NewTemplate; 7407 } 7408 7409 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7410 CompleteMemberSpecialization(NewVD, Previous); 7411 7412 return NewVD; 7413 } 7414 7415 /// Enum describing the %select options in diag::warn_decl_shadow. 7416 enum ShadowedDeclKind { 7417 SDK_Local, 7418 SDK_Global, 7419 SDK_StaticMember, 7420 SDK_Field, 7421 SDK_Typedef, 7422 SDK_Using 7423 }; 7424 7425 /// Determine what kind of declaration we're shadowing. 7426 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7427 const DeclContext *OldDC) { 7428 if (isa<TypeAliasDecl>(ShadowedDecl)) 7429 return SDK_Using; 7430 else if (isa<TypedefDecl>(ShadowedDecl)) 7431 return SDK_Typedef; 7432 else if (isa<RecordDecl>(OldDC)) 7433 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7434 7435 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7436 } 7437 7438 /// Return the location of the capture if the given lambda captures the given 7439 /// variable \p VD, or an invalid source location otherwise. 7440 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7441 const VarDecl *VD) { 7442 for (const Capture &Capture : LSI->Captures) { 7443 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7444 return Capture.getLocation(); 7445 } 7446 return SourceLocation(); 7447 } 7448 7449 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7450 const LookupResult &R) { 7451 // Only diagnose if we're shadowing an unambiguous field or variable. 7452 if (R.getResultKind() != LookupResult::Found) 7453 return false; 7454 7455 // Return false if warning is ignored. 7456 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7457 } 7458 7459 /// Return the declaration shadowed by the given variable \p D, or null 7460 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7461 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7462 const LookupResult &R) { 7463 if (!shouldWarnIfShadowedDecl(Diags, R)) 7464 return nullptr; 7465 7466 // Don't diagnose declarations at file scope. 7467 if (D->hasGlobalStorage()) 7468 return nullptr; 7469 7470 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7471 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7472 ? ShadowedDecl 7473 : nullptr; 7474 } 7475 7476 /// Return the declaration shadowed by the given typedef \p D, or null 7477 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7478 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7479 const LookupResult &R) { 7480 // Don't warn if typedef declaration is part of a class 7481 if (D->getDeclContext()->isRecord()) 7482 return nullptr; 7483 7484 if (!shouldWarnIfShadowedDecl(Diags, R)) 7485 return nullptr; 7486 7487 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7488 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7489 } 7490 7491 /// Diagnose variable or built-in function shadowing. Implements 7492 /// -Wshadow. 7493 /// 7494 /// This method is called whenever a VarDecl is added to a "useful" 7495 /// scope. 7496 /// 7497 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7498 /// \param R the lookup of the name 7499 /// 7500 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7501 const LookupResult &R) { 7502 DeclContext *NewDC = D->getDeclContext(); 7503 7504 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7505 // Fields are not shadowed by variables in C++ static methods. 7506 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7507 if (MD->isStatic()) 7508 return; 7509 7510 // Fields shadowed by constructor parameters are a special case. Usually 7511 // the constructor initializes the field with the parameter. 7512 if (isa<CXXConstructorDecl>(NewDC)) 7513 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7514 // Remember that this was shadowed so we can either warn about its 7515 // modification or its existence depending on warning settings. 7516 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7517 return; 7518 } 7519 } 7520 7521 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7522 if (shadowedVar->isExternC()) { 7523 // For shadowing external vars, make sure that we point to the global 7524 // declaration, not a locally scoped extern declaration. 7525 for (auto I : shadowedVar->redecls()) 7526 if (I->isFileVarDecl()) { 7527 ShadowedDecl = I; 7528 break; 7529 } 7530 } 7531 7532 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7533 7534 unsigned WarningDiag = diag::warn_decl_shadow; 7535 SourceLocation CaptureLoc; 7536 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7537 isa<CXXMethodDecl>(NewDC)) { 7538 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7539 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7540 if (RD->getLambdaCaptureDefault() == LCD_None) { 7541 // Try to avoid warnings for lambdas with an explicit capture list. 7542 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7543 // Warn only when the lambda captures the shadowed decl explicitly. 7544 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7545 if (CaptureLoc.isInvalid()) 7546 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7547 } else { 7548 // Remember that this was shadowed so we can avoid the warning if the 7549 // shadowed decl isn't captured and the warning settings allow it. 7550 cast<LambdaScopeInfo>(getCurFunction()) 7551 ->ShadowingDecls.push_back( 7552 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7553 return; 7554 } 7555 } 7556 7557 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7558 // A variable can't shadow a local variable in an enclosing scope, if 7559 // they are separated by a non-capturing declaration context. 7560 for (DeclContext *ParentDC = NewDC; 7561 ParentDC && !ParentDC->Equals(OldDC); 7562 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7563 // Only block literals, captured statements, and lambda expressions 7564 // can capture; other scopes don't. 7565 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7566 !isLambdaCallOperator(ParentDC)) { 7567 return; 7568 } 7569 } 7570 } 7571 } 7572 } 7573 7574 // Only warn about certain kinds of shadowing for class members. 7575 if (NewDC && NewDC->isRecord()) { 7576 // In particular, don't warn about shadowing non-class members. 7577 if (!OldDC->isRecord()) 7578 return; 7579 7580 // TODO: should we warn about static data members shadowing 7581 // static data members from base classes? 7582 7583 // TODO: don't diagnose for inaccessible shadowed members. 7584 // This is hard to do perfectly because we might friend the 7585 // shadowing context, but that's just a false negative. 7586 } 7587 7588 7589 DeclarationName Name = R.getLookupName(); 7590 7591 // Emit warning and note. 7592 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7593 return; 7594 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7595 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7596 if (!CaptureLoc.isInvalid()) 7597 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7598 << Name << /*explicitly*/ 1; 7599 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7600 } 7601 7602 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7603 /// when these variables are captured by the lambda. 7604 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7605 for (const auto &Shadow : LSI->ShadowingDecls) { 7606 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7607 // Try to avoid the warning when the shadowed decl isn't captured. 7608 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7609 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7610 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7611 ? diag::warn_decl_shadow_uncaptured_local 7612 : diag::warn_decl_shadow) 7613 << Shadow.VD->getDeclName() 7614 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7615 if (!CaptureLoc.isInvalid()) 7616 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7617 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7618 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7619 } 7620 } 7621 7622 /// Check -Wshadow without the advantage of a previous lookup. 7623 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7624 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7625 return; 7626 7627 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7628 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7629 LookupName(R, S); 7630 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7631 CheckShadow(D, ShadowedDecl, R); 7632 } 7633 7634 /// Check if 'E', which is an expression that is about to be modified, refers 7635 /// to a constructor parameter that shadows a field. 7636 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7637 // Quickly ignore expressions that can't be shadowing ctor parameters. 7638 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7639 return; 7640 E = E->IgnoreParenImpCasts(); 7641 auto *DRE = dyn_cast<DeclRefExpr>(E); 7642 if (!DRE) 7643 return; 7644 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7645 auto I = ShadowingDecls.find(D); 7646 if (I == ShadowingDecls.end()) 7647 return; 7648 const NamedDecl *ShadowedDecl = I->second; 7649 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7650 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7651 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7652 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7653 7654 // Avoid issuing multiple warnings about the same decl. 7655 ShadowingDecls.erase(I); 7656 } 7657 7658 /// Check for conflict between this global or extern "C" declaration and 7659 /// previous global or extern "C" declarations. This is only used in C++. 7660 template<typename T> 7661 static bool checkGlobalOrExternCConflict( 7662 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7663 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7664 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7665 7666 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7667 // The common case: this global doesn't conflict with any extern "C" 7668 // declaration. 7669 return false; 7670 } 7671 7672 if (Prev) { 7673 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7674 // Both the old and new declarations have C language linkage. This is a 7675 // redeclaration. 7676 Previous.clear(); 7677 Previous.addDecl(Prev); 7678 return true; 7679 } 7680 7681 // This is a global, non-extern "C" declaration, and there is a previous 7682 // non-global extern "C" declaration. Diagnose if this is a variable 7683 // declaration. 7684 if (!isa<VarDecl>(ND)) 7685 return false; 7686 } else { 7687 // The declaration is extern "C". Check for any declaration in the 7688 // translation unit which might conflict. 7689 if (IsGlobal) { 7690 // We have already performed the lookup into the translation unit. 7691 IsGlobal = false; 7692 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7693 I != E; ++I) { 7694 if (isa<VarDecl>(*I)) { 7695 Prev = *I; 7696 break; 7697 } 7698 } 7699 } else { 7700 DeclContext::lookup_result R = 7701 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7702 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7703 I != E; ++I) { 7704 if (isa<VarDecl>(*I)) { 7705 Prev = *I; 7706 break; 7707 } 7708 // FIXME: If we have any other entity with this name in global scope, 7709 // the declaration is ill-formed, but that is a defect: it breaks the 7710 // 'stat' hack, for instance. Only variables can have mangled name 7711 // clashes with extern "C" declarations, so only they deserve a 7712 // diagnostic. 7713 } 7714 } 7715 7716 if (!Prev) 7717 return false; 7718 } 7719 7720 // Use the first declaration's location to ensure we point at something which 7721 // is lexically inside an extern "C" linkage-spec. 7722 assert(Prev && "should have found a previous declaration to diagnose"); 7723 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7724 Prev = FD->getFirstDecl(); 7725 else 7726 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7727 7728 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7729 << IsGlobal << ND; 7730 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7731 << IsGlobal; 7732 return false; 7733 } 7734 7735 /// Apply special rules for handling extern "C" declarations. Returns \c true 7736 /// if we have found that this is a redeclaration of some prior entity. 7737 /// 7738 /// Per C++ [dcl.link]p6: 7739 /// Two declarations [for a function or variable] with C language linkage 7740 /// with the same name that appear in different scopes refer to the same 7741 /// [entity]. An entity with C language linkage shall not be declared with 7742 /// the same name as an entity in global scope. 7743 template<typename T> 7744 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7745 LookupResult &Previous) { 7746 if (!S.getLangOpts().CPlusPlus) { 7747 // In C, when declaring a global variable, look for a corresponding 'extern' 7748 // variable declared in function scope. We don't need this in C++, because 7749 // we find local extern decls in the surrounding file-scope DeclContext. 7750 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7751 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7752 Previous.clear(); 7753 Previous.addDecl(Prev); 7754 return true; 7755 } 7756 } 7757 return false; 7758 } 7759 7760 // A declaration in the translation unit can conflict with an extern "C" 7761 // declaration. 7762 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7763 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7764 7765 // An extern "C" declaration can conflict with a declaration in the 7766 // translation unit or can be a redeclaration of an extern "C" declaration 7767 // in another scope. 7768 if (isIncompleteDeclExternC(S,ND)) 7769 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7770 7771 // Neither global nor extern "C": nothing to do. 7772 return false; 7773 } 7774 7775 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7776 // If the decl is already known invalid, don't check it. 7777 if (NewVD->isInvalidDecl()) 7778 return; 7779 7780 QualType T = NewVD->getType(); 7781 7782 // Defer checking an 'auto' type until its initializer is attached. 7783 if (T->isUndeducedType()) 7784 return; 7785 7786 if (NewVD->hasAttrs()) 7787 CheckAlignasUnderalignment(NewVD); 7788 7789 if (T->isObjCObjectType()) { 7790 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7791 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7792 T = Context.getObjCObjectPointerType(T); 7793 NewVD->setType(T); 7794 } 7795 7796 // Emit an error if an address space was applied to decl with local storage. 7797 // This includes arrays of objects with address space qualifiers, but not 7798 // automatic variables that point to other address spaces. 7799 // ISO/IEC TR 18037 S5.1.2 7800 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7801 T.getAddressSpace() != LangAS::Default) { 7802 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7803 NewVD->setInvalidDecl(); 7804 return; 7805 } 7806 7807 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7808 // scope. 7809 if (getLangOpts().OpenCLVersion == 120 && 7810 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7811 NewVD->isStaticLocal()) { 7812 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7813 NewVD->setInvalidDecl(); 7814 return; 7815 } 7816 7817 if (getLangOpts().OpenCL) { 7818 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7819 if (NewVD->hasAttr<BlocksAttr>()) { 7820 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7821 return; 7822 } 7823 7824 if (T->isBlockPointerType()) { 7825 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7826 // can't use 'extern' storage class. 7827 if (!T.isConstQualified()) { 7828 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7829 << 0 /*const*/; 7830 NewVD->setInvalidDecl(); 7831 return; 7832 } 7833 if (NewVD->hasExternalStorage()) { 7834 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7835 NewVD->setInvalidDecl(); 7836 return; 7837 } 7838 } 7839 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7840 // __constant address space. 7841 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7842 // variables inside a function can also be declared in the global 7843 // address space. 7844 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7845 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7846 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7847 NewVD->hasExternalStorage()) { 7848 if (!T->isSamplerT() && 7849 !(T.getAddressSpace() == LangAS::opencl_constant || 7850 (T.getAddressSpace() == LangAS::opencl_global && 7851 (getLangOpts().OpenCLVersion == 200 || 7852 getLangOpts().OpenCLCPlusPlus)))) { 7853 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7854 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7855 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7856 << Scope << "global or constant"; 7857 else 7858 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7859 << Scope << "constant"; 7860 NewVD->setInvalidDecl(); 7861 return; 7862 } 7863 } else { 7864 if (T.getAddressSpace() == LangAS::opencl_global) { 7865 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7866 << 1 /*is any function*/ << "global"; 7867 NewVD->setInvalidDecl(); 7868 return; 7869 } 7870 if (T.getAddressSpace() == LangAS::opencl_constant || 7871 T.getAddressSpace() == LangAS::opencl_local) { 7872 FunctionDecl *FD = getCurFunctionDecl(); 7873 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7874 // in functions. 7875 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7876 if (T.getAddressSpace() == LangAS::opencl_constant) 7877 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7878 << 0 /*non-kernel only*/ << "constant"; 7879 else 7880 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7881 << 0 /*non-kernel only*/ << "local"; 7882 NewVD->setInvalidDecl(); 7883 return; 7884 } 7885 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7886 // in the outermost scope of a kernel function. 7887 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7888 if (!getCurScope()->isFunctionScope()) { 7889 if (T.getAddressSpace() == LangAS::opencl_constant) 7890 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7891 << "constant"; 7892 else 7893 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7894 << "local"; 7895 NewVD->setInvalidDecl(); 7896 return; 7897 } 7898 } 7899 } else if (T.getAddressSpace() != LangAS::opencl_private && 7900 // If we are parsing a template we didn't deduce an addr 7901 // space yet. 7902 T.getAddressSpace() != LangAS::Default) { 7903 // Do not allow other address spaces on automatic variable. 7904 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7905 NewVD->setInvalidDecl(); 7906 return; 7907 } 7908 } 7909 } 7910 7911 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7912 && !NewVD->hasAttr<BlocksAttr>()) { 7913 if (getLangOpts().getGC() != LangOptions::NonGC) 7914 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7915 else { 7916 assert(!getLangOpts().ObjCAutoRefCount); 7917 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7918 } 7919 } 7920 7921 bool isVM = T->isVariablyModifiedType(); 7922 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7923 NewVD->hasAttr<BlocksAttr>()) 7924 setFunctionHasBranchProtectedScope(); 7925 7926 if ((isVM && NewVD->hasLinkage()) || 7927 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7928 bool SizeIsNegative; 7929 llvm::APSInt Oversized; 7930 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7931 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7932 QualType FixedT; 7933 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7934 FixedT = FixedTInfo->getType(); 7935 else if (FixedTInfo) { 7936 // Type and type-as-written are canonically different. We need to fix up 7937 // both types separately. 7938 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7939 Oversized); 7940 } 7941 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7942 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7943 // FIXME: This won't give the correct result for 7944 // int a[10][n]; 7945 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7946 7947 if (NewVD->isFileVarDecl()) 7948 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7949 << SizeRange; 7950 else if (NewVD->isStaticLocal()) 7951 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7952 << SizeRange; 7953 else 7954 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7955 << SizeRange; 7956 NewVD->setInvalidDecl(); 7957 return; 7958 } 7959 7960 if (!FixedTInfo) { 7961 if (NewVD->isFileVarDecl()) 7962 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7963 else 7964 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7965 NewVD->setInvalidDecl(); 7966 return; 7967 } 7968 7969 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7970 NewVD->setType(FixedT); 7971 NewVD->setTypeSourceInfo(FixedTInfo); 7972 } 7973 7974 if (T->isVoidType()) { 7975 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7976 // of objects and functions. 7977 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7978 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7979 << T; 7980 NewVD->setInvalidDecl(); 7981 return; 7982 } 7983 } 7984 7985 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7986 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7987 NewVD->setInvalidDecl(); 7988 return; 7989 } 7990 7991 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 7992 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 7993 NewVD->setInvalidDecl(); 7994 return; 7995 } 7996 7997 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7998 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7999 NewVD->setInvalidDecl(); 8000 return; 8001 } 8002 8003 if (NewVD->isConstexpr() && !T->isDependentType() && 8004 RequireLiteralType(NewVD->getLocation(), T, 8005 diag::err_constexpr_var_non_literal)) { 8006 NewVD->setInvalidDecl(); 8007 return; 8008 } 8009 } 8010 8011 /// Perform semantic checking on a newly-created variable 8012 /// declaration. 8013 /// 8014 /// This routine performs all of the type-checking required for a 8015 /// variable declaration once it has been built. It is used both to 8016 /// check variables after they have been parsed and their declarators 8017 /// have been translated into a declaration, and to check variables 8018 /// that have been instantiated from a template. 8019 /// 8020 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8021 /// 8022 /// Returns true if the variable declaration is a redeclaration. 8023 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8024 CheckVariableDeclarationType(NewVD); 8025 8026 // If the decl is already known invalid, don't check it. 8027 if (NewVD->isInvalidDecl()) 8028 return false; 8029 8030 // If we did not find anything by this name, look for a non-visible 8031 // extern "C" declaration with the same name. 8032 if (Previous.empty() && 8033 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8034 Previous.setShadowed(); 8035 8036 if (!Previous.empty()) { 8037 MergeVarDecl(NewVD, Previous); 8038 return true; 8039 } 8040 return false; 8041 } 8042 8043 namespace { 8044 struct FindOverriddenMethod { 8045 Sema *S; 8046 CXXMethodDecl *Method; 8047 8048 /// Member lookup function that determines whether a given C++ 8049 /// method overrides a method in a base class, to be used with 8050 /// CXXRecordDecl::lookupInBases(). 8051 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8052 RecordDecl *BaseRecord = 8053 Specifier->getType()->castAs<RecordType>()->getDecl(); 8054 8055 DeclarationName Name = Method->getDeclName(); 8056 8057 // FIXME: Do we care about other names here too? 8058 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8059 // We really want to find the base class destructor here. 8060 QualType T = S->Context.getTypeDeclType(BaseRecord); 8061 CanQualType CT = S->Context.getCanonicalType(T); 8062 8063 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 8064 } 8065 8066 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 8067 Path.Decls = Path.Decls.slice(1)) { 8068 NamedDecl *D = Path.Decls.front(); 8069 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 8070 if (MD->isVirtual() && 8071 !S->IsOverload( 8072 Method, MD, /*UseMemberUsingDeclRules=*/false, 8073 /*ConsiderCudaAttrs=*/true, 8074 // C++2a [class.virtual]p2 does not consider requires clauses 8075 // when overriding. 8076 /*ConsiderRequiresClauses=*/false)) 8077 return true; 8078 } 8079 } 8080 8081 return false; 8082 } 8083 }; 8084 } // end anonymous namespace 8085 8086 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8087 /// and if so, check that it's a valid override and remember it. 8088 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8089 // Look for methods in base classes that this method might override. 8090 CXXBasePaths Paths; 8091 FindOverriddenMethod FOM; 8092 FOM.Method = MD; 8093 FOM.S = this; 8094 bool AddedAny = false; 8095 if (DC->lookupInBases(FOM, Paths)) { 8096 for (auto *I : Paths.found_decls()) { 8097 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 8098 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 8099 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 8100 !CheckOverridingFunctionAttributes(MD, OldMD) && 8101 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 8102 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 8103 AddedAny = true; 8104 } 8105 } 8106 } 8107 } 8108 8109 return AddedAny; 8110 } 8111 8112 namespace { 8113 // Struct for holding all of the extra arguments needed by 8114 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8115 struct ActOnFDArgs { 8116 Scope *S; 8117 Declarator &D; 8118 MultiTemplateParamsArg TemplateParamLists; 8119 bool AddToScope; 8120 }; 8121 } // end anonymous namespace 8122 8123 namespace { 8124 8125 // Callback to only accept typo corrections that have a non-zero edit distance. 8126 // Also only accept corrections that have the same parent decl. 8127 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8128 public: 8129 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8130 CXXRecordDecl *Parent) 8131 : Context(Context), OriginalFD(TypoFD), 8132 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8133 8134 bool ValidateCandidate(const TypoCorrection &candidate) override { 8135 if (candidate.getEditDistance() == 0) 8136 return false; 8137 8138 SmallVector<unsigned, 1> MismatchedParams; 8139 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8140 CDeclEnd = candidate.end(); 8141 CDecl != CDeclEnd; ++CDecl) { 8142 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8143 8144 if (FD && !FD->hasBody() && 8145 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8146 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8147 CXXRecordDecl *Parent = MD->getParent(); 8148 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8149 return true; 8150 } else if (!ExpectedParent) { 8151 return true; 8152 } 8153 } 8154 } 8155 8156 return false; 8157 } 8158 8159 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8160 return std::make_unique<DifferentNameValidatorCCC>(*this); 8161 } 8162 8163 private: 8164 ASTContext &Context; 8165 FunctionDecl *OriginalFD; 8166 CXXRecordDecl *ExpectedParent; 8167 }; 8168 8169 } // end anonymous namespace 8170 8171 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8172 TypoCorrectedFunctionDefinitions.insert(F); 8173 } 8174 8175 /// Generate diagnostics for an invalid function redeclaration. 8176 /// 8177 /// This routine handles generating the diagnostic messages for an invalid 8178 /// function redeclaration, including finding possible similar declarations 8179 /// or performing typo correction if there are no previous declarations with 8180 /// the same name. 8181 /// 8182 /// Returns a NamedDecl iff typo correction was performed and substituting in 8183 /// the new declaration name does not cause new errors. 8184 static NamedDecl *DiagnoseInvalidRedeclaration( 8185 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8186 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8187 DeclarationName Name = NewFD->getDeclName(); 8188 DeclContext *NewDC = NewFD->getDeclContext(); 8189 SmallVector<unsigned, 1> MismatchedParams; 8190 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8191 TypoCorrection Correction; 8192 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8193 unsigned DiagMsg = 8194 IsLocalFriend ? diag::err_no_matching_local_friend : 8195 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8196 diag::err_member_decl_does_not_match; 8197 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8198 IsLocalFriend ? Sema::LookupLocalFriendName 8199 : Sema::LookupOrdinaryName, 8200 Sema::ForVisibleRedeclaration); 8201 8202 NewFD->setInvalidDecl(); 8203 if (IsLocalFriend) 8204 SemaRef.LookupName(Prev, S); 8205 else 8206 SemaRef.LookupQualifiedName(Prev, NewDC); 8207 assert(!Prev.isAmbiguous() && 8208 "Cannot have an ambiguity in previous-declaration lookup"); 8209 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8210 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8211 MD ? MD->getParent() : nullptr); 8212 if (!Prev.empty()) { 8213 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8214 Func != FuncEnd; ++Func) { 8215 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8216 if (FD && 8217 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8218 // Add 1 to the index so that 0 can mean the mismatch didn't 8219 // involve a parameter 8220 unsigned ParamNum = 8221 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8222 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8223 } 8224 } 8225 // If the qualified name lookup yielded nothing, try typo correction 8226 } else if ((Correction = SemaRef.CorrectTypo( 8227 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8228 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8229 IsLocalFriend ? nullptr : NewDC))) { 8230 // Set up everything for the call to ActOnFunctionDeclarator 8231 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8232 ExtraArgs.D.getIdentifierLoc()); 8233 Previous.clear(); 8234 Previous.setLookupName(Correction.getCorrection()); 8235 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8236 CDeclEnd = Correction.end(); 8237 CDecl != CDeclEnd; ++CDecl) { 8238 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8239 if (FD && !FD->hasBody() && 8240 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8241 Previous.addDecl(FD); 8242 } 8243 } 8244 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8245 8246 NamedDecl *Result; 8247 // Retry building the function declaration with the new previous 8248 // declarations, and with errors suppressed. 8249 { 8250 // Trap errors. 8251 Sema::SFINAETrap Trap(SemaRef); 8252 8253 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8254 // pieces need to verify the typo-corrected C++ declaration and hopefully 8255 // eliminate the need for the parameter pack ExtraArgs. 8256 Result = SemaRef.ActOnFunctionDeclarator( 8257 ExtraArgs.S, ExtraArgs.D, 8258 Correction.getCorrectionDecl()->getDeclContext(), 8259 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8260 ExtraArgs.AddToScope); 8261 8262 if (Trap.hasErrorOccurred()) 8263 Result = nullptr; 8264 } 8265 8266 if (Result) { 8267 // Determine which correction we picked. 8268 Decl *Canonical = Result->getCanonicalDecl(); 8269 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8270 I != E; ++I) 8271 if ((*I)->getCanonicalDecl() == Canonical) 8272 Correction.setCorrectionDecl(*I); 8273 8274 // Let Sema know about the correction. 8275 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8276 SemaRef.diagnoseTypo( 8277 Correction, 8278 SemaRef.PDiag(IsLocalFriend 8279 ? diag::err_no_matching_local_friend_suggest 8280 : diag::err_member_decl_does_not_match_suggest) 8281 << Name << NewDC << IsDefinition); 8282 return Result; 8283 } 8284 8285 // Pretend the typo correction never occurred 8286 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8287 ExtraArgs.D.getIdentifierLoc()); 8288 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8289 Previous.clear(); 8290 Previous.setLookupName(Name); 8291 } 8292 8293 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8294 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8295 8296 bool NewFDisConst = false; 8297 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8298 NewFDisConst = NewMD->isConst(); 8299 8300 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8301 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8302 NearMatch != NearMatchEnd; ++NearMatch) { 8303 FunctionDecl *FD = NearMatch->first; 8304 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8305 bool FDisConst = MD && MD->isConst(); 8306 bool IsMember = MD || !IsLocalFriend; 8307 8308 // FIXME: These notes are poorly worded for the local friend case. 8309 if (unsigned Idx = NearMatch->second) { 8310 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8311 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8312 if (Loc.isInvalid()) Loc = FD->getLocation(); 8313 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8314 : diag::note_local_decl_close_param_match) 8315 << Idx << FDParam->getType() 8316 << NewFD->getParamDecl(Idx - 1)->getType(); 8317 } else if (FDisConst != NewFDisConst) { 8318 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8319 << NewFDisConst << FD->getSourceRange().getEnd(); 8320 } else 8321 SemaRef.Diag(FD->getLocation(), 8322 IsMember ? diag::note_member_def_close_match 8323 : diag::note_local_decl_close_match); 8324 } 8325 return nullptr; 8326 } 8327 8328 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8329 switch (D.getDeclSpec().getStorageClassSpec()) { 8330 default: llvm_unreachable("Unknown storage class!"); 8331 case DeclSpec::SCS_auto: 8332 case DeclSpec::SCS_register: 8333 case DeclSpec::SCS_mutable: 8334 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8335 diag::err_typecheck_sclass_func); 8336 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8337 D.setInvalidType(); 8338 break; 8339 case DeclSpec::SCS_unspecified: break; 8340 case DeclSpec::SCS_extern: 8341 if (D.getDeclSpec().isExternInLinkageSpec()) 8342 return SC_None; 8343 return SC_Extern; 8344 case DeclSpec::SCS_static: { 8345 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8346 // C99 6.7.1p5: 8347 // The declaration of an identifier for a function that has 8348 // block scope shall have no explicit storage-class specifier 8349 // other than extern 8350 // See also (C++ [dcl.stc]p4). 8351 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8352 diag::err_static_block_func); 8353 break; 8354 } else 8355 return SC_Static; 8356 } 8357 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8358 } 8359 8360 // No explicit storage class has already been returned 8361 return SC_None; 8362 } 8363 8364 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8365 DeclContext *DC, QualType &R, 8366 TypeSourceInfo *TInfo, 8367 StorageClass SC, 8368 bool &IsVirtualOkay) { 8369 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8370 DeclarationName Name = NameInfo.getName(); 8371 8372 FunctionDecl *NewFD = nullptr; 8373 bool isInline = D.getDeclSpec().isInlineSpecified(); 8374 8375 if (!SemaRef.getLangOpts().CPlusPlus) { 8376 // Determine whether the function was written with a 8377 // prototype. This true when: 8378 // - there is a prototype in the declarator, or 8379 // - the type R of the function is some kind of typedef or other non- 8380 // attributed reference to a type name (which eventually refers to a 8381 // function type). 8382 bool HasPrototype = 8383 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8384 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8385 8386 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8387 R, TInfo, SC, isInline, HasPrototype, 8388 CSK_unspecified, 8389 /*TrailingRequiresClause=*/nullptr); 8390 if (D.isInvalidType()) 8391 NewFD->setInvalidDecl(); 8392 8393 return NewFD; 8394 } 8395 8396 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8397 8398 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8399 if (ConstexprKind == CSK_constinit) { 8400 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8401 diag::err_constexpr_wrong_decl_kind) 8402 << ConstexprKind; 8403 ConstexprKind = CSK_unspecified; 8404 D.getMutableDeclSpec().ClearConstexprSpec(); 8405 } 8406 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8407 8408 // Check that the return type is not an abstract class type. 8409 // For record types, this is done by the AbstractClassUsageDiagnoser once 8410 // the class has been completely parsed. 8411 if (!DC->isRecord() && 8412 SemaRef.RequireNonAbstractType( 8413 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8414 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8415 D.setInvalidType(); 8416 8417 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8418 // This is a C++ constructor declaration. 8419 assert(DC->isRecord() && 8420 "Constructors can only be declared in a member context"); 8421 8422 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8423 return CXXConstructorDecl::Create( 8424 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8425 TInfo, ExplicitSpecifier, isInline, 8426 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8427 TrailingRequiresClause); 8428 8429 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8430 // This is a C++ destructor declaration. 8431 if (DC->isRecord()) { 8432 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8433 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8434 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8435 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8436 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8437 TrailingRequiresClause); 8438 8439 // If the destructor needs an implicit exception specification, set it 8440 // now. FIXME: It'd be nice to be able to create the right type to start 8441 // with, but the type needs to reference the destructor declaration. 8442 if (SemaRef.getLangOpts().CPlusPlus11) 8443 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8444 8445 IsVirtualOkay = true; 8446 return NewDD; 8447 8448 } else { 8449 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8450 D.setInvalidType(); 8451 8452 // Create a FunctionDecl to satisfy the function definition parsing 8453 // code path. 8454 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8455 D.getIdentifierLoc(), Name, R, TInfo, SC, 8456 isInline, 8457 /*hasPrototype=*/true, ConstexprKind, 8458 TrailingRequiresClause); 8459 } 8460 8461 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8462 if (!DC->isRecord()) { 8463 SemaRef.Diag(D.getIdentifierLoc(), 8464 diag::err_conv_function_not_member); 8465 return nullptr; 8466 } 8467 8468 SemaRef.CheckConversionDeclarator(D, R, SC); 8469 if (D.isInvalidType()) 8470 return nullptr; 8471 8472 IsVirtualOkay = true; 8473 return CXXConversionDecl::Create( 8474 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8475 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8476 TrailingRequiresClause); 8477 8478 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8479 if (TrailingRequiresClause) 8480 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8481 diag::err_trailing_requires_clause_on_deduction_guide) 8482 << TrailingRequiresClause->getSourceRange(); 8483 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8484 8485 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8486 ExplicitSpecifier, NameInfo, R, TInfo, 8487 D.getEndLoc()); 8488 } else if (DC->isRecord()) { 8489 // If the name of the function is the same as the name of the record, 8490 // then this must be an invalid constructor that has a return type. 8491 // (The parser checks for a return type and makes the declarator a 8492 // constructor if it has no return type). 8493 if (Name.getAsIdentifierInfo() && 8494 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8495 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8496 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8497 << SourceRange(D.getIdentifierLoc()); 8498 return nullptr; 8499 } 8500 8501 // This is a C++ method declaration. 8502 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8503 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8504 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8505 TrailingRequiresClause); 8506 IsVirtualOkay = !Ret->isStatic(); 8507 return Ret; 8508 } else { 8509 bool isFriend = 8510 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8511 if (!isFriend && SemaRef.CurContext->isRecord()) 8512 return nullptr; 8513 8514 // Determine whether the function was written with a 8515 // prototype. This true when: 8516 // - we're in C++ (where every function has a prototype), 8517 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8518 R, TInfo, SC, isInline, true /*HasPrototype*/, 8519 ConstexprKind, TrailingRequiresClause); 8520 } 8521 } 8522 8523 enum OpenCLParamType { 8524 ValidKernelParam, 8525 PtrPtrKernelParam, 8526 PtrKernelParam, 8527 InvalidAddrSpacePtrKernelParam, 8528 InvalidKernelParam, 8529 RecordKernelParam 8530 }; 8531 8532 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8533 // Size dependent types are just typedefs to normal integer types 8534 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8535 // integers other than by their names. 8536 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8537 8538 // Remove typedefs one by one until we reach a typedef 8539 // for a size dependent type. 8540 QualType DesugaredTy = Ty; 8541 do { 8542 ArrayRef<StringRef> Names(SizeTypeNames); 8543 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8544 if (Names.end() != Match) 8545 return true; 8546 8547 Ty = DesugaredTy; 8548 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8549 } while (DesugaredTy != Ty); 8550 8551 return false; 8552 } 8553 8554 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8555 if (PT->isPointerType()) { 8556 QualType PointeeType = PT->getPointeeType(); 8557 if (PointeeType->isPointerType()) 8558 return PtrPtrKernelParam; 8559 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8560 PointeeType.getAddressSpace() == LangAS::opencl_private || 8561 PointeeType.getAddressSpace() == LangAS::Default) 8562 return InvalidAddrSpacePtrKernelParam; 8563 return PtrKernelParam; 8564 } 8565 8566 // OpenCL v1.2 s6.9.k: 8567 // Arguments to kernel functions in a program cannot be declared with the 8568 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8569 // uintptr_t or a struct and/or union that contain fields declared to be one 8570 // of these built-in scalar types. 8571 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8572 return InvalidKernelParam; 8573 8574 if (PT->isImageType()) 8575 return PtrKernelParam; 8576 8577 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8578 return InvalidKernelParam; 8579 8580 // OpenCL extension spec v1.2 s9.5: 8581 // This extension adds support for half scalar and vector types as built-in 8582 // types that can be used for arithmetic operations, conversions etc. 8583 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8584 return InvalidKernelParam; 8585 8586 if (PT->isRecordType()) 8587 return RecordKernelParam; 8588 8589 // Look into an array argument to check if it has a forbidden type. 8590 if (PT->isArrayType()) { 8591 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8592 // Call ourself to check an underlying type of an array. Since the 8593 // getPointeeOrArrayElementType returns an innermost type which is not an 8594 // array, this recursive call only happens once. 8595 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8596 } 8597 8598 return ValidKernelParam; 8599 } 8600 8601 static void checkIsValidOpenCLKernelParameter( 8602 Sema &S, 8603 Declarator &D, 8604 ParmVarDecl *Param, 8605 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8606 QualType PT = Param->getType(); 8607 8608 // Cache the valid types we encounter to avoid rechecking structs that are 8609 // used again 8610 if (ValidTypes.count(PT.getTypePtr())) 8611 return; 8612 8613 switch (getOpenCLKernelParameterType(S, PT)) { 8614 case PtrPtrKernelParam: 8615 // OpenCL v1.2 s6.9.a: 8616 // A kernel function argument cannot be declared as a 8617 // pointer to a pointer type. 8618 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8619 D.setInvalidType(); 8620 return; 8621 8622 case InvalidAddrSpacePtrKernelParam: 8623 // OpenCL v1.0 s6.5: 8624 // __kernel function arguments declared to be a pointer of a type can point 8625 // to one of the following address spaces only : __global, __local or 8626 // __constant. 8627 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8628 D.setInvalidType(); 8629 return; 8630 8631 // OpenCL v1.2 s6.9.k: 8632 // Arguments to kernel functions in a program cannot be declared with the 8633 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8634 // uintptr_t or a struct and/or union that contain fields declared to be 8635 // one of these built-in scalar types. 8636 8637 case InvalidKernelParam: 8638 // OpenCL v1.2 s6.8 n: 8639 // A kernel function argument cannot be declared 8640 // of event_t type. 8641 // Do not diagnose half type since it is diagnosed as invalid argument 8642 // type for any function elsewhere. 8643 if (!PT->isHalfType()) { 8644 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8645 8646 // Explain what typedefs are involved. 8647 const TypedefType *Typedef = nullptr; 8648 while ((Typedef = PT->getAs<TypedefType>())) { 8649 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8650 // SourceLocation may be invalid for a built-in type. 8651 if (Loc.isValid()) 8652 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8653 PT = Typedef->desugar(); 8654 } 8655 } 8656 8657 D.setInvalidType(); 8658 return; 8659 8660 case PtrKernelParam: 8661 case ValidKernelParam: 8662 ValidTypes.insert(PT.getTypePtr()); 8663 return; 8664 8665 case RecordKernelParam: 8666 break; 8667 } 8668 8669 // Track nested structs we will inspect 8670 SmallVector<const Decl *, 4> VisitStack; 8671 8672 // Track where we are in the nested structs. Items will migrate from 8673 // VisitStack to HistoryStack as we do the DFS for bad field. 8674 SmallVector<const FieldDecl *, 4> HistoryStack; 8675 HistoryStack.push_back(nullptr); 8676 8677 // At this point we already handled everything except of a RecordType or 8678 // an ArrayType of a RecordType. 8679 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8680 const RecordType *RecTy = 8681 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8682 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8683 8684 VisitStack.push_back(RecTy->getDecl()); 8685 assert(VisitStack.back() && "First decl null?"); 8686 8687 do { 8688 const Decl *Next = VisitStack.pop_back_val(); 8689 if (!Next) { 8690 assert(!HistoryStack.empty()); 8691 // Found a marker, we have gone up a level 8692 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8693 ValidTypes.insert(Hist->getType().getTypePtr()); 8694 8695 continue; 8696 } 8697 8698 // Adds everything except the original parameter declaration (which is not a 8699 // field itself) to the history stack. 8700 const RecordDecl *RD; 8701 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8702 HistoryStack.push_back(Field); 8703 8704 QualType FieldTy = Field->getType(); 8705 // Other field types (known to be valid or invalid) are handled while we 8706 // walk around RecordDecl::fields(). 8707 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8708 "Unexpected type."); 8709 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8710 8711 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8712 } else { 8713 RD = cast<RecordDecl>(Next); 8714 } 8715 8716 // Add a null marker so we know when we've gone back up a level 8717 VisitStack.push_back(nullptr); 8718 8719 for (const auto *FD : RD->fields()) { 8720 QualType QT = FD->getType(); 8721 8722 if (ValidTypes.count(QT.getTypePtr())) 8723 continue; 8724 8725 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8726 if (ParamType == ValidKernelParam) 8727 continue; 8728 8729 if (ParamType == RecordKernelParam) { 8730 VisitStack.push_back(FD); 8731 continue; 8732 } 8733 8734 // OpenCL v1.2 s6.9.p: 8735 // Arguments to kernel functions that are declared to be a struct or union 8736 // do not allow OpenCL objects to be passed as elements of the struct or 8737 // union. 8738 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8739 ParamType == InvalidAddrSpacePtrKernelParam) { 8740 S.Diag(Param->getLocation(), 8741 diag::err_record_with_pointers_kernel_param) 8742 << PT->isUnionType() 8743 << PT; 8744 } else { 8745 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8746 } 8747 8748 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8749 << OrigRecDecl->getDeclName(); 8750 8751 // We have an error, now let's go back up through history and show where 8752 // the offending field came from 8753 for (ArrayRef<const FieldDecl *>::const_iterator 8754 I = HistoryStack.begin() + 1, 8755 E = HistoryStack.end(); 8756 I != E; ++I) { 8757 const FieldDecl *OuterField = *I; 8758 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8759 << OuterField->getType(); 8760 } 8761 8762 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8763 << QT->isPointerType() 8764 << QT; 8765 D.setInvalidType(); 8766 return; 8767 } 8768 } while (!VisitStack.empty()); 8769 } 8770 8771 /// Find the DeclContext in which a tag is implicitly declared if we see an 8772 /// elaborated type specifier in the specified context, and lookup finds 8773 /// nothing. 8774 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8775 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8776 DC = DC->getParent(); 8777 return DC; 8778 } 8779 8780 /// Find the Scope in which a tag is implicitly declared if we see an 8781 /// elaborated type specifier in the specified context, and lookup finds 8782 /// nothing. 8783 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8784 while (S->isClassScope() || 8785 (LangOpts.CPlusPlus && 8786 S->isFunctionPrototypeScope()) || 8787 ((S->getFlags() & Scope::DeclScope) == 0) || 8788 (S->getEntity() && S->getEntity()->isTransparentContext())) 8789 S = S->getParent(); 8790 return S; 8791 } 8792 8793 NamedDecl* 8794 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8795 TypeSourceInfo *TInfo, LookupResult &Previous, 8796 MultiTemplateParamsArg TemplateParamListsRef, 8797 bool &AddToScope) { 8798 QualType R = TInfo->getType(); 8799 8800 assert(R->isFunctionType()); 8801 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 8802 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 8803 8804 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8805 for (TemplateParameterList *TPL : TemplateParamListsRef) 8806 TemplateParamLists.push_back(TPL); 8807 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8808 if (!TemplateParamLists.empty() && 8809 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8810 TemplateParamLists.back() = Invented; 8811 else 8812 TemplateParamLists.push_back(Invented); 8813 } 8814 8815 // TODO: consider using NameInfo for diagnostic. 8816 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8817 DeclarationName Name = NameInfo.getName(); 8818 StorageClass SC = getFunctionStorageClass(*this, D); 8819 8820 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8821 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8822 diag::err_invalid_thread) 8823 << DeclSpec::getSpecifierName(TSCS); 8824 8825 if (D.isFirstDeclarationOfMember()) 8826 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8827 D.getIdentifierLoc()); 8828 8829 bool isFriend = false; 8830 FunctionTemplateDecl *FunctionTemplate = nullptr; 8831 bool isMemberSpecialization = false; 8832 bool isFunctionTemplateSpecialization = false; 8833 8834 bool isDependentClassScopeExplicitSpecialization = false; 8835 bool HasExplicitTemplateArgs = false; 8836 TemplateArgumentListInfo TemplateArgs; 8837 8838 bool isVirtualOkay = false; 8839 8840 DeclContext *OriginalDC = DC; 8841 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8842 8843 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8844 isVirtualOkay); 8845 if (!NewFD) return nullptr; 8846 8847 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8848 NewFD->setTopLevelDeclInObjCContainer(); 8849 8850 // Set the lexical context. If this is a function-scope declaration, or has a 8851 // C++ scope specifier, or is the object of a friend declaration, the lexical 8852 // context will be different from the semantic context. 8853 NewFD->setLexicalDeclContext(CurContext); 8854 8855 if (IsLocalExternDecl) 8856 NewFD->setLocalExternDecl(); 8857 8858 if (getLangOpts().CPlusPlus) { 8859 bool isInline = D.getDeclSpec().isInlineSpecified(); 8860 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8861 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8862 isFriend = D.getDeclSpec().isFriendSpecified(); 8863 if (isFriend && !isInline && D.isFunctionDefinition()) { 8864 // C++ [class.friend]p5 8865 // A function can be defined in a friend declaration of a 8866 // class . . . . Such a function is implicitly inline. 8867 NewFD->setImplicitlyInline(); 8868 } 8869 8870 // If this is a method defined in an __interface, and is not a constructor 8871 // or an overloaded operator, then set the pure flag (isVirtual will already 8872 // return true). 8873 if (const CXXRecordDecl *Parent = 8874 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8875 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8876 NewFD->setPure(true); 8877 8878 // C++ [class.union]p2 8879 // A union can have member functions, but not virtual functions. 8880 if (isVirtual && Parent->isUnion()) 8881 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8882 } 8883 8884 SetNestedNameSpecifier(*this, NewFD, D); 8885 isMemberSpecialization = false; 8886 isFunctionTemplateSpecialization = false; 8887 if (D.isInvalidType()) 8888 NewFD->setInvalidDecl(); 8889 8890 // Match up the template parameter lists with the scope specifier, then 8891 // determine whether we have a template or a template specialization. 8892 bool Invalid = false; 8893 TemplateParameterList *TemplateParams = 8894 MatchTemplateParametersToScopeSpecifier( 8895 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8896 D.getCXXScopeSpec(), 8897 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8898 ? D.getName().TemplateId 8899 : nullptr, 8900 TemplateParamLists, isFriend, isMemberSpecialization, 8901 Invalid); 8902 if (TemplateParams) { 8903 if (TemplateParams->size() > 0) { 8904 // This is a function template 8905 8906 // Check that we can declare a template here. 8907 if (CheckTemplateDeclScope(S, TemplateParams)) 8908 NewFD->setInvalidDecl(); 8909 8910 // A destructor cannot be a template. 8911 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8912 Diag(NewFD->getLocation(), diag::err_destructor_template); 8913 NewFD->setInvalidDecl(); 8914 } 8915 8916 // If we're adding a template to a dependent context, we may need to 8917 // rebuilding some of the types used within the template parameter list, 8918 // now that we know what the current instantiation is. 8919 if (DC->isDependentContext()) { 8920 ContextRAII SavedContext(*this, DC); 8921 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8922 Invalid = true; 8923 } 8924 8925 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8926 NewFD->getLocation(), 8927 Name, TemplateParams, 8928 NewFD); 8929 FunctionTemplate->setLexicalDeclContext(CurContext); 8930 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8931 8932 // For source fidelity, store the other template param lists. 8933 if (TemplateParamLists.size() > 1) { 8934 NewFD->setTemplateParameterListsInfo(Context, 8935 ArrayRef<TemplateParameterList *>(TemplateParamLists) 8936 .drop_back(1)); 8937 } 8938 } else { 8939 // This is a function template specialization. 8940 isFunctionTemplateSpecialization = true; 8941 // For source fidelity, store all the template param lists. 8942 if (TemplateParamLists.size() > 0) 8943 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8944 8945 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8946 if (isFriend) { 8947 // We want to remove the "template<>", found here. 8948 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8949 8950 // If we remove the template<> and the name is not a 8951 // template-id, we're actually silently creating a problem: 8952 // the friend declaration will refer to an untemplated decl, 8953 // and clearly the user wants a template specialization. So 8954 // we need to insert '<>' after the name. 8955 SourceLocation InsertLoc; 8956 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8957 InsertLoc = D.getName().getSourceRange().getEnd(); 8958 InsertLoc = getLocForEndOfToken(InsertLoc); 8959 } 8960 8961 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8962 << Name << RemoveRange 8963 << FixItHint::CreateRemoval(RemoveRange) 8964 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8965 } 8966 } 8967 } else { 8968 // All template param lists were matched against the scope specifier: 8969 // this is NOT (an explicit specialization of) a template. 8970 if (TemplateParamLists.size() > 0) 8971 // For source fidelity, store all the template param lists. 8972 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8973 } 8974 8975 if (Invalid) { 8976 NewFD->setInvalidDecl(); 8977 if (FunctionTemplate) 8978 FunctionTemplate->setInvalidDecl(); 8979 } 8980 8981 // C++ [dcl.fct.spec]p5: 8982 // The virtual specifier shall only be used in declarations of 8983 // nonstatic class member functions that appear within a 8984 // member-specification of a class declaration; see 10.3. 8985 // 8986 if (isVirtual && !NewFD->isInvalidDecl()) { 8987 if (!isVirtualOkay) { 8988 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8989 diag::err_virtual_non_function); 8990 } else if (!CurContext->isRecord()) { 8991 // 'virtual' was specified outside of the class. 8992 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8993 diag::err_virtual_out_of_class) 8994 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8995 } else if (NewFD->getDescribedFunctionTemplate()) { 8996 // C++ [temp.mem]p3: 8997 // A member function template shall not be virtual. 8998 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8999 diag::err_virtual_member_function_template) 9000 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9001 } else { 9002 // Okay: Add virtual to the method. 9003 NewFD->setVirtualAsWritten(true); 9004 } 9005 9006 if (getLangOpts().CPlusPlus14 && 9007 NewFD->getReturnType()->isUndeducedType()) 9008 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9009 } 9010 9011 if (getLangOpts().CPlusPlus14 && 9012 (NewFD->isDependentContext() || 9013 (isFriend && CurContext->isDependentContext())) && 9014 NewFD->getReturnType()->isUndeducedType()) { 9015 // If the function template is referenced directly (for instance, as a 9016 // member of the current instantiation), pretend it has a dependent type. 9017 // This is not really justified by the standard, but is the only sane 9018 // thing to do. 9019 // FIXME: For a friend function, we have not marked the function as being 9020 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9021 const FunctionProtoType *FPT = 9022 NewFD->getType()->castAs<FunctionProtoType>(); 9023 QualType Result = 9024 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9025 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9026 FPT->getExtProtoInfo())); 9027 } 9028 9029 // C++ [dcl.fct.spec]p3: 9030 // The inline specifier shall not appear on a block scope function 9031 // declaration. 9032 if (isInline && !NewFD->isInvalidDecl()) { 9033 if (CurContext->isFunctionOrMethod()) { 9034 // 'inline' is not allowed on block scope function declaration. 9035 Diag(D.getDeclSpec().getInlineSpecLoc(), 9036 diag::err_inline_declaration_block_scope) << Name 9037 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9038 } 9039 } 9040 9041 // C++ [dcl.fct.spec]p6: 9042 // The explicit specifier shall be used only in the declaration of a 9043 // constructor or conversion function within its class definition; 9044 // see 12.3.1 and 12.3.2. 9045 if (hasExplicit && !NewFD->isInvalidDecl() && 9046 !isa<CXXDeductionGuideDecl>(NewFD)) { 9047 if (!CurContext->isRecord()) { 9048 // 'explicit' was specified outside of the class. 9049 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9050 diag::err_explicit_out_of_class) 9051 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9052 } else if (!isa<CXXConstructorDecl>(NewFD) && 9053 !isa<CXXConversionDecl>(NewFD)) { 9054 // 'explicit' was specified on a function that wasn't a constructor 9055 // or conversion function. 9056 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9057 diag::err_explicit_non_ctor_or_conv_function) 9058 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9059 } 9060 } 9061 9062 if (ConstexprSpecKind ConstexprKind = 9063 D.getDeclSpec().getConstexprSpecifier()) { 9064 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9065 // are implicitly inline. 9066 NewFD->setImplicitlyInline(); 9067 9068 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9069 // be either constructors or to return a literal type. Therefore, 9070 // destructors cannot be declared constexpr. 9071 if (isa<CXXDestructorDecl>(NewFD) && 9072 (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) { 9073 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9074 << ConstexprKind; 9075 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr); 9076 } 9077 // C++20 [dcl.constexpr]p2: An allocation function, or a 9078 // deallocation function shall not be declared with the consteval 9079 // specifier. 9080 if (ConstexprKind == CSK_consteval && 9081 (NewFD->getOverloadedOperator() == OO_New || 9082 NewFD->getOverloadedOperator() == OO_Array_New || 9083 NewFD->getOverloadedOperator() == OO_Delete || 9084 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9085 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9086 diag::err_invalid_consteval_decl_kind) 9087 << NewFD; 9088 NewFD->setConstexprKind(CSK_constexpr); 9089 } 9090 } 9091 9092 // If __module_private__ was specified, mark the function accordingly. 9093 if (D.getDeclSpec().isModulePrivateSpecified()) { 9094 if (isFunctionTemplateSpecialization) { 9095 SourceLocation ModulePrivateLoc 9096 = D.getDeclSpec().getModulePrivateSpecLoc(); 9097 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9098 << 0 9099 << FixItHint::CreateRemoval(ModulePrivateLoc); 9100 } else { 9101 NewFD->setModulePrivate(); 9102 if (FunctionTemplate) 9103 FunctionTemplate->setModulePrivate(); 9104 } 9105 } 9106 9107 if (isFriend) { 9108 if (FunctionTemplate) { 9109 FunctionTemplate->setObjectOfFriendDecl(); 9110 FunctionTemplate->setAccess(AS_public); 9111 } 9112 NewFD->setObjectOfFriendDecl(); 9113 NewFD->setAccess(AS_public); 9114 } 9115 9116 // If a function is defined as defaulted or deleted, mark it as such now. 9117 // We'll do the relevant checks on defaulted / deleted functions later. 9118 switch (D.getFunctionDefinitionKind()) { 9119 case FDK_Declaration: 9120 case FDK_Definition: 9121 break; 9122 9123 case FDK_Defaulted: 9124 NewFD->setDefaulted(); 9125 break; 9126 9127 case FDK_Deleted: 9128 NewFD->setDeletedAsWritten(); 9129 break; 9130 } 9131 9132 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9133 D.isFunctionDefinition()) { 9134 // C++ [class.mfct]p2: 9135 // A member function may be defined (8.4) in its class definition, in 9136 // which case it is an inline member function (7.1.2) 9137 NewFD->setImplicitlyInline(); 9138 } 9139 9140 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9141 !CurContext->isRecord()) { 9142 // C++ [class.static]p1: 9143 // A data or function member of a class may be declared static 9144 // in a class definition, in which case it is a static member of 9145 // the class. 9146 9147 // Complain about the 'static' specifier if it's on an out-of-line 9148 // member function definition. 9149 9150 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9151 // member function template declaration and class member template 9152 // declaration (MSVC versions before 2015), warn about this. 9153 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9154 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9155 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9156 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9157 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9158 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9159 } 9160 9161 // C++11 [except.spec]p15: 9162 // A deallocation function with no exception-specification is treated 9163 // as if it were specified with noexcept(true). 9164 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9165 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9166 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9167 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9168 NewFD->setType(Context.getFunctionType( 9169 FPT->getReturnType(), FPT->getParamTypes(), 9170 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9171 } 9172 9173 // Filter out previous declarations that don't match the scope. 9174 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9175 D.getCXXScopeSpec().isNotEmpty() || 9176 isMemberSpecialization || 9177 isFunctionTemplateSpecialization); 9178 9179 // Handle GNU asm-label extension (encoded as an attribute). 9180 if (Expr *E = (Expr*) D.getAsmLabel()) { 9181 // The parser guarantees this is a string. 9182 StringLiteral *SE = cast<StringLiteral>(E); 9183 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9184 /*IsLiteralLabel=*/true, 9185 SE->getStrTokenLoc(0))); 9186 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9187 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9188 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9189 if (I != ExtnameUndeclaredIdentifiers.end()) { 9190 if (isDeclExternC(NewFD)) { 9191 NewFD->addAttr(I->second); 9192 ExtnameUndeclaredIdentifiers.erase(I); 9193 } else 9194 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9195 << /*Variable*/0 << NewFD; 9196 } 9197 } 9198 9199 // Copy the parameter declarations from the declarator D to the function 9200 // declaration NewFD, if they are available. First scavenge them into Params. 9201 SmallVector<ParmVarDecl*, 16> Params; 9202 unsigned FTIIdx; 9203 if (D.isFunctionDeclarator(FTIIdx)) { 9204 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9205 9206 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9207 // function that takes no arguments, not a function that takes a 9208 // single void argument. 9209 // We let through "const void" here because Sema::GetTypeForDeclarator 9210 // already checks for that case. 9211 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9212 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9213 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9214 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9215 Param->setDeclContext(NewFD); 9216 Params.push_back(Param); 9217 9218 if (Param->isInvalidDecl()) 9219 NewFD->setInvalidDecl(); 9220 } 9221 } 9222 9223 if (!getLangOpts().CPlusPlus) { 9224 // In C, find all the tag declarations from the prototype and move them 9225 // into the function DeclContext. Remove them from the surrounding tag 9226 // injection context of the function, which is typically but not always 9227 // the TU. 9228 DeclContext *PrototypeTagContext = 9229 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9230 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9231 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9232 9233 // We don't want to reparent enumerators. Look at their parent enum 9234 // instead. 9235 if (!TD) { 9236 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9237 TD = cast<EnumDecl>(ECD->getDeclContext()); 9238 } 9239 if (!TD) 9240 continue; 9241 DeclContext *TagDC = TD->getLexicalDeclContext(); 9242 if (!TagDC->containsDecl(TD)) 9243 continue; 9244 TagDC->removeDecl(TD); 9245 TD->setDeclContext(NewFD); 9246 NewFD->addDecl(TD); 9247 9248 // Preserve the lexical DeclContext if it is not the surrounding tag 9249 // injection context of the FD. In this example, the semantic context of 9250 // E will be f and the lexical context will be S, while both the 9251 // semantic and lexical contexts of S will be f: 9252 // void f(struct S { enum E { a } f; } s); 9253 if (TagDC != PrototypeTagContext) 9254 TD->setLexicalDeclContext(TagDC); 9255 } 9256 } 9257 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9258 // When we're declaring a function with a typedef, typeof, etc as in the 9259 // following example, we'll need to synthesize (unnamed) 9260 // parameters for use in the declaration. 9261 // 9262 // @code 9263 // typedef void fn(int); 9264 // fn f; 9265 // @endcode 9266 9267 // Synthesize a parameter for each argument type. 9268 for (const auto &AI : FT->param_types()) { 9269 ParmVarDecl *Param = 9270 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9271 Param->setScopeInfo(0, Params.size()); 9272 Params.push_back(Param); 9273 } 9274 } else { 9275 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9276 "Should not need args for typedef of non-prototype fn"); 9277 } 9278 9279 // Finally, we know we have the right number of parameters, install them. 9280 NewFD->setParams(Params); 9281 9282 if (D.getDeclSpec().isNoreturnSpecified()) 9283 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9284 D.getDeclSpec().getNoreturnSpecLoc(), 9285 AttributeCommonInfo::AS_Keyword)); 9286 9287 // Functions returning a variably modified type violate C99 6.7.5.2p2 9288 // because all functions have linkage. 9289 if (!NewFD->isInvalidDecl() && 9290 NewFD->getReturnType()->isVariablyModifiedType()) { 9291 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9292 NewFD->setInvalidDecl(); 9293 } 9294 9295 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9296 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9297 !NewFD->hasAttr<SectionAttr>()) 9298 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9299 Context, PragmaClangTextSection.SectionName, 9300 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9301 9302 // Apply an implicit SectionAttr if #pragma code_seg is active. 9303 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9304 !NewFD->hasAttr<SectionAttr>()) { 9305 NewFD->addAttr(SectionAttr::CreateImplicit( 9306 Context, CodeSegStack.CurrentValue->getString(), 9307 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9308 SectionAttr::Declspec_allocate)); 9309 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9310 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9311 ASTContext::PSF_Read, 9312 NewFD)) 9313 NewFD->dropAttr<SectionAttr>(); 9314 } 9315 9316 // Apply an implicit CodeSegAttr from class declspec or 9317 // apply an implicit SectionAttr from #pragma code_seg if active. 9318 if (!NewFD->hasAttr<CodeSegAttr>()) { 9319 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9320 D.isFunctionDefinition())) { 9321 NewFD->addAttr(SAttr); 9322 } 9323 } 9324 9325 // Handle attributes. 9326 ProcessDeclAttributes(S, NewFD, D); 9327 9328 if (getLangOpts().OpenCL) { 9329 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9330 // type declaration will generate a compilation error. 9331 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9332 if (AddressSpace != LangAS::Default) { 9333 Diag(NewFD->getLocation(), 9334 diag::err_opencl_return_value_with_address_space); 9335 NewFD->setInvalidDecl(); 9336 } 9337 } 9338 9339 if (!getLangOpts().CPlusPlus) { 9340 // Perform semantic checking on the function declaration. 9341 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9342 CheckMain(NewFD, D.getDeclSpec()); 9343 9344 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9345 CheckMSVCRTEntryPoint(NewFD); 9346 9347 if (!NewFD->isInvalidDecl()) 9348 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9349 isMemberSpecialization)); 9350 else if (!Previous.empty()) 9351 // Recover gracefully from an invalid redeclaration. 9352 D.setRedeclaration(true); 9353 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9354 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9355 "previous declaration set still overloaded"); 9356 9357 // Diagnose no-prototype function declarations with calling conventions that 9358 // don't support variadic calls. Only do this in C and do it after merging 9359 // possibly prototyped redeclarations. 9360 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9361 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9362 CallingConv CC = FT->getExtInfo().getCC(); 9363 if (!supportsVariadicCall(CC)) { 9364 // Windows system headers sometimes accidentally use stdcall without 9365 // (void) parameters, so we relax this to a warning. 9366 int DiagID = 9367 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9368 Diag(NewFD->getLocation(), DiagID) 9369 << FunctionType::getNameForCallConv(CC); 9370 } 9371 } 9372 9373 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9374 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9375 checkNonTrivialCUnion(NewFD->getReturnType(), 9376 NewFD->getReturnTypeSourceRange().getBegin(), 9377 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9378 } else { 9379 // C++11 [replacement.functions]p3: 9380 // The program's definitions shall not be specified as inline. 9381 // 9382 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9383 // 9384 // Suppress the diagnostic if the function is __attribute__((used)), since 9385 // that forces an external definition to be emitted. 9386 if (D.getDeclSpec().isInlineSpecified() && 9387 NewFD->isReplaceableGlobalAllocationFunction() && 9388 !NewFD->hasAttr<UsedAttr>()) 9389 Diag(D.getDeclSpec().getInlineSpecLoc(), 9390 diag::ext_operator_new_delete_declared_inline) 9391 << NewFD->getDeclName(); 9392 9393 // If the declarator is a template-id, translate the parser's template 9394 // argument list into our AST format. 9395 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9396 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9397 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9398 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9399 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9400 TemplateId->NumArgs); 9401 translateTemplateArguments(TemplateArgsPtr, 9402 TemplateArgs); 9403 9404 HasExplicitTemplateArgs = true; 9405 9406 if (NewFD->isInvalidDecl()) { 9407 HasExplicitTemplateArgs = false; 9408 } else if (FunctionTemplate) { 9409 // Function template with explicit template arguments. 9410 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9411 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9412 9413 HasExplicitTemplateArgs = false; 9414 } else { 9415 assert((isFunctionTemplateSpecialization || 9416 D.getDeclSpec().isFriendSpecified()) && 9417 "should have a 'template<>' for this decl"); 9418 // "friend void foo<>(int);" is an implicit specialization decl. 9419 isFunctionTemplateSpecialization = true; 9420 } 9421 } else if (isFriend && isFunctionTemplateSpecialization) { 9422 // This combination is only possible in a recovery case; the user 9423 // wrote something like: 9424 // template <> friend void foo(int); 9425 // which we're recovering from as if the user had written: 9426 // friend void foo<>(int); 9427 // Go ahead and fake up a template id. 9428 HasExplicitTemplateArgs = true; 9429 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9430 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9431 } 9432 9433 // We do not add HD attributes to specializations here because 9434 // they may have different constexpr-ness compared to their 9435 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9436 // may end up with different effective targets. Instead, a 9437 // specialization inherits its target attributes from its template 9438 // in the CheckFunctionTemplateSpecialization() call below. 9439 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9440 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9441 9442 // If it's a friend (and only if it's a friend), it's possible 9443 // that either the specialized function type or the specialized 9444 // template is dependent, and therefore matching will fail. In 9445 // this case, don't check the specialization yet. 9446 bool InstantiationDependent = false; 9447 if (isFunctionTemplateSpecialization && isFriend && 9448 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9449 TemplateSpecializationType::anyDependentTemplateArguments( 9450 TemplateArgs, 9451 InstantiationDependent))) { 9452 assert(HasExplicitTemplateArgs && 9453 "friend function specialization without template args"); 9454 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9455 Previous)) 9456 NewFD->setInvalidDecl(); 9457 } else if (isFunctionTemplateSpecialization) { 9458 if (CurContext->isDependentContext() && CurContext->isRecord() 9459 && !isFriend) { 9460 isDependentClassScopeExplicitSpecialization = true; 9461 } else if (!NewFD->isInvalidDecl() && 9462 CheckFunctionTemplateSpecialization( 9463 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9464 Previous)) 9465 NewFD->setInvalidDecl(); 9466 9467 // C++ [dcl.stc]p1: 9468 // A storage-class-specifier shall not be specified in an explicit 9469 // specialization (14.7.3) 9470 FunctionTemplateSpecializationInfo *Info = 9471 NewFD->getTemplateSpecializationInfo(); 9472 if (Info && SC != SC_None) { 9473 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9474 Diag(NewFD->getLocation(), 9475 diag::err_explicit_specialization_inconsistent_storage_class) 9476 << SC 9477 << FixItHint::CreateRemoval( 9478 D.getDeclSpec().getStorageClassSpecLoc()); 9479 9480 else 9481 Diag(NewFD->getLocation(), 9482 diag::ext_explicit_specialization_storage_class) 9483 << FixItHint::CreateRemoval( 9484 D.getDeclSpec().getStorageClassSpecLoc()); 9485 } 9486 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9487 if (CheckMemberSpecialization(NewFD, Previous)) 9488 NewFD->setInvalidDecl(); 9489 } 9490 9491 // Perform semantic checking on the function declaration. 9492 if (!isDependentClassScopeExplicitSpecialization) { 9493 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9494 CheckMain(NewFD, D.getDeclSpec()); 9495 9496 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9497 CheckMSVCRTEntryPoint(NewFD); 9498 9499 if (!NewFD->isInvalidDecl()) 9500 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9501 isMemberSpecialization)); 9502 else if (!Previous.empty()) 9503 // Recover gracefully from an invalid redeclaration. 9504 D.setRedeclaration(true); 9505 } 9506 9507 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9508 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9509 "previous declaration set still overloaded"); 9510 9511 NamedDecl *PrincipalDecl = (FunctionTemplate 9512 ? cast<NamedDecl>(FunctionTemplate) 9513 : NewFD); 9514 9515 if (isFriend && NewFD->getPreviousDecl()) { 9516 AccessSpecifier Access = AS_public; 9517 if (!NewFD->isInvalidDecl()) 9518 Access = NewFD->getPreviousDecl()->getAccess(); 9519 9520 NewFD->setAccess(Access); 9521 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9522 } 9523 9524 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9525 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9526 PrincipalDecl->setNonMemberOperator(); 9527 9528 // If we have a function template, check the template parameter 9529 // list. This will check and merge default template arguments. 9530 if (FunctionTemplate) { 9531 FunctionTemplateDecl *PrevTemplate = 9532 FunctionTemplate->getPreviousDecl(); 9533 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9534 PrevTemplate ? PrevTemplate->getTemplateParameters() 9535 : nullptr, 9536 D.getDeclSpec().isFriendSpecified() 9537 ? (D.isFunctionDefinition() 9538 ? TPC_FriendFunctionTemplateDefinition 9539 : TPC_FriendFunctionTemplate) 9540 : (D.getCXXScopeSpec().isSet() && 9541 DC && DC->isRecord() && 9542 DC->isDependentContext()) 9543 ? TPC_ClassTemplateMember 9544 : TPC_FunctionTemplate); 9545 } 9546 9547 if (NewFD->isInvalidDecl()) { 9548 // Ignore all the rest of this. 9549 } else if (!D.isRedeclaration()) { 9550 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9551 AddToScope }; 9552 // Fake up an access specifier if it's supposed to be a class member. 9553 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9554 NewFD->setAccess(AS_public); 9555 9556 // Qualified decls generally require a previous declaration. 9557 if (D.getCXXScopeSpec().isSet()) { 9558 // ...with the major exception of templated-scope or 9559 // dependent-scope friend declarations. 9560 9561 // TODO: we currently also suppress this check in dependent 9562 // contexts because (1) the parameter depth will be off when 9563 // matching friend templates and (2) we might actually be 9564 // selecting a friend based on a dependent factor. But there 9565 // are situations where these conditions don't apply and we 9566 // can actually do this check immediately. 9567 // 9568 // Unless the scope is dependent, it's always an error if qualified 9569 // redeclaration lookup found nothing at all. Diagnose that now; 9570 // nothing will diagnose that error later. 9571 if (isFriend && 9572 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9573 (!Previous.empty() && CurContext->isDependentContext()))) { 9574 // ignore these 9575 } else { 9576 // The user tried to provide an out-of-line definition for a 9577 // function that is a member of a class or namespace, but there 9578 // was no such member function declared (C++ [class.mfct]p2, 9579 // C++ [namespace.memdef]p2). For example: 9580 // 9581 // class X { 9582 // void f() const; 9583 // }; 9584 // 9585 // void X::f() { } // ill-formed 9586 // 9587 // Complain about this problem, and attempt to suggest close 9588 // matches (e.g., those that differ only in cv-qualifiers and 9589 // whether the parameter types are references). 9590 9591 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9592 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9593 AddToScope = ExtraArgs.AddToScope; 9594 return Result; 9595 } 9596 } 9597 9598 // Unqualified local friend declarations are required to resolve 9599 // to something. 9600 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9601 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9602 *this, Previous, NewFD, ExtraArgs, true, S)) { 9603 AddToScope = ExtraArgs.AddToScope; 9604 return Result; 9605 } 9606 } 9607 } else if (!D.isFunctionDefinition() && 9608 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9609 !isFriend && !isFunctionTemplateSpecialization && 9610 !isMemberSpecialization) { 9611 // An out-of-line member function declaration must also be a 9612 // definition (C++ [class.mfct]p2). 9613 // Note that this is not the case for explicit specializations of 9614 // function templates or member functions of class templates, per 9615 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9616 // extension for compatibility with old SWIG code which likes to 9617 // generate them. 9618 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9619 << D.getCXXScopeSpec().getRange(); 9620 } 9621 } 9622 9623 ProcessPragmaWeak(S, NewFD); 9624 checkAttributesAfterMerging(*this, *NewFD); 9625 9626 AddKnownFunctionAttributes(NewFD); 9627 9628 if (NewFD->hasAttr<OverloadableAttr>() && 9629 !NewFD->getType()->getAs<FunctionProtoType>()) { 9630 Diag(NewFD->getLocation(), 9631 diag::err_attribute_overloadable_no_prototype) 9632 << NewFD; 9633 9634 // Turn this into a variadic function with no parameters. 9635 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9636 FunctionProtoType::ExtProtoInfo EPI( 9637 Context.getDefaultCallingConvention(true, false)); 9638 EPI.Variadic = true; 9639 EPI.ExtInfo = FT->getExtInfo(); 9640 9641 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9642 NewFD->setType(R); 9643 } 9644 9645 // If there's a #pragma GCC visibility in scope, and this isn't a class 9646 // member, set the visibility of this function. 9647 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9648 AddPushedVisibilityAttribute(NewFD); 9649 9650 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9651 // marking the function. 9652 AddCFAuditedAttribute(NewFD); 9653 9654 // If this is a function definition, check if we have to apply optnone due to 9655 // a pragma. 9656 if(D.isFunctionDefinition()) 9657 AddRangeBasedOptnone(NewFD); 9658 9659 // If this is the first declaration of an extern C variable, update 9660 // the map of such variables. 9661 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9662 isIncompleteDeclExternC(*this, NewFD)) 9663 RegisterLocallyScopedExternCDecl(NewFD, S); 9664 9665 // Set this FunctionDecl's range up to the right paren. 9666 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9667 9668 if (D.isRedeclaration() && !Previous.empty()) { 9669 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9670 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9671 isMemberSpecialization || 9672 isFunctionTemplateSpecialization, 9673 D.isFunctionDefinition()); 9674 } 9675 9676 if (getLangOpts().CUDA) { 9677 IdentifierInfo *II = NewFD->getIdentifier(); 9678 if (II && II->isStr(getCudaConfigureFuncName()) && 9679 !NewFD->isInvalidDecl() && 9680 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9681 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9682 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9683 << getCudaConfigureFuncName(); 9684 Context.setcudaConfigureCallDecl(NewFD); 9685 } 9686 9687 // Variadic functions, other than a *declaration* of printf, are not allowed 9688 // in device-side CUDA code, unless someone passed 9689 // -fcuda-allow-variadic-functions. 9690 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9691 (NewFD->hasAttr<CUDADeviceAttr>() || 9692 NewFD->hasAttr<CUDAGlobalAttr>()) && 9693 !(II && II->isStr("printf") && NewFD->isExternC() && 9694 !D.isFunctionDefinition())) { 9695 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9696 } 9697 } 9698 9699 MarkUnusedFileScopedDecl(NewFD); 9700 9701 9702 9703 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9704 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9705 if ((getLangOpts().OpenCLVersion >= 120) 9706 && (SC == SC_Static)) { 9707 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9708 D.setInvalidType(); 9709 } 9710 9711 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9712 if (!NewFD->getReturnType()->isVoidType()) { 9713 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9714 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9715 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9716 : FixItHint()); 9717 D.setInvalidType(); 9718 } 9719 9720 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9721 for (auto Param : NewFD->parameters()) 9722 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9723 9724 if (getLangOpts().OpenCLCPlusPlus) { 9725 if (DC->isRecord()) { 9726 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9727 D.setInvalidType(); 9728 } 9729 if (FunctionTemplate) { 9730 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9731 D.setInvalidType(); 9732 } 9733 } 9734 } 9735 9736 if (getLangOpts().CPlusPlus) { 9737 if (FunctionTemplate) { 9738 if (NewFD->isInvalidDecl()) 9739 FunctionTemplate->setInvalidDecl(); 9740 return FunctionTemplate; 9741 } 9742 9743 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9744 CompleteMemberSpecialization(NewFD, Previous); 9745 } 9746 9747 for (const ParmVarDecl *Param : NewFD->parameters()) { 9748 QualType PT = Param->getType(); 9749 9750 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9751 // types. 9752 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9753 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9754 QualType ElemTy = PipeTy->getElementType(); 9755 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9756 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9757 D.setInvalidType(); 9758 } 9759 } 9760 } 9761 } 9762 9763 // Here we have an function template explicit specialization at class scope. 9764 // The actual specialization will be postponed to template instatiation 9765 // time via the ClassScopeFunctionSpecializationDecl node. 9766 if (isDependentClassScopeExplicitSpecialization) { 9767 ClassScopeFunctionSpecializationDecl *NewSpec = 9768 ClassScopeFunctionSpecializationDecl::Create( 9769 Context, CurContext, NewFD->getLocation(), 9770 cast<CXXMethodDecl>(NewFD), 9771 HasExplicitTemplateArgs, TemplateArgs); 9772 CurContext->addDecl(NewSpec); 9773 AddToScope = false; 9774 } 9775 9776 // Diagnose availability attributes. Availability cannot be used on functions 9777 // that are run during load/unload. 9778 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9779 if (NewFD->hasAttr<ConstructorAttr>()) { 9780 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9781 << 1; 9782 NewFD->dropAttr<AvailabilityAttr>(); 9783 } 9784 if (NewFD->hasAttr<DestructorAttr>()) { 9785 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9786 << 2; 9787 NewFD->dropAttr<AvailabilityAttr>(); 9788 } 9789 } 9790 9791 // Diagnose no_builtin attribute on function declaration that are not a 9792 // definition. 9793 // FIXME: We should really be doing this in 9794 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9795 // the FunctionDecl and at this point of the code 9796 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9797 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9798 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9799 switch (D.getFunctionDefinitionKind()) { 9800 case FDK_Defaulted: 9801 case FDK_Deleted: 9802 Diag(NBA->getLocation(), 9803 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9804 << NBA->getSpelling(); 9805 break; 9806 case FDK_Declaration: 9807 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9808 << NBA->getSpelling(); 9809 break; 9810 case FDK_Definition: 9811 break; 9812 } 9813 9814 return NewFD; 9815 } 9816 9817 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9818 /// when __declspec(code_seg) "is applied to a class, all member functions of 9819 /// the class and nested classes -- this includes compiler-generated special 9820 /// member functions -- are put in the specified segment." 9821 /// The actual behavior is a little more complicated. The Microsoft compiler 9822 /// won't check outer classes if there is an active value from #pragma code_seg. 9823 /// The CodeSeg is always applied from the direct parent but only from outer 9824 /// classes when the #pragma code_seg stack is empty. See: 9825 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9826 /// available since MS has removed the page. 9827 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9828 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9829 if (!Method) 9830 return nullptr; 9831 const CXXRecordDecl *Parent = Method->getParent(); 9832 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9833 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9834 NewAttr->setImplicit(true); 9835 return NewAttr; 9836 } 9837 9838 // The Microsoft compiler won't check outer classes for the CodeSeg 9839 // when the #pragma code_seg stack is active. 9840 if (S.CodeSegStack.CurrentValue) 9841 return nullptr; 9842 9843 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9844 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9845 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9846 NewAttr->setImplicit(true); 9847 return NewAttr; 9848 } 9849 } 9850 return nullptr; 9851 } 9852 9853 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9854 /// containing class. Otherwise it will return implicit SectionAttr if the 9855 /// function is a definition and there is an active value on CodeSegStack 9856 /// (from the current #pragma code-seg value). 9857 /// 9858 /// \param FD Function being declared. 9859 /// \param IsDefinition Whether it is a definition or just a declarartion. 9860 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9861 /// nullptr if no attribute should be added. 9862 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9863 bool IsDefinition) { 9864 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9865 return A; 9866 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9867 CodeSegStack.CurrentValue) 9868 return SectionAttr::CreateImplicit( 9869 getASTContext(), CodeSegStack.CurrentValue->getString(), 9870 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9871 SectionAttr::Declspec_allocate); 9872 return nullptr; 9873 } 9874 9875 /// Determines if we can perform a correct type check for \p D as a 9876 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9877 /// best-effort check. 9878 /// 9879 /// \param NewD The new declaration. 9880 /// \param OldD The old declaration. 9881 /// \param NewT The portion of the type of the new declaration to check. 9882 /// \param OldT The portion of the type of the old declaration to check. 9883 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9884 QualType NewT, QualType OldT) { 9885 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9886 return true; 9887 9888 // For dependently-typed local extern declarations and friends, we can't 9889 // perform a correct type check in general until instantiation: 9890 // 9891 // int f(); 9892 // template<typename T> void g() { T f(); } 9893 // 9894 // (valid if g() is only instantiated with T = int). 9895 if (NewT->isDependentType() && 9896 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9897 return false; 9898 9899 // Similarly, if the previous declaration was a dependent local extern 9900 // declaration, we don't really know its type yet. 9901 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9902 return false; 9903 9904 return true; 9905 } 9906 9907 /// Checks if the new declaration declared in dependent context must be 9908 /// put in the same redeclaration chain as the specified declaration. 9909 /// 9910 /// \param D Declaration that is checked. 9911 /// \param PrevDecl Previous declaration found with proper lookup method for the 9912 /// same declaration name. 9913 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9914 /// belongs to. 9915 /// 9916 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9917 if (!D->getLexicalDeclContext()->isDependentContext()) 9918 return true; 9919 9920 // Don't chain dependent friend function definitions until instantiation, to 9921 // permit cases like 9922 // 9923 // void func(); 9924 // template<typename T> class C1 { friend void func() {} }; 9925 // template<typename T> class C2 { friend void func() {} }; 9926 // 9927 // ... which is valid if only one of C1 and C2 is ever instantiated. 9928 // 9929 // FIXME: This need only apply to function definitions. For now, we proxy 9930 // this by checking for a file-scope function. We do not want this to apply 9931 // to friend declarations nominating member functions, because that gets in 9932 // the way of access checks. 9933 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9934 return false; 9935 9936 auto *VD = dyn_cast<ValueDecl>(D); 9937 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 9938 return !VD || !PrevVD || 9939 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 9940 PrevVD->getType()); 9941 } 9942 9943 /// Check the target attribute of the function for MultiVersion 9944 /// validity. 9945 /// 9946 /// Returns true if there was an error, false otherwise. 9947 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9948 const auto *TA = FD->getAttr<TargetAttr>(); 9949 assert(TA && "MultiVersion Candidate requires a target attribute"); 9950 ParsedTargetAttr ParseInfo = TA->parse(); 9951 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9952 enum ErrType { Feature = 0, Architecture = 1 }; 9953 9954 if (!ParseInfo.Architecture.empty() && 9955 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9956 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9957 << Architecture << ParseInfo.Architecture; 9958 return true; 9959 } 9960 9961 for (const auto &Feat : ParseInfo.Features) { 9962 auto BareFeat = StringRef{Feat}.substr(1); 9963 if (Feat[0] == '-') { 9964 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9965 << Feature << ("no-" + BareFeat).str(); 9966 return true; 9967 } 9968 9969 if (!TargetInfo.validateCpuSupports(BareFeat) || 9970 !TargetInfo.isValidFeatureName(BareFeat)) { 9971 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9972 << Feature << BareFeat; 9973 return true; 9974 } 9975 } 9976 return false; 9977 } 9978 9979 // Provide a white-list of attributes that are allowed to be combined with 9980 // multiversion functions. 9981 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 9982 MultiVersionKind MVType) { 9983 switch (Kind) { 9984 default: 9985 return false; 9986 case attr::Used: 9987 return MVType == MultiVersionKind::Target; 9988 } 9989 } 9990 9991 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, 9992 MultiVersionKind MVType) { 9993 for (const Attr *A : FD->attrs()) { 9994 switch (A->getKind()) { 9995 case attr::CPUDispatch: 9996 case attr::CPUSpecific: 9997 if (MVType != MultiVersionKind::CPUDispatch && 9998 MVType != MultiVersionKind::CPUSpecific) 9999 return true; 10000 break; 10001 case attr::Target: 10002 if (MVType != MultiVersionKind::Target) 10003 return true; 10004 break; 10005 default: 10006 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10007 return true; 10008 break; 10009 } 10010 } 10011 return false; 10012 } 10013 10014 bool Sema::areMultiversionVariantFunctionsCompatible( 10015 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10016 const PartialDiagnostic &NoProtoDiagID, 10017 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10018 const PartialDiagnosticAt &NoSupportDiagIDAt, 10019 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10020 bool ConstexprSupported, bool CLinkageMayDiffer) { 10021 enum DoesntSupport { 10022 FuncTemplates = 0, 10023 VirtFuncs = 1, 10024 DeducedReturn = 2, 10025 Constructors = 3, 10026 Destructors = 4, 10027 DeletedFuncs = 5, 10028 DefaultedFuncs = 6, 10029 ConstexprFuncs = 7, 10030 ConstevalFuncs = 8, 10031 }; 10032 enum Different { 10033 CallingConv = 0, 10034 ReturnType = 1, 10035 ConstexprSpec = 2, 10036 InlineSpec = 3, 10037 StorageClass = 4, 10038 Linkage = 5, 10039 }; 10040 10041 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10042 !OldFD->getType()->getAs<FunctionProtoType>()) { 10043 Diag(OldFD->getLocation(), NoProtoDiagID); 10044 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10045 return true; 10046 } 10047 10048 if (NoProtoDiagID.getDiagID() != 0 && 10049 !NewFD->getType()->getAs<FunctionProtoType>()) 10050 return Diag(NewFD->getLocation(), NoProtoDiagID); 10051 10052 if (!TemplatesSupported && 10053 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10054 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10055 << FuncTemplates; 10056 10057 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10058 if (NewCXXFD->isVirtual()) 10059 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10060 << VirtFuncs; 10061 10062 if (isa<CXXConstructorDecl>(NewCXXFD)) 10063 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10064 << Constructors; 10065 10066 if (isa<CXXDestructorDecl>(NewCXXFD)) 10067 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10068 << Destructors; 10069 } 10070 10071 if (NewFD->isDeleted()) 10072 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10073 << DeletedFuncs; 10074 10075 if (NewFD->isDefaulted()) 10076 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10077 << DefaultedFuncs; 10078 10079 if (!ConstexprSupported && NewFD->isConstexpr()) 10080 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10081 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10082 10083 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10084 const auto *NewType = cast<FunctionType>(NewQType); 10085 QualType NewReturnType = NewType->getReturnType(); 10086 10087 if (NewReturnType->isUndeducedType()) 10088 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10089 << DeducedReturn; 10090 10091 // Ensure the return type is identical. 10092 if (OldFD) { 10093 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10094 const auto *OldType = cast<FunctionType>(OldQType); 10095 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10096 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10097 10098 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10099 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10100 10101 QualType OldReturnType = OldType->getReturnType(); 10102 10103 if (OldReturnType != NewReturnType) 10104 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10105 10106 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10107 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10108 10109 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10110 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10111 10112 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10113 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10114 10115 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10116 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10117 10118 if (CheckEquivalentExceptionSpec( 10119 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10120 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10121 return true; 10122 } 10123 return false; 10124 } 10125 10126 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10127 const FunctionDecl *NewFD, 10128 bool CausesMV, 10129 MultiVersionKind MVType) { 10130 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10131 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10132 if (OldFD) 10133 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10134 return true; 10135 } 10136 10137 bool IsCPUSpecificCPUDispatchMVType = 10138 MVType == MultiVersionKind::CPUDispatch || 10139 MVType == MultiVersionKind::CPUSpecific; 10140 10141 // For now, disallow all other attributes. These should be opt-in, but 10142 // an analysis of all of them is a future FIXME. 10143 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { 10144 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) 10145 << IsCPUSpecificCPUDispatchMVType; 10146 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10147 return true; 10148 } 10149 10150 if (HasNonMultiVersionAttributes(NewFD, MVType)) 10151 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) 10152 << IsCPUSpecificCPUDispatchMVType; 10153 10154 // Only allow transition to MultiVersion if it hasn't been used. 10155 if (OldFD && CausesMV && OldFD->isUsed(false)) 10156 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10157 10158 return S.areMultiversionVariantFunctionsCompatible( 10159 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10160 PartialDiagnosticAt(NewFD->getLocation(), 10161 S.PDiag(diag::note_multiversioning_caused_here)), 10162 PartialDiagnosticAt(NewFD->getLocation(), 10163 S.PDiag(diag::err_multiversion_doesnt_support) 10164 << IsCPUSpecificCPUDispatchMVType), 10165 PartialDiagnosticAt(NewFD->getLocation(), 10166 S.PDiag(diag::err_multiversion_diff)), 10167 /*TemplatesSupported=*/false, 10168 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10169 /*CLinkageMayDiffer=*/false); 10170 } 10171 10172 /// Check the validity of a multiversion function declaration that is the 10173 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10174 /// 10175 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10176 /// 10177 /// Returns true if there was an error, false otherwise. 10178 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10179 MultiVersionKind MVType, 10180 const TargetAttr *TA) { 10181 assert(MVType != MultiVersionKind::None && 10182 "Function lacks multiversion attribute"); 10183 10184 // Target only causes MV if it is default, otherwise this is a normal 10185 // function. 10186 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10187 return false; 10188 10189 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10190 FD->setInvalidDecl(); 10191 return true; 10192 } 10193 10194 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10195 FD->setInvalidDecl(); 10196 return true; 10197 } 10198 10199 FD->setIsMultiVersion(); 10200 return false; 10201 } 10202 10203 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10204 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10205 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10206 return true; 10207 } 10208 10209 return false; 10210 } 10211 10212 static bool CheckTargetCausesMultiVersioning( 10213 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10214 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10215 LookupResult &Previous) { 10216 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10217 ParsedTargetAttr NewParsed = NewTA->parse(); 10218 // Sort order doesn't matter, it just needs to be consistent. 10219 llvm::sort(NewParsed.Features); 10220 10221 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10222 // to change, this is a simple redeclaration. 10223 if (!NewTA->isDefaultVersion() && 10224 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10225 return false; 10226 10227 // Otherwise, this decl causes MultiVersioning. 10228 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10229 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10230 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10231 NewFD->setInvalidDecl(); 10232 return true; 10233 } 10234 10235 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10236 MultiVersionKind::Target)) { 10237 NewFD->setInvalidDecl(); 10238 return true; 10239 } 10240 10241 if (CheckMultiVersionValue(S, NewFD)) { 10242 NewFD->setInvalidDecl(); 10243 return true; 10244 } 10245 10246 // If this is 'default', permit the forward declaration. 10247 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10248 Redeclaration = true; 10249 OldDecl = OldFD; 10250 OldFD->setIsMultiVersion(); 10251 NewFD->setIsMultiVersion(); 10252 return false; 10253 } 10254 10255 if (CheckMultiVersionValue(S, OldFD)) { 10256 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10257 NewFD->setInvalidDecl(); 10258 return true; 10259 } 10260 10261 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10262 10263 if (OldParsed == NewParsed) { 10264 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10265 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10266 NewFD->setInvalidDecl(); 10267 return true; 10268 } 10269 10270 for (const auto *FD : OldFD->redecls()) { 10271 const auto *CurTA = FD->getAttr<TargetAttr>(); 10272 // We allow forward declarations before ANY multiversioning attributes, but 10273 // nothing after the fact. 10274 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10275 (!CurTA || CurTA->isInherited())) { 10276 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10277 << 0; 10278 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10279 NewFD->setInvalidDecl(); 10280 return true; 10281 } 10282 } 10283 10284 OldFD->setIsMultiVersion(); 10285 NewFD->setIsMultiVersion(); 10286 Redeclaration = false; 10287 MergeTypeWithPrevious = false; 10288 OldDecl = nullptr; 10289 Previous.clear(); 10290 return false; 10291 } 10292 10293 /// Check the validity of a new function declaration being added to an existing 10294 /// multiversioned declaration collection. 10295 static bool CheckMultiVersionAdditionalDecl( 10296 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10297 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10298 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10299 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10300 LookupResult &Previous) { 10301 10302 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10303 // Disallow mixing of multiversioning types. 10304 if ((OldMVType == MultiVersionKind::Target && 10305 NewMVType != MultiVersionKind::Target) || 10306 (NewMVType == MultiVersionKind::Target && 10307 OldMVType != MultiVersionKind::Target)) { 10308 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10309 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10310 NewFD->setInvalidDecl(); 10311 return true; 10312 } 10313 10314 ParsedTargetAttr NewParsed; 10315 if (NewTA) { 10316 NewParsed = NewTA->parse(); 10317 llvm::sort(NewParsed.Features); 10318 } 10319 10320 bool UseMemberUsingDeclRules = 10321 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10322 10323 // Next, check ALL non-overloads to see if this is a redeclaration of a 10324 // previous member of the MultiVersion set. 10325 for (NamedDecl *ND : Previous) { 10326 FunctionDecl *CurFD = ND->getAsFunction(); 10327 if (!CurFD) 10328 continue; 10329 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10330 continue; 10331 10332 if (NewMVType == MultiVersionKind::Target) { 10333 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10334 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10335 NewFD->setIsMultiVersion(); 10336 Redeclaration = true; 10337 OldDecl = ND; 10338 return false; 10339 } 10340 10341 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10342 if (CurParsed == NewParsed) { 10343 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10344 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10345 NewFD->setInvalidDecl(); 10346 return true; 10347 } 10348 } else { 10349 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10350 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10351 // Handle CPUDispatch/CPUSpecific versions. 10352 // Only 1 CPUDispatch function is allowed, this will make it go through 10353 // the redeclaration errors. 10354 if (NewMVType == MultiVersionKind::CPUDispatch && 10355 CurFD->hasAttr<CPUDispatchAttr>()) { 10356 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10357 std::equal( 10358 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10359 NewCPUDisp->cpus_begin(), 10360 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10361 return Cur->getName() == New->getName(); 10362 })) { 10363 NewFD->setIsMultiVersion(); 10364 Redeclaration = true; 10365 OldDecl = ND; 10366 return false; 10367 } 10368 10369 // If the declarations don't match, this is an error condition. 10370 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10371 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10372 NewFD->setInvalidDecl(); 10373 return true; 10374 } 10375 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10376 10377 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10378 std::equal( 10379 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10380 NewCPUSpec->cpus_begin(), 10381 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10382 return Cur->getName() == New->getName(); 10383 })) { 10384 NewFD->setIsMultiVersion(); 10385 Redeclaration = true; 10386 OldDecl = ND; 10387 return false; 10388 } 10389 10390 // Only 1 version of CPUSpecific is allowed for each CPU. 10391 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10392 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10393 if (CurII == NewII) { 10394 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10395 << NewII; 10396 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10397 NewFD->setInvalidDecl(); 10398 return true; 10399 } 10400 } 10401 } 10402 } 10403 // If the two decls aren't the same MVType, there is no possible error 10404 // condition. 10405 } 10406 } 10407 10408 // Else, this is simply a non-redecl case. Checking the 'value' is only 10409 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10410 // handled in the attribute adding step. 10411 if (NewMVType == MultiVersionKind::Target && 10412 CheckMultiVersionValue(S, NewFD)) { 10413 NewFD->setInvalidDecl(); 10414 return true; 10415 } 10416 10417 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10418 !OldFD->isMultiVersion(), NewMVType)) { 10419 NewFD->setInvalidDecl(); 10420 return true; 10421 } 10422 10423 // Permit forward declarations in the case where these two are compatible. 10424 if (!OldFD->isMultiVersion()) { 10425 OldFD->setIsMultiVersion(); 10426 NewFD->setIsMultiVersion(); 10427 Redeclaration = true; 10428 OldDecl = OldFD; 10429 return false; 10430 } 10431 10432 NewFD->setIsMultiVersion(); 10433 Redeclaration = false; 10434 MergeTypeWithPrevious = false; 10435 OldDecl = nullptr; 10436 Previous.clear(); 10437 return false; 10438 } 10439 10440 10441 /// Check the validity of a mulitversion function declaration. 10442 /// Also sets the multiversion'ness' of the function itself. 10443 /// 10444 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10445 /// 10446 /// Returns true if there was an error, false otherwise. 10447 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10448 bool &Redeclaration, NamedDecl *&OldDecl, 10449 bool &MergeTypeWithPrevious, 10450 LookupResult &Previous) { 10451 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10452 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10453 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10454 10455 // Mixing Multiversioning types is prohibited. 10456 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10457 (NewCPUDisp && NewCPUSpec)) { 10458 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10459 NewFD->setInvalidDecl(); 10460 return true; 10461 } 10462 10463 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10464 10465 // Main isn't allowed to become a multiversion function, however it IS 10466 // permitted to have 'main' be marked with the 'target' optimization hint. 10467 if (NewFD->isMain()) { 10468 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10469 MVType == MultiVersionKind::CPUDispatch || 10470 MVType == MultiVersionKind::CPUSpecific) { 10471 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10472 NewFD->setInvalidDecl(); 10473 return true; 10474 } 10475 return false; 10476 } 10477 10478 if (!OldDecl || !OldDecl->getAsFunction() || 10479 OldDecl->getDeclContext()->getRedeclContext() != 10480 NewFD->getDeclContext()->getRedeclContext()) { 10481 // If there's no previous declaration, AND this isn't attempting to cause 10482 // multiversioning, this isn't an error condition. 10483 if (MVType == MultiVersionKind::None) 10484 return false; 10485 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10486 } 10487 10488 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10489 10490 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10491 return false; 10492 10493 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10494 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10495 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10496 NewFD->setInvalidDecl(); 10497 return true; 10498 } 10499 10500 // Handle the target potentially causes multiversioning case. 10501 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10502 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10503 Redeclaration, OldDecl, 10504 MergeTypeWithPrevious, Previous); 10505 10506 // At this point, we have a multiversion function decl (in OldFD) AND an 10507 // appropriate attribute in the current function decl. Resolve that these are 10508 // still compatible with previous declarations. 10509 return CheckMultiVersionAdditionalDecl( 10510 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10511 OldDecl, MergeTypeWithPrevious, Previous); 10512 } 10513 10514 /// Perform semantic checking of a new function declaration. 10515 /// 10516 /// Performs semantic analysis of the new function declaration 10517 /// NewFD. This routine performs all semantic checking that does not 10518 /// require the actual declarator involved in the declaration, and is 10519 /// used both for the declaration of functions as they are parsed 10520 /// (called via ActOnDeclarator) and for the declaration of functions 10521 /// that have been instantiated via C++ template instantiation (called 10522 /// via InstantiateDecl). 10523 /// 10524 /// \param IsMemberSpecialization whether this new function declaration is 10525 /// a member specialization (that replaces any definition provided by the 10526 /// previous declaration). 10527 /// 10528 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10529 /// 10530 /// \returns true if the function declaration is a redeclaration. 10531 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10532 LookupResult &Previous, 10533 bool IsMemberSpecialization) { 10534 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10535 "Variably modified return types are not handled here"); 10536 10537 // Determine whether the type of this function should be merged with 10538 // a previous visible declaration. This never happens for functions in C++, 10539 // and always happens in C if the previous declaration was visible. 10540 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10541 !Previous.isShadowed(); 10542 10543 bool Redeclaration = false; 10544 NamedDecl *OldDecl = nullptr; 10545 bool MayNeedOverloadableChecks = false; 10546 10547 // Merge or overload the declaration with an existing declaration of 10548 // the same name, if appropriate. 10549 if (!Previous.empty()) { 10550 // Determine whether NewFD is an overload of PrevDecl or 10551 // a declaration that requires merging. If it's an overload, 10552 // there's no more work to do here; we'll just add the new 10553 // function to the scope. 10554 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10555 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10556 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10557 Redeclaration = true; 10558 OldDecl = Candidate; 10559 } 10560 } else { 10561 MayNeedOverloadableChecks = true; 10562 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10563 /*NewIsUsingDecl*/ false)) { 10564 case Ovl_Match: 10565 Redeclaration = true; 10566 break; 10567 10568 case Ovl_NonFunction: 10569 Redeclaration = true; 10570 break; 10571 10572 case Ovl_Overload: 10573 Redeclaration = false; 10574 break; 10575 } 10576 } 10577 } 10578 10579 // Check for a previous extern "C" declaration with this name. 10580 if (!Redeclaration && 10581 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10582 if (!Previous.empty()) { 10583 // This is an extern "C" declaration with the same name as a previous 10584 // declaration, and thus redeclares that entity... 10585 Redeclaration = true; 10586 OldDecl = Previous.getFoundDecl(); 10587 MergeTypeWithPrevious = false; 10588 10589 // ... except in the presence of __attribute__((overloadable)). 10590 if (OldDecl->hasAttr<OverloadableAttr>() || 10591 NewFD->hasAttr<OverloadableAttr>()) { 10592 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10593 MayNeedOverloadableChecks = true; 10594 Redeclaration = false; 10595 OldDecl = nullptr; 10596 } 10597 } 10598 } 10599 } 10600 10601 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10602 MergeTypeWithPrevious, Previous)) 10603 return Redeclaration; 10604 10605 // C++11 [dcl.constexpr]p8: 10606 // A constexpr specifier for a non-static member function that is not 10607 // a constructor declares that member function to be const. 10608 // 10609 // This needs to be delayed until we know whether this is an out-of-line 10610 // definition of a static member function. 10611 // 10612 // This rule is not present in C++1y, so we produce a backwards 10613 // compatibility warning whenever it happens in C++11. 10614 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10615 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10616 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10617 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10618 CXXMethodDecl *OldMD = nullptr; 10619 if (OldDecl) 10620 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10621 if (!OldMD || !OldMD->isStatic()) { 10622 const FunctionProtoType *FPT = 10623 MD->getType()->castAs<FunctionProtoType>(); 10624 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10625 EPI.TypeQuals.addConst(); 10626 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10627 FPT->getParamTypes(), EPI)); 10628 10629 // Warn that we did this, if we're not performing template instantiation. 10630 // In that case, we'll have warned already when the template was defined. 10631 if (!inTemplateInstantiation()) { 10632 SourceLocation AddConstLoc; 10633 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10634 .IgnoreParens().getAs<FunctionTypeLoc>()) 10635 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10636 10637 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10638 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10639 } 10640 } 10641 } 10642 10643 if (Redeclaration) { 10644 // NewFD and OldDecl represent declarations that need to be 10645 // merged. 10646 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10647 NewFD->setInvalidDecl(); 10648 return Redeclaration; 10649 } 10650 10651 Previous.clear(); 10652 Previous.addDecl(OldDecl); 10653 10654 if (FunctionTemplateDecl *OldTemplateDecl = 10655 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10656 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10657 FunctionTemplateDecl *NewTemplateDecl 10658 = NewFD->getDescribedFunctionTemplate(); 10659 assert(NewTemplateDecl && "Template/non-template mismatch"); 10660 10661 // The call to MergeFunctionDecl above may have created some state in 10662 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10663 // can add it as a redeclaration. 10664 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10665 10666 NewFD->setPreviousDeclaration(OldFD); 10667 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10668 if (NewFD->isCXXClassMember()) { 10669 NewFD->setAccess(OldTemplateDecl->getAccess()); 10670 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10671 } 10672 10673 // If this is an explicit specialization of a member that is a function 10674 // template, mark it as a member specialization. 10675 if (IsMemberSpecialization && 10676 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10677 NewTemplateDecl->setMemberSpecialization(); 10678 assert(OldTemplateDecl->isMemberSpecialization()); 10679 // Explicit specializations of a member template do not inherit deleted 10680 // status from the parent member template that they are specializing. 10681 if (OldFD->isDeleted()) { 10682 // FIXME: This assert will not hold in the presence of modules. 10683 assert(OldFD->getCanonicalDecl() == OldFD); 10684 // FIXME: We need an update record for this AST mutation. 10685 OldFD->setDeletedAsWritten(false); 10686 } 10687 } 10688 10689 } else { 10690 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10691 auto *OldFD = cast<FunctionDecl>(OldDecl); 10692 // This needs to happen first so that 'inline' propagates. 10693 NewFD->setPreviousDeclaration(OldFD); 10694 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10695 if (NewFD->isCXXClassMember()) 10696 NewFD->setAccess(OldFD->getAccess()); 10697 } 10698 } 10699 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10700 !NewFD->getAttr<OverloadableAttr>()) { 10701 assert((Previous.empty() || 10702 llvm::any_of(Previous, 10703 [](const NamedDecl *ND) { 10704 return ND->hasAttr<OverloadableAttr>(); 10705 })) && 10706 "Non-redecls shouldn't happen without overloadable present"); 10707 10708 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10709 const auto *FD = dyn_cast<FunctionDecl>(ND); 10710 return FD && !FD->hasAttr<OverloadableAttr>(); 10711 }); 10712 10713 if (OtherUnmarkedIter != Previous.end()) { 10714 Diag(NewFD->getLocation(), 10715 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10716 Diag((*OtherUnmarkedIter)->getLocation(), 10717 diag::note_attribute_overloadable_prev_overload) 10718 << false; 10719 10720 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10721 } 10722 } 10723 10724 // Semantic checking for this function declaration (in isolation). 10725 10726 if (getLangOpts().CPlusPlus) { 10727 // C++-specific checks. 10728 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10729 CheckConstructor(Constructor); 10730 } else if (CXXDestructorDecl *Destructor = 10731 dyn_cast<CXXDestructorDecl>(NewFD)) { 10732 CXXRecordDecl *Record = Destructor->getParent(); 10733 QualType ClassType = Context.getTypeDeclType(Record); 10734 10735 // FIXME: Shouldn't we be able to perform this check even when the class 10736 // type is dependent? Both gcc and edg can handle that. 10737 if (!ClassType->isDependentType()) { 10738 DeclarationName Name 10739 = Context.DeclarationNames.getCXXDestructorName( 10740 Context.getCanonicalType(ClassType)); 10741 if (NewFD->getDeclName() != Name) { 10742 Diag(NewFD->getLocation(), diag::err_destructor_name); 10743 NewFD->setInvalidDecl(); 10744 return Redeclaration; 10745 } 10746 } 10747 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10748 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10749 CheckDeductionGuideTemplate(TD); 10750 10751 // A deduction guide is not on the list of entities that can be 10752 // explicitly specialized. 10753 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10754 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10755 << /*explicit specialization*/ 1; 10756 } 10757 10758 // Find any virtual functions that this function overrides. 10759 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10760 if (!Method->isFunctionTemplateSpecialization() && 10761 !Method->getDescribedFunctionTemplate() && 10762 Method->isCanonicalDecl()) { 10763 AddOverriddenMethods(Method->getParent(), Method); 10764 } 10765 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10766 // C++2a [class.virtual]p6 10767 // A virtual method shall not have a requires-clause. 10768 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10769 diag::err_constrained_virtual_method); 10770 10771 if (Method->isStatic()) 10772 checkThisInStaticMemberFunctionType(Method); 10773 } 10774 10775 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 10776 ActOnConversionDeclarator(Conversion); 10777 10778 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10779 if (NewFD->isOverloadedOperator() && 10780 CheckOverloadedOperatorDeclaration(NewFD)) { 10781 NewFD->setInvalidDecl(); 10782 return Redeclaration; 10783 } 10784 10785 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10786 if (NewFD->getLiteralIdentifier() && 10787 CheckLiteralOperatorDeclaration(NewFD)) { 10788 NewFD->setInvalidDecl(); 10789 return Redeclaration; 10790 } 10791 10792 // In C++, check default arguments now that we have merged decls. Unless 10793 // the lexical context is the class, because in this case this is done 10794 // during delayed parsing anyway. 10795 if (!CurContext->isRecord()) 10796 CheckCXXDefaultArguments(NewFD); 10797 10798 // If this function declares a builtin function, check the type of this 10799 // declaration against the expected type for the builtin. 10800 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10801 ASTContext::GetBuiltinTypeError Error; 10802 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 10803 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10804 // If the type of the builtin differs only in its exception 10805 // specification, that's OK. 10806 // FIXME: If the types do differ in this way, it would be better to 10807 // retain the 'noexcept' form of the type. 10808 if (!T.isNull() && 10809 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10810 NewFD->getType())) 10811 // The type of this function differs from the type of the builtin, 10812 // so forget about the builtin entirely. 10813 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10814 } 10815 10816 // If this function is declared as being extern "C", then check to see if 10817 // the function returns a UDT (class, struct, or union type) that is not C 10818 // compatible, and if it does, warn the user. 10819 // But, issue any diagnostic on the first declaration only. 10820 if (Previous.empty() && NewFD->isExternC()) { 10821 QualType R = NewFD->getReturnType(); 10822 if (R->isIncompleteType() && !R->isVoidType()) 10823 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10824 << NewFD << R; 10825 else if (!R.isPODType(Context) && !R->isVoidType() && 10826 !R->isObjCObjectPointerType()) 10827 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10828 } 10829 10830 // C++1z [dcl.fct]p6: 10831 // [...] whether the function has a non-throwing exception-specification 10832 // [is] part of the function type 10833 // 10834 // This results in an ABI break between C++14 and C++17 for functions whose 10835 // declared type includes an exception-specification in a parameter or 10836 // return type. (Exception specifications on the function itself are OK in 10837 // most cases, and exception specifications are not permitted in most other 10838 // contexts where they could make it into a mangling.) 10839 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10840 auto HasNoexcept = [&](QualType T) -> bool { 10841 // Strip off declarator chunks that could be between us and a function 10842 // type. We don't need to look far, exception specifications are very 10843 // restricted prior to C++17. 10844 if (auto *RT = T->getAs<ReferenceType>()) 10845 T = RT->getPointeeType(); 10846 else if (T->isAnyPointerType()) 10847 T = T->getPointeeType(); 10848 else if (auto *MPT = T->getAs<MemberPointerType>()) 10849 T = MPT->getPointeeType(); 10850 if (auto *FPT = T->getAs<FunctionProtoType>()) 10851 if (FPT->isNothrow()) 10852 return true; 10853 return false; 10854 }; 10855 10856 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10857 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10858 for (QualType T : FPT->param_types()) 10859 AnyNoexcept |= HasNoexcept(T); 10860 if (AnyNoexcept) 10861 Diag(NewFD->getLocation(), 10862 diag::warn_cxx17_compat_exception_spec_in_signature) 10863 << NewFD; 10864 } 10865 10866 if (!Redeclaration && LangOpts.CUDA) 10867 checkCUDATargetOverload(NewFD, Previous); 10868 } 10869 return Redeclaration; 10870 } 10871 10872 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10873 // C++11 [basic.start.main]p3: 10874 // A program that [...] declares main to be inline, static or 10875 // constexpr is ill-formed. 10876 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10877 // appear in a declaration of main. 10878 // static main is not an error under C99, but we should warn about it. 10879 // We accept _Noreturn main as an extension. 10880 if (FD->getStorageClass() == SC_Static) 10881 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10882 ? diag::err_static_main : diag::warn_static_main) 10883 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10884 if (FD->isInlineSpecified()) 10885 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10886 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10887 if (DS.isNoreturnSpecified()) { 10888 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10889 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10890 Diag(NoreturnLoc, diag::ext_noreturn_main); 10891 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10892 << FixItHint::CreateRemoval(NoreturnRange); 10893 } 10894 if (FD->isConstexpr()) { 10895 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10896 << FD->isConsteval() 10897 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10898 FD->setConstexprKind(CSK_unspecified); 10899 } 10900 10901 if (getLangOpts().OpenCL) { 10902 Diag(FD->getLocation(), diag::err_opencl_no_main) 10903 << FD->hasAttr<OpenCLKernelAttr>(); 10904 FD->setInvalidDecl(); 10905 return; 10906 } 10907 10908 QualType T = FD->getType(); 10909 assert(T->isFunctionType() && "function decl is not of function type"); 10910 const FunctionType* FT = T->castAs<FunctionType>(); 10911 10912 // Set default calling convention for main() 10913 if (FT->getCallConv() != CC_C) { 10914 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10915 FD->setType(QualType(FT, 0)); 10916 T = Context.getCanonicalType(FD->getType()); 10917 } 10918 10919 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10920 // In C with GNU extensions we allow main() to have non-integer return 10921 // type, but we should warn about the extension, and we disable the 10922 // implicit-return-zero rule. 10923 10924 // GCC in C mode accepts qualified 'int'. 10925 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10926 FD->setHasImplicitReturnZero(true); 10927 else { 10928 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10929 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10930 if (RTRange.isValid()) 10931 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10932 << FixItHint::CreateReplacement(RTRange, "int"); 10933 } 10934 } else { 10935 // In C and C++, main magically returns 0 if you fall off the end; 10936 // set the flag which tells us that. 10937 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 10938 10939 // All the standards say that main() should return 'int'. 10940 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 10941 FD->setHasImplicitReturnZero(true); 10942 else { 10943 // Otherwise, this is just a flat-out error. 10944 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10945 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 10946 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 10947 : FixItHint()); 10948 FD->setInvalidDecl(true); 10949 } 10950 } 10951 10952 // Treat protoless main() as nullary. 10953 if (isa<FunctionNoProtoType>(FT)) return; 10954 10955 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 10956 unsigned nparams = FTP->getNumParams(); 10957 assert(FD->getNumParams() == nparams); 10958 10959 bool HasExtraParameters = (nparams > 3); 10960 10961 if (FTP->isVariadic()) { 10962 Diag(FD->getLocation(), diag::ext_variadic_main); 10963 // FIXME: if we had information about the location of the ellipsis, we 10964 // could add a FixIt hint to remove it as a parameter. 10965 } 10966 10967 // Darwin passes an undocumented fourth argument of type char**. If 10968 // other platforms start sprouting these, the logic below will start 10969 // getting shifty. 10970 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 10971 HasExtraParameters = false; 10972 10973 if (HasExtraParameters) { 10974 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 10975 FD->setInvalidDecl(true); 10976 nparams = 3; 10977 } 10978 10979 // FIXME: a lot of the following diagnostics would be improved 10980 // if we had some location information about types. 10981 10982 QualType CharPP = 10983 Context.getPointerType(Context.getPointerType(Context.CharTy)); 10984 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 10985 10986 for (unsigned i = 0; i < nparams; ++i) { 10987 QualType AT = FTP->getParamType(i); 10988 10989 bool mismatch = true; 10990 10991 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 10992 mismatch = false; 10993 else if (Expected[i] == CharPP) { 10994 // As an extension, the following forms are okay: 10995 // char const ** 10996 // char const * const * 10997 // char * const * 10998 10999 QualifierCollector qs; 11000 const PointerType* PT; 11001 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11002 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11003 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11004 Context.CharTy)) { 11005 qs.removeConst(); 11006 mismatch = !qs.empty(); 11007 } 11008 } 11009 11010 if (mismatch) { 11011 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11012 // TODO: suggest replacing given type with expected type 11013 FD->setInvalidDecl(true); 11014 } 11015 } 11016 11017 if (nparams == 1 && !FD->isInvalidDecl()) { 11018 Diag(FD->getLocation(), diag::warn_main_one_arg); 11019 } 11020 11021 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11022 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11023 FD->setInvalidDecl(); 11024 } 11025 } 11026 11027 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11028 QualType T = FD->getType(); 11029 assert(T->isFunctionType() && "function decl is not of function type"); 11030 const FunctionType *FT = T->castAs<FunctionType>(); 11031 11032 // Set an implicit return of 'zero' if the function can return some integral, 11033 // enumeration, pointer or nullptr type. 11034 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11035 FT->getReturnType()->isAnyPointerType() || 11036 FT->getReturnType()->isNullPtrType()) 11037 // DllMain is exempt because a return value of zero means it failed. 11038 if (FD->getName() != "DllMain") 11039 FD->setHasImplicitReturnZero(true); 11040 11041 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11042 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11043 FD->setInvalidDecl(); 11044 } 11045 } 11046 11047 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11048 // FIXME: Need strict checking. In C89, we need to check for 11049 // any assignment, increment, decrement, function-calls, or 11050 // commas outside of a sizeof. In C99, it's the same list, 11051 // except that the aforementioned are allowed in unevaluated 11052 // expressions. Everything else falls under the 11053 // "may accept other forms of constant expressions" exception. 11054 // (We never end up here for C++, so the constant expression 11055 // rules there don't matter.) 11056 const Expr *Culprit; 11057 if (Init->isConstantInitializer(Context, false, &Culprit)) 11058 return false; 11059 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11060 << Culprit->getSourceRange(); 11061 return true; 11062 } 11063 11064 namespace { 11065 // Visits an initialization expression to see if OrigDecl is evaluated in 11066 // its own initialization and throws a warning if it does. 11067 class SelfReferenceChecker 11068 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11069 Sema &S; 11070 Decl *OrigDecl; 11071 bool isRecordType; 11072 bool isPODType; 11073 bool isReferenceType; 11074 11075 bool isInitList; 11076 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11077 11078 public: 11079 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11080 11081 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11082 S(S), OrigDecl(OrigDecl) { 11083 isPODType = false; 11084 isRecordType = false; 11085 isReferenceType = false; 11086 isInitList = false; 11087 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11088 isPODType = VD->getType().isPODType(S.Context); 11089 isRecordType = VD->getType()->isRecordType(); 11090 isReferenceType = VD->getType()->isReferenceType(); 11091 } 11092 } 11093 11094 // For most expressions, just call the visitor. For initializer lists, 11095 // track the index of the field being initialized since fields are 11096 // initialized in order allowing use of previously initialized fields. 11097 void CheckExpr(Expr *E) { 11098 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11099 if (!InitList) { 11100 Visit(E); 11101 return; 11102 } 11103 11104 // Track and increment the index here. 11105 isInitList = true; 11106 InitFieldIndex.push_back(0); 11107 for (auto Child : InitList->children()) { 11108 CheckExpr(cast<Expr>(Child)); 11109 ++InitFieldIndex.back(); 11110 } 11111 InitFieldIndex.pop_back(); 11112 } 11113 11114 // Returns true if MemberExpr is checked and no further checking is needed. 11115 // Returns false if additional checking is required. 11116 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11117 llvm::SmallVector<FieldDecl*, 4> Fields; 11118 Expr *Base = E; 11119 bool ReferenceField = false; 11120 11121 // Get the field members used. 11122 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11123 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11124 if (!FD) 11125 return false; 11126 Fields.push_back(FD); 11127 if (FD->getType()->isReferenceType()) 11128 ReferenceField = true; 11129 Base = ME->getBase()->IgnoreParenImpCasts(); 11130 } 11131 11132 // Keep checking only if the base Decl is the same. 11133 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11134 if (!DRE || DRE->getDecl() != OrigDecl) 11135 return false; 11136 11137 // A reference field can be bound to an unininitialized field. 11138 if (CheckReference && !ReferenceField) 11139 return true; 11140 11141 // Convert FieldDecls to their index number. 11142 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11143 for (const FieldDecl *I : llvm::reverse(Fields)) 11144 UsedFieldIndex.push_back(I->getFieldIndex()); 11145 11146 // See if a warning is needed by checking the first difference in index 11147 // numbers. If field being used has index less than the field being 11148 // initialized, then the use is safe. 11149 for (auto UsedIter = UsedFieldIndex.begin(), 11150 UsedEnd = UsedFieldIndex.end(), 11151 OrigIter = InitFieldIndex.begin(), 11152 OrigEnd = InitFieldIndex.end(); 11153 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11154 if (*UsedIter < *OrigIter) 11155 return true; 11156 if (*UsedIter > *OrigIter) 11157 break; 11158 } 11159 11160 // TODO: Add a different warning which will print the field names. 11161 HandleDeclRefExpr(DRE); 11162 return true; 11163 } 11164 11165 // For most expressions, the cast is directly above the DeclRefExpr. 11166 // For conditional operators, the cast can be outside the conditional 11167 // operator if both expressions are DeclRefExpr's. 11168 void HandleValue(Expr *E) { 11169 E = E->IgnoreParens(); 11170 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11171 HandleDeclRefExpr(DRE); 11172 return; 11173 } 11174 11175 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11176 Visit(CO->getCond()); 11177 HandleValue(CO->getTrueExpr()); 11178 HandleValue(CO->getFalseExpr()); 11179 return; 11180 } 11181 11182 if (BinaryConditionalOperator *BCO = 11183 dyn_cast<BinaryConditionalOperator>(E)) { 11184 Visit(BCO->getCond()); 11185 HandleValue(BCO->getFalseExpr()); 11186 return; 11187 } 11188 11189 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11190 HandleValue(OVE->getSourceExpr()); 11191 return; 11192 } 11193 11194 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11195 if (BO->getOpcode() == BO_Comma) { 11196 Visit(BO->getLHS()); 11197 HandleValue(BO->getRHS()); 11198 return; 11199 } 11200 } 11201 11202 if (isa<MemberExpr>(E)) { 11203 if (isInitList) { 11204 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11205 false /*CheckReference*/)) 11206 return; 11207 } 11208 11209 Expr *Base = E->IgnoreParenImpCasts(); 11210 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11211 // Check for static member variables and don't warn on them. 11212 if (!isa<FieldDecl>(ME->getMemberDecl())) 11213 return; 11214 Base = ME->getBase()->IgnoreParenImpCasts(); 11215 } 11216 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11217 HandleDeclRefExpr(DRE); 11218 return; 11219 } 11220 11221 Visit(E); 11222 } 11223 11224 // Reference types not handled in HandleValue are handled here since all 11225 // uses of references are bad, not just r-value uses. 11226 void VisitDeclRefExpr(DeclRefExpr *E) { 11227 if (isReferenceType) 11228 HandleDeclRefExpr(E); 11229 } 11230 11231 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11232 if (E->getCastKind() == CK_LValueToRValue) { 11233 HandleValue(E->getSubExpr()); 11234 return; 11235 } 11236 11237 Inherited::VisitImplicitCastExpr(E); 11238 } 11239 11240 void VisitMemberExpr(MemberExpr *E) { 11241 if (isInitList) { 11242 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11243 return; 11244 } 11245 11246 // Don't warn on arrays since they can be treated as pointers. 11247 if (E->getType()->canDecayToPointerType()) return; 11248 11249 // Warn when a non-static method call is followed by non-static member 11250 // field accesses, which is followed by a DeclRefExpr. 11251 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11252 bool Warn = (MD && !MD->isStatic()); 11253 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11254 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11255 if (!isa<FieldDecl>(ME->getMemberDecl())) 11256 Warn = false; 11257 Base = ME->getBase()->IgnoreParenImpCasts(); 11258 } 11259 11260 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11261 if (Warn) 11262 HandleDeclRefExpr(DRE); 11263 return; 11264 } 11265 11266 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11267 // Visit that expression. 11268 Visit(Base); 11269 } 11270 11271 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11272 Expr *Callee = E->getCallee(); 11273 11274 if (isa<UnresolvedLookupExpr>(Callee)) 11275 return Inherited::VisitCXXOperatorCallExpr(E); 11276 11277 Visit(Callee); 11278 for (auto Arg: E->arguments()) 11279 HandleValue(Arg->IgnoreParenImpCasts()); 11280 } 11281 11282 void VisitUnaryOperator(UnaryOperator *E) { 11283 // For POD record types, addresses of its own members are well-defined. 11284 if (E->getOpcode() == UO_AddrOf && isRecordType && 11285 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11286 if (!isPODType) 11287 HandleValue(E->getSubExpr()); 11288 return; 11289 } 11290 11291 if (E->isIncrementDecrementOp()) { 11292 HandleValue(E->getSubExpr()); 11293 return; 11294 } 11295 11296 Inherited::VisitUnaryOperator(E); 11297 } 11298 11299 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11300 11301 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11302 if (E->getConstructor()->isCopyConstructor()) { 11303 Expr *ArgExpr = E->getArg(0); 11304 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11305 if (ILE->getNumInits() == 1) 11306 ArgExpr = ILE->getInit(0); 11307 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11308 if (ICE->getCastKind() == CK_NoOp) 11309 ArgExpr = ICE->getSubExpr(); 11310 HandleValue(ArgExpr); 11311 return; 11312 } 11313 Inherited::VisitCXXConstructExpr(E); 11314 } 11315 11316 void VisitCallExpr(CallExpr *E) { 11317 // Treat std::move as a use. 11318 if (E->isCallToStdMove()) { 11319 HandleValue(E->getArg(0)); 11320 return; 11321 } 11322 11323 Inherited::VisitCallExpr(E); 11324 } 11325 11326 void VisitBinaryOperator(BinaryOperator *E) { 11327 if (E->isCompoundAssignmentOp()) { 11328 HandleValue(E->getLHS()); 11329 Visit(E->getRHS()); 11330 return; 11331 } 11332 11333 Inherited::VisitBinaryOperator(E); 11334 } 11335 11336 // A custom visitor for BinaryConditionalOperator is needed because the 11337 // regular visitor would check the condition and true expression separately 11338 // but both point to the same place giving duplicate diagnostics. 11339 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11340 Visit(E->getCond()); 11341 Visit(E->getFalseExpr()); 11342 } 11343 11344 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11345 Decl* ReferenceDecl = DRE->getDecl(); 11346 if (OrigDecl != ReferenceDecl) return; 11347 unsigned diag; 11348 if (isReferenceType) { 11349 diag = diag::warn_uninit_self_reference_in_reference_init; 11350 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11351 diag = diag::warn_static_self_reference_in_init; 11352 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11353 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11354 DRE->getDecl()->getType()->isRecordType()) { 11355 diag = diag::warn_uninit_self_reference_in_init; 11356 } else { 11357 // Local variables will be handled by the CFG analysis. 11358 return; 11359 } 11360 11361 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11362 S.PDiag(diag) 11363 << DRE->getDecl() << OrigDecl->getLocation() 11364 << DRE->getSourceRange()); 11365 } 11366 }; 11367 11368 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11369 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11370 bool DirectInit) { 11371 // Parameters arguments are occassionially constructed with itself, 11372 // for instance, in recursive functions. Skip them. 11373 if (isa<ParmVarDecl>(OrigDecl)) 11374 return; 11375 11376 E = E->IgnoreParens(); 11377 11378 // Skip checking T a = a where T is not a record or reference type. 11379 // Doing so is a way to silence uninitialized warnings. 11380 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11381 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11382 if (ICE->getCastKind() == CK_LValueToRValue) 11383 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11384 if (DRE->getDecl() == OrigDecl) 11385 return; 11386 11387 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11388 } 11389 } // end anonymous namespace 11390 11391 namespace { 11392 // Simple wrapper to add the name of a variable or (if no variable is 11393 // available) a DeclarationName into a diagnostic. 11394 struct VarDeclOrName { 11395 VarDecl *VDecl; 11396 DeclarationName Name; 11397 11398 friend const Sema::SemaDiagnosticBuilder & 11399 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11400 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11401 } 11402 }; 11403 } // end anonymous namespace 11404 11405 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11406 DeclarationName Name, QualType Type, 11407 TypeSourceInfo *TSI, 11408 SourceRange Range, bool DirectInit, 11409 Expr *Init) { 11410 bool IsInitCapture = !VDecl; 11411 assert((!VDecl || !VDecl->isInitCapture()) && 11412 "init captures are expected to be deduced prior to initialization"); 11413 11414 VarDeclOrName VN{VDecl, Name}; 11415 11416 DeducedType *Deduced = Type->getContainedDeducedType(); 11417 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11418 11419 // C++11 [dcl.spec.auto]p3 11420 if (!Init) { 11421 assert(VDecl && "no init for init capture deduction?"); 11422 11423 // Except for class argument deduction, and then for an initializing 11424 // declaration only, i.e. no static at class scope or extern. 11425 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11426 VDecl->hasExternalStorage() || 11427 VDecl->isStaticDataMember()) { 11428 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11429 << VDecl->getDeclName() << Type; 11430 return QualType(); 11431 } 11432 } 11433 11434 ArrayRef<Expr*> DeduceInits; 11435 if (Init) 11436 DeduceInits = Init; 11437 11438 if (DirectInit) { 11439 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11440 DeduceInits = PL->exprs(); 11441 } 11442 11443 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11444 assert(VDecl && "non-auto type for init capture deduction?"); 11445 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11446 InitializationKind Kind = InitializationKind::CreateForInit( 11447 VDecl->getLocation(), DirectInit, Init); 11448 // FIXME: Initialization should not be taking a mutable list of inits. 11449 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11450 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11451 InitsCopy); 11452 } 11453 11454 if (DirectInit) { 11455 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11456 DeduceInits = IL->inits(); 11457 } 11458 11459 // Deduction only works if we have exactly one source expression. 11460 if (DeduceInits.empty()) { 11461 // It isn't possible to write this directly, but it is possible to 11462 // end up in this situation with "auto x(some_pack...);" 11463 Diag(Init->getBeginLoc(), IsInitCapture 11464 ? diag::err_init_capture_no_expression 11465 : diag::err_auto_var_init_no_expression) 11466 << VN << Type << Range; 11467 return QualType(); 11468 } 11469 11470 if (DeduceInits.size() > 1) { 11471 Diag(DeduceInits[1]->getBeginLoc(), 11472 IsInitCapture ? diag::err_init_capture_multiple_expressions 11473 : diag::err_auto_var_init_multiple_expressions) 11474 << VN << Type << Range; 11475 return QualType(); 11476 } 11477 11478 Expr *DeduceInit = DeduceInits[0]; 11479 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11480 Diag(Init->getBeginLoc(), IsInitCapture 11481 ? diag::err_init_capture_paren_braces 11482 : diag::err_auto_var_init_paren_braces) 11483 << isa<InitListExpr>(Init) << VN << Type << Range; 11484 return QualType(); 11485 } 11486 11487 // Expressions default to 'id' when we're in a debugger. 11488 bool DefaultedAnyToId = false; 11489 if (getLangOpts().DebuggerCastResultToId && 11490 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11491 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11492 if (Result.isInvalid()) { 11493 return QualType(); 11494 } 11495 Init = Result.get(); 11496 DefaultedAnyToId = true; 11497 } 11498 11499 // C++ [dcl.decomp]p1: 11500 // If the assignment-expression [...] has array type A and no ref-qualifier 11501 // is present, e has type cv A 11502 if (VDecl && isa<DecompositionDecl>(VDecl) && 11503 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11504 DeduceInit->getType()->isConstantArrayType()) 11505 return Context.getQualifiedType(DeduceInit->getType(), 11506 Type.getQualifiers()); 11507 11508 QualType DeducedType; 11509 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11510 if (!IsInitCapture) 11511 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11512 else if (isa<InitListExpr>(Init)) 11513 Diag(Range.getBegin(), 11514 diag::err_init_capture_deduction_failure_from_init_list) 11515 << VN 11516 << (DeduceInit->getType().isNull() ? TSI->getType() 11517 : DeduceInit->getType()) 11518 << DeduceInit->getSourceRange(); 11519 else 11520 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11521 << VN << TSI->getType() 11522 << (DeduceInit->getType().isNull() ? TSI->getType() 11523 : DeduceInit->getType()) 11524 << DeduceInit->getSourceRange(); 11525 } 11526 11527 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11528 // 'id' instead of a specific object type prevents most of our usual 11529 // checks. 11530 // We only want to warn outside of template instantiations, though: 11531 // inside a template, the 'id' could have come from a parameter. 11532 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11533 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11534 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11535 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11536 } 11537 11538 return DeducedType; 11539 } 11540 11541 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11542 Expr *Init) { 11543 assert(!Init || !Init->containsErrors()); 11544 QualType DeducedType = deduceVarTypeFromInitializer( 11545 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11546 VDecl->getSourceRange(), DirectInit, Init); 11547 if (DeducedType.isNull()) { 11548 VDecl->setInvalidDecl(); 11549 return true; 11550 } 11551 11552 VDecl->setType(DeducedType); 11553 assert(VDecl->isLinkageValid()); 11554 11555 // In ARC, infer lifetime. 11556 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11557 VDecl->setInvalidDecl(); 11558 11559 if (getLangOpts().OpenCL) 11560 deduceOpenCLAddressSpace(VDecl); 11561 11562 // If this is a redeclaration, check that the type we just deduced matches 11563 // the previously declared type. 11564 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11565 // We never need to merge the type, because we cannot form an incomplete 11566 // array of auto, nor deduce such a type. 11567 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11568 } 11569 11570 // Check the deduced type is valid for a variable declaration. 11571 CheckVariableDeclarationType(VDecl); 11572 return VDecl->isInvalidDecl(); 11573 } 11574 11575 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11576 SourceLocation Loc) { 11577 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11578 Init = EWC->getSubExpr(); 11579 11580 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11581 Init = CE->getSubExpr(); 11582 11583 QualType InitType = Init->getType(); 11584 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11585 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11586 "shouldn't be called if type doesn't have a non-trivial C struct"); 11587 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11588 for (auto I : ILE->inits()) { 11589 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11590 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11591 continue; 11592 SourceLocation SL = I->getExprLoc(); 11593 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11594 } 11595 return; 11596 } 11597 11598 if (isa<ImplicitValueInitExpr>(Init)) { 11599 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11600 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11601 NTCUK_Init); 11602 } else { 11603 // Assume all other explicit initializers involving copying some existing 11604 // object. 11605 // TODO: ignore any explicit initializers where we can guarantee 11606 // copy-elision. 11607 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11608 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11609 } 11610 } 11611 11612 namespace { 11613 11614 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11615 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11616 // in the source code or implicitly by the compiler if it is in a union 11617 // defined in a system header and has non-trivial ObjC ownership 11618 // qualifications. We don't want those fields to participate in determining 11619 // whether the containing union is non-trivial. 11620 return FD->hasAttr<UnavailableAttr>(); 11621 } 11622 11623 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11624 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11625 void> { 11626 using Super = 11627 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11628 void>; 11629 11630 DiagNonTrivalCUnionDefaultInitializeVisitor( 11631 QualType OrigTy, SourceLocation OrigLoc, 11632 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11633 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11634 11635 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11636 const FieldDecl *FD, bool InNonTrivialUnion) { 11637 if (const auto *AT = S.Context.getAsArrayType(QT)) 11638 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11639 InNonTrivialUnion); 11640 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11641 } 11642 11643 void visitARCStrong(QualType QT, const FieldDecl *FD, 11644 bool InNonTrivialUnion) { 11645 if (InNonTrivialUnion) 11646 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11647 << 1 << 0 << QT << FD->getName(); 11648 } 11649 11650 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11651 if (InNonTrivialUnion) 11652 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11653 << 1 << 0 << QT << FD->getName(); 11654 } 11655 11656 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11657 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11658 if (RD->isUnion()) { 11659 if (OrigLoc.isValid()) { 11660 bool IsUnion = false; 11661 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11662 IsUnion = OrigRD->isUnion(); 11663 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11664 << 0 << OrigTy << IsUnion << UseContext; 11665 // Reset OrigLoc so that this diagnostic is emitted only once. 11666 OrigLoc = SourceLocation(); 11667 } 11668 InNonTrivialUnion = true; 11669 } 11670 11671 if (InNonTrivialUnion) 11672 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11673 << 0 << 0 << QT.getUnqualifiedType() << ""; 11674 11675 for (const FieldDecl *FD : RD->fields()) 11676 if (!shouldIgnoreForRecordTriviality(FD)) 11677 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11678 } 11679 11680 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11681 11682 // The non-trivial C union type or the struct/union type that contains a 11683 // non-trivial C union. 11684 QualType OrigTy; 11685 SourceLocation OrigLoc; 11686 Sema::NonTrivialCUnionContext UseContext; 11687 Sema &S; 11688 }; 11689 11690 struct DiagNonTrivalCUnionDestructedTypeVisitor 11691 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11692 using Super = 11693 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11694 11695 DiagNonTrivalCUnionDestructedTypeVisitor( 11696 QualType OrigTy, SourceLocation OrigLoc, 11697 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11698 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11699 11700 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11701 const FieldDecl *FD, bool InNonTrivialUnion) { 11702 if (const auto *AT = S.Context.getAsArrayType(QT)) 11703 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11704 InNonTrivialUnion); 11705 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11706 } 11707 11708 void visitARCStrong(QualType QT, const FieldDecl *FD, 11709 bool InNonTrivialUnion) { 11710 if (InNonTrivialUnion) 11711 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11712 << 1 << 1 << QT << FD->getName(); 11713 } 11714 11715 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11716 if (InNonTrivialUnion) 11717 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11718 << 1 << 1 << QT << FD->getName(); 11719 } 11720 11721 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11722 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11723 if (RD->isUnion()) { 11724 if (OrigLoc.isValid()) { 11725 bool IsUnion = false; 11726 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11727 IsUnion = OrigRD->isUnion(); 11728 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11729 << 1 << OrigTy << IsUnion << UseContext; 11730 // Reset OrigLoc so that this diagnostic is emitted only once. 11731 OrigLoc = SourceLocation(); 11732 } 11733 InNonTrivialUnion = true; 11734 } 11735 11736 if (InNonTrivialUnion) 11737 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11738 << 0 << 1 << QT.getUnqualifiedType() << ""; 11739 11740 for (const FieldDecl *FD : RD->fields()) 11741 if (!shouldIgnoreForRecordTriviality(FD)) 11742 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11743 } 11744 11745 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11746 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11747 bool InNonTrivialUnion) {} 11748 11749 // The non-trivial C union type or the struct/union type that contains a 11750 // non-trivial C union. 11751 QualType OrigTy; 11752 SourceLocation OrigLoc; 11753 Sema::NonTrivialCUnionContext UseContext; 11754 Sema &S; 11755 }; 11756 11757 struct DiagNonTrivalCUnionCopyVisitor 11758 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11759 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11760 11761 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11762 Sema::NonTrivialCUnionContext UseContext, 11763 Sema &S) 11764 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11765 11766 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11767 const FieldDecl *FD, bool InNonTrivialUnion) { 11768 if (const auto *AT = S.Context.getAsArrayType(QT)) 11769 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11770 InNonTrivialUnion); 11771 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11772 } 11773 11774 void visitARCStrong(QualType QT, const FieldDecl *FD, 11775 bool InNonTrivialUnion) { 11776 if (InNonTrivialUnion) 11777 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11778 << 1 << 2 << QT << FD->getName(); 11779 } 11780 11781 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11782 if (InNonTrivialUnion) 11783 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11784 << 1 << 2 << QT << FD->getName(); 11785 } 11786 11787 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11788 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11789 if (RD->isUnion()) { 11790 if (OrigLoc.isValid()) { 11791 bool IsUnion = false; 11792 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11793 IsUnion = OrigRD->isUnion(); 11794 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11795 << 2 << OrigTy << IsUnion << UseContext; 11796 // Reset OrigLoc so that this diagnostic is emitted only once. 11797 OrigLoc = SourceLocation(); 11798 } 11799 InNonTrivialUnion = true; 11800 } 11801 11802 if (InNonTrivialUnion) 11803 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11804 << 0 << 2 << QT.getUnqualifiedType() << ""; 11805 11806 for (const FieldDecl *FD : RD->fields()) 11807 if (!shouldIgnoreForRecordTriviality(FD)) 11808 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11809 } 11810 11811 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 11812 const FieldDecl *FD, bool InNonTrivialUnion) {} 11813 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11814 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 11815 bool InNonTrivialUnion) {} 11816 11817 // The non-trivial C union type or the struct/union type that contains a 11818 // non-trivial C union. 11819 QualType OrigTy; 11820 SourceLocation OrigLoc; 11821 Sema::NonTrivialCUnionContext UseContext; 11822 Sema &S; 11823 }; 11824 11825 } // namespace 11826 11827 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 11828 NonTrivialCUnionContext UseContext, 11829 unsigned NonTrivialKind) { 11830 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11831 QT.hasNonTrivialToPrimitiveDestructCUnion() || 11832 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 11833 "shouldn't be called if type doesn't have a non-trivial C union"); 11834 11835 if ((NonTrivialKind & NTCUK_Init) && 11836 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11837 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 11838 .visit(QT, nullptr, false); 11839 if ((NonTrivialKind & NTCUK_Destruct) && 11840 QT.hasNonTrivialToPrimitiveDestructCUnion()) 11841 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 11842 .visit(QT, nullptr, false); 11843 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 11844 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 11845 .visit(QT, nullptr, false); 11846 } 11847 11848 /// AddInitializerToDecl - Adds the initializer Init to the 11849 /// declaration dcl. If DirectInit is true, this is C++ direct 11850 /// initialization rather than copy initialization. 11851 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11852 // If there is no declaration, there was an error parsing it. Just ignore 11853 // the initializer. 11854 if (!RealDecl || RealDecl->isInvalidDecl()) { 11855 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11856 return; 11857 } 11858 11859 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11860 // Pure-specifiers are handled in ActOnPureSpecifier. 11861 Diag(Method->getLocation(), diag::err_member_function_initialization) 11862 << Method->getDeclName() << Init->getSourceRange(); 11863 Method->setInvalidDecl(); 11864 return; 11865 } 11866 11867 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 11868 if (!VDecl) { 11869 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 11870 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 11871 RealDecl->setInvalidDecl(); 11872 return; 11873 } 11874 11875 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11876 if (VDecl->getType()->isUndeducedType()) { 11877 // Attempt typo correction early so that the type of the init expression can 11878 // be deduced based on the chosen correction if the original init contains a 11879 // TypoExpr. 11880 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11881 if (!Res.isUsable()) { 11882 // There are unresolved typos in Init, just drop them. 11883 // FIXME: improve the recovery strategy to preserve the Init. 11884 RealDecl->setInvalidDecl(); 11885 return; 11886 } 11887 if (Res.get()->containsErrors()) { 11888 // Invalidate the decl as we don't know the type for recovery-expr yet. 11889 RealDecl->setInvalidDecl(); 11890 VDecl->setInit(Res.get()); 11891 return; 11892 } 11893 Init = Res.get(); 11894 11895 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11896 return; 11897 } 11898 11899 // dllimport cannot be used on variable definitions. 11900 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11901 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11902 VDecl->setInvalidDecl(); 11903 return; 11904 } 11905 11906 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11907 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11908 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11909 VDecl->setInvalidDecl(); 11910 return; 11911 } 11912 11913 if (!VDecl->getType()->isDependentType()) { 11914 // A definition must end up with a complete type, which means it must be 11915 // complete with the restriction that an array type might be completed by 11916 // the initializer; note that later code assumes this restriction. 11917 QualType BaseDeclType = VDecl->getType(); 11918 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 11919 BaseDeclType = Array->getElementType(); 11920 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 11921 diag::err_typecheck_decl_incomplete_type)) { 11922 RealDecl->setInvalidDecl(); 11923 return; 11924 } 11925 11926 // The variable can not have an abstract class type. 11927 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 11928 diag::err_abstract_type_in_decl, 11929 AbstractVariableType)) 11930 VDecl->setInvalidDecl(); 11931 } 11932 11933 // If adding the initializer will turn this declaration into a definition, 11934 // and we already have a definition for this variable, diagnose or otherwise 11935 // handle the situation. 11936 VarDecl *Def; 11937 if ((Def = VDecl->getDefinition()) && Def != VDecl && 11938 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 11939 !VDecl->isThisDeclarationADemotedDefinition() && 11940 checkVarDeclRedefinition(Def, VDecl)) 11941 return; 11942 11943 if (getLangOpts().CPlusPlus) { 11944 // C++ [class.static.data]p4 11945 // If a static data member is of const integral or const 11946 // enumeration type, its declaration in the class definition can 11947 // specify a constant-initializer which shall be an integral 11948 // constant expression (5.19). In that case, the member can appear 11949 // in integral constant expressions. The member shall still be 11950 // defined in a namespace scope if it is used in the program and the 11951 // namespace scope definition shall not contain an initializer. 11952 // 11953 // We already performed a redefinition check above, but for static 11954 // data members we also need to check whether there was an in-class 11955 // declaration with an initializer. 11956 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 11957 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 11958 << VDecl->getDeclName(); 11959 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 11960 diag::note_previous_initializer) 11961 << 0; 11962 return; 11963 } 11964 11965 if (VDecl->hasLocalStorage()) 11966 setFunctionHasBranchProtectedScope(); 11967 11968 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 11969 VDecl->setInvalidDecl(); 11970 return; 11971 } 11972 } 11973 11974 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 11975 // a kernel function cannot be initialized." 11976 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 11977 Diag(VDecl->getLocation(), diag::err_local_cant_init); 11978 VDecl->setInvalidDecl(); 11979 return; 11980 } 11981 11982 // The LoaderUninitialized attribute acts as a definition (of undef). 11983 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 11984 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 11985 VDecl->setInvalidDecl(); 11986 return; 11987 } 11988 11989 // Get the decls type and save a reference for later, since 11990 // CheckInitializerTypes may change it. 11991 QualType DclT = VDecl->getType(), SavT = DclT; 11992 11993 // Expressions default to 'id' when we're in a debugger 11994 // and we are assigning it to a variable of Objective-C pointer type. 11995 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 11996 Init->getType() == Context.UnknownAnyTy) { 11997 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11998 if (Result.isInvalid()) { 11999 VDecl->setInvalidDecl(); 12000 return; 12001 } 12002 Init = Result.get(); 12003 } 12004 12005 // Perform the initialization. 12006 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12007 if (!VDecl->isInvalidDecl()) { 12008 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12009 InitializationKind Kind = InitializationKind::CreateForInit( 12010 VDecl->getLocation(), DirectInit, Init); 12011 12012 MultiExprArg Args = Init; 12013 if (CXXDirectInit) 12014 Args = MultiExprArg(CXXDirectInit->getExprs(), 12015 CXXDirectInit->getNumExprs()); 12016 12017 // Try to correct any TypoExprs in the initialization arguments. 12018 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12019 ExprResult Res = CorrectDelayedTyposInExpr( 12020 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/false, 12021 [this, Entity, Kind](Expr *E) { 12022 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12023 return Init.Failed() ? ExprError() : E; 12024 }); 12025 if (Res.isInvalid()) { 12026 VDecl->setInvalidDecl(); 12027 } else if (Res.get() != Args[Idx]) { 12028 Args[Idx] = Res.get(); 12029 } 12030 } 12031 if (VDecl->isInvalidDecl()) 12032 return; 12033 12034 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12035 /*TopLevelOfInitList=*/false, 12036 /*TreatUnavailableAsInvalid=*/false); 12037 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12038 if (Result.isInvalid()) { 12039 // If the provied initializer fails to initialize the var decl, 12040 // we attach a recovery expr for better recovery. 12041 auto RecoveryExpr = 12042 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12043 if (RecoveryExpr.get()) 12044 VDecl->setInit(RecoveryExpr.get()); 12045 return; 12046 } 12047 12048 Init = Result.getAs<Expr>(); 12049 } 12050 12051 // Check for self-references within variable initializers. 12052 // Variables declared within a function/method body (except for references) 12053 // are handled by a dataflow analysis. 12054 // This is undefined behavior in C++, but valid in C. 12055 if (getLangOpts().CPlusPlus) { 12056 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12057 VDecl->getType()->isReferenceType()) { 12058 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12059 } 12060 } 12061 12062 // If the type changed, it means we had an incomplete type that was 12063 // completed by the initializer. For example: 12064 // int ary[] = { 1, 3, 5 }; 12065 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12066 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12067 VDecl->setType(DclT); 12068 12069 if (!VDecl->isInvalidDecl()) { 12070 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12071 12072 if (VDecl->hasAttr<BlocksAttr>()) 12073 checkRetainCycles(VDecl, Init); 12074 12075 // It is safe to assign a weak reference into a strong variable. 12076 // Although this code can still have problems: 12077 // id x = self.weakProp; 12078 // id y = self.weakProp; 12079 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12080 // paths through the function. This should be revisited if 12081 // -Wrepeated-use-of-weak is made flow-sensitive. 12082 if (FunctionScopeInfo *FSI = getCurFunction()) 12083 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12084 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12085 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12086 Init->getBeginLoc())) 12087 FSI->markSafeWeakUse(Init); 12088 } 12089 12090 // The initialization is usually a full-expression. 12091 // 12092 // FIXME: If this is a braced initialization of an aggregate, it is not 12093 // an expression, and each individual field initializer is a separate 12094 // full-expression. For instance, in: 12095 // 12096 // struct Temp { ~Temp(); }; 12097 // struct S { S(Temp); }; 12098 // struct T { S a, b; } t = { Temp(), Temp() } 12099 // 12100 // we should destroy the first Temp before constructing the second. 12101 ExprResult Result = 12102 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12103 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12104 if (Result.isInvalid()) { 12105 VDecl->setInvalidDecl(); 12106 return; 12107 } 12108 Init = Result.get(); 12109 12110 // Attach the initializer to the decl. 12111 VDecl->setInit(Init); 12112 12113 if (VDecl->isLocalVarDecl()) { 12114 // Don't check the initializer if the declaration is malformed. 12115 if (VDecl->isInvalidDecl()) { 12116 // do nothing 12117 12118 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12119 // This is true even in C++ for OpenCL. 12120 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12121 CheckForConstantInitializer(Init, DclT); 12122 12123 // Otherwise, C++ does not restrict the initializer. 12124 } else if (getLangOpts().CPlusPlus) { 12125 // do nothing 12126 12127 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12128 // static storage duration shall be constant expressions or string literals. 12129 } else if (VDecl->getStorageClass() == SC_Static) { 12130 CheckForConstantInitializer(Init, DclT); 12131 12132 // C89 is stricter than C99 for aggregate initializers. 12133 // C89 6.5.7p3: All the expressions [...] in an initializer list 12134 // for an object that has aggregate or union type shall be 12135 // constant expressions. 12136 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12137 isa<InitListExpr>(Init)) { 12138 const Expr *Culprit; 12139 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12140 Diag(Culprit->getExprLoc(), 12141 diag::ext_aggregate_init_not_constant) 12142 << Culprit->getSourceRange(); 12143 } 12144 } 12145 12146 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12147 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12148 if (VDecl->hasLocalStorage()) 12149 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12150 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12151 VDecl->getLexicalDeclContext()->isRecord()) { 12152 // This is an in-class initialization for a static data member, e.g., 12153 // 12154 // struct S { 12155 // static const int value = 17; 12156 // }; 12157 12158 // C++ [class.mem]p4: 12159 // A member-declarator can contain a constant-initializer only 12160 // if it declares a static member (9.4) of const integral or 12161 // const enumeration type, see 9.4.2. 12162 // 12163 // C++11 [class.static.data]p3: 12164 // If a non-volatile non-inline const static data member is of integral 12165 // or enumeration type, its declaration in the class definition can 12166 // specify a brace-or-equal-initializer in which every initializer-clause 12167 // that is an assignment-expression is a constant expression. A static 12168 // data member of literal type can be declared in the class definition 12169 // with the constexpr specifier; if so, its declaration shall specify a 12170 // brace-or-equal-initializer in which every initializer-clause that is 12171 // an assignment-expression is a constant expression. 12172 12173 // Do nothing on dependent types. 12174 if (DclT->isDependentType()) { 12175 12176 // Allow any 'static constexpr' members, whether or not they are of literal 12177 // type. We separately check that every constexpr variable is of literal 12178 // type. 12179 } else if (VDecl->isConstexpr()) { 12180 12181 // Require constness. 12182 } else if (!DclT.isConstQualified()) { 12183 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12184 << Init->getSourceRange(); 12185 VDecl->setInvalidDecl(); 12186 12187 // We allow integer constant expressions in all cases. 12188 } else if (DclT->isIntegralOrEnumerationType()) { 12189 // Check whether the expression is a constant expression. 12190 SourceLocation Loc; 12191 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12192 // In C++11, a non-constexpr const static data member with an 12193 // in-class initializer cannot be volatile. 12194 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12195 else if (Init->isValueDependent()) 12196 ; // Nothing to check. 12197 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12198 ; // Ok, it's an ICE! 12199 else if (Init->getType()->isScopedEnumeralType() && 12200 Init->isCXX11ConstantExpr(Context)) 12201 ; // Ok, it is a scoped-enum constant expression. 12202 else if (Init->isEvaluatable(Context)) { 12203 // If we can constant fold the initializer through heroics, accept it, 12204 // but report this as a use of an extension for -pedantic. 12205 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12206 << Init->getSourceRange(); 12207 } else { 12208 // Otherwise, this is some crazy unknown case. Report the issue at the 12209 // location provided by the isIntegerConstantExpr failed check. 12210 Diag(Loc, diag::err_in_class_initializer_non_constant) 12211 << Init->getSourceRange(); 12212 VDecl->setInvalidDecl(); 12213 } 12214 12215 // We allow foldable floating-point constants as an extension. 12216 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12217 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12218 // it anyway and provide a fixit to add the 'constexpr'. 12219 if (getLangOpts().CPlusPlus11) { 12220 Diag(VDecl->getLocation(), 12221 diag::ext_in_class_initializer_float_type_cxx11) 12222 << DclT << Init->getSourceRange(); 12223 Diag(VDecl->getBeginLoc(), 12224 diag::note_in_class_initializer_float_type_cxx11) 12225 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12226 } else { 12227 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12228 << DclT << Init->getSourceRange(); 12229 12230 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12231 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12232 << Init->getSourceRange(); 12233 VDecl->setInvalidDecl(); 12234 } 12235 } 12236 12237 // Suggest adding 'constexpr' in C++11 for literal types. 12238 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12239 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12240 << DclT << Init->getSourceRange() 12241 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12242 VDecl->setConstexpr(true); 12243 12244 } else { 12245 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12246 << DclT << Init->getSourceRange(); 12247 VDecl->setInvalidDecl(); 12248 } 12249 } else if (VDecl->isFileVarDecl()) { 12250 // In C, extern is typically used to avoid tentative definitions when 12251 // declaring variables in headers, but adding an intializer makes it a 12252 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12253 // In C++, extern is often used to give implictly static const variables 12254 // external linkage, so don't warn in that case. If selectany is present, 12255 // this might be header code intended for C and C++ inclusion, so apply the 12256 // C++ rules. 12257 if (VDecl->getStorageClass() == SC_Extern && 12258 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12259 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12260 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12261 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12262 Diag(VDecl->getLocation(), diag::warn_extern_init); 12263 12264 // In Microsoft C++ mode, a const variable defined in namespace scope has 12265 // external linkage by default if the variable is declared with 12266 // __declspec(dllexport). 12267 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12268 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12269 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12270 VDecl->setStorageClass(SC_Extern); 12271 12272 // C99 6.7.8p4. All file scoped initializers need to be constant. 12273 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12274 CheckForConstantInitializer(Init, DclT); 12275 } 12276 12277 QualType InitType = Init->getType(); 12278 if (!InitType.isNull() && 12279 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12280 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12281 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12282 12283 // We will represent direct-initialization similarly to copy-initialization: 12284 // int x(1); -as-> int x = 1; 12285 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12286 // 12287 // Clients that want to distinguish between the two forms, can check for 12288 // direct initializer using VarDecl::getInitStyle(). 12289 // A major benefit is that clients that don't particularly care about which 12290 // exactly form was it (like the CodeGen) can handle both cases without 12291 // special case code. 12292 12293 // C++ 8.5p11: 12294 // The form of initialization (using parentheses or '=') is generally 12295 // insignificant, but does matter when the entity being initialized has a 12296 // class type. 12297 if (CXXDirectInit) { 12298 assert(DirectInit && "Call-style initializer must be direct init."); 12299 VDecl->setInitStyle(VarDecl::CallInit); 12300 } else if (DirectInit) { 12301 // This must be list-initialization. No other way is direct-initialization. 12302 VDecl->setInitStyle(VarDecl::ListInit); 12303 } 12304 12305 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12306 DeclsToCheckForDeferredDiags.push_back(VDecl); 12307 CheckCompleteVariableDeclaration(VDecl); 12308 } 12309 12310 /// ActOnInitializerError - Given that there was an error parsing an 12311 /// initializer for the given declaration, try to return to some form 12312 /// of sanity. 12313 void Sema::ActOnInitializerError(Decl *D) { 12314 // Our main concern here is re-establishing invariants like "a 12315 // variable's type is either dependent or complete". 12316 if (!D || D->isInvalidDecl()) return; 12317 12318 VarDecl *VD = dyn_cast<VarDecl>(D); 12319 if (!VD) return; 12320 12321 // Bindings are not usable if we can't make sense of the initializer. 12322 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12323 for (auto *BD : DD->bindings()) 12324 BD->setInvalidDecl(); 12325 12326 // Auto types are meaningless if we can't make sense of the initializer. 12327 if (VD->getType()->isUndeducedType()) { 12328 D->setInvalidDecl(); 12329 return; 12330 } 12331 12332 QualType Ty = VD->getType(); 12333 if (Ty->isDependentType()) return; 12334 12335 // Require a complete type. 12336 if (RequireCompleteType(VD->getLocation(), 12337 Context.getBaseElementType(Ty), 12338 diag::err_typecheck_decl_incomplete_type)) { 12339 VD->setInvalidDecl(); 12340 return; 12341 } 12342 12343 // Require a non-abstract type. 12344 if (RequireNonAbstractType(VD->getLocation(), Ty, 12345 diag::err_abstract_type_in_decl, 12346 AbstractVariableType)) { 12347 VD->setInvalidDecl(); 12348 return; 12349 } 12350 12351 // Don't bother complaining about constructors or destructors, 12352 // though. 12353 } 12354 12355 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12356 // If there is no declaration, there was an error parsing it. Just ignore it. 12357 if (!RealDecl) 12358 return; 12359 12360 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12361 QualType Type = Var->getType(); 12362 12363 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12364 if (isa<DecompositionDecl>(RealDecl)) { 12365 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12366 Var->setInvalidDecl(); 12367 return; 12368 } 12369 12370 if (Type->isUndeducedType() && 12371 DeduceVariableDeclarationType(Var, false, nullptr)) 12372 return; 12373 12374 // C++11 [class.static.data]p3: A static data member can be declared with 12375 // the constexpr specifier; if so, its declaration shall specify 12376 // a brace-or-equal-initializer. 12377 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12378 // the definition of a variable [...] or the declaration of a static data 12379 // member. 12380 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12381 !Var->isThisDeclarationADemotedDefinition()) { 12382 if (Var->isStaticDataMember()) { 12383 // C++1z removes the relevant rule; the in-class declaration is always 12384 // a definition there. 12385 if (!getLangOpts().CPlusPlus17 && 12386 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12387 Diag(Var->getLocation(), 12388 diag::err_constexpr_static_mem_var_requires_init) 12389 << Var->getDeclName(); 12390 Var->setInvalidDecl(); 12391 return; 12392 } 12393 } else { 12394 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12395 Var->setInvalidDecl(); 12396 return; 12397 } 12398 } 12399 12400 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12401 // be initialized. 12402 if (!Var->isInvalidDecl() && 12403 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12404 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12405 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12406 Var->setInvalidDecl(); 12407 return; 12408 } 12409 12410 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12411 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12412 if (!RD->hasTrivialDefaultConstructor()) { 12413 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12414 Var->setInvalidDecl(); 12415 return; 12416 } 12417 } 12418 if (Var->getStorageClass() == SC_Extern) { 12419 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12420 << Var; 12421 Var->setInvalidDecl(); 12422 return; 12423 } 12424 } 12425 12426 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12427 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12428 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12429 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12430 NTCUC_DefaultInitializedObject, NTCUK_Init); 12431 12432 12433 switch (DefKind) { 12434 case VarDecl::Definition: 12435 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12436 break; 12437 12438 // We have an out-of-line definition of a static data member 12439 // that has an in-class initializer, so we type-check this like 12440 // a declaration. 12441 // 12442 LLVM_FALLTHROUGH; 12443 12444 case VarDecl::DeclarationOnly: 12445 // It's only a declaration. 12446 12447 // Block scope. C99 6.7p7: If an identifier for an object is 12448 // declared with no linkage (C99 6.2.2p6), the type for the 12449 // object shall be complete. 12450 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12451 !Var->hasLinkage() && !Var->isInvalidDecl() && 12452 RequireCompleteType(Var->getLocation(), Type, 12453 diag::err_typecheck_decl_incomplete_type)) 12454 Var->setInvalidDecl(); 12455 12456 // Make sure that the type is not abstract. 12457 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12458 RequireNonAbstractType(Var->getLocation(), Type, 12459 diag::err_abstract_type_in_decl, 12460 AbstractVariableType)) 12461 Var->setInvalidDecl(); 12462 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12463 Var->getStorageClass() == SC_PrivateExtern) { 12464 Diag(Var->getLocation(), diag::warn_private_extern); 12465 Diag(Var->getLocation(), diag::note_private_extern); 12466 } 12467 12468 if (Context.getTargetInfo().allowDebugInfoForExternalVar() && 12469 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12470 ExternalDeclarations.push_back(Var); 12471 12472 return; 12473 12474 case VarDecl::TentativeDefinition: 12475 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12476 // object that has file scope without an initializer, and without a 12477 // storage-class specifier or with the storage-class specifier "static", 12478 // constitutes a tentative definition. Note: A tentative definition with 12479 // external linkage is valid (C99 6.2.2p5). 12480 if (!Var->isInvalidDecl()) { 12481 if (const IncompleteArrayType *ArrayT 12482 = Context.getAsIncompleteArrayType(Type)) { 12483 if (RequireCompleteSizedType( 12484 Var->getLocation(), ArrayT->getElementType(), 12485 diag::err_array_incomplete_or_sizeless_type)) 12486 Var->setInvalidDecl(); 12487 } else if (Var->getStorageClass() == SC_Static) { 12488 // C99 6.9.2p3: If the declaration of an identifier for an object is 12489 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12490 // declared type shall not be an incomplete type. 12491 // NOTE: code such as the following 12492 // static struct s; 12493 // struct s { int a; }; 12494 // is accepted by gcc. Hence here we issue a warning instead of 12495 // an error and we do not invalidate the static declaration. 12496 // NOTE: to avoid multiple warnings, only check the first declaration. 12497 if (Var->isFirstDecl()) 12498 RequireCompleteType(Var->getLocation(), Type, 12499 diag::ext_typecheck_decl_incomplete_type); 12500 } 12501 } 12502 12503 // Record the tentative definition; we're done. 12504 if (!Var->isInvalidDecl()) 12505 TentativeDefinitions.push_back(Var); 12506 return; 12507 } 12508 12509 // Provide a specific diagnostic for uninitialized variable 12510 // definitions with incomplete array type. 12511 if (Type->isIncompleteArrayType()) { 12512 Diag(Var->getLocation(), 12513 diag::err_typecheck_incomplete_array_needs_initializer); 12514 Var->setInvalidDecl(); 12515 return; 12516 } 12517 12518 // Provide a specific diagnostic for uninitialized variable 12519 // definitions with reference type. 12520 if (Type->isReferenceType()) { 12521 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12522 << Var->getDeclName() 12523 << SourceRange(Var->getLocation(), Var->getLocation()); 12524 Var->setInvalidDecl(); 12525 return; 12526 } 12527 12528 // Do not attempt to type-check the default initializer for a 12529 // variable with dependent type. 12530 if (Type->isDependentType()) 12531 return; 12532 12533 if (Var->isInvalidDecl()) 12534 return; 12535 12536 if (!Var->hasAttr<AliasAttr>()) { 12537 if (RequireCompleteType(Var->getLocation(), 12538 Context.getBaseElementType(Type), 12539 diag::err_typecheck_decl_incomplete_type)) { 12540 Var->setInvalidDecl(); 12541 return; 12542 } 12543 } else { 12544 return; 12545 } 12546 12547 // The variable can not have an abstract class type. 12548 if (RequireNonAbstractType(Var->getLocation(), Type, 12549 diag::err_abstract_type_in_decl, 12550 AbstractVariableType)) { 12551 Var->setInvalidDecl(); 12552 return; 12553 } 12554 12555 // Check for jumps past the implicit initializer. C++0x 12556 // clarifies that this applies to a "variable with automatic 12557 // storage duration", not a "local variable". 12558 // C++11 [stmt.dcl]p3 12559 // A program that jumps from a point where a variable with automatic 12560 // storage duration is not in scope to a point where it is in scope is 12561 // ill-formed unless the variable has scalar type, class type with a 12562 // trivial default constructor and a trivial destructor, a cv-qualified 12563 // version of one of these types, or an array of one of the preceding 12564 // types and is declared without an initializer. 12565 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12566 if (const RecordType *Record 12567 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12568 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12569 // Mark the function (if we're in one) for further checking even if the 12570 // looser rules of C++11 do not require such checks, so that we can 12571 // diagnose incompatibilities with C++98. 12572 if (!CXXRecord->isPOD()) 12573 setFunctionHasBranchProtectedScope(); 12574 } 12575 } 12576 // In OpenCL, we can't initialize objects in the __local address space, 12577 // even implicitly, so don't synthesize an implicit initializer. 12578 if (getLangOpts().OpenCL && 12579 Var->getType().getAddressSpace() == LangAS::opencl_local) 12580 return; 12581 // C++03 [dcl.init]p9: 12582 // If no initializer is specified for an object, and the 12583 // object is of (possibly cv-qualified) non-POD class type (or 12584 // array thereof), the object shall be default-initialized; if 12585 // the object is of const-qualified type, the underlying class 12586 // type shall have a user-declared default 12587 // constructor. Otherwise, if no initializer is specified for 12588 // a non- static object, the object and its subobjects, if 12589 // any, have an indeterminate initial value); if the object 12590 // or any of its subobjects are of const-qualified type, the 12591 // program is ill-formed. 12592 // C++0x [dcl.init]p11: 12593 // If no initializer is specified for an object, the object is 12594 // default-initialized; [...]. 12595 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12596 InitializationKind Kind 12597 = InitializationKind::CreateDefault(Var->getLocation()); 12598 12599 InitializationSequence InitSeq(*this, Entity, Kind, None); 12600 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12601 12602 if (Init.get()) { 12603 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12604 // This is important for template substitution. 12605 Var->setInitStyle(VarDecl::CallInit); 12606 } else if (Init.isInvalid()) { 12607 // If default-init fails, attach a recovery-expr initializer to track 12608 // that initialization was attempted and failed. 12609 auto RecoveryExpr = 12610 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12611 if (RecoveryExpr.get()) 12612 Var->setInit(RecoveryExpr.get()); 12613 } 12614 12615 CheckCompleteVariableDeclaration(Var); 12616 } 12617 } 12618 12619 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12620 // If there is no declaration, there was an error parsing it. Ignore it. 12621 if (!D) 12622 return; 12623 12624 VarDecl *VD = dyn_cast<VarDecl>(D); 12625 if (!VD) { 12626 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12627 D->setInvalidDecl(); 12628 return; 12629 } 12630 12631 VD->setCXXForRangeDecl(true); 12632 12633 // for-range-declaration cannot be given a storage class specifier. 12634 int Error = -1; 12635 switch (VD->getStorageClass()) { 12636 case SC_None: 12637 break; 12638 case SC_Extern: 12639 Error = 0; 12640 break; 12641 case SC_Static: 12642 Error = 1; 12643 break; 12644 case SC_PrivateExtern: 12645 Error = 2; 12646 break; 12647 case SC_Auto: 12648 Error = 3; 12649 break; 12650 case SC_Register: 12651 Error = 4; 12652 break; 12653 } 12654 if (Error != -1) { 12655 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12656 << VD->getDeclName() << Error; 12657 D->setInvalidDecl(); 12658 } 12659 } 12660 12661 StmtResult 12662 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12663 IdentifierInfo *Ident, 12664 ParsedAttributes &Attrs, 12665 SourceLocation AttrEnd) { 12666 // C++1y [stmt.iter]p1: 12667 // A range-based for statement of the form 12668 // for ( for-range-identifier : for-range-initializer ) statement 12669 // is equivalent to 12670 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12671 DeclSpec DS(Attrs.getPool().getFactory()); 12672 12673 const char *PrevSpec; 12674 unsigned DiagID; 12675 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12676 getPrintingPolicy()); 12677 12678 Declarator D(DS, DeclaratorContext::ForContext); 12679 D.SetIdentifier(Ident, IdentLoc); 12680 D.takeAttributes(Attrs, AttrEnd); 12681 12682 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12683 IdentLoc); 12684 Decl *Var = ActOnDeclarator(S, D); 12685 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12686 FinalizeDeclaration(Var); 12687 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12688 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12689 } 12690 12691 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12692 if (var->isInvalidDecl()) return; 12693 12694 if (getLangOpts().OpenCL) { 12695 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12696 // initialiser 12697 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12698 !var->hasInit()) { 12699 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12700 << 1 /*Init*/; 12701 var->setInvalidDecl(); 12702 return; 12703 } 12704 } 12705 12706 // In Objective-C, don't allow jumps past the implicit initialization of a 12707 // local retaining variable. 12708 if (getLangOpts().ObjC && 12709 var->hasLocalStorage()) { 12710 switch (var->getType().getObjCLifetime()) { 12711 case Qualifiers::OCL_None: 12712 case Qualifiers::OCL_ExplicitNone: 12713 case Qualifiers::OCL_Autoreleasing: 12714 break; 12715 12716 case Qualifiers::OCL_Weak: 12717 case Qualifiers::OCL_Strong: 12718 setFunctionHasBranchProtectedScope(); 12719 break; 12720 } 12721 } 12722 12723 if (var->hasLocalStorage() && 12724 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12725 setFunctionHasBranchProtectedScope(); 12726 12727 // Warn about externally-visible variables being defined without a 12728 // prior declaration. We only want to do this for global 12729 // declarations, but we also specifically need to avoid doing it for 12730 // class members because the linkage of an anonymous class can 12731 // change if it's later given a typedef name. 12732 if (var->isThisDeclarationADefinition() && 12733 var->getDeclContext()->getRedeclContext()->isFileContext() && 12734 var->isExternallyVisible() && var->hasLinkage() && 12735 !var->isInline() && !var->getDescribedVarTemplate() && 12736 !isa<VarTemplatePartialSpecializationDecl>(var) && 12737 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12738 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12739 var->getLocation())) { 12740 // Find a previous declaration that's not a definition. 12741 VarDecl *prev = var->getPreviousDecl(); 12742 while (prev && prev->isThisDeclarationADefinition()) 12743 prev = prev->getPreviousDecl(); 12744 12745 if (!prev) { 12746 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12747 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12748 << /* variable */ 0; 12749 } 12750 } 12751 12752 // Cache the result of checking for constant initialization. 12753 Optional<bool> CacheHasConstInit; 12754 const Expr *CacheCulprit = nullptr; 12755 auto checkConstInit = [&]() mutable { 12756 if (!CacheHasConstInit) 12757 CacheHasConstInit = var->getInit()->isConstantInitializer( 12758 Context, var->getType()->isReferenceType(), &CacheCulprit); 12759 return *CacheHasConstInit; 12760 }; 12761 12762 if (var->getTLSKind() == VarDecl::TLS_Static) { 12763 if (var->getType().isDestructedType()) { 12764 // GNU C++98 edits for __thread, [basic.start.term]p3: 12765 // The type of an object with thread storage duration shall not 12766 // have a non-trivial destructor. 12767 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12768 if (getLangOpts().CPlusPlus11) 12769 Diag(var->getLocation(), diag::note_use_thread_local); 12770 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12771 if (!checkConstInit()) { 12772 // GNU C++98 edits for __thread, [basic.start.init]p4: 12773 // An object of thread storage duration shall not require dynamic 12774 // initialization. 12775 // FIXME: Need strict checking here. 12776 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12777 << CacheCulprit->getSourceRange(); 12778 if (getLangOpts().CPlusPlus11) 12779 Diag(var->getLocation(), diag::note_use_thread_local); 12780 } 12781 } 12782 } 12783 12784 // Apply section attributes and pragmas to global variables. 12785 bool GlobalStorage = var->hasGlobalStorage(); 12786 if (GlobalStorage && var->isThisDeclarationADefinition() && 12787 !inTemplateInstantiation()) { 12788 PragmaStack<StringLiteral *> *Stack = nullptr; 12789 int SectionFlags = ASTContext::PSF_Read; 12790 if (var->getType().isConstQualified()) 12791 Stack = &ConstSegStack; 12792 else if (!var->getInit()) { 12793 Stack = &BSSSegStack; 12794 SectionFlags |= ASTContext::PSF_Write; 12795 } else { 12796 Stack = &DataSegStack; 12797 SectionFlags |= ASTContext::PSF_Write; 12798 } 12799 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 12800 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 12801 SectionFlags |= ASTContext::PSF_Implicit; 12802 UnifySection(SA->getName(), SectionFlags, var); 12803 } else if (Stack->CurrentValue) { 12804 SectionFlags |= ASTContext::PSF_Implicit; 12805 auto SectionName = Stack->CurrentValue->getString(); 12806 var->addAttr(SectionAttr::CreateImplicit( 12807 Context, SectionName, Stack->CurrentPragmaLocation, 12808 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 12809 if (UnifySection(SectionName, SectionFlags, var)) 12810 var->dropAttr<SectionAttr>(); 12811 } 12812 12813 // Apply the init_seg attribute if this has an initializer. If the 12814 // initializer turns out to not be dynamic, we'll end up ignoring this 12815 // attribute. 12816 if (CurInitSeg && var->getInit()) 12817 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 12818 CurInitSegLoc, 12819 AttributeCommonInfo::AS_Pragma)); 12820 } 12821 12822 // All the following checks are C++ only. 12823 if (!getLangOpts().CPlusPlus) { 12824 // If this variable must be emitted, add it as an initializer for the 12825 // current module. 12826 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12827 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12828 return; 12829 } 12830 12831 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 12832 CheckCompleteDecompositionDeclaration(DD); 12833 12834 QualType type = var->getType(); 12835 if (type->isDependentType()) return; 12836 12837 if (var->hasAttr<BlocksAttr>()) 12838 getCurFunction()->addByrefBlockVar(var); 12839 12840 Expr *Init = var->getInit(); 12841 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 12842 QualType baseType = Context.getBaseElementType(type); 12843 12844 if (Init && !Init->isValueDependent()) { 12845 if (var->isConstexpr()) { 12846 SmallVector<PartialDiagnosticAt, 8> Notes; 12847 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 12848 SourceLocation DiagLoc = var->getLocation(); 12849 // If the note doesn't add any useful information other than a source 12850 // location, fold it into the primary diagnostic. 12851 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12852 diag::note_invalid_subexpr_in_const_expr) { 12853 DiagLoc = Notes[0].first; 12854 Notes.clear(); 12855 } 12856 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 12857 << var << Init->getSourceRange(); 12858 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12859 Diag(Notes[I].first, Notes[I].second); 12860 } 12861 } else if (var->mightBeUsableInConstantExpressions(Context)) { 12862 // Check whether the initializer of a const variable of integral or 12863 // enumeration type is an ICE now, since we can't tell whether it was 12864 // initialized by a constant expression if we check later. 12865 var->checkInitIsICE(); 12866 } 12867 12868 // Don't emit further diagnostics about constexpr globals since they 12869 // were just diagnosed. 12870 if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) { 12871 // FIXME: Need strict checking in C++03 here. 12872 bool DiagErr = getLangOpts().CPlusPlus11 12873 ? !var->checkInitIsICE() : !checkConstInit(); 12874 if (DiagErr) { 12875 auto *Attr = var->getAttr<ConstInitAttr>(); 12876 Diag(var->getLocation(), diag::err_require_constant_init_failed) 12877 << Init->getSourceRange(); 12878 Diag(Attr->getLocation(), 12879 diag::note_declared_required_constant_init_here) 12880 << Attr->getRange() << Attr->isConstinit(); 12881 if (getLangOpts().CPlusPlus11) { 12882 APValue Value; 12883 SmallVector<PartialDiagnosticAt, 8> Notes; 12884 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 12885 for (auto &it : Notes) 12886 Diag(it.first, it.second); 12887 } else { 12888 Diag(CacheCulprit->getExprLoc(), 12889 diag::note_invalid_subexpr_in_const_expr) 12890 << CacheCulprit->getSourceRange(); 12891 } 12892 } 12893 } 12894 else if (!var->isConstexpr() && IsGlobal && 12895 !getDiagnostics().isIgnored(diag::warn_global_constructor, 12896 var->getLocation())) { 12897 // Warn about globals which don't have a constant initializer. Don't 12898 // warn about globals with a non-trivial destructor because we already 12899 // warned about them. 12900 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 12901 if (!(RD && !RD->hasTrivialDestructor())) { 12902 if (!checkConstInit()) 12903 Diag(var->getLocation(), diag::warn_global_constructor) 12904 << Init->getSourceRange(); 12905 } 12906 } 12907 } 12908 12909 // Require the destructor. 12910 if (const RecordType *recordType = baseType->getAs<RecordType>()) 12911 FinalizeVarWithDestructor(var, recordType); 12912 12913 // If this variable must be emitted, add it as an initializer for the current 12914 // module. 12915 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12916 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12917 } 12918 12919 /// Determines if a variable's alignment is dependent. 12920 static bool hasDependentAlignment(VarDecl *VD) { 12921 if (VD->getType()->isDependentType()) 12922 return true; 12923 for (auto *I : VD->specific_attrs<AlignedAttr>()) 12924 if (I->isAlignmentDependent()) 12925 return true; 12926 return false; 12927 } 12928 12929 /// Check if VD needs to be dllexport/dllimport due to being in a 12930 /// dllexport/import function. 12931 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 12932 assert(VD->isStaticLocal()); 12933 12934 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12935 12936 // Find outermost function when VD is in lambda function. 12937 while (FD && !getDLLAttr(FD) && 12938 !FD->hasAttr<DLLExportStaticLocalAttr>() && 12939 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 12940 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 12941 } 12942 12943 if (!FD) 12944 return; 12945 12946 // Static locals inherit dll attributes from their function. 12947 if (Attr *A = getDLLAttr(FD)) { 12948 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 12949 NewAttr->setInherited(true); 12950 VD->addAttr(NewAttr); 12951 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 12952 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 12953 NewAttr->setInherited(true); 12954 VD->addAttr(NewAttr); 12955 12956 // Export this function to enforce exporting this static variable even 12957 // if it is not used in this compilation unit. 12958 if (!FD->hasAttr<DLLExportAttr>()) 12959 FD->addAttr(NewAttr); 12960 12961 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 12962 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 12963 NewAttr->setInherited(true); 12964 VD->addAttr(NewAttr); 12965 } 12966 } 12967 12968 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 12969 /// any semantic actions necessary after any initializer has been attached. 12970 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 12971 // Note that we are no longer parsing the initializer for this declaration. 12972 ParsingInitForAutoVars.erase(ThisDecl); 12973 12974 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 12975 if (!VD) 12976 return; 12977 12978 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 12979 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 12980 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 12981 if (PragmaClangBSSSection.Valid) 12982 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 12983 Context, PragmaClangBSSSection.SectionName, 12984 PragmaClangBSSSection.PragmaLocation, 12985 AttributeCommonInfo::AS_Pragma)); 12986 if (PragmaClangDataSection.Valid) 12987 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 12988 Context, PragmaClangDataSection.SectionName, 12989 PragmaClangDataSection.PragmaLocation, 12990 AttributeCommonInfo::AS_Pragma)); 12991 if (PragmaClangRodataSection.Valid) 12992 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 12993 Context, PragmaClangRodataSection.SectionName, 12994 PragmaClangRodataSection.PragmaLocation, 12995 AttributeCommonInfo::AS_Pragma)); 12996 if (PragmaClangRelroSection.Valid) 12997 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 12998 Context, PragmaClangRelroSection.SectionName, 12999 PragmaClangRelroSection.PragmaLocation, 13000 AttributeCommonInfo::AS_Pragma)); 13001 } 13002 13003 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13004 for (auto *BD : DD->bindings()) { 13005 FinalizeDeclaration(BD); 13006 } 13007 } 13008 13009 checkAttributesAfterMerging(*this, *VD); 13010 13011 // Perform TLS alignment check here after attributes attached to the variable 13012 // which may affect the alignment have been processed. Only perform the check 13013 // if the target has a maximum TLS alignment (zero means no constraints). 13014 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13015 // Protect the check so that it's not performed on dependent types and 13016 // dependent alignments (we can't determine the alignment in that case). 13017 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 13018 !VD->isInvalidDecl()) { 13019 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13020 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13021 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13022 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13023 << (unsigned)MaxAlignChars.getQuantity(); 13024 } 13025 } 13026 } 13027 13028 if (VD->isStaticLocal()) { 13029 CheckStaticLocalForDllExport(VD); 13030 13031 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 13032 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 13033 // function, only __shared__ variables or variables without any device 13034 // memory qualifiers may be declared with static storage class. 13035 // Note: It is unclear how a function-scope non-const static variable 13036 // without device memory qualifier is implemented, therefore only static 13037 // const variable without device memory qualifier is allowed. 13038 [&]() { 13039 if (!getLangOpts().CUDA) 13040 return; 13041 if (VD->hasAttr<CUDASharedAttr>()) 13042 return; 13043 if (VD->getType().isConstQualified() && 13044 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 13045 return; 13046 if (CUDADiagIfDeviceCode(VD->getLocation(), 13047 diag::err_device_static_local_var) 13048 << CurrentCUDATarget()) 13049 VD->setInvalidDecl(); 13050 }(); 13051 } 13052 } 13053 13054 // Perform check for initializers of device-side global variables. 13055 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13056 // 7.5). We must also apply the same checks to all __shared__ 13057 // variables whether they are local or not. CUDA also allows 13058 // constant initializers for __constant__ and __device__ variables. 13059 if (getLangOpts().CUDA) 13060 checkAllowedCUDAInitializer(VD); 13061 13062 // Grab the dllimport or dllexport attribute off of the VarDecl. 13063 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13064 13065 // Imported static data members cannot be defined out-of-line. 13066 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13067 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13068 VD->isThisDeclarationADefinition()) { 13069 // We allow definitions of dllimport class template static data members 13070 // with a warning. 13071 CXXRecordDecl *Context = 13072 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13073 bool IsClassTemplateMember = 13074 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13075 Context->getDescribedClassTemplate(); 13076 13077 Diag(VD->getLocation(), 13078 IsClassTemplateMember 13079 ? diag::warn_attribute_dllimport_static_field_definition 13080 : diag::err_attribute_dllimport_static_field_definition); 13081 Diag(IA->getLocation(), diag::note_attribute); 13082 if (!IsClassTemplateMember) 13083 VD->setInvalidDecl(); 13084 } 13085 } 13086 13087 // dllimport/dllexport variables cannot be thread local, their TLS index 13088 // isn't exported with the variable. 13089 if (DLLAttr && VD->getTLSKind()) { 13090 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13091 if (F && getDLLAttr(F)) { 13092 assert(VD->isStaticLocal()); 13093 // But if this is a static local in a dlimport/dllexport function, the 13094 // function will never be inlined, which means the var would never be 13095 // imported, so having it marked import/export is safe. 13096 } else { 13097 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13098 << DLLAttr; 13099 VD->setInvalidDecl(); 13100 } 13101 } 13102 13103 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13104 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13105 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 13106 VD->dropAttr<UsedAttr>(); 13107 } 13108 } 13109 13110 const DeclContext *DC = VD->getDeclContext(); 13111 // If there's a #pragma GCC visibility in scope, and this isn't a class 13112 // member, set the visibility of this variable. 13113 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13114 AddPushedVisibilityAttribute(VD); 13115 13116 // FIXME: Warn on unused var template partial specializations. 13117 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13118 MarkUnusedFileScopedDecl(VD); 13119 13120 // Now we have parsed the initializer and can update the table of magic 13121 // tag values. 13122 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13123 !VD->getType()->isIntegralOrEnumerationType()) 13124 return; 13125 13126 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13127 const Expr *MagicValueExpr = VD->getInit(); 13128 if (!MagicValueExpr) { 13129 continue; 13130 } 13131 llvm::APSInt MagicValueInt; 13132 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 13133 Diag(I->getRange().getBegin(), 13134 diag::err_type_tag_for_datatype_not_ice) 13135 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13136 continue; 13137 } 13138 if (MagicValueInt.getActiveBits() > 64) { 13139 Diag(I->getRange().getBegin(), 13140 diag::err_type_tag_for_datatype_too_large) 13141 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13142 continue; 13143 } 13144 uint64_t MagicValue = MagicValueInt.getZExtValue(); 13145 RegisterTypeTagForDatatype(I->getArgumentKind(), 13146 MagicValue, 13147 I->getMatchingCType(), 13148 I->getLayoutCompatible(), 13149 I->getMustBeNull()); 13150 } 13151 } 13152 13153 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13154 auto *VD = dyn_cast<VarDecl>(DD); 13155 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13156 } 13157 13158 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13159 ArrayRef<Decl *> Group) { 13160 SmallVector<Decl*, 8> Decls; 13161 13162 if (DS.isTypeSpecOwned()) 13163 Decls.push_back(DS.getRepAsDecl()); 13164 13165 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13166 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13167 bool DiagnosedMultipleDecomps = false; 13168 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13169 bool DiagnosedNonDeducedAuto = false; 13170 13171 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13172 if (Decl *D = Group[i]) { 13173 // For declarators, there are some additional syntactic-ish checks we need 13174 // to perform. 13175 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13176 if (!FirstDeclaratorInGroup) 13177 FirstDeclaratorInGroup = DD; 13178 if (!FirstDecompDeclaratorInGroup) 13179 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13180 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13181 !hasDeducedAuto(DD)) 13182 FirstNonDeducedAutoInGroup = DD; 13183 13184 if (FirstDeclaratorInGroup != DD) { 13185 // A decomposition declaration cannot be combined with any other 13186 // declaration in the same group. 13187 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13188 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13189 diag::err_decomp_decl_not_alone) 13190 << FirstDeclaratorInGroup->getSourceRange() 13191 << DD->getSourceRange(); 13192 DiagnosedMultipleDecomps = true; 13193 } 13194 13195 // A declarator that uses 'auto' in any way other than to declare a 13196 // variable with a deduced type cannot be combined with any other 13197 // declarator in the same group. 13198 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13199 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13200 diag::err_auto_non_deduced_not_alone) 13201 << FirstNonDeducedAutoInGroup->getType() 13202 ->hasAutoForTrailingReturnType() 13203 << FirstDeclaratorInGroup->getSourceRange() 13204 << DD->getSourceRange(); 13205 DiagnosedNonDeducedAuto = true; 13206 } 13207 } 13208 } 13209 13210 Decls.push_back(D); 13211 } 13212 } 13213 13214 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13215 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13216 handleTagNumbering(Tag, S); 13217 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13218 getLangOpts().CPlusPlus) 13219 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13220 } 13221 } 13222 13223 return BuildDeclaratorGroup(Decls); 13224 } 13225 13226 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13227 /// group, performing any necessary semantic checking. 13228 Sema::DeclGroupPtrTy 13229 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13230 // C++14 [dcl.spec.auto]p7: (DR1347) 13231 // If the type that replaces the placeholder type is not the same in each 13232 // deduction, the program is ill-formed. 13233 if (Group.size() > 1) { 13234 QualType Deduced; 13235 VarDecl *DeducedDecl = nullptr; 13236 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13237 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13238 if (!D || D->isInvalidDecl()) 13239 break; 13240 DeducedType *DT = D->getType()->getContainedDeducedType(); 13241 if (!DT || DT->getDeducedType().isNull()) 13242 continue; 13243 if (Deduced.isNull()) { 13244 Deduced = DT->getDeducedType(); 13245 DeducedDecl = D; 13246 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13247 auto *AT = dyn_cast<AutoType>(DT); 13248 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13249 diag::err_auto_different_deductions) 13250 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13251 << DeducedDecl->getDeclName() << DT->getDeducedType() 13252 << D->getDeclName(); 13253 if (DeducedDecl->hasInit()) 13254 Dia << DeducedDecl->getInit()->getSourceRange(); 13255 if (D->getInit()) 13256 Dia << D->getInit()->getSourceRange(); 13257 D->setInvalidDecl(); 13258 break; 13259 } 13260 } 13261 } 13262 13263 ActOnDocumentableDecls(Group); 13264 13265 return DeclGroupPtrTy::make( 13266 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13267 } 13268 13269 void Sema::ActOnDocumentableDecl(Decl *D) { 13270 ActOnDocumentableDecls(D); 13271 } 13272 13273 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13274 // Don't parse the comment if Doxygen diagnostics are ignored. 13275 if (Group.empty() || !Group[0]) 13276 return; 13277 13278 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13279 Group[0]->getLocation()) && 13280 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13281 Group[0]->getLocation())) 13282 return; 13283 13284 if (Group.size() >= 2) { 13285 // This is a decl group. Normally it will contain only declarations 13286 // produced from declarator list. But in case we have any definitions or 13287 // additional declaration references: 13288 // 'typedef struct S {} S;' 13289 // 'typedef struct S *S;' 13290 // 'struct S *pS;' 13291 // FinalizeDeclaratorGroup adds these as separate declarations. 13292 Decl *MaybeTagDecl = Group[0]; 13293 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13294 Group = Group.slice(1); 13295 } 13296 } 13297 13298 // FIMXE: We assume every Decl in the group is in the same file. 13299 // This is false when preprocessor constructs the group from decls in 13300 // different files (e. g. macros or #include). 13301 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13302 } 13303 13304 /// Common checks for a parameter-declaration that should apply to both function 13305 /// parameters and non-type template parameters. 13306 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13307 // Check that there are no default arguments inside the type of this 13308 // parameter. 13309 if (getLangOpts().CPlusPlus) 13310 CheckExtraCXXDefaultArguments(D); 13311 13312 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13313 if (D.getCXXScopeSpec().isSet()) { 13314 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13315 << D.getCXXScopeSpec().getRange(); 13316 } 13317 13318 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13319 // simple identifier except [...irrelevant cases...]. 13320 switch (D.getName().getKind()) { 13321 case UnqualifiedIdKind::IK_Identifier: 13322 break; 13323 13324 case UnqualifiedIdKind::IK_OperatorFunctionId: 13325 case UnqualifiedIdKind::IK_ConversionFunctionId: 13326 case UnqualifiedIdKind::IK_LiteralOperatorId: 13327 case UnqualifiedIdKind::IK_ConstructorName: 13328 case UnqualifiedIdKind::IK_DestructorName: 13329 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13330 case UnqualifiedIdKind::IK_DeductionGuideName: 13331 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13332 << GetNameForDeclarator(D).getName(); 13333 break; 13334 13335 case UnqualifiedIdKind::IK_TemplateId: 13336 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13337 // GetNameForDeclarator would not produce a useful name in this case. 13338 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13339 break; 13340 } 13341 } 13342 13343 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13344 /// to introduce parameters into function prototype scope. 13345 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13346 const DeclSpec &DS = D.getDeclSpec(); 13347 13348 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13349 13350 // C++03 [dcl.stc]p2 also permits 'auto'. 13351 StorageClass SC = SC_None; 13352 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13353 SC = SC_Register; 13354 // In C++11, the 'register' storage class specifier is deprecated. 13355 // In C++17, it is not allowed, but we tolerate it as an extension. 13356 if (getLangOpts().CPlusPlus11) { 13357 Diag(DS.getStorageClassSpecLoc(), 13358 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13359 : diag::warn_deprecated_register) 13360 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13361 } 13362 } else if (getLangOpts().CPlusPlus && 13363 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13364 SC = SC_Auto; 13365 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13366 Diag(DS.getStorageClassSpecLoc(), 13367 diag::err_invalid_storage_class_in_func_decl); 13368 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13369 } 13370 13371 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13372 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13373 << DeclSpec::getSpecifierName(TSCS); 13374 if (DS.isInlineSpecified()) 13375 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13376 << getLangOpts().CPlusPlus17; 13377 if (DS.hasConstexprSpecifier()) 13378 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13379 << 0 << D.getDeclSpec().getConstexprSpecifier(); 13380 13381 DiagnoseFunctionSpecifiers(DS); 13382 13383 CheckFunctionOrTemplateParamDeclarator(S, D); 13384 13385 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13386 QualType parmDeclType = TInfo->getType(); 13387 13388 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13389 IdentifierInfo *II = D.getIdentifier(); 13390 if (II) { 13391 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13392 ForVisibleRedeclaration); 13393 LookupName(R, S); 13394 if (R.isSingleResult()) { 13395 NamedDecl *PrevDecl = R.getFoundDecl(); 13396 if (PrevDecl->isTemplateParameter()) { 13397 // Maybe we will complain about the shadowed template parameter. 13398 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13399 // Just pretend that we didn't see the previous declaration. 13400 PrevDecl = nullptr; 13401 } else if (S->isDeclScope(PrevDecl)) { 13402 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13403 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13404 13405 // Recover by removing the name 13406 II = nullptr; 13407 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13408 D.setInvalidType(true); 13409 } 13410 } 13411 } 13412 13413 // Temporarily put parameter variables in the translation unit, not 13414 // the enclosing context. This prevents them from accidentally 13415 // looking like class members in C++. 13416 ParmVarDecl *New = 13417 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13418 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13419 13420 if (D.isInvalidType()) 13421 New->setInvalidDecl(); 13422 13423 assert(S->isFunctionPrototypeScope()); 13424 assert(S->getFunctionPrototypeDepth() >= 1); 13425 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13426 S->getNextFunctionPrototypeIndex()); 13427 13428 // Add the parameter declaration into this scope. 13429 S->AddDecl(New); 13430 if (II) 13431 IdResolver.AddDecl(New); 13432 13433 ProcessDeclAttributes(S, New, D); 13434 13435 if (D.getDeclSpec().isModulePrivateSpecified()) 13436 Diag(New->getLocation(), diag::err_module_private_local) 13437 << 1 << New->getDeclName() 13438 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13439 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13440 13441 if (New->hasAttr<BlocksAttr>()) { 13442 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13443 } 13444 13445 if (getLangOpts().OpenCL) 13446 deduceOpenCLAddressSpace(New); 13447 13448 return New; 13449 } 13450 13451 /// Synthesizes a variable for a parameter arising from a 13452 /// typedef. 13453 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13454 SourceLocation Loc, 13455 QualType T) { 13456 /* FIXME: setting StartLoc == Loc. 13457 Would it be worth to modify callers so as to provide proper source 13458 location for the unnamed parameters, embedding the parameter's type? */ 13459 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13460 T, Context.getTrivialTypeSourceInfo(T, Loc), 13461 SC_None, nullptr); 13462 Param->setImplicit(); 13463 return Param; 13464 } 13465 13466 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13467 // Don't diagnose unused-parameter errors in template instantiations; we 13468 // will already have done so in the template itself. 13469 if (inTemplateInstantiation()) 13470 return; 13471 13472 for (const ParmVarDecl *Parameter : Parameters) { 13473 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13474 !Parameter->hasAttr<UnusedAttr>()) { 13475 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13476 << Parameter->getDeclName(); 13477 } 13478 } 13479 } 13480 13481 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13482 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13483 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13484 return; 13485 13486 // Warn if the return value is pass-by-value and larger than the specified 13487 // threshold. 13488 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13489 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13490 if (Size > LangOpts.NumLargeByValueCopy) 13491 Diag(D->getLocation(), diag::warn_return_value_size) 13492 << D->getDeclName() << Size; 13493 } 13494 13495 // Warn if any parameter is pass-by-value and larger than the specified 13496 // threshold. 13497 for (const ParmVarDecl *Parameter : Parameters) { 13498 QualType T = Parameter->getType(); 13499 if (T->isDependentType() || !T.isPODType(Context)) 13500 continue; 13501 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13502 if (Size > LangOpts.NumLargeByValueCopy) 13503 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13504 << Parameter->getDeclName() << Size; 13505 } 13506 } 13507 13508 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13509 SourceLocation NameLoc, IdentifierInfo *Name, 13510 QualType T, TypeSourceInfo *TSInfo, 13511 StorageClass SC) { 13512 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13513 if (getLangOpts().ObjCAutoRefCount && 13514 T.getObjCLifetime() == Qualifiers::OCL_None && 13515 T->isObjCLifetimeType()) { 13516 13517 Qualifiers::ObjCLifetime lifetime; 13518 13519 // Special cases for arrays: 13520 // - if it's const, use __unsafe_unretained 13521 // - otherwise, it's an error 13522 if (T->isArrayType()) { 13523 if (!T.isConstQualified()) { 13524 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13525 DelayedDiagnostics.add( 13526 sema::DelayedDiagnostic::makeForbiddenType( 13527 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13528 else 13529 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13530 << TSInfo->getTypeLoc().getSourceRange(); 13531 } 13532 lifetime = Qualifiers::OCL_ExplicitNone; 13533 } else { 13534 lifetime = T->getObjCARCImplicitLifetime(); 13535 } 13536 T = Context.getLifetimeQualifiedType(T, lifetime); 13537 } 13538 13539 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13540 Context.getAdjustedParameterType(T), 13541 TSInfo, SC, nullptr); 13542 13543 // Make a note if we created a new pack in the scope of a lambda, so that 13544 // we know that references to that pack must also be expanded within the 13545 // lambda scope. 13546 if (New->isParameterPack()) 13547 if (auto *LSI = getEnclosingLambda()) 13548 LSI->LocalPacks.push_back(New); 13549 13550 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13551 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13552 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13553 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13554 13555 // Parameters can not be abstract class types. 13556 // For record types, this is done by the AbstractClassUsageDiagnoser once 13557 // the class has been completely parsed. 13558 if (!CurContext->isRecord() && 13559 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13560 AbstractParamType)) 13561 New->setInvalidDecl(); 13562 13563 // Parameter declarators cannot be interface types. All ObjC objects are 13564 // passed by reference. 13565 if (T->isObjCObjectType()) { 13566 SourceLocation TypeEndLoc = 13567 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13568 Diag(NameLoc, 13569 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13570 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13571 T = Context.getObjCObjectPointerType(T); 13572 New->setType(T); 13573 } 13574 13575 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13576 // duration shall not be qualified by an address-space qualifier." 13577 // Since all parameters have automatic store duration, they can not have 13578 // an address space. 13579 if (T.getAddressSpace() != LangAS::Default && 13580 // OpenCL allows function arguments declared to be an array of a type 13581 // to be qualified with an address space. 13582 !(getLangOpts().OpenCL && 13583 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13584 Diag(NameLoc, diag::err_arg_with_address_space); 13585 New->setInvalidDecl(); 13586 } 13587 13588 return New; 13589 } 13590 13591 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13592 SourceLocation LocAfterDecls) { 13593 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13594 13595 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13596 // for a K&R function. 13597 if (!FTI.hasPrototype) { 13598 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13599 --i; 13600 if (FTI.Params[i].Param == nullptr) { 13601 SmallString<256> Code; 13602 llvm::raw_svector_ostream(Code) 13603 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13604 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13605 << FTI.Params[i].Ident 13606 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13607 13608 // Implicitly declare the argument as type 'int' for lack of a better 13609 // type. 13610 AttributeFactory attrs; 13611 DeclSpec DS(attrs); 13612 const char* PrevSpec; // unused 13613 unsigned DiagID; // unused 13614 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13615 DiagID, Context.getPrintingPolicy()); 13616 // Use the identifier location for the type source range. 13617 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13618 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13619 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 13620 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13621 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13622 } 13623 } 13624 } 13625 } 13626 13627 Decl * 13628 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13629 MultiTemplateParamsArg TemplateParameterLists, 13630 SkipBodyInfo *SkipBody) { 13631 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13632 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13633 Scope *ParentScope = FnBodyScope->getParent(); 13634 13635 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 13636 // we define a non-templated function definition, we will create a declaration 13637 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 13638 // The base function declaration will have the equivalent of an `omp declare 13639 // variant` annotation which specifies the mangled definition as a 13640 // specialization function under the OpenMP context defined as part of the 13641 // `omp begin declare variant`. 13642 FunctionDecl *BaseFD = nullptr; 13643 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope() && 13644 TemplateParameterLists.empty()) 13645 BaseFD = ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 13646 ParentScope, D); 13647 13648 D.setFunctionDefinitionKind(FDK_Definition); 13649 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13650 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13651 13652 if (BaseFD) 13653 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 13654 cast<FunctionDecl>(Dcl), BaseFD); 13655 13656 return Dcl; 13657 } 13658 13659 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13660 Consumer.HandleInlineFunctionDefinition(D); 13661 } 13662 13663 static bool 13664 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13665 const FunctionDecl *&PossiblePrototype) { 13666 // Don't warn about invalid declarations. 13667 if (FD->isInvalidDecl()) 13668 return false; 13669 13670 // Or declarations that aren't global. 13671 if (!FD->isGlobal()) 13672 return false; 13673 13674 // Don't warn about C++ member functions. 13675 if (isa<CXXMethodDecl>(FD)) 13676 return false; 13677 13678 // Don't warn about 'main'. 13679 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13680 if (IdentifierInfo *II = FD->getIdentifier()) 13681 if (II->isStr("main")) 13682 return false; 13683 13684 // Don't warn about inline functions. 13685 if (FD->isInlined()) 13686 return false; 13687 13688 // Don't warn about function templates. 13689 if (FD->getDescribedFunctionTemplate()) 13690 return false; 13691 13692 // Don't warn about function template specializations. 13693 if (FD->isFunctionTemplateSpecialization()) 13694 return false; 13695 13696 // Don't warn for OpenCL kernels. 13697 if (FD->hasAttr<OpenCLKernelAttr>()) 13698 return false; 13699 13700 // Don't warn on explicitly deleted functions. 13701 if (FD->isDeleted()) 13702 return false; 13703 13704 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13705 Prev; Prev = Prev->getPreviousDecl()) { 13706 // Ignore any declarations that occur in function or method 13707 // scope, because they aren't visible from the header. 13708 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13709 continue; 13710 13711 PossiblePrototype = Prev; 13712 return Prev->getType()->isFunctionNoProtoType(); 13713 } 13714 13715 return true; 13716 } 13717 13718 void 13719 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13720 const FunctionDecl *EffectiveDefinition, 13721 SkipBodyInfo *SkipBody) { 13722 const FunctionDecl *Definition = EffectiveDefinition; 13723 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 13724 // If this is a friend function defined in a class template, it does not 13725 // have a body until it is used, nevertheless it is a definition, see 13726 // [temp.inst]p2: 13727 // 13728 // ... for the purpose of determining whether an instantiated redeclaration 13729 // is valid according to [basic.def.odr] and [class.mem], a declaration that 13730 // corresponds to a definition in the template is considered to be a 13731 // definition. 13732 // 13733 // The following code must produce redefinition error: 13734 // 13735 // template<typename T> struct C20 { friend void func_20() {} }; 13736 // C20<int> c20i; 13737 // void func_20() {} 13738 // 13739 for (auto I : FD->redecls()) { 13740 if (I != FD && !I->isInvalidDecl() && 13741 I->getFriendObjectKind() != Decl::FOK_None) { 13742 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 13743 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13744 // A merged copy of the same function, instantiated as a member of 13745 // the same class, is OK. 13746 if (declaresSameEntity(OrigFD, Original) && 13747 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 13748 cast<Decl>(FD->getLexicalDeclContext()))) 13749 continue; 13750 } 13751 13752 if (Original->isThisDeclarationADefinition()) { 13753 Definition = I; 13754 break; 13755 } 13756 } 13757 } 13758 } 13759 } 13760 13761 if (!Definition) 13762 // Similar to friend functions a friend function template may be a 13763 // definition and do not have a body if it is instantiated in a class 13764 // template. 13765 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 13766 for (auto I : FTD->redecls()) { 13767 auto D = cast<FunctionTemplateDecl>(I); 13768 if (D != FTD) { 13769 assert(!D->isThisDeclarationADefinition() && 13770 "More than one definition in redeclaration chain"); 13771 if (D->getFriendObjectKind() != Decl::FOK_None) 13772 if (FunctionTemplateDecl *FT = 13773 D->getInstantiatedFromMemberTemplate()) { 13774 if (FT->isThisDeclarationADefinition()) { 13775 Definition = D->getTemplatedDecl(); 13776 break; 13777 } 13778 } 13779 } 13780 } 13781 } 13782 13783 if (!Definition) 13784 return; 13785 13786 if (canRedefineFunction(Definition, getLangOpts())) 13787 return; 13788 13789 // Don't emit an error when this is redefinition of a typo-corrected 13790 // definition. 13791 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13792 return; 13793 13794 // If we don't have a visible definition of the function, and it's inline or 13795 // a template, skip the new definition. 13796 if (SkipBody && !hasVisibleDefinition(Definition) && 13797 (Definition->getFormalLinkage() == InternalLinkage || 13798 Definition->isInlined() || 13799 Definition->getDescribedFunctionTemplate() || 13800 Definition->getNumTemplateParameterLists())) { 13801 SkipBody->ShouldSkip = true; 13802 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 13803 if (auto *TD = Definition->getDescribedFunctionTemplate()) 13804 makeMergedDefinitionVisible(TD); 13805 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 13806 return; 13807 } 13808 13809 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 13810 Definition->getStorageClass() == SC_Extern) 13811 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 13812 << FD->getDeclName() << getLangOpts().CPlusPlus; 13813 else 13814 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 13815 13816 Diag(Definition->getLocation(), diag::note_previous_definition); 13817 FD->setInvalidDecl(); 13818 } 13819 13820 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 13821 Sema &S) { 13822 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 13823 13824 LambdaScopeInfo *LSI = S.PushLambdaScope(); 13825 LSI->CallOperator = CallOperator; 13826 LSI->Lambda = LambdaClass; 13827 LSI->ReturnType = CallOperator->getReturnType(); 13828 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 13829 13830 if (LCD == LCD_None) 13831 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 13832 else if (LCD == LCD_ByCopy) 13833 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 13834 else if (LCD == LCD_ByRef) 13835 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 13836 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 13837 13838 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 13839 LSI->Mutable = !CallOperator->isConst(); 13840 13841 // Add the captures to the LSI so they can be noted as already 13842 // captured within tryCaptureVar. 13843 auto I = LambdaClass->field_begin(); 13844 for (const auto &C : LambdaClass->captures()) { 13845 if (C.capturesVariable()) { 13846 VarDecl *VD = C.getCapturedVar(); 13847 if (VD->isInitCapture()) 13848 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 13849 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 13850 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 13851 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 13852 /*EllipsisLoc*/C.isPackExpansion() 13853 ? C.getEllipsisLoc() : SourceLocation(), 13854 I->getType(), /*Invalid*/false); 13855 13856 } else if (C.capturesThis()) { 13857 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 13858 C.getCaptureKind() == LCK_StarThis); 13859 } else { 13860 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 13861 I->getType()); 13862 } 13863 ++I; 13864 } 13865 } 13866 13867 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 13868 SkipBodyInfo *SkipBody) { 13869 if (!D) { 13870 // Parsing the function declaration failed in some way. Push on a fake scope 13871 // anyway so we can try to parse the function body. 13872 PushFunctionScope(); 13873 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13874 return D; 13875 } 13876 13877 FunctionDecl *FD = nullptr; 13878 13879 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 13880 FD = FunTmpl->getTemplatedDecl(); 13881 else 13882 FD = cast<FunctionDecl>(D); 13883 13884 // Do not push if it is a lambda because one is already pushed when building 13885 // the lambda in ActOnStartOfLambdaDefinition(). 13886 if (!isLambdaCallOperator(FD)) 13887 PushExpressionEvaluationContext( 13888 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 13889 : ExprEvalContexts.back().Context); 13890 13891 // Check for defining attributes before the check for redefinition. 13892 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 13893 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 13894 FD->dropAttr<AliasAttr>(); 13895 FD->setInvalidDecl(); 13896 } 13897 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 13898 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 13899 FD->dropAttr<IFuncAttr>(); 13900 FD->setInvalidDecl(); 13901 } 13902 13903 // See if this is a redefinition. If 'will have body' is already set, then 13904 // these checks were already performed when it was set. 13905 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 13906 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 13907 13908 // If we're skipping the body, we're done. Don't enter the scope. 13909 if (SkipBody && SkipBody->ShouldSkip) 13910 return D; 13911 } 13912 13913 // Mark this function as "will have a body eventually". This lets users to 13914 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 13915 // this function. 13916 FD->setWillHaveBody(); 13917 13918 // If we are instantiating a generic lambda call operator, push 13919 // a LambdaScopeInfo onto the function stack. But use the information 13920 // that's already been calculated (ActOnLambdaExpr) to prime the current 13921 // LambdaScopeInfo. 13922 // When the template operator is being specialized, the LambdaScopeInfo, 13923 // has to be properly restored so that tryCaptureVariable doesn't try 13924 // and capture any new variables. In addition when calculating potential 13925 // captures during transformation of nested lambdas, it is necessary to 13926 // have the LSI properly restored. 13927 if (isGenericLambdaCallOperatorSpecialization(FD)) { 13928 assert(inTemplateInstantiation() && 13929 "There should be an active template instantiation on the stack " 13930 "when instantiating a generic lambda!"); 13931 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 13932 } else { 13933 // Enter a new function scope 13934 PushFunctionScope(); 13935 } 13936 13937 // Builtin functions cannot be defined. 13938 if (unsigned BuiltinID = FD->getBuiltinID()) { 13939 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 13940 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 13941 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 13942 FD->setInvalidDecl(); 13943 } 13944 } 13945 13946 // The return type of a function definition must be complete 13947 // (C99 6.9.1p3, C++ [dcl.fct]p6). 13948 QualType ResultType = FD->getReturnType(); 13949 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 13950 !FD->isInvalidDecl() && 13951 RequireCompleteType(FD->getLocation(), ResultType, 13952 diag::err_func_def_incomplete_result)) 13953 FD->setInvalidDecl(); 13954 13955 if (FnBodyScope) 13956 PushDeclContext(FnBodyScope, FD); 13957 13958 // Check the validity of our function parameters 13959 CheckParmsForFunctionDef(FD->parameters(), 13960 /*CheckParameterNames=*/true); 13961 13962 // Add non-parameter declarations already in the function to the current 13963 // scope. 13964 if (FnBodyScope) { 13965 for (Decl *NPD : FD->decls()) { 13966 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 13967 if (!NonParmDecl) 13968 continue; 13969 assert(!isa<ParmVarDecl>(NonParmDecl) && 13970 "parameters should not be in newly created FD yet"); 13971 13972 // If the decl has a name, make it accessible in the current scope. 13973 if (NonParmDecl->getDeclName()) 13974 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 13975 13976 // Similarly, dive into enums and fish their constants out, making them 13977 // accessible in this scope. 13978 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 13979 for (auto *EI : ED->enumerators()) 13980 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 13981 } 13982 } 13983 } 13984 13985 // Introduce our parameters into the function scope 13986 for (auto Param : FD->parameters()) { 13987 Param->setOwningFunction(FD); 13988 13989 // If this has an identifier, add it to the scope stack. 13990 if (Param->getIdentifier() && FnBodyScope) { 13991 CheckShadow(FnBodyScope, Param); 13992 13993 PushOnScopeChains(Param, FnBodyScope); 13994 } 13995 } 13996 13997 // Ensure that the function's exception specification is instantiated. 13998 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 13999 ResolveExceptionSpec(D->getLocation(), FPT); 14000 14001 // dllimport cannot be applied to non-inline function definitions. 14002 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14003 !FD->isTemplateInstantiation()) { 14004 assert(!FD->hasAttr<DLLExportAttr>()); 14005 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14006 FD->setInvalidDecl(); 14007 return D; 14008 } 14009 // We want to attach documentation to original Decl (which might be 14010 // a function template). 14011 ActOnDocumentableDecl(D); 14012 if (getCurLexicalContext()->isObjCContainer() && 14013 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14014 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14015 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14016 14017 return D; 14018 } 14019 14020 /// Given the set of return statements within a function body, 14021 /// compute the variables that are subject to the named return value 14022 /// optimization. 14023 /// 14024 /// Each of the variables that is subject to the named return value 14025 /// optimization will be marked as NRVO variables in the AST, and any 14026 /// return statement that has a marked NRVO variable as its NRVO candidate can 14027 /// use the named return value optimization. 14028 /// 14029 /// This function applies a very simplistic algorithm for NRVO: if every return 14030 /// statement in the scope of a variable has the same NRVO candidate, that 14031 /// candidate is an NRVO variable. 14032 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14033 ReturnStmt **Returns = Scope->Returns.data(); 14034 14035 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14036 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14037 if (!NRVOCandidate->isNRVOVariable()) 14038 Returns[I]->setNRVOCandidate(nullptr); 14039 } 14040 } 14041 } 14042 14043 bool Sema::canDelayFunctionBody(const Declarator &D) { 14044 // We can't delay parsing the body of a constexpr function template (yet). 14045 if (D.getDeclSpec().hasConstexprSpecifier()) 14046 return false; 14047 14048 // We can't delay parsing the body of a function template with a deduced 14049 // return type (yet). 14050 if (D.getDeclSpec().hasAutoTypeSpec()) { 14051 // If the placeholder introduces a non-deduced trailing return type, 14052 // we can still delay parsing it. 14053 if (D.getNumTypeObjects()) { 14054 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14055 if (Outer.Kind == DeclaratorChunk::Function && 14056 Outer.Fun.hasTrailingReturnType()) { 14057 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14058 return Ty.isNull() || !Ty->isUndeducedType(); 14059 } 14060 } 14061 return false; 14062 } 14063 14064 return true; 14065 } 14066 14067 bool Sema::canSkipFunctionBody(Decl *D) { 14068 // We cannot skip the body of a function (or function template) which is 14069 // constexpr, since we may need to evaluate its body in order to parse the 14070 // rest of the file. 14071 // We cannot skip the body of a function with an undeduced return type, 14072 // because any callers of that function need to know the type. 14073 if (const FunctionDecl *FD = D->getAsFunction()) { 14074 if (FD->isConstexpr()) 14075 return false; 14076 // We can't simply call Type::isUndeducedType here, because inside template 14077 // auto can be deduced to a dependent type, which is not considered 14078 // "undeduced". 14079 if (FD->getReturnType()->getContainedDeducedType()) 14080 return false; 14081 } 14082 return Consumer.shouldSkipFunctionBody(D); 14083 } 14084 14085 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14086 if (!Decl) 14087 return nullptr; 14088 if (FunctionDecl *FD = Decl->getAsFunction()) 14089 FD->setHasSkippedBody(); 14090 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14091 MD->setHasSkippedBody(); 14092 return Decl; 14093 } 14094 14095 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14096 return ActOnFinishFunctionBody(D, BodyArg, false); 14097 } 14098 14099 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14100 /// body. 14101 class ExitFunctionBodyRAII { 14102 public: 14103 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14104 ~ExitFunctionBodyRAII() { 14105 if (!IsLambda) 14106 S.PopExpressionEvaluationContext(); 14107 } 14108 14109 private: 14110 Sema &S; 14111 bool IsLambda = false; 14112 }; 14113 14114 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14115 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14116 14117 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14118 if (EscapeInfo.count(BD)) 14119 return EscapeInfo[BD]; 14120 14121 bool R = false; 14122 const BlockDecl *CurBD = BD; 14123 14124 do { 14125 R = !CurBD->doesNotEscape(); 14126 if (R) 14127 break; 14128 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14129 } while (CurBD); 14130 14131 return EscapeInfo[BD] = R; 14132 }; 14133 14134 // If the location where 'self' is implicitly retained is inside a escaping 14135 // block, emit a diagnostic. 14136 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14137 S.ImplicitlyRetainedSelfLocs) 14138 if (IsOrNestedInEscapingBlock(P.second)) 14139 S.Diag(P.first, diag::warn_implicitly_retains_self) 14140 << FixItHint::CreateInsertion(P.first, "self->"); 14141 } 14142 14143 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14144 bool IsInstantiation) { 14145 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14146 14147 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14148 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14149 14150 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) 14151 CheckCompletedCoroutineBody(FD, Body); 14152 14153 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14154 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14155 // meant to pop the context added in ActOnStartOfFunctionDef(). 14156 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14157 14158 if (FD) { 14159 FD->setBody(Body); 14160 FD->setWillHaveBody(false); 14161 14162 if (getLangOpts().CPlusPlus14) { 14163 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14164 FD->getReturnType()->isUndeducedType()) { 14165 // If the function has a deduced result type but contains no 'return' 14166 // statements, the result type as written must be exactly 'auto', and 14167 // the deduced result type is 'void'. 14168 if (!FD->getReturnType()->getAs<AutoType>()) { 14169 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14170 << FD->getReturnType(); 14171 FD->setInvalidDecl(); 14172 } else { 14173 // Substitute 'void' for the 'auto' in the type. 14174 TypeLoc ResultType = getReturnTypeLoc(FD); 14175 Context.adjustDeducedFunctionResultType( 14176 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14177 } 14178 } 14179 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14180 // In C++11, we don't use 'auto' deduction rules for lambda call 14181 // operators because we don't support return type deduction. 14182 auto *LSI = getCurLambda(); 14183 if (LSI->HasImplicitReturnType) { 14184 deduceClosureReturnType(*LSI); 14185 14186 // C++11 [expr.prim.lambda]p4: 14187 // [...] if there are no return statements in the compound-statement 14188 // [the deduced type is] the type void 14189 QualType RetType = 14190 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14191 14192 // Update the return type to the deduced type. 14193 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14194 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14195 Proto->getExtProtoInfo())); 14196 } 14197 } 14198 14199 // If the function implicitly returns zero (like 'main') or is naked, 14200 // don't complain about missing return statements. 14201 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14202 WP.disableCheckFallThrough(); 14203 14204 // MSVC permits the use of pure specifier (=0) on function definition, 14205 // defined at class scope, warn about this non-standard construct. 14206 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14207 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14208 14209 if (!FD->isInvalidDecl()) { 14210 // Don't diagnose unused parameters of defaulted or deleted functions. 14211 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14212 DiagnoseUnusedParameters(FD->parameters()); 14213 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14214 FD->getReturnType(), FD); 14215 14216 // If this is a structor, we need a vtable. 14217 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14218 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14219 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14220 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14221 14222 // Try to apply the named return value optimization. We have to check 14223 // if we can do this here because lambdas keep return statements around 14224 // to deduce an implicit return type. 14225 if (FD->getReturnType()->isRecordType() && 14226 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14227 computeNRVO(Body, getCurFunction()); 14228 } 14229 14230 // GNU warning -Wmissing-prototypes: 14231 // Warn if a global function is defined without a previous 14232 // prototype declaration. This warning is issued even if the 14233 // definition itself provides a prototype. The aim is to detect 14234 // global functions that fail to be declared in header files. 14235 const FunctionDecl *PossiblePrototype = nullptr; 14236 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14237 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14238 14239 if (PossiblePrototype) { 14240 // We found a declaration that is not a prototype, 14241 // but that could be a zero-parameter prototype 14242 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14243 TypeLoc TL = TI->getTypeLoc(); 14244 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14245 Diag(PossiblePrototype->getLocation(), 14246 diag::note_declaration_not_a_prototype) 14247 << (FD->getNumParams() != 0) 14248 << (FD->getNumParams() == 0 14249 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14250 : FixItHint{}); 14251 } 14252 } else { 14253 // Returns true if the token beginning at this Loc is `const`. 14254 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14255 const LangOptions &LangOpts) { 14256 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14257 if (LocInfo.first.isInvalid()) 14258 return false; 14259 14260 bool Invalid = false; 14261 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14262 if (Invalid) 14263 return false; 14264 14265 if (LocInfo.second > Buffer.size()) 14266 return false; 14267 14268 const char *LexStart = Buffer.data() + LocInfo.second; 14269 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14270 14271 return StartTok.consume_front("const") && 14272 (StartTok.empty() || isWhitespace(StartTok[0]) || 14273 StartTok.startswith("/*") || StartTok.startswith("//")); 14274 }; 14275 14276 auto findBeginLoc = [&]() { 14277 // If the return type has `const` qualifier, we want to insert 14278 // `static` before `const` (and not before the typename). 14279 if ((FD->getReturnType()->isAnyPointerType() && 14280 FD->getReturnType()->getPointeeType().isConstQualified()) || 14281 FD->getReturnType().isConstQualified()) { 14282 // But only do this if we can determine where the `const` is. 14283 14284 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14285 getLangOpts())) 14286 14287 return FD->getBeginLoc(); 14288 } 14289 return FD->getTypeSpecStartLoc(); 14290 }; 14291 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14292 << /* function */ 1 14293 << (FD->getStorageClass() == SC_None 14294 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14295 : FixItHint{}); 14296 } 14297 14298 // GNU warning -Wstrict-prototypes 14299 // Warn if K&R function is defined without a previous declaration. 14300 // This warning is issued only if the definition itself does not provide 14301 // a prototype. Only K&R definitions do not provide a prototype. 14302 if (!FD->hasWrittenPrototype()) { 14303 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14304 TypeLoc TL = TI->getTypeLoc(); 14305 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14306 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14307 } 14308 } 14309 14310 // Warn on CPUDispatch with an actual body. 14311 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14312 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14313 if (!CmpndBody->body_empty()) 14314 Diag(CmpndBody->body_front()->getBeginLoc(), 14315 diag::warn_dispatch_body_ignored); 14316 14317 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14318 const CXXMethodDecl *KeyFunction; 14319 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14320 MD->isVirtual() && 14321 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14322 MD == KeyFunction->getCanonicalDecl()) { 14323 // Update the key-function state if necessary for this ABI. 14324 if (FD->isInlined() && 14325 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14326 Context.setNonKeyFunction(MD); 14327 14328 // If the newly-chosen key function is already defined, then we 14329 // need to mark the vtable as used retroactively. 14330 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14331 const FunctionDecl *Definition; 14332 if (KeyFunction && KeyFunction->isDefined(Definition)) 14333 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14334 } else { 14335 // We just defined they key function; mark the vtable as used. 14336 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14337 } 14338 } 14339 } 14340 14341 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14342 "Function parsing confused"); 14343 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14344 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14345 MD->setBody(Body); 14346 if (!MD->isInvalidDecl()) { 14347 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14348 MD->getReturnType(), MD); 14349 14350 if (Body) 14351 computeNRVO(Body, getCurFunction()); 14352 } 14353 if (getCurFunction()->ObjCShouldCallSuper) { 14354 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14355 << MD->getSelector().getAsString(); 14356 getCurFunction()->ObjCShouldCallSuper = false; 14357 } 14358 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 14359 const ObjCMethodDecl *InitMethod = nullptr; 14360 bool isDesignated = 14361 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14362 assert(isDesignated && InitMethod); 14363 (void)isDesignated; 14364 14365 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14366 auto IFace = MD->getClassInterface(); 14367 if (!IFace) 14368 return false; 14369 auto SuperD = IFace->getSuperClass(); 14370 if (!SuperD) 14371 return false; 14372 return SuperD->getIdentifier() == 14373 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14374 }; 14375 // Don't issue this warning for unavailable inits or direct subclasses 14376 // of NSObject. 14377 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14378 Diag(MD->getLocation(), 14379 diag::warn_objc_designated_init_missing_super_call); 14380 Diag(InitMethod->getLocation(), 14381 diag::note_objc_designated_init_marked_here); 14382 } 14383 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 14384 } 14385 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 14386 // Don't issue this warning for unavaialable inits. 14387 if (!MD->isUnavailable()) 14388 Diag(MD->getLocation(), 14389 diag::warn_objc_secondary_init_missing_init_call); 14390 getCurFunction()->ObjCWarnForNoInitDelegation = false; 14391 } 14392 14393 diagnoseImplicitlyRetainedSelf(*this); 14394 } else { 14395 // Parsing the function declaration failed in some way. Pop the fake scope 14396 // we pushed on. 14397 PopFunctionScopeInfo(ActivePolicy, dcl); 14398 return nullptr; 14399 } 14400 14401 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14402 DiagnoseUnguardedAvailabilityViolations(dcl); 14403 14404 assert(!getCurFunction()->ObjCShouldCallSuper && 14405 "This should only be set for ObjC methods, which should have been " 14406 "handled in the block above."); 14407 14408 // Verify and clean out per-function state. 14409 if (Body && (!FD || !FD->isDefaulted())) { 14410 // C++ constructors that have function-try-blocks can't have return 14411 // statements in the handlers of that block. (C++ [except.handle]p14) 14412 // Verify this. 14413 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14414 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14415 14416 // Verify that gotos and switch cases don't jump into scopes illegally. 14417 if (getCurFunction()->NeedsScopeChecking() && 14418 !PP.isCodeCompletionEnabled()) 14419 DiagnoseInvalidJumps(Body); 14420 14421 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14422 if (!Destructor->getParent()->isDependentType()) 14423 CheckDestructor(Destructor); 14424 14425 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14426 Destructor->getParent()); 14427 } 14428 14429 // If any errors have occurred, clear out any temporaries that may have 14430 // been leftover. This ensures that these temporaries won't be picked up for 14431 // deletion in some later function. 14432 if (getDiagnostics().hasUncompilableErrorOccurred() || 14433 getDiagnostics().getSuppressAllDiagnostics()) { 14434 DiscardCleanupsInEvaluationContext(); 14435 } 14436 if (!getDiagnostics().hasUncompilableErrorOccurred() && 14437 !isa<FunctionTemplateDecl>(dcl)) { 14438 // Since the body is valid, issue any analysis-based warnings that are 14439 // enabled. 14440 ActivePolicy = &WP; 14441 } 14442 14443 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14444 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14445 FD->setInvalidDecl(); 14446 14447 if (FD && FD->hasAttr<NakedAttr>()) { 14448 for (const Stmt *S : Body->children()) { 14449 // Allow local register variables without initializer as they don't 14450 // require prologue. 14451 bool RegisterVariables = false; 14452 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14453 for (const auto *Decl : DS->decls()) { 14454 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14455 RegisterVariables = 14456 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14457 if (!RegisterVariables) 14458 break; 14459 } 14460 } 14461 } 14462 if (RegisterVariables) 14463 continue; 14464 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14465 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14466 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14467 FD->setInvalidDecl(); 14468 break; 14469 } 14470 } 14471 } 14472 14473 assert(ExprCleanupObjects.size() == 14474 ExprEvalContexts.back().NumCleanupObjects && 14475 "Leftover temporaries in function"); 14476 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14477 assert(MaybeODRUseExprs.empty() && 14478 "Leftover expressions for odr-use checking"); 14479 } 14480 14481 if (!IsInstantiation) 14482 PopDeclContext(); 14483 14484 PopFunctionScopeInfo(ActivePolicy, dcl); 14485 // If any errors have occurred, clear out any temporaries that may have 14486 // been leftover. This ensures that these temporaries won't be picked up for 14487 // deletion in some later function. 14488 if (getDiagnostics().hasUncompilableErrorOccurred()) { 14489 DiscardCleanupsInEvaluationContext(); 14490 } 14491 14492 if (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice) { 14493 auto ES = getEmissionStatus(FD); 14494 if (ES == Sema::FunctionEmissionStatus::Emitted || 14495 ES == Sema::FunctionEmissionStatus::Unknown) 14496 DeclsToCheckForDeferredDiags.push_back(FD); 14497 } 14498 14499 return dcl; 14500 } 14501 14502 /// When we finish delayed parsing of an attribute, we must attach it to the 14503 /// relevant Decl. 14504 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14505 ParsedAttributes &Attrs) { 14506 // Always attach attributes to the underlying decl. 14507 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14508 D = TD->getTemplatedDecl(); 14509 ProcessDeclAttributeList(S, D, Attrs); 14510 14511 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14512 if (Method->isStatic()) 14513 checkThisInStaticMemberFunctionAttributes(Method); 14514 } 14515 14516 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14517 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14518 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14519 IdentifierInfo &II, Scope *S) { 14520 // Find the scope in which the identifier is injected and the corresponding 14521 // DeclContext. 14522 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14523 // In that case, we inject the declaration into the translation unit scope 14524 // instead. 14525 Scope *BlockScope = S; 14526 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14527 BlockScope = BlockScope->getParent(); 14528 14529 Scope *ContextScope = BlockScope; 14530 while (!ContextScope->getEntity()) 14531 ContextScope = ContextScope->getParent(); 14532 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14533 14534 // Before we produce a declaration for an implicitly defined 14535 // function, see whether there was a locally-scoped declaration of 14536 // this name as a function or variable. If so, use that 14537 // (non-visible) declaration, and complain about it. 14538 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14539 if (ExternCPrev) { 14540 // We still need to inject the function into the enclosing block scope so 14541 // that later (non-call) uses can see it. 14542 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14543 14544 // C89 footnote 38: 14545 // If in fact it is not defined as having type "function returning int", 14546 // the behavior is undefined. 14547 if (!isa<FunctionDecl>(ExternCPrev) || 14548 !Context.typesAreCompatible( 14549 cast<FunctionDecl>(ExternCPrev)->getType(), 14550 Context.getFunctionNoProtoType(Context.IntTy))) { 14551 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14552 << ExternCPrev << !getLangOpts().C99; 14553 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14554 return ExternCPrev; 14555 } 14556 } 14557 14558 // Extension in C99. Legal in C90, but warn about it. 14559 unsigned diag_id; 14560 if (II.getName().startswith("__builtin_")) 14561 diag_id = diag::warn_builtin_unknown; 14562 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14563 else if (getLangOpts().OpenCL) 14564 diag_id = diag::err_opencl_implicit_function_decl; 14565 else if (getLangOpts().C99) 14566 diag_id = diag::ext_implicit_function_decl; 14567 else 14568 diag_id = diag::warn_implicit_function_decl; 14569 Diag(Loc, diag_id) << &II; 14570 14571 // If we found a prior declaration of this function, don't bother building 14572 // another one. We've already pushed that one into scope, so there's nothing 14573 // more to do. 14574 if (ExternCPrev) 14575 return ExternCPrev; 14576 14577 // Because typo correction is expensive, only do it if the implicit 14578 // function declaration is going to be treated as an error. 14579 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14580 TypoCorrection Corrected; 14581 DeclFilterCCC<FunctionDecl> CCC{}; 14582 if (S && (Corrected = 14583 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14584 S, nullptr, CCC, CTK_NonError))) 14585 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14586 /*ErrorRecovery*/false); 14587 } 14588 14589 // Set a Declarator for the implicit definition: int foo(); 14590 const char *Dummy; 14591 AttributeFactory attrFactory; 14592 DeclSpec DS(attrFactory); 14593 unsigned DiagID; 14594 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14595 Context.getPrintingPolicy()); 14596 (void)Error; // Silence warning. 14597 assert(!Error && "Error setting up implicit decl!"); 14598 SourceLocation NoLoc; 14599 Declarator D(DS, DeclaratorContext::BlockContext); 14600 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14601 /*IsAmbiguous=*/false, 14602 /*LParenLoc=*/NoLoc, 14603 /*Params=*/nullptr, 14604 /*NumParams=*/0, 14605 /*EllipsisLoc=*/NoLoc, 14606 /*RParenLoc=*/NoLoc, 14607 /*RefQualifierIsLvalueRef=*/true, 14608 /*RefQualifierLoc=*/NoLoc, 14609 /*MutableLoc=*/NoLoc, EST_None, 14610 /*ESpecRange=*/SourceRange(), 14611 /*Exceptions=*/nullptr, 14612 /*ExceptionRanges=*/nullptr, 14613 /*NumExceptions=*/0, 14614 /*NoexceptExpr=*/nullptr, 14615 /*ExceptionSpecTokens=*/nullptr, 14616 /*DeclsInPrototype=*/None, Loc, 14617 Loc, D), 14618 std::move(DS.getAttributes()), SourceLocation()); 14619 D.SetIdentifier(&II, Loc); 14620 14621 // Insert this function into the enclosing block scope. 14622 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14623 FD->setImplicit(); 14624 14625 AddKnownFunctionAttributes(FD); 14626 14627 return FD; 14628 } 14629 14630 /// If this function is a C++ replaceable global allocation function 14631 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14632 /// adds any function attributes that we know a priori based on the standard. 14633 /// 14634 /// We need to check for duplicate attributes both here and where user-written 14635 /// attributes are applied to declarations. 14636 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14637 FunctionDecl *FD) { 14638 if (FD->isInvalidDecl()) 14639 return; 14640 14641 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14642 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14643 return; 14644 14645 Optional<unsigned> AlignmentParam; 14646 bool IsNothrow = false; 14647 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14648 return; 14649 14650 // C++2a [basic.stc.dynamic.allocation]p4: 14651 // An allocation function that has a non-throwing exception specification 14652 // indicates failure by returning a null pointer value. Any other allocation 14653 // function never returns a null pointer value and indicates failure only by 14654 // throwing an exception [...] 14655 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14656 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14657 14658 // C++2a [basic.stc.dynamic.allocation]p2: 14659 // An allocation function attempts to allocate the requested amount of 14660 // storage. [...] If the request succeeds, the value returned by a 14661 // replaceable allocation function is a [...] pointer value p0 different 14662 // from any previously returned value p1 [...] 14663 // 14664 // However, this particular information is being added in codegen, 14665 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14666 14667 // C++2a [basic.stc.dynamic.allocation]p2: 14668 // An allocation function attempts to allocate the requested amount of 14669 // storage. If it is successful, it returns the address of the start of a 14670 // block of storage whose length in bytes is at least as large as the 14671 // requested size. 14672 if (!FD->hasAttr<AllocSizeAttr>()) { 14673 FD->addAttr(AllocSizeAttr::CreateImplicit( 14674 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14675 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14676 } 14677 14678 // C++2a [basic.stc.dynamic.allocation]p3: 14679 // For an allocation function [...], the pointer returned on a successful 14680 // call shall represent the address of storage that is aligned as follows: 14681 // (3.1) If the allocation function takes an argument of type 14682 // std::align_val_t, the storage will have the alignment 14683 // specified by the value of this argument. 14684 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14685 FD->addAttr(AllocAlignAttr::CreateImplicit( 14686 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14687 } 14688 14689 // FIXME: 14690 // C++2a [basic.stc.dynamic.allocation]p3: 14691 // For an allocation function [...], the pointer returned on a successful 14692 // call shall represent the address of storage that is aligned as follows: 14693 // (3.2) Otherwise, if the allocation function is named operator new[], 14694 // the storage is aligned for any object that does not have 14695 // new-extended alignment ([basic.align]) and is no larger than the 14696 // requested size. 14697 // (3.3) Otherwise, the storage is aligned for any object that does not 14698 // have new-extended alignment and is of the requested size. 14699 } 14700 14701 /// Adds any function attributes that we know a priori based on 14702 /// the declaration of this function. 14703 /// 14704 /// These attributes can apply both to implicitly-declared builtins 14705 /// (like __builtin___printf_chk) or to library-declared functions 14706 /// like NSLog or printf. 14707 /// 14708 /// We need to check for duplicate attributes both here and where user-written 14709 /// attributes are applied to declarations. 14710 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14711 if (FD->isInvalidDecl()) 14712 return; 14713 14714 // If this is a built-in function, map its builtin attributes to 14715 // actual attributes. 14716 if (unsigned BuiltinID = FD->getBuiltinID()) { 14717 // Handle printf-formatting attributes. 14718 unsigned FormatIdx; 14719 bool HasVAListArg; 14720 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14721 if (!FD->hasAttr<FormatAttr>()) { 14722 const char *fmt = "printf"; 14723 unsigned int NumParams = FD->getNumParams(); 14724 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14725 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14726 fmt = "NSString"; 14727 FD->addAttr(FormatAttr::CreateImplicit(Context, 14728 &Context.Idents.get(fmt), 14729 FormatIdx+1, 14730 HasVAListArg ? 0 : FormatIdx+2, 14731 FD->getLocation())); 14732 } 14733 } 14734 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14735 HasVAListArg)) { 14736 if (!FD->hasAttr<FormatAttr>()) 14737 FD->addAttr(FormatAttr::CreateImplicit(Context, 14738 &Context.Idents.get("scanf"), 14739 FormatIdx+1, 14740 HasVAListArg ? 0 : FormatIdx+2, 14741 FD->getLocation())); 14742 } 14743 14744 // Handle automatically recognized callbacks. 14745 SmallVector<int, 4> Encoding; 14746 if (!FD->hasAttr<CallbackAttr>() && 14747 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14748 FD->addAttr(CallbackAttr::CreateImplicit( 14749 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14750 14751 // Mark const if we don't care about errno and that is the only thing 14752 // preventing the function from being const. This allows IRgen to use LLVM 14753 // intrinsics for such functions. 14754 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14755 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14756 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14757 14758 // We make "fma" on some platforms const because we know it does not set 14759 // errno in those environments even though it could set errno based on the 14760 // C standard. 14761 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14762 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14763 !FD->hasAttr<ConstAttr>()) { 14764 switch (BuiltinID) { 14765 case Builtin::BI__builtin_fma: 14766 case Builtin::BI__builtin_fmaf: 14767 case Builtin::BI__builtin_fmal: 14768 case Builtin::BIfma: 14769 case Builtin::BIfmaf: 14770 case Builtin::BIfmal: 14771 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14772 break; 14773 default: 14774 break; 14775 } 14776 } 14777 14778 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14779 !FD->hasAttr<ReturnsTwiceAttr>()) 14780 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 14781 FD->getLocation())); 14782 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 14783 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14784 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 14785 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 14786 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 14787 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14788 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 14789 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 14790 // Add the appropriate attribute, depending on the CUDA compilation mode 14791 // and which target the builtin belongs to. For example, during host 14792 // compilation, aux builtins are __device__, while the rest are __host__. 14793 if (getLangOpts().CUDAIsDevice != 14794 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 14795 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 14796 else 14797 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 14798 } 14799 } 14800 14801 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 14802 14803 // If C++ exceptions are enabled but we are told extern "C" functions cannot 14804 // throw, add an implicit nothrow attribute to any extern "C" function we come 14805 // across. 14806 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 14807 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 14808 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 14809 if (!FPT || FPT->getExceptionSpecType() == EST_None) 14810 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14811 } 14812 14813 IdentifierInfo *Name = FD->getIdentifier(); 14814 if (!Name) 14815 return; 14816 if ((!getLangOpts().CPlusPlus && 14817 FD->getDeclContext()->isTranslationUnit()) || 14818 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 14819 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 14820 LinkageSpecDecl::lang_c)) { 14821 // Okay: this could be a libc/libm/Objective-C function we know 14822 // about. 14823 } else 14824 return; 14825 14826 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 14827 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 14828 // target-specific builtins, perhaps? 14829 if (!FD->hasAttr<FormatAttr>()) 14830 FD->addAttr(FormatAttr::CreateImplicit(Context, 14831 &Context.Idents.get("printf"), 2, 14832 Name->isStr("vasprintf") ? 0 : 3, 14833 FD->getLocation())); 14834 } 14835 14836 if (Name->isStr("__CFStringMakeConstantString")) { 14837 // We already have a __builtin___CFStringMakeConstantString, 14838 // but builds that use -fno-constant-cfstrings don't go through that. 14839 if (!FD->hasAttr<FormatArgAttr>()) 14840 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 14841 FD->getLocation())); 14842 } 14843 } 14844 14845 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 14846 TypeSourceInfo *TInfo) { 14847 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 14848 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 14849 14850 if (!TInfo) { 14851 assert(D.isInvalidType() && "no declarator info for valid type"); 14852 TInfo = Context.getTrivialTypeSourceInfo(T); 14853 } 14854 14855 // Scope manipulation handled by caller. 14856 TypedefDecl *NewTD = 14857 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 14858 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 14859 14860 // Bail out immediately if we have an invalid declaration. 14861 if (D.isInvalidType()) { 14862 NewTD->setInvalidDecl(); 14863 return NewTD; 14864 } 14865 14866 if (D.getDeclSpec().isModulePrivateSpecified()) { 14867 if (CurContext->isFunctionOrMethod()) 14868 Diag(NewTD->getLocation(), diag::err_module_private_local) 14869 << 2 << NewTD->getDeclName() 14870 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 14871 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 14872 else 14873 NewTD->setModulePrivate(); 14874 } 14875 14876 // C++ [dcl.typedef]p8: 14877 // If the typedef declaration defines an unnamed class (or 14878 // enum), the first typedef-name declared by the declaration 14879 // to be that class type (or enum type) is used to denote the 14880 // class type (or enum type) for linkage purposes only. 14881 // We need to check whether the type was declared in the declaration. 14882 switch (D.getDeclSpec().getTypeSpecType()) { 14883 case TST_enum: 14884 case TST_struct: 14885 case TST_interface: 14886 case TST_union: 14887 case TST_class: { 14888 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 14889 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 14890 break; 14891 } 14892 14893 default: 14894 break; 14895 } 14896 14897 return NewTD; 14898 } 14899 14900 /// Check that this is a valid underlying type for an enum declaration. 14901 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 14902 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 14903 QualType T = TI->getType(); 14904 14905 if (T->isDependentType()) 14906 return false; 14907 14908 // This doesn't use 'isIntegralType' despite the error message mentioning 14909 // integral type because isIntegralType would also allow enum types in C. 14910 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 14911 if (BT->isInteger()) 14912 return false; 14913 14914 if (T->isExtIntType()) 14915 return false; 14916 14917 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 14918 } 14919 14920 /// Check whether this is a valid redeclaration of a previous enumeration. 14921 /// \return true if the redeclaration was invalid. 14922 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 14923 QualType EnumUnderlyingTy, bool IsFixed, 14924 const EnumDecl *Prev) { 14925 if (IsScoped != Prev->isScoped()) { 14926 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 14927 << Prev->isScoped(); 14928 Diag(Prev->getLocation(), diag::note_previous_declaration); 14929 return true; 14930 } 14931 14932 if (IsFixed && Prev->isFixed()) { 14933 if (!EnumUnderlyingTy->isDependentType() && 14934 !Prev->getIntegerType()->isDependentType() && 14935 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 14936 Prev->getIntegerType())) { 14937 // TODO: Highlight the underlying type of the redeclaration. 14938 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 14939 << EnumUnderlyingTy << Prev->getIntegerType(); 14940 Diag(Prev->getLocation(), diag::note_previous_declaration) 14941 << Prev->getIntegerTypeRange(); 14942 return true; 14943 } 14944 } else if (IsFixed != Prev->isFixed()) { 14945 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 14946 << Prev->isFixed(); 14947 Diag(Prev->getLocation(), diag::note_previous_declaration); 14948 return true; 14949 } 14950 14951 return false; 14952 } 14953 14954 /// Get diagnostic %select index for tag kind for 14955 /// redeclaration diagnostic message. 14956 /// WARNING: Indexes apply to particular diagnostics only! 14957 /// 14958 /// \returns diagnostic %select index. 14959 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 14960 switch (Tag) { 14961 case TTK_Struct: return 0; 14962 case TTK_Interface: return 1; 14963 case TTK_Class: return 2; 14964 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 14965 } 14966 } 14967 14968 /// Determine if tag kind is a class-key compatible with 14969 /// class for redeclaration (class, struct, or __interface). 14970 /// 14971 /// \returns true iff the tag kind is compatible. 14972 static bool isClassCompatTagKind(TagTypeKind Tag) 14973 { 14974 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 14975 } 14976 14977 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 14978 TagTypeKind TTK) { 14979 if (isa<TypedefDecl>(PrevDecl)) 14980 return NTK_Typedef; 14981 else if (isa<TypeAliasDecl>(PrevDecl)) 14982 return NTK_TypeAlias; 14983 else if (isa<ClassTemplateDecl>(PrevDecl)) 14984 return NTK_Template; 14985 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 14986 return NTK_TypeAliasTemplate; 14987 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 14988 return NTK_TemplateTemplateArgument; 14989 switch (TTK) { 14990 case TTK_Struct: 14991 case TTK_Interface: 14992 case TTK_Class: 14993 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 14994 case TTK_Union: 14995 return NTK_NonUnion; 14996 case TTK_Enum: 14997 return NTK_NonEnum; 14998 } 14999 llvm_unreachable("invalid TTK"); 15000 } 15001 15002 /// Determine whether a tag with a given kind is acceptable 15003 /// as a redeclaration of the given tag declaration. 15004 /// 15005 /// \returns true if the new tag kind is acceptable, false otherwise. 15006 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15007 TagTypeKind NewTag, bool isDefinition, 15008 SourceLocation NewTagLoc, 15009 const IdentifierInfo *Name) { 15010 // C++ [dcl.type.elab]p3: 15011 // The class-key or enum keyword present in the 15012 // elaborated-type-specifier shall agree in kind with the 15013 // declaration to which the name in the elaborated-type-specifier 15014 // refers. This rule also applies to the form of 15015 // elaborated-type-specifier that declares a class-name or 15016 // friend class since it can be construed as referring to the 15017 // definition of the class. Thus, in any 15018 // elaborated-type-specifier, the enum keyword shall be used to 15019 // refer to an enumeration (7.2), the union class-key shall be 15020 // used to refer to a union (clause 9), and either the class or 15021 // struct class-key shall be used to refer to a class (clause 9) 15022 // declared using the class or struct class-key. 15023 TagTypeKind OldTag = Previous->getTagKind(); 15024 if (OldTag != NewTag && 15025 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15026 return false; 15027 15028 // Tags are compatible, but we might still want to warn on mismatched tags. 15029 // Non-class tags can't be mismatched at this point. 15030 if (!isClassCompatTagKind(NewTag)) 15031 return true; 15032 15033 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15034 // by our warning analysis. We don't want to warn about mismatches with (eg) 15035 // declarations in system headers that are designed to be specialized, but if 15036 // a user asks us to warn, we should warn if their code contains mismatched 15037 // declarations. 15038 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15039 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15040 Loc); 15041 }; 15042 if (IsIgnoredLoc(NewTagLoc)) 15043 return true; 15044 15045 auto IsIgnored = [&](const TagDecl *Tag) { 15046 return IsIgnoredLoc(Tag->getLocation()); 15047 }; 15048 while (IsIgnored(Previous)) { 15049 Previous = Previous->getPreviousDecl(); 15050 if (!Previous) 15051 return true; 15052 OldTag = Previous->getTagKind(); 15053 } 15054 15055 bool isTemplate = false; 15056 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15057 isTemplate = Record->getDescribedClassTemplate(); 15058 15059 if (inTemplateInstantiation()) { 15060 if (OldTag != NewTag) { 15061 // In a template instantiation, do not offer fix-its for tag mismatches 15062 // since they usually mess up the template instead of fixing the problem. 15063 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15064 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15065 << getRedeclDiagFromTagKind(OldTag); 15066 // FIXME: Note previous location? 15067 } 15068 return true; 15069 } 15070 15071 if (isDefinition) { 15072 // On definitions, check all previous tags and issue a fix-it for each 15073 // one that doesn't match the current tag. 15074 if (Previous->getDefinition()) { 15075 // Don't suggest fix-its for redefinitions. 15076 return true; 15077 } 15078 15079 bool previousMismatch = false; 15080 for (const TagDecl *I : Previous->redecls()) { 15081 if (I->getTagKind() != NewTag) { 15082 // Ignore previous declarations for which the warning was disabled. 15083 if (IsIgnored(I)) 15084 continue; 15085 15086 if (!previousMismatch) { 15087 previousMismatch = true; 15088 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15089 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15090 << getRedeclDiagFromTagKind(I->getTagKind()); 15091 } 15092 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15093 << getRedeclDiagFromTagKind(NewTag) 15094 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15095 TypeWithKeyword::getTagTypeKindName(NewTag)); 15096 } 15097 } 15098 return true; 15099 } 15100 15101 // Identify the prevailing tag kind: this is the kind of the definition (if 15102 // there is a non-ignored definition), or otherwise the kind of the prior 15103 // (non-ignored) declaration. 15104 const TagDecl *PrevDef = Previous->getDefinition(); 15105 if (PrevDef && IsIgnored(PrevDef)) 15106 PrevDef = nullptr; 15107 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15108 if (Redecl->getTagKind() != NewTag) { 15109 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15110 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15111 << getRedeclDiagFromTagKind(OldTag); 15112 Diag(Redecl->getLocation(), diag::note_previous_use); 15113 15114 // If there is a previous definition, suggest a fix-it. 15115 if (PrevDef) { 15116 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15117 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15118 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15119 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15120 } 15121 } 15122 15123 return true; 15124 } 15125 15126 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15127 /// from an outer enclosing namespace or file scope inside a friend declaration. 15128 /// This should provide the commented out code in the following snippet: 15129 /// namespace N { 15130 /// struct X; 15131 /// namespace M { 15132 /// struct Y { friend struct /*N::*/ X; }; 15133 /// } 15134 /// } 15135 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15136 SourceLocation NameLoc) { 15137 // While the decl is in a namespace, do repeated lookup of that name and see 15138 // if we get the same namespace back. If we do not, continue until 15139 // translation unit scope, at which point we have a fully qualified NNS. 15140 SmallVector<IdentifierInfo *, 4> Namespaces; 15141 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15142 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15143 // This tag should be declared in a namespace, which can only be enclosed by 15144 // other namespaces. Bail if there's an anonymous namespace in the chain. 15145 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15146 if (!Namespace || Namespace->isAnonymousNamespace()) 15147 return FixItHint(); 15148 IdentifierInfo *II = Namespace->getIdentifier(); 15149 Namespaces.push_back(II); 15150 NamedDecl *Lookup = SemaRef.LookupSingleName( 15151 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15152 if (Lookup == Namespace) 15153 break; 15154 } 15155 15156 // Once we have all the namespaces, reverse them to go outermost first, and 15157 // build an NNS. 15158 SmallString<64> Insertion; 15159 llvm::raw_svector_ostream OS(Insertion); 15160 if (DC->isTranslationUnit()) 15161 OS << "::"; 15162 std::reverse(Namespaces.begin(), Namespaces.end()); 15163 for (auto *II : Namespaces) 15164 OS << II->getName() << "::"; 15165 return FixItHint::CreateInsertion(NameLoc, Insertion); 15166 } 15167 15168 /// Determine whether a tag originally declared in context \p OldDC can 15169 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15170 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15171 /// using-declaration). 15172 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15173 DeclContext *NewDC) { 15174 OldDC = OldDC->getRedeclContext(); 15175 NewDC = NewDC->getRedeclContext(); 15176 15177 if (OldDC->Equals(NewDC)) 15178 return true; 15179 15180 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15181 // encloses the other). 15182 if (S.getLangOpts().MSVCCompat && 15183 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15184 return true; 15185 15186 return false; 15187 } 15188 15189 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15190 /// former case, Name will be non-null. In the later case, Name will be null. 15191 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15192 /// reference/declaration/definition of a tag. 15193 /// 15194 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15195 /// trailing-type-specifier) other than one in an alias-declaration. 15196 /// 15197 /// \param SkipBody If non-null, will be set to indicate if the caller should 15198 /// skip the definition of this tag and treat it as if it were a declaration. 15199 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15200 SourceLocation KWLoc, CXXScopeSpec &SS, 15201 IdentifierInfo *Name, SourceLocation NameLoc, 15202 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15203 SourceLocation ModulePrivateLoc, 15204 MultiTemplateParamsArg TemplateParameterLists, 15205 bool &OwnedDecl, bool &IsDependent, 15206 SourceLocation ScopedEnumKWLoc, 15207 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15208 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15209 SkipBodyInfo *SkipBody) { 15210 // If this is not a definition, it must have a name. 15211 IdentifierInfo *OrigName = Name; 15212 assert((Name != nullptr || TUK == TUK_Definition) && 15213 "Nameless record must be a definition!"); 15214 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15215 15216 OwnedDecl = false; 15217 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15218 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15219 15220 // FIXME: Check member specializations more carefully. 15221 bool isMemberSpecialization = false; 15222 bool Invalid = false; 15223 15224 // We only need to do this matching if we have template parameters 15225 // or a scope specifier, which also conveniently avoids this work 15226 // for non-C++ cases. 15227 if (TemplateParameterLists.size() > 0 || 15228 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15229 if (TemplateParameterList *TemplateParams = 15230 MatchTemplateParametersToScopeSpecifier( 15231 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15232 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15233 if (Kind == TTK_Enum) { 15234 Diag(KWLoc, diag::err_enum_template); 15235 return nullptr; 15236 } 15237 15238 if (TemplateParams->size() > 0) { 15239 // This is a declaration or definition of a class template (which may 15240 // be a member of another template). 15241 15242 if (Invalid) 15243 return nullptr; 15244 15245 OwnedDecl = false; 15246 DeclResult Result = CheckClassTemplate( 15247 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15248 AS, ModulePrivateLoc, 15249 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15250 TemplateParameterLists.data(), SkipBody); 15251 return Result.get(); 15252 } else { 15253 // The "template<>" header is extraneous. 15254 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15255 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15256 isMemberSpecialization = true; 15257 } 15258 } 15259 } 15260 15261 // Figure out the underlying type if this a enum declaration. We need to do 15262 // this early, because it's needed to detect if this is an incompatible 15263 // redeclaration. 15264 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15265 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15266 15267 if (Kind == TTK_Enum) { 15268 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15269 // No underlying type explicitly specified, or we failed to parse the 15270 // type, default to int. 15271 EnumUnderlying = Context.IntTy.getTypePtr(); 15272 } else if (UnderlyingType.get()) { 15273 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15274 // integral type; any cv-qualification is ignored. 15275 TypeSourceInfo *TI = nullptr; 15276 GetTypeFromParser(UnderlyingType.get(), &TI); 15277 EnumUnderlying = TI; 15278 15279 if (CheckEnumUnderlyingType(TI)) 15280 // Recover by falling back to int. 15281 EnumUnderlying = Context.IntTy.getTypePtr(); 15282 15283 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15284 UPPC_FixedUnderlyingType)) 15285 EnumUnderlying = Context.IntTy.getTypePtr(); 15286 15287 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15288 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15289 // of 'int'. However, if this is an unfixed forward declaration, don't set 15290 // the underlying type unless the user enables -fms-compatibility. This 15291 // makes unfixed forward declared enums incomplete and is more conforming. 15292 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15293 EnumUnderlying = Context.IntTy.getTypePtr(); 15294 } 15295 } 15296 15297 DeclContext *SearchDC = CurContext; 15298 DeclContext *DC = CurContext; 15299 bool isStdBadAlloc = false; 15300 bool isStdAlignValT = false; 15301 15302 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15303 if (TUK == TUK_Friend || TUK == TUK_Reference) 15304 Redecl = NotForRedeclaration; 15305 15306 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15307 /// implemented asks for structural equivalence checking, the returned decl 15308 /// here is passed back to the parser, allowing the tag body to be parsed. 15309 auto createTagFromNewDecl = [&]() -> TagDecl * { 15310 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15311 // If there is an identifier, use the location of the identifier as the 15312 // location of the decl, otherwise use the location of the struct/union 15313 // keyword. 15314 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15315 TagDecl *New = nullptr; 15316 15317 if (Kind == TTK_Enum) { 15318 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15319 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15320 // If this is an undefined enum, bail. 15321 if (TUK != TUK_Definition && !Invalid) 15322 return nullptr; 15323 if (EnumUnderlying) { 15324 EnumDecl *ED = cast<EnumDecl>(New); 15325 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15326 ED->setIntegerTypeSourceInfo(TI); 15327 else 15328 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15329 ED->setPromotionType(ED->getIntegerType()); 15330 } 15331 } else { // struct/union 15332 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15333 nullptr); 15334 } 15335 15336 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15337 // Add alignment attributes if necessary; these attributes are checked 15338 // when the ASTContext lays out the structure. 15339 // 15340 // It is important for implementing the correct semantics that this 15341 // happen here (in ActOnTag). The #pragma pack stack is 15342 // maintained as a result of parser callbacks which can occur at 15343 // many points during the parsing of a struct declaration (because 15344 // the #pragma tokens are effectively skipped over during the 15345 // parsing of the struct). 15346 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15347 AddAlignmentAttributesForRecord(RD); 15348 AddMsStructLayoutForRecord(RD); 15349 } 15350 } 15351 New->setLexicalDeclContext(CurContext); 15352 return New; 15353 }; 15354 15355 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15356 if (Name && SS.isNotEmpty()) { 15357 // We have a nested-name tag ('struct foo::bar'). 15358 15359 // Check for invalid 'foo::'. 15360 if (SS.isInvalid()) { 15361 Name = nullptr; 15362 goto CreateNewDecl; 15363 } 15364 15365 // If this is a friend or a reference to a class in a dependent 15366 // context, don't try to make a decl for it. 15367 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15368 DC = computeDeclContext(SS, false); 15369 if (!DC) { 15370 IsDependent = true; 15371 return nullptr; 15372 } 15373 } else { 15374 DC = computeDeclContext(SS, true); 15375 if (!DC) { 15376 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15377 << SS.getRange(); 15378 return nullptr; 15379 } 15380 } 15381 15382 if (RequireCompleteDeclContext(SS, DC)) 15383 return nullptr; 15384 15385 SearchDC = DC; 15386 // Look-up name inside 'foo::'. 15387 LookupQualifiedName(Previous, DC); 15388 15389 if (Previous.isAmbiguous()) 15390 return nullptr; 15391 15392 if (Previous.empty()) { 15393 // Name lookup did not find anything. However, if the 15394 // nested-name-specifier refers to the current instantiation, 15395 // and that current instantiation has any dependent base 15396 // classes, we might find something at instantiation time: treat 15397 // this as a dependent elaborated-type-specifier. 15398 // But this only makes any sense for reference-like lookups. 15399 if (Previous.wasNotFoundInCurrentInstantiation() && 15400 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15401 IsDependent = true; 15402 return nullptr; 15403 } 15404 15405 // A tag 'foo::bar' must already exist. 15406 Diag(NameLoc, diag::err_not_tag_in_scope) 15407 << Kind << Name << DC << SS.getRange(); 15408 Name = nullptr; 15409 Invalid = true; 15410 goto CreateNewDecl; 15411 } 15412 } else if (Name) { 15413 // C++14 [class.mem]p14: 15414 // If T is the name of a class, then each of the following shall have a 15415 // name different from T: 15416 // -- every member of class T that is itself a type 15417 if (TUK != TUK_Reference && TUK != TUK_Friend && 15418 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15419 return nullptr; 15420 15421 // If this is a named struct, check to see if there was a previous forward 15422 // declaration or definition. 15423 // FIXME: We're looking into outer scopes here, even when we 15424 // shouldn't be. Doing so can result in ambiguities that we 15425 // shouldn't be diagnosing. 15426 LookupName(Previous, S); 15427 15428 // When declaring or defining a tag, ignore ambiguities introduced 15429 // by types using'ed into this scope. 15430 if (Previous.isAmbiguous() && 15431 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15432 LookupResult::Filter F = Previous.makeFilter(); 15433 while (F.hasNext()) { 15434 NamedDecl *ND = F.next(); 15435 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15436 SearchDC->getRedeclContext())) 15437 F.erase(); 15438 } 15439 F.done(); 15440 } 15441 15442 // C++11 [namespace.memdef]p3: 15443 // If the name in a friend declaration is neither qualified nor 15444 // a template-id and the declaration is a function or an 15445 // elaborated-type-specifier, the lookup to determine whether 15446 // the entity has been previously declared shall not consider 15447 // any scopes outside the innermost enclosing namespace. 15448 // 15449 // MSVC doesn't implement the above rule for types, so a friend tag 15450 // declaration may be a redeclaration of a type declared in an enclosing 15451 // scope. They do implement this rule for friend functions. 15452 // 15453 // Does it matter that this should be by scope instead of by 15454 // semantic context? 15455 if (!Previous.empty() && TUK == TUK_Friend) { 15456 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15457 LookupResult::Filter F = Previous.makeFilter(); 15458 bool FriendSawTagOutsideEnclosingNamespace = false; 15459 while (F.hasNext()) { 15460 NamedDecl *ND = F.next(); 15461 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15462 if (DC->isFileContext() && 15463 !EnclosingNS->Encloses(ND->getDeclContext())) { 15464 if (getLangOpts().MSVCCompat) 15465 FriendSawTagOutsideEnclosingNamespace = true; 15466 else 15467 F.erase(); 15468 } 15469 } 15470 F.done(); 15471 15472 // Diagnose this MSVC extension in the easy case where lookup would have 15473 // unambiguously found something outside the enclosing namespace. 15474 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15475 NamedDecl *ND = Previous.getFoundDecl(); 15476 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15477 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15478 } 15479 } 15480 15481 // Note: there used to be some attempt at recovery here. 15482 if (Previous.isAmbiguous()) 15483 return nullptr; 15484 15485 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15486 // FIXME: This makes sure that we ignore the contexts associated 15487 // with C structs, unions, and enums when looking for a matching 15488 // tag declaration or definition. See the similar lookup tweak 15489 // in Sema::LookupName; is there a better way to deal with this? 15490 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15491 SearchDC = SearchDC->getParent(); 15492 } 15493 } 15494 15495 if (Previous.isSingleResult() && 15496 Previous.getFoundDecl()->isTemplateParameter()) { 15497 // Maybe we will complain about the shadowed template parameter. 15498 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15499 // Just pretend that we didn't see the previous declaration. 15500 Previous.clear(); 15501 } 15502 15503 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15504 DC->Equals(getStdNamespace())) { 15505 if (Name->isStr("bad_alloc")) { 15506 // This is a declaration of or a reference to "std::bad_alloc". 15507 isStdBadAlloc = true; 15508 15509 // If std::bad_alloc has been implicitly declared (but made invisible to 15510 // name lookup), fill in this implicit declaration as the previous 15511 // declaration, so that the declarations get chained appropriately. 15512 if (Previous.empty() && StdBadAlloc) 15513 Previous.addDecl(getStdBadAlloc()); 15514 } else if (Name->isStr("align_val_t")) { 15515 isStdAlignValT = true; 15516 if (Previous.empty() && StdAlignValT) 15517 Previous.addDecl(getStdAlignValT()); 15518 } 15519 } 15520 15521 // If we didn't find a previous declaration, and this is a reference 15522 // (or friend reference), move to the correct scope. In C++, we 15523 // also need to do a redeclaration lookup there, just in case 15524 // there's a shadow friend decl. 15525 if (Name && Previous.empty() && 15526 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15527 if (Invalid) goto CreateNewDecl; 15528 assert(SS.isEmpty()); 15529 15530 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15531 // C++ [basic.scope.pdecl]p5: 15532 // -- for an elaborated-type-specifier of the form 15533 // 15534 // class-key identifier 15535 // 15536 // if the elaborated-type-specifier is used in the 15537 // decl-specifier-seq or parameter-declaration-clause of a 15538 // function defined in namespace scope, the identifier is 15539 // declared as a class-name in the namespace that contains 15540 // the declaration; otherwise, except as a friend 15541 // declaration, the identifier is declared in the smallest 15542 // non-class, non-function-prototype scope that contains the 15543 // declaration. 15544 // 15545 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15546 // C structs and unions. 15547 // 15548 // It is an error in C++ to declare (rather than define) an enum 15549 // type, including via an elaborated type specifier. We'll 15550 // diagnose that later; for now, declare the enum in the same 15551 // scope as we would have picked for any other tag type. 15552 // 15553 // GNU C also supports this behavior as part of its incomplete 15554 // enum types extension, while GNU C++ does not. 15555 // 15556 // Find the context where we'll be declaring the tag. 15557 // FIXME: We would like to maintain the current DeclContext as the 15558 // lexical context, 15559 SearchDC = getTagInjectionContext(SearchDC); 15560 15561 // Find the scope where we'll be declaring the tag. 15562 S = getTagInjectionScope(S, getLangOpts()); 15563 } else { 15564 assert(TUK == TUK_Friend); 15565 // C++ [namespace.memdef]p3: 15566 // If a friend declaration in a non-local class first declares a 15567 // class or function, the friend class or function is a member of 15568 // the innermost enclosing namespace. 15569 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15570 } 15571 15572 // In C++, we need to do a redeclaration lookup to properly 15573 // diagnose some problems. 15574 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15575 // hidden declaration so that we don't get ambiguity errors when using a 15576 // type declared by an elaborated-type-specifier. In C that is not correct 15577 // and we should instead merge compatible types found by lookup. 15578 if (getLangOpts().CPlusPlus) { 15579 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15580 LookupQualifiedName(Previous, SearchDC); 15581 } else { 15582 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15583 LookupName(Previous, S); 15584 } 15585 } 15586 15587 // If we have a known previous declaration to use, then use it. 15588 if (Previous.empty() && SkipBody && SkipBody->Previous) 15589 Previous.addDecl(SkipBody->Previous); 15590 15591 if (!Previous.empty()) { 15592 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15593 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15594 15595 // It's okay to have a tag decl in the same scope as a typedef 15596 // which hides a tag decl in the same scope. Finding this 15597 // insanity with a redeclaration lookup can only actually happen 15598 // in C++. 15599 // 15600 // This is also okay for elaborated-type-specifiers, which is 15601 // technically forbidden by the current standard but which is 15602 // okay according to the likely resolution of an open issue; 15603 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15604 if (getLangOpts().CPlusPlus) { 15605 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15606 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15607 TagDecl *Tag = TT->getDecl(); 15608 if (Tag->getDeclName() == Name && 15609 Tag->getDeclContext()->getRedeclContext() 15610 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15611 PrevDecl = Tag; 15612 Previous.clear(); 15613 Previous.addDecl(Tag); 15614 Previous.resolveKind(); 15615 } 15616 } 15617 } 15618 } 15619 15620 // If this is a redeclaration of a using shadow declaration, it must 15621 // declare a tag in the same context. In MSVC mode, we allow a 15622 // redefinition if either context is within the other. 15623 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15624 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15625 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15626 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15627 !(OldTag && isAcceptableTagRedeclContext( 15628 *this, OldTag->getDeclContext(), SearchDC))) { 15629 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15630 Diag(Shadow->getTargetDecl()->getLocation(), 15631 diag::note_using_decl_target); 15632 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15633 << 0; 15634 // Recover by ignoring the old declaration. 15635 Previous.clear(); 15636 goto CreateNewDecl; 15637 } 15638 } 15639 15640 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15641 // If this is a use of a previous tag, or if the tag is already declared 15642 // in the same scope (so that the definition/declaration completes or 15643 // rementions the tag), reuse the decl. 15644 if (TUK == TUK_Reference || TUK == TUK_Friend || 15645 isDeclInScope(DirectPrevDecl, SearchDC, S, 15646 SS.isNotEmpty() || isMemberSpecialization)) { 15647 // Make sure that this wasn't declared as an enum and now used as a 15648 // struct or something similar. 15649 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15650 TUK == TUK_Definition, KWLoc, 15651 Name)) { 15652 bool SafeToContinue 15653 = (PrevTagDecl->getTagKind() != TTK_Enum && 15654 Kind != TTK_Enum); 15655 if (SafeToContinue) 15656 Diag(KWLoc, diag::err_use_with_wrong_tag) 15657 << Name 15658 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15659 PrevTagDecl->getKindName()); 15660 else 15661 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15662 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15663 15664 if (SafeToContinue) 15665 Kind = PrevTagDecl->getTagKind(); 15666 else { 15667 // Recover by making this an anonymous redefinition. 15668 Name = nullptr; 15669 Previous.clear(); 15670 Invalid = true; 15671 } 15672 } 15673 15674 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15675 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15676 if (TUK == TUK_Reference || TUK == TUK_Friend) 15677 return PrevTagDecl; 15678 15679 QualType EnumUnderlyingTy; 15680 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15681 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15682 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15683 EnumUnderlyingTy = QualType(T, 0); 15684 15685 // All conflicts with previous declarations are recovered by 15686 // returning the previous declaration, unless this is a definition, 15687 // in which case we want the caller to bail out. 15688 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15689 ScopedEnum, EnumUnderlyingTy, 15690 IsFixed, PrevEnum)) 15691 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15692 } 15693 15694 // C++11 [class.mem]p1: 15695 // A member shall not be declared twice in the member-specification, 15696 // except that a nested class or member class template can be declared 15697 // and then later defined. 15698 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15699 S->isDeclScope(PrevDecl)) { 15700 Diag(NameLoc, diag::ext_member_redeclared); 15701 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15702 } 15703 15704 if (!Invalid) { 15705 // If this is a use, just return the declaration we found, unless 15706 // we have attributes. 15707 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15708 if (!Attrs.empty()) { 15709 // FIXME: Diagnose these attributes. For now, we create a new 15710 // declaration to hold them. 15711 } else if (TUK == TUK_Reference && 15712 (PrevTagDecl->getFriendObjectKind() == 15713 Decl::FOK_Undeclared || 15714 PrevDecl->getOwningModule() != getCurrentModule()) && 15715 SS.isEmpty()) { 15716 // This declaration is a reference to an existing entity, but 15717 // has different visibility from that entity: it either makes 15718 // a friend visible or it makes a type visible in a new module. 15719 // In either case, create a new declaration. We only do this if 15720 // the declaration would have meant the same thing if no prior 15721 // declaration were found, that is, if it was found in the same 15722 // scope where we would have injected a declaration. 15723 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15724 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15725 return PrevTagDecl; 15726 // This is in the injected scope, create a new declaration in 15727 // that scope. 15728 S = getTagInjectionScope(S, getLangOpts()); 15729 } else { 15730 return PrevTagDecl; 15731 } 15732 } 15733 15734 // Diagnose attempts to redefine a tag. 15735 if (TUK == TUK_Definition) { 15736 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15737 // If we're defining a specialization and the previous definition 15738 // is from an implicit instantiation, don't emit an error 15739 // here; we'll catch this in the general case below. 15740 bool IsExplicitSpecializationAfterInstantiation = false; 15741 if (isMemberSpecialization) { 15742 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15743 IsExplicitSpecializationAfterInstantiation = 15744 RD->getTemplateSpecializationKind() != 15745 TSK_ExplicitSpecialization; 15746 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15747 IsExplicitSpecializationAfterInstantiation = 15748 ED->getTemplateSpecializationKind() != 15749 TSK_ExplicitSpecialization; 15750 } 15751 15752 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15753 // not keep more that one definition around (merge them). However, 15754 // ensure the decl passes the structural compatibility check in 15755 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15756 NamedDecl *Hidden = nullptr; 15757 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15758 // There is a definition of this tag, but it is not visible. We 15759 // explicitly make use of C++'s one definition rule here, and 15760 // assume that this definition is identical to the hidden one 15761 // we already have. Make the existing definition visible and 15762 // use it in place of this one. 15763 if (!getLangOpts().CPlusPlus) { 15764 // Postpone making the old definition visible until after we 15765 // complete parsing the new one and do the structural 15766 // comparison. 15767 SkipBody->CheckSameAsPrevious = true; 15768 SkipBody->New = createTagFromNewDecl(); 15769 SkipBody->Previous = Def; 15770 return Def; 15771 } else { 15772 SkipBody->ShouldSkip = true; 15773 SkipBody->Previous = Def; 15774 makeMergedDefinitionVisible(Hidden); 15775 // Carry on and handle it like a normal definition. We'll 15776 // skip starting the definitiion later. 15777 } 15778 } else if (!IsExplicitSpecializationAfterInstantiation) { 15779 // A redeclaration in function prototype scope in C isn't 15780 // visible elsewhere, so merely issue a warning. 15781 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 15782 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 15783 else 15784 Diag(NameLoc, diag::err_redefinition) << Name; 15785 notePreviousDefinition(Def, 15786 NameLoc.isValid() ? NameLoc : KWLoc); 15787 // If this is a redefinition, recover by making this 15788 // struct be anonymous, which will make any later 15789 // references get the previous definition. 15790 Name = nullptr; 15791 Previous.clear(); 15792 Invalid = true; 15793 } 15794 } else { 15795 // If the type is currently being defined, complain 15796 // about a nested redefinition. 15797 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 15798 if (TD->isBeingDefined()) { 15799 Diag(NameLoc, diag::err_nested_redefinition) << Name; 15800 Diag(PrevTagDecl->getLocation(), 15801 diag::note_previous_definition); 15802 Name = nullptr; 15803 Previous.clear(); 15804 Invalid = true; 15805 } 15806 } 15807 15808 // Okay, this is definition of a previously declared or referenced 15809 // tag. We're going to create a new Decl for it. 15810 } 15811 15812 // Okay, we're going to make a redeclaration. If this is some kind 15813 // of reference, make sure we build the redeclaration in the same DC 15814 // as the original, and ignore the current access specifier. 15815 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15816 SearchDC = PrevTagDecl->getDeclContext(); 15817 AS = AS_none; 15818 } 15819 } 15820 // If we get here we have (another) forward declaration or we 15821 // have a definition. Just create a new decl. 15822 15823 } else { 15824 // If we get here, this is a definition of a new tag type in a nested 15825 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 15826 // new decl/type. We set PrevDecl to NULL so that the entities 15827 // have distinct types. 15828 Previous.clear(); 15829 } 15830 // If we get here, we're going to create a new Decl. If PrevDecl 15831 // is non-NULL, it's a definition of the tag declared by 15832 // PrevDecl. If it's NULL, we have a new definition. 15833 15834 // Otherwise, PrevDecl is not a tag, but was found with tag 15835 // lookup. This is only actually possible in C++, where a few 15836 // things like templates still live in the tag namespace. 15837 } else { 15838 // Use a better diagnostic if an elaborated-type-specifier 15839 // found the wrong kind of type on the first 15840 // (non-redeclaration) lookup. 15841 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 15842 !Previous.isForRedeclaration()) { 15843 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15844 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 15845 << Kind; 15846 Diag(PrevDecl->getLocation(), diag::note_declared_at); 15847 Invalid = true; 15848 15849 // Otherwise, only diagnose if the declaration is in scope. 15850 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 15851 SS.isNotEmpty() || isMemberSpecialization)) { 15852 // do nothing 15853 15854 // Diagnose implicit declarations introduced by elaborated types. 15855 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 15856 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15857 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 15858 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15859 Invalid = true; 15860 15861 // Otherwise it's a declaration. Call out a particularly common 15862 // case here. 15863 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15864 unsigned Kind = 0; 15865 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 15866 Diag(NameLoc, diag::err_tag_definition_of_typedef) 15867 << Name << Kind << TND->getUnderlyingType(); 15868 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15869 Invalid = true; 15870 15871 // Otherwise, diagnose. 15872 } else { 15873 // The tag name clashes with something else in the target scope, 15874 // issue an error and recover by making this tag be anonymous. 15875 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 15876 notePreviousDefinition(PrevDecl, NameLoc); 15877 Name = nullptr; 15878 Invalid = true; 15879 } 15880 15881 // The existing declaration isn't relevant to us; we're in a 15882 // new scope, so clear out the previous declaration. 15883 Previous.clear(); 15884 } 15885 } 15886 15887 CreateNewDecl: 15888 15889 TagDecl *PrevDecl = nullptr; 15890 if (Previous.isSingleResult()) 15891 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 15892 15893 // If there is an identifier, use the location of the identifier as the 15894 // location of the decl, otherwise use the location of the struct/union 15895 // keyword. 15896 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15897 15898 // Otherwise, create a new declaration. If there is a previous 15899 // declaration of the same entity, the two will be linked via 15900 // PrevDecl. 15901 TagDecl *New; 15902 15903 if (Kind == TTK_Enum) { 15904 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15905 // enum X { A, B, C } D; D should chain to X. 15906 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 15907 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 15908 ScopedEnumUsesClassTag, IsFixed); 15909 15910 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 15911 StdAlignValT = cast<EnumDecl>(New); 15912 15913 // If this is an undefined enum, warn. 15914 if (TUK != TUK_Definition && !Invalid) { 15915 TagDecl *Def; 15916 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 15917 // C++0x: 7.2p2: opaque-enum-declaration. 15918 // Conflicts are diagnosed above. Do nothing. 15919 } 15920 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 15921 Diag(Loc, diag::ext_forward_ref_enum_def) 15922 << New; 15923 Diag(Def->getLocation(), diag::note_previous_definition); 15924 } else { 15925 unsigned DiagID = diag::ext_forward_ref_enum; 15926 if (getLangOpts().MSVCCompat) 15927 DiagID = diag::ext_ms_forward_ref_enum; 15928 else if (getLangOpts().CPlusPlus) 15929 DiagID = diag::err_forward_ref_enum; 15930 Diag(Loc, DiagID); 15931 } 15932 } 15933 15934 if (EnumUnderlying) { 15935 EnumDecl *ED = cast<EnumDecl>(New); 15936 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15937 ED->setIntegerTypeSourceInfo(TI); 15938 else 15939 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 15940 ED->setPromotionType(ED->getIntegerType()); 15941 assert(ED->isComplete() && "enum with type should be complete"); 15942 } 15943 } else { 15944 // struct/union/class 15945 15946 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15947 // struct X { int A; } D; D should chain to X. 15948 if (getLangOpts().CPlusPlus) { 15949 // FIXME: Look for a way to use RecordDecl for simple structs. 15950 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15951 cast_or_null<CXXRecordDecl>(PrevDecl)); 15952 15953 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 15954 StdBadAlloc = cast<CXXRecordDecl>(New); 15955 } else 15956 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15957 cast_or_null<RecordDecl>(PrevDecl)); 15958 } 15959 15960 // C++11 [dcl.type]p3: 15961 // A type-specifier-seq shall not define a class or enumeration [...]. 15962 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 15963 TUK == TUK_Definition) { 15964 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 15965 << Context.getTagDeclType(New); 15966 Invalid = true; 15967 } 15968 15969 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 15970 DC->getDeclKind() == Decl::Enum) { 15971 Diag(New->getLocation(), diag::err_type_defined_in_enum) 15972 << Context.getTagDeclType(New); 15973 Invalid = true; 15974 } 15975 15976 // Maybe add qualifier info. 15977 if (SS.isNotEmpty()) { 15978 if (SS.isSet()) { 15979 // If this is either a declaration or a definition, check the 15980 // nested-name-specifier against the current context. 15981 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 15982 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 15983 isMemberSpecialization)) 15984 Invalid = true; 15985 15986 New->setQualifierInfo(SS.getWithLocInContext(Context)); 15987 if (TemplateParameterLists.size() > 0) { 15988 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 15989 } 15990 } 15991 else 15992 Invalid = true; 15993 } 15994 15995 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15996 // Add alignment attributes if necessary; these attributes are checked when 15997 // the ASTContext lays out the structure. 15998 // 15999 // It is important for implementing the correct semantics that this 16000 // happen here (in ActOnTag). The #pragma pack stack is 16001 // maintained as a result of parser callbacks which can occur at 16002 // many points during the parsing of a struct declaration (because 16003 // the #pragma tokens are effectively skipped over during the 16004 // parsing of the struct). 16005 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16006 AddAlignmentAttributesForRecord(RD); 16007 AddMsStructLayoutForRecord(RD); 16008 } 16009 } 16010 16011 if (ModulePrivateLoc.isValid()) { 16012 if (isMemberSpecialization) 16013 Diag(New->getLocation(), diag::err_module_private_specialization) 16014 << 2 16015 << FixItHint::CreateRemoval(ModulePrivateLoc); 16016 // __module_private__ does not apply to local classes. However, we only 16017 // diagnose this as an error when the declaration specifiers are 16018 // freestanding. Here, we just ignore the __module_private__. 16019 else if (!SearchDC->isFunctionOrMethod()) 16020 New->setModulePrivate(); 16021 } 16022 16023 // If this is a specialization of a member class (of a class template), 16024 // check the specialization. 16025 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16026 Invalid = true; 16027 16028 // If we're declaring or defining a tag in function prototype scope in C, 16029 // note that this type can only be used within the function and add it to 16030 // the list of decls to inject into the function definition scope. 16031 if ((Name || Kind == TTK_Enum) && 16032 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16033 if (getLangOpts().CPlusPlus) { 16034 // C++ [dcl.fct]p6: 16035 // Types shall not be defined in return or parameter types. 16036 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16037 Diag(Loc, diag::err_type_defined_in_param_type) 16038 << Name; 16039 Invalid = true; 16040 } 16041 } else if (!PrevDecl) { 16042 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16043 } 16044 } 16045 16046 if (Invalid) 16047 New->setInvalidDecl(); 16048 16049 // Set the lexical context. If the tag has a C++ scope specifier, the 16050 // lexical context will be different from the semantic context. 16051 New->setLexicalDeclContext(CurContext); 16052 16053 // Mark this as a friend decl if applicable. 16054 // In Microsoft mode, a friend declaration also acts as a forward 16055 // declaration so we always pass true to setObjectOfFriendDecl to make 16056 // the tag name visible. 16057 if (TUK == TUK_Friend) 16058 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16059 16060 // Set the access specifier. 16061 if (!Invalid && SearchDC->isRecord()) 16062 SetMemberAccessSpecifier(New, PrevDecl, AS); 16063 16064 if (PrevDecl) 16065 CheckRedeclarationModuleOwnership(New, PrevDecl); 16066 16067 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16068 New->startDefinition(); 16069 16070 ProcessDeclAttributeList(S, New, Attrs); 16071 AddPragmaAttributes(S, New); 16072 16073 // If this has an identifier, add it to the scope stack. 16074 if (TUK == TUK_Friend) { 16075 // We might be replacing an existing declaration in the lookup tables; 16076 // if so, borrow its access specifier. 16077 if (PrevDecl) 16078 New->setAccess(PrevDecl->getAccess()); 16079 16080 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16081 DC->makeDeclVisibleInContext(New); 16082 if (Name) // can be null along some error paths 16083 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16084 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16085 } else if (Name) { 16086 S = getNonFieldDeclScope(S); 16087 PushOnScopeChains(New, S, true); 16088 } else { 16089 CurContext->addDecl(New); 16090 } 16091 16092 // If this is the C FILE type, notify the AST context. 16093 if (IdentifierInfo *II = New->getIdentifier()) 16094 if (!New->isInvalidDecl() && 16095 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16096 II->isStr("FILE")) 16097 Context.setFILEDecl(New); 16098 16099 if (PrevDecl) 16100 mergeDeclAttributes(New, PrevDecl); 16101 16102 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16103 inferGslOwnerPointerAttribute(CXXRD); 16104 16105 // If there's a #pragma GCC visibility in scope, set the visibility of this 16106 // record. 16107 AddPushedVisibilityAttribute(New); 16108 16109 if (isMemberSpecialization && !New->isInvalidDecl()) 16110 CompleteMemberSpecialization(New, Previous); 16111 16112 OwnedDecl = true; 16113 // In C++, don't return an invalid declaration. We can't recover well from 16114 // the cases where we make the type anonymous. 16115 if (Invalid && getLangOpts().CPlusPlus) { 16116 if (New->isBeingDefined()) 16117 if (auto RD = dyn_cast<RecordDecl>(New)) 16118 RD->completeDefinition(); 16119 return nullptr; 16120 } else if (SkipBody && SkipBody->ShouldSkip) { 16121 return SkipBody->Previous; 16122 } else { 16123 return New; 16124 } 16125 } 16126 16127 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16128 AdjustDeclIfTemplate(TagD); 16129 TagDecl *Tag = cast<TagDecl>(TagD); 16130 16131 // Enter the tag context. 16132 PushDeclContext(S, Tag); 16133 16134 ActOnDocumentableDecl(TagD); 16135 16136 // If there's a #pragma GCC visibility in scope, set the visibility of this 16137 // record. 16138 AddPushedVisibilityAttribute(Tag); 16139 } 16140 16141 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16142 SkipBodyInfo &SkipBody) { 16143 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16144 return false; 16145 16146 // Make the previous decl visible. 16147 makeMergedDefinitionVisible(SkipBody.Previous); 16148 return true; 16149 } 16150 16151 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16152 assert(isa<ObjCContainerDecl>(IDecl) && 16153 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16154 DeclContext *OCD = cast<DeclContext>(IDecl); 16155 assert(getContainingDC(OCD) == CurContext && 16156 "The next DeclContext should be lexically contained in the current one."); 16157 CurContext = OCD; 16158 return IDecl; 16159 } 16160 16161 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16162 SourceLocation FinalLoc, 16163 bool IsFinalSpelledSealed, 16164 SourceLocation LBraceLoc) { 16165 AdjustDeclIfTemplate(TagD); 16166 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16167 16168 FieldCollector->StartClass(); 16169 16170 if (!Record->getIdentifier()) 16171 return; 16172 16173 if (FinalLoc.isValid()) 16174 Record->addAttr(FinalAttr::Create( 16175 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16176 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16177 16178 // C++ [class]p2: 16179 // [...] The class-name is also inserted into the scope of the 16180 // class itself; this is known as the injected-class-name. For 16181 // purposes of access checking, the injected-class-name is treated 16182 // as if it were a public member name. 16183 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16184 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16185 Record->getLocation(), Record->getIdentifier(), 16186 /*PrevDecl=*/nullptr, 16187 /*DelayTypeCreation=*/true); 16188 Context.getTypeDeclType(InjectedClassName, Record); 16189 InjectedClassName->setImplicit(); 16190 InjectedClassName->setAccess(AS_public); 16191 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16192 InjectedClassName->setDescribedClassTemplate(Template); 16193 PushOnScopeChains(InjectedClassName, S); 16194 assert(InjectedClassName->isInjectedClassName() && 16195 "Broken injected-class-name"); 16196 } 16197 16198 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16199 SourceRange BraceRange) { 16200 AdjustDeclIfTemplate(TagD); 16201 TagDecl *Tag = cast<TagDecl>(TagD); 16202 Tag->setBraceRange(BraceRange); 16203 16204 // Make sure we "complete" the definition even it is invalid. 16205 if (Tag->isBeingDefined()) { 16206 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16207 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16208 RD->completeDefinition(); 16209 } 16210 16211 if (isa<CXXRecordDecl>(Tag)) { 16212 FieldCollector->FinishClass(); 16213 } 16214 16215 // Exit this scope of this tag's definition. 16216 PopDeclContext(); 16217 16218 if (getCurLexicalContext()->isObjCContainer() && 16219 Tag->getDeclContext()->isFileContext()) 16220 Tag->setTopLevelDeclInObjCContainer(); 16221 16222 // Notify the consumer that we've defined a tag. 16223 if (!Tag->isInvalidDecl()) 16224 Consumer.HandleTagDeclDefinition(Tag); 16225 } 16226 16227 void Sema::ActOnObjCContainerFinishDefinition() { 16228 // Exit this scope of this interface definition. 16229 PopDeclContext(); 16230 } 16231 16232 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16233 assert(DC == CurContext && "Mismatch of container contexts"); 16234 OriginalLexicalContext = DC; 16235 ActOnObjCContainerFinishDefinition(); 16236 } 16237 16238 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16239 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16240 OriginalLexicalContext = nullptr; 16241 } 16242 16243 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16244 AdjustDeclIfTemplate(TagD); 16245 TagDecl *Tag = cast<TagDecl>(TagD); 16246 Tag->setInvalidDecl(); 16247 16248 // Make sure we "complete" the definition even it is invalid. 16249 if (Tag->isBeingDefined()) { 16250 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16251 RD->completeDefinition(); 16252 } 16253 16254 // We're undoing ActOnTagStartDefinition here, not 16255 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16256 // the FieldCollector. 16257 16258 PopDeclContext(); 16259 } 16260 16261 // Note that FieldName may be null for anonymous bitfields. 16262 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16263 IdentifierInfo *FieldName, 16264 QualType FieldTy, bool IsMsStruct, 16265 Expr *BitWidth, bool *ZeroWidth) { 16266 assert(BitWidth); 16267 if (BitWidth->containsErrors()) 16268 return ExprError(); 16269 16270 // Default to true; that shouldn't confuse checks for emptiness 16271 if (ZeroWidth) 16272 *ZeroWidth = true; 16273 16274 // C99 6.7.2.1p4 - verify the field type. 16275 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16276 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16277 // Handle incomplete and sizeless types with a specific error. 16278 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16279 diag::err_field_incomplete_or_sizeless)) 16280 return ExprError(); 16281 if (FieldName) 16282 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16283 << FieldName << FieldTy << BitWidth->getSourceRange(); 16284 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16285 << FieldTy << BitWidth->getSourceRange(); 16286 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16287 UPPC_BitFieldWidth)) 16288 return ExprError(); 16289 16290 // If the bit-width is type- or value-dependent, don't try to check 16291 // it now. 16292 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16293 return BitWidth; 16294 16295 llvm::APSInt Value; 16296 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 16297 if (ICE.isInvalid()) 16298 return ICE; 16299 BitWidth = ICE.get(); 16300 16301 if (Value != 0 && ZeroWidth) 16302 *ZeroWidth = false; 16303 16304 // Zero-width bitfield is ok for anonymous field. 16305 if (Value == 0 && FieldName) 16306 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16307 16308 if (Value.isSigned() && Value.isNegative()) { 16309 if (FieldName) 16310 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16311 << FieldName << Value.toString(10); 16312 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16313 << Value.toString(10); 16314 } 16315 16316 if (!FieldTy->isDependentType()) { 16317 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16318 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16319 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16320 16321 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16322 // ABI. 16323 bool CStdConstraintViolation = 16324 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16325 bool MSBitfieldViolation = 16326 Value.ugt(TypeStorageSize) && 16327 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16328 if (CStdConstraintViolation || MSBitfieldViolation) { 16329 unsigned DiagWidth = 16330 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16331 if (FieldName) 16332 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16333 << FieldName << (unsigned)Value.getZExtValue() 16334 << !CStdConstraintViolation << DiagWidth; 16335 16336 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16337 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 16338 << DiagWidth; 16339 } 16340 16341 // Warn on types where the user might conceivably expect to get all 16342 // specified bits as value bits: that's all integral types other than 16343 // 'bool'. 16344 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 16345 if (FieldName) 16346 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16347 << FieldName << (unsigned)Value.getZExtValue() 16348 << (unsigned)TypeWidth; 16349 else 16350 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 16351 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 16352 } 16353 } 16354 16355 return BitWidth; 16356 } 16357 16358 /// ActOnField - Each field of a C struct/union is passed into this in order 16359 /// to create a FieldDecl object for it. 16360 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16361 Declarator &D, Expr *BitfieldWidth) { 16362 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16363 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16364 /*InitStyle=*/ICIS_NoInit, AS_public); 16365 return Res; 16366 } 16367 16368 /// HandleField - Analyze a field of a C struct or a C++ data member. 16369 /// 16370 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16371 SourceLocation DeclStart, 16372 Declarator &D, Expr *BitWidth, 16373 InClassInitStyle InitStyle, 16374 AccessSpecifier AS) { 16375 if (D.isDecompositionDeclarator()) { 16376 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16377 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16378 << Decomp.getSourceRange(); 16379 return nullptr; 16380 } 16381 16382 IdentifierInfo *II = D.getIdentifier(); 16383 SourceLocation Loc = DeclStart; 16384 if (II) Loc = D.getIdentifierLoc(); 16385 16386 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16387 QualType T = TInfo->getType(); 16388 if (getLangOpts().CPlusPlus) { 16389 CheckExtraCXXDefaultArguments(D); 16390 16391 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16392 UPPC_DataMemberType)) { 16393 D.setInvalidType(); 16394 T = Context.IntTy; 16395 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16396 } 16397 } 16398 16399 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16400 16401 if (D.getDeclSpec().isInlineSpecified()) 16402 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16403 << getLangOpts().CPlusPlus17; 16404 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16405 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16406 diag::err_invalid_thread) 16407 << DeclSpec::getSpecifierName(TSCS); 16408 16409 // Check to see if this name was declared as a member previously 16410 NamedDecl *PrevDecl = nullptr; 16411 LookupResult Previous(*this, II, Loc, LookupMemberName, 16412 ForVisibleRedeclaration); 16413 LookupName(Previous, S); 16414 switch (Previous.getResultKind()) { 16415 case LookupResult::Found: 16416 case LookupResult::FoundUnresolvedValue: 16417 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16418 break; 16419 16420 case LookupResult::FoundOverloaded: 16421 PrevDecl = Previous.getRepresentativeDecl(); 16422 break; 16423 16424 case LookupResult::NotFound: 16425 case LookupResult::NotFoundInCurrentInstantiation: 16426 case LookupResult::Ambiguous: 16427 break; 16428 } 16429 Previous.suppressDiagnostics(); 16430 16431 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16432 // Maybe we will complain about the shadowed template parameter. 16433 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16434 // Just pretend that we didn't see the previous declaration. 16435 PrevDecl = nullptr; 16436 } 16437 16438 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16439 PrevDecl = nullptr; 16440 16441 bool Mutable 16442 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16443 SourceLocation TSSL = D.getBeginLoc(); 16444 FieldDecl *NewFD 16445 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16446 TSSL, AS, PrevDecl, &D); 16447 16448 if (NewFD->isInvalidDecl()) 16449 Record->setInvalidDecl(); 16450 16451 if (D.getDeclSpec().isModulePrivateSpecified()) 16452 NewFD->setModulePrivate(); 16453 16454 if (NewFD->isInvalidDecl() && PrevDecl) { 16455 // Don't introduce NewFD into scope; there's already something 16456 // with the same name in the same scope. 16457 } else if (II) { 16458 PushOnScopeChains(NewFD, S); 16459 } else 16460 Record->addDecl(NewFD); 16461 16462 return NewFD; 16463 } 16464 16465 /// Build a new FieldDecl and check its well-formedness. 16466 /// 16467 /// This routine builds a new FieldDecl given the fields name, type, 16468 /// record, etc. \p PrevDecl should refer to any previous declaration 16469 /// with the same name and in the same scope as the field to be 16470 /// created. 16471 /// 16472 /// \returns a new FieldDecl. 16473 /// 16474 /// \todo The Declarator argument is a hack. It will be removed once 16475 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16476 TypeSourceInfo *TInfo, 16477 RecordDecl *Record, SourceLocation Loc, 16478 bool Mutable, Expr *BitWidth, 16479 InClassInitStyle InitStyle, 16480 SourceLocation TSSL, 16481 AccessSpecifier AS, NamedDecl *PrevDecl, 16482 Declarator *D) { 16483 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16484 bool InvalidDecl = false; 16485 if (D) InvalidDecl = D->isInvalidType(); 16486 16487 // If we receive a broken type, recover by assuming 'int' and 16488 // marking this declaration as invalid. 16489 if (T.isNull() || T->containsErrors()) { 16490 InvalidDecl = true; 16491 T = Context.IntTy; 16492 } 16493 16494 QualType EltTy = Context.getBaseElementType(T); 16495 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16496 if (RequireCompleteSizedType(Loc, EltTy, 16497 diag::err_field_incomplete_or_sizeless)) { 16498 // Fields of incomplete type force their record to be invalid. 16499 Record->setInvalidDecl(); 16500 InvalidDecl = true; 16501 } else { 16502 NamedDecl *Def; 16503 EltTy->isIncompleteType(&Def); 16504 if (Def && Def->isInvalidDecl()) { 16505 Record->setInvalidDecl(); 16506 InvalidDecl = true; 16507 } 16508 } 16509 } 16510 16511 // TR 18037 does not allow fields to be declared with address space 16512 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16513 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16514 Diag(Loc, diag::err_field_with_address_space); 16515 Record->setInvalidDecl(); 16516 InvalidDecl = true; 16517 } 16518 16519 if (LangOpts.OpenCL) { 16520 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16521 // used as structure or union field: image, sampler, event or block types. 16522 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16523 T->isBlockPointerType()) { 16524 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16525 Record->setInvalidDecl(); 16526 InvalidDecl = true; 16527 } 16528 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16529 if (BitWidth) { 16530 Diag(Loc, diag::err_opencl_bitfields); 16531 InvalidDecl = true; 16532 } 16533 } 16534 16535 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16536 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16537 T.hasQualifiers()) { 16538 InvalidDecl = true; 16539 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16540 } 16541 16542 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16543 // than a variably modified type. 16544 if (!InvalidDecl && T->isVariablyModifiedType()) { 16545 bool SizeIsNegative; 16546 llvm::APSInt Oversized; 16547 16548 TypeSourceInfo *FixedTInfo = 16549 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 16550 SizeIsNegative, 16551 Oversized); 16552 if (FixedTInfo) { 16553 Diag(Loc, diag::warn_illegal_constant_array_size); 16554 TInfo = FixedTInfo; 16555 T = FixedTInfo->getType(); 16556 } else { 16557 if (SizeIsNegative) 16558 Diag(Loc, diag::err_typecheck_negative_array_size); 16559 else if (Oversized.getBoolValue()) 16560 Diag(Loc, diag::err_array_too_large) 16561 << Oversized.toString(10); 16562 else 16563 Diag(Loc, diag::err_typecheck_field_variable_size); 16564 InvalidDecl = true; 16565 } 16566 } 16567 16568 // Fields can not have abstract class types 16569 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16570 diag::err_abstract_type_in_decl, 16571 AbstractFieldType)) 16572 InvalidDecl = true; 16573 16574 bool ZeroWidth = false; 16575 if (InvalidDecl) 16576 BitWidth = nullptr; 16577 // If this is declared as a bit-field, check the bit-field. 16578 if (BitWidth) { 16579 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16580 &ZeroWidth).get(); 16581 if (!BitWidth) { 16582 InvalidDecl = true; 16583 BitWidth = nullptr; 16584 ZeroWidth = false; 16585 } 16586 16587 // Only data members can have in-class initializers. 16588 if (BitWidth && !II && InitStyle) { 16589 Diag(Loc, diag::err_anon_bitfield_init); 16590 InvalidDecl = true; 16591 BitWidth = nullptr; 16592 ZeroWidth = false; 16593 } 16594 } 16595 16596 // Check that 'mutable' is consistent with the type of the declaration. 16597 if (!InvalidDecl && Mutable) { 16598 unsigned DiagID = 0; 16599 if (T->isReferenceType()) 16600 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16601 : diag::err_mutable_reference; 16602 else if (T.isConstQualified()) 16603 DiagID = diag::err_mutable_const; 16604 16605 if (DiagID) { 16606 SourceLocation ErrLoc = Loc; 16607 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16608 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16609 Diag(ErrLoc, DiagID); 16610 if (DiagID != diag::ext_mutable_reference) { 16611 Mutable = false; 16612 InvalidDecl = true; 16613 } 16614 } 16615 } 16616 16617 // C++11 [class.union]p8 (DR1460): 16618 // At most one variant member of a union may have a 16619 // brace-or-equal-initializer. 16620 if (InitStyle != ICIS_NoInit) 16621 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16622 16623 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16624 BitWidth, Mutable, InitStyle); 16625 if (InvalidDecl) 16626 NewFD->setInvalidDecl(); 16627 16628 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16629 Diag(Loc, diag::err_duplicate_member) << II; 16630 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16631 NewFD->setInvalidDecl(); 16632 } 16633 16634 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16635 if (Record->isUnion()) { 16636 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16637 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16638 if (RDecl->getDefinition()) { 16639 // C++ [class.union]p1: An object of a class with a non-trivial 16640 // constructor, a non-trivial copy constructor, a non-trivial 16641 // destructor, or a non-trivial copy assignment operator 16642 // cannot be a member of a union, nor can an array of such 16643 // objects. 16644 if (CheckNontrivialField(NewFD)) 16645 NewFD->setInvalidDecl(); 16646 } 16647 } 16648 16649 // C++ [class.union]p1: If a union contains a member of reference type, 16650 // the program is ill-formed, except when compiling with MSVC extensions 16651 // enabled. 16652 if (EltTy->isReferenceType()) { 16653 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16654 diag::ext_union_member_of_reference_type : 16655 diag::err_union_member_of_reference_type) 16656 << NewFD->getDeclName() << EltTy; 16657 if (!getLangOpts().MicrosoftExt) 16658 NewFD->setInvalidDecl(); 16659 } 16660 } 16661 } 16662 16663 // FIXME: We need to pass in the attributes given an AST 16664 // representation, not a parser representation. 16665 if (D) { 16666 // FIXME: The current scope is almost... but not entirely... correct here. 16667 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16668 16669 if (NewFD->hasAttrs()) 16670 CheckAlignasUnderalignment(NewFD); 16671 } 16672 16673 // In auto-retain/release, infer strong retension for fields of 16674 // retainable type. 16675 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16676 NewFD->setInvalidDecl(); 16677 16678 if (T.isObjCGCWeak()) 16679 Diag(Loc, diag::warn_attribute_weak_on_field); 16680 16681 NewFD->setAccess(AS); 16682 return NewFD; 16683 } 16684 16685 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16686 assert(FD); 16687 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16688 16689 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16690 return false; 16691 16692 QualType EltTy = Context.getBaseElementType(FD->getType()); 16693 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16694 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16695 if (RDecl->getDefinition()) { 16696 // We check for copy constructors before constructors 16697 // because otherwise we'll never get complaints about 16698 // copy constructors. 16699 16700 CXXSpecialMember member = CXXInvalid; 16701 // We're required to check for any non-trivial constructors. Since the 16702 // implicit default constructor is suppressed if there are any 16703 // user-declared constructors, we just need to check that there is a 16704 // trivial default constructor and a trivial copy constructor. (We don't 16705 // worry about move constructors here, since this is a C++98 check.) 16706 if (RDecl->hasNonTrivialCopyConstructor()) 16707 member = CXXCopyConstructor; 16708 else if (!RDecl->hasTrivialDefaultConstructor()) 16709 member = CXXDefaultConstructor; 16710 else if (RDecl->hasNonTrivialCopyAssignment()) 16711 member = CXXCopyAssignment; 16712 else if (RDecl->hasNonTrivialDestructor()) 16713 member = CXXDestructor; 16714 16715 if (member != CXXInvalid) { 16716 if (!getLangOpts().CPlusPlus11 && 16717 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16718 // Objective-C++ ARC: it is an error to have a non-trivial field of 16719 // a union. However, system headers in Objective-C programs 16720 // occasionally have Objective-C lifetime objects within unions, 16721 // and rather than cause the program to fail, we make those 16722 // members unavailable. 16723 SourceLocation Loc = FD->getLocation(); 16724 if (getSourceManager().isInSystemHeader(Loc)) { 16725 if (!FD->hasAttr<UnavailableAttr>()) 16726 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16727 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16728 return false; 16729 } 16730 } 16731 16732 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16733 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16734 diag::err_illegal_union_or_anon_struct_member) 16735 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16736 DiagnoseNontrivial(RDecl, member); 16737 return !getLangOpts().CPlusPlus11; 16738 } 16739 } 16740 } 16741 16742 return false; 16743 } 16744 16745 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16746 /// AST enum value. 16747 static ObjCIvarDecl::AccessControl 16748 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16749 switch (ivarVisibility) { 16750 default: llvm_unreachable("Unknown visitibility kind"); 16751 case tok::objc_private: return ObjCIvarDecl::Private; 16752 case tok::objc_public: return ObjCIvarDecl::Public; 16753 case tok::objc_protected: return ObjCIvarDecl::Protected; 16754 case tok::objc_package: return ObjCIvarDecl::Package; 16755 } 16756 } 16757 16758 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16759 /// in order to create an IvarDecl object for it. 16760 Decl *Sema::ActOnIvar(Scope *S, 16761 SourceLocation DeclStart, 16762 Declarator &D, Expr *BitfieldWidth, 16763 tok::ObjCKeywordKind Visibility) { 16764 16765 IdentifierInfo *II = D.getIdentifier(); 16766 Expr *BitWidth = (Expr*)BitfieldWidth; 16767 SourceLocation Loc = DeclStart; 16768 if (II) Loc = D.getIdentifierLoc(); 16769 16770 // FIXME: Unnamed fields can be handled in various different ways, for 16771 // example, unnamed unions inject all members into the struct namespace! 16772 16773 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16774 QualType T = TInfo->getType(); 16775 16776 if (BitWidth) { 16777 // 6.7.2.1p3, 6.7.2.1p4 16778 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16779 if (!BitWidth) 16780 D.setInvalidType(); 16781 } else { 16782 // Not a bitfield. 16783 16784 // validate II. 16785 16786 } 16787 if (T->isReferenceType()) { 16788 Diag(Loc, diag::err_ivar_reference_type); 16789 D.setInvalidType(); 16790 } 16791 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16792 // than a variably modified type. 16793 else if (T->isVariablyModifiedType()) { 16794 Diag(Loc, diag::err_typecheck_ivar_variable_size); 16795 D.setInvalidType(); 16796 } 16797 16798 // Get the visibility (access control) for this ivar. 16799 ObjCIvarDecl::AccessControl ac = 16800 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 16801 : ObjCIvarDecl::None; 16802 // Must set ivar's DeclContext to its enclosing interface. 16803 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 16804 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 16805 return nullptr; 16806 ObjCContainerDecl *EnclosingContext; 16807 if (ObjCImplementationDecl *IMPDecl = 16808 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16809 if (LangOpts.ObjCRuntime.isFragile()) { 16810 // Case of ivar declared in an implementation. Context is that of its class. 16811 EnclosingContext = IMPDecl->getClassInterface(); 16812 assert(EnclosingContext && "Implementation has no class interface!"); 16813 } 16814 else 16815 EnclosingContext = EnclosingDecl; 16816 } else { 16817 if (ObjCCategoryDecl *CDecl = 16818 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16819 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 16820 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 16821 return nullptr; 16822 } 16823 } 16824 EnclosingContext = EnclosingDecl; 16825 } 16826 16827 // Construct the decl. 16828 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 16829 DeclStart, Loc, II, T, 16830 TInfo, ac, (Expr *)BitfieldWidth); 16831 16832 if (II) { 16833 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 16834 ForVisibleRedeclaration); 16835 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 16836 && !isa<TagDecl>(PrevDecl)) { 16837 Diag(Loc, diag::err_duplicate_member) << II; 16838 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16839 NewID->setInvalidDecl(); 16840 } 16841 } 16842 16843 // Process attributes attached to the ivar. 16844 ProcessDeclAttributes(S, NewID, D); 16845 16846 if (D.isInvalidType()) 16847 NewID->setInvalidDecl(); 16848 16849 // In ARC, infer 'retaining' for ivars of retainable type. 16850 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 16851 NewID->setInvalidDecl(); 16852 16853 if (D.getDeclSpec().isModulePrivateSpecified()) 16854 NewID->setModulePrivate(); 16855 16856 if (II) { 16857 // FIXME: When interfaces are DeclContexts, we'll need to add 16858 // these to the interface. 16859 S->AddDecl(NewID); 16860 IdResolver.AddDecl(NewID); 16861 } 16862 16863 if (LangOpts.ObjCRuntime.isNonFragile() && 16864 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 16865 Diag(Loc, diag::warn_ivars_in_interface); 16866 16867 return NewID; 16868 } 16869 16870 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 16871 /// class and class extensions. For every class \@interface and class 16872 /// extension \@interface, if the last ivar is a bitfield of any type, 16873 /// then add an implicit `char :0` ivar to the end of that interface. 16874 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 16875 SmallVectorImpl<Decl *> &AllIvarDecls) { 16876 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 16877 return; 16878 16879 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 16880 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 16881 16882 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 16883 return; 16884 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 16885 if (!ID) { 16886 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 16887 if (!CD->IsClassExtension()) 16888 return; 16889 } 16890 // No need to add this to end of @implementation. 16891 else 16892 return; 16893 } 16894 // All conditions are met. Add a new bitfield to the tail end of ivars. 16895 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 16896 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 16897 16898 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 16899 DeclLoc, DeclLoc, nullptr, 16900 Context.CharTy, 16901 Context.getTrivialTypeSourceInfo(Context.CharTy, 16902 DeclLoc), 16903 ObjCIvarDecl::Private, BW, 16904 true); 16905 AllIvarDecls.push_back(Ivar); 16906 } 16907 16908 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 16909 ArrayRef<Decl *> Fields, SourceLocation LBrac, 16910 SourceLocation RBrac, 16911 const ParsedAttributesView &Attrs) { 16912 assert(EnclosingDecl && "missing record or interface decl"); 16913 16914 // If this is an Objective-C @implementation or category and we have 16915 // new fields here we should reset the layout of the interface since 16916 // it will now change. 16917 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 16918 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 16919 switch (DC->getKind()) { 16920 default: break; 16921 case Decl::ObjCCategory: 16922 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 16923 break; 16924 case Decl::ObjCImplementation: 16925 Context. 16926 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 16927 break; 16928 } 16929 } 16930 16931 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 16932 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 16933 16934 // Start counting up the number of named members; make sure to include 16935 // members of anonymous structs and unions in the total. 16936 unsigned NumNamedMembers = 0; 16937 if (Record) { 16938 for (const auto *I : Record->decls()) { 16939 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 16940 if (IFD->getDeclName()) 16941 ++NumNamedMembers; 16942 } 16943 } 16944 16945 // Verify that all the fields are okay. 16946 SmallVector<FieldDecl*, 32> RecFields; 16947 16948 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 16949 i != end; ++i) { 16950 FieldDecl *FD = cast<FieldDecl>(*i); 16951 16952 // Get the type for the field. 16953 const Type *FDTy = FD->getType().getTypePtr(); 16954 16955 if (!FD->isAnonymousStructOrUnion()) { 16956 // Remember all fields written by the user. 16957 RecFields.push_back(FD); 16958 } 16959 16960 // If the field is already invalid for some reason, don't emit more 16961 // diagnostics about it. 16962 if (FD->isInvalidDecl()) { 16963 EnclosingDecl->setInvalidDecl(); 16964 continue; 16965 } 16966 16967 // C99 6.7.2.1p2: 16968 // A structure or union shall not contain a member with 16969 // incomplete or function type (hence, a structure shall not 16970 // contain an instance of itself, but may contain a pointer to 16971 // an instance of itself), except that the last member of a 16972 // structure with more than one named member may have incomplete 16973 // array type; such a structure (and any union containing, 16974 // possibly recursively, a member that is such a structure) 16975 // shall not be a member of a structure or an element of an 16976 // array. 16977 bool IsLastField = (i + 1 == Fields.end()); 16978 if (FDTy->isFunctionType()) { 16979 // Field declared as a function. 16980 Diag(FD->getLocation(), diag::err_field_declared_as_function) 16981 << FD->getDeclName(); 16982 FD->setInvalidDecl(); 16983 EnclosingDecl->setInvalidDecl(); 16984 continue; 16985 } else if (FDTy->isIncompleteArrayType() && 16986 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 16987 if (Record) { 16988 // Flexible array member. 16989 // Microsoft and g++ is more permissive regarding flexible array. 16990 // It will accept flexible array in union and also 16991 // as the sole element of a struct/class. 16992 unsigned DiagID = 0; 16993 if (!Record->isUnion() && !IsLastField) { 16994 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 16995 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 16996 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 16997 FD->setInvalidDecl(); 16998 EnclosingDecl->setInvalidDecl(); 16999 continue; 17000 } else if (Record->isUnion()) 17001 DiagID = getLangOpts().MicrosoftExt 17002 ? diag::ext_flexible_array_union_ms 17003 : getLangOpts().CPlusPlus 17004 ? diag::ext_flexible_array_union_gnu 17005 : diag::err_flexible_array_union; 17006 else if (NumNamedMembers < 1) 17007 DiagID = getLangOpts().MicrosoftExt 17008 ? diag::ext_flexible_array_empty_aggregate_ms 17009 : getLangOpts().CPlusPlus 17010 ? diag::ext_flexible_array_empty_aggregate_gnu 17011 : diag::err_flexible_array_empty_aggregate; 17012 17013 if (DiagID) 17014 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17015 << Record->getTagKind(); 17016 // While the layout of types that contain virtual bases is not specified 17017 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17018 // virtual bases after the derived members. This would make a flexible 17019 // array member declared at the end of an object not adjacent to the end 17020 // of the type. 17021 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17022 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17023 << FD->getDeclName() << Record->getTagKind(); 17024 if (!getLangOpts().C99) 17025 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17026 << FD->getDeclName() << Record->getTagKind(); 17027 17028 // If the element type has a non-trivial destructor, we would not 17029 // implicitly destroy the elements, so disallow it for now. 17030 // 17031 // FIXME: GCC allows this. We should probably either implicitly delete 17032 // the destructor of the containing class, or just allow this. 17033 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17034 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17035 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17036 << FD->getDeclName() << FD->getType(); 17037 FD->setInvalidDecl(); 17038 EnclosingDecl->setInvalidDecl(); 17039 continue; 17040 } 17041 // Okay, we have a legal flexible array member at the end of the struct. 17042 Record->setHasFlexibleArrayMember(true); 17043 } else { 17044 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17045 // unless they are followed by another ivar. That check is done 17046 // elsewhere, after synthesized ivars are known. 17047 } 17048 } else if (!FDTy->isDependentType() && 17049 RequireCompleteSizedType( 17050 FD->getLocation(), FD->getType(), 17051 diag::err_field_incomplete_or_sizeless)) { 17052 // Incomplete type 17053 FD->setInvalidDecl(); 17054 EnclosingDecl->setInvalidDecl(); 17055 continue; 17056 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17057 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17058 // A type which contains a flexible array member is considered to be a 17059 // flexible array member. 17060 Record->setHasFlexibleArrayMember(true); 17061 if (!Record->isUnion()) { 17062 // If this is a struct/class and this is not the last element, reject 17063 // it. Note that GCC supports variable sized arrays in the middle of 17064 // structures. 17065 if (!IsLastField) 17066 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17067 << FD->getDeclName() << FD->getType(); 17068 else { 17069 // We support flexible arrays at the end of structs in 17070 // other structs as an extension. 17071 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17072 << FD->getDeclName(); 17073 } 17074 } 17075 } 17076 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17077 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17078 diag::err_abstract_type_in_decl, 17079 AbstractIvarType)) { 17080 // Ivars can not have abstract class types 17081 FD->setInvalidDecl(); 17082 } 17083 if (Record && FDTTy->getDecl()->hasObjectMember()) 17084 Record->setHasObjectMember(true); 17085 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17086 Record->setHasVolatileMember(true); 17087 } else if (FDTy->isObjCObjectType()) { 17088 /// A field cannot be an Objective-c object 17089 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17090 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17091 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17092 FD->setType(T); 17093 } else if (Record && Record->isUnion() && 17094 FD->getType().hasNonTrivialObjCLifetime() && 17095 getSourceManager().isInSystemHeader(FD->getLocation()) && 17096 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17097 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17098 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17099 // For backward compatibility, fields of C unions declared in system 17100 // headers that have non-trivial ObjC ownership qualifications are marked 17101 // as unavailable unless the qualifier is explicit and __strong. This can 17102 // break ABI compatibility between programs compiled with ARC and MRR, but 17103 // is a better option than rejecting programs using those unions under 17104 // ARC. 17105 FD->addAttr(UnavailableAttr::CreateImplicit( 17106 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17107 FD->getLocation())); 17108 } else if (getLangOpts().ObjC && 17109 getLangOpts().getGC() != LangOptions::NonGC && Record && 17110 !Record->hasObjectMember()) { 17111 if (FD->getType()->isObjCObjectPointerType() || 17112 FD->getType().isObjCGCStrong()) 17113 Record->setHasObjectMember(true); 17114 else if (Context.getAsArrayType(FD->getType())) { 17115 QualType BaseType = Context.getBaseElementType(FD->getType()); 17116 if (BaseType->isRecordType() && 17117 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17118 Record->setHasObjectMember(true); 17119 else if (BaseType->isObjCObjectPointerType() || 17120 BaseType.isObjCGCStrong()) 17121 Record->setHasObjectMember(true); 17122 } 17123 } 17124 17125 if (Record && !getLangOpts().CPlusPlus && 17126 !shouldIgnoreForRecordTriviality(FD)) { 17127 QualType FT = FD->getType(); 17128 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17129 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17130 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17131 Record->isUnion()) 17132 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17133 } 17134 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17135 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17136 Record->setNonTrivialToPrimitiveCopy(true); 17137 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17138 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17139 } 17140 if (FT.isDestructedType()) { 17141 Record->setNonTrivialToPrimitiveDestroy(true); 17142 Record->setParamDestroyedInCallee(true); 17143 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17144 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17145 } 17146 17147 if (const auto *RT = FT->getAs<RecordType>()) { 17148 if (RT->getDecl()->getArgPassingRestrictions() == 17149 RecordDecl::APK_CanNeverPassInRegs) 17150 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17151 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17152 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17153 } 17154 17155 if (Record && FD->getType().isVolatileQualified()) 17156 Record->setHasVolatileMember(true); 17157 // Keep track of the number of named members. 17158 if (FD->getIdentifier()) 17159 ++NumNamedMembers; 17160 } 17161 17162 // Okay, we successfully defined 'Record'. 17163 if (Record) { 17164 bool Completed = false; 17165 if (CXXRecord) { 17166 if (!CXXRecord->isInvalidDecl()) { 17167 // Set access bits correctly on the directly-declared conversions. 17168 for (CXXRecordDecl::conversion_iterator 17169 I = CXXRecord->conversion_begin(), 17170 E = CXXRecord->conversion_end(); I != E; ++I) 17171 I.setAccess((*I)->getAccess()); 17172 } 17173 17174 if (!CXXRecord->isDependentType()) { 17175 // Add any implicitly-declared members to this class. 17176 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17177 17178 if (!CXXRecord->isInvalidDecl()) { 17179 // If we have virtual base classes, we may end up finding multiple 17180 // final overriders for a given virtual function. Check for this 17181 // problem now. 17182 if (CXXRecord->getNumVBases()) { 17183 CXXFinalOverriderMap FinalOverriders; 17184 CXXRecord->getFinalOverriders(FinalOverriders); 17185 17186 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17187 MEnd = FinalOverriders.end(); 17188 M != MEnd; ++M) { 17189 for (OverridingMethods::iterator SO = M->second.begin(), 17190 SOEnd = M->second.end(); 17191 SO != SOEnd; ++SO) { 17192 assert(SO->second.size() > 0 && 17193 "Virtual function without overriding functions?"); 17194 if (SO->second.size() == 1) 17195 continue; 17196 17197 // C++ [class.virtual]p2: 17198 // In a derived class, if a virtual member function of a base 17199 // class subobject has more than one final overrider the 17200 // program is ill-formed. 17201 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17202 << (const NamedDecl *)M->first << Record; 17203 Diag(M->first->getLocation(), 17204 diag::note_overridden_virtual_function); 17205 for (OverridingMethods::overriding_iterator 17206 OM = SO->second.begin(), 17207 OMEnd = SO->second.end(); 17208 OM != OMEnd; ++OM) 17209 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17210 << (const NamedDecl *)M->first << OM->Method->getParent(); 17211 17212 Record->setInvalidDecl(); 17213 } 17214 } 17215 CXXRecord->completeDefinition(&FinalOverriders); 17216 Completed = true; 17217 } 17218 } 17219 } 17220 } 17221 17222 if (!Completed) 17223 Record->completeDefinition(); 17224 17225 // Handle attributes before checking the layout. 17226 ProcessDeclAttributeList(S, Record, Attrs); 17227 17228 // We may have deferred checking for a deleted destructor. Check now. 17229 if (CXXRecord) { 17230 auto *Dtor = CXXRecord->getDestructor(); 17231 if (Dtor && Dtor->isImplicit() && 17232 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17233 CXXRecord->setImplicitDestructorIsDeleted(); 17234 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17235 } 17236 } 17237 17238 if (Record->hasAttrs()) { 17239 CheckAlignasUnderalignment(Record); 17240 17241 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17242 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17243 IA->getRange(), IA->getBestCase(), 17244 IA->getInheritanceModel()); 17245 } 17246 17247 // Check if the structure/union declaration is a type that can have zero 17248 // size in C. For C this is a language extension, for C++ it may cause 17249 // compatibility problems. 17250 bool CheckForZeroSize; 17251 if (!getLangOpts().CPlusPlus) { 17252 CheckForZeroSize = true; 17253 } else { 17254 // For C++ filter out types that cannot be referenced in C code. 17255 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17256 CheckForZeroSize = 17257 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17258 !CXXRecord->isDependentType() && 17259 CXXRecord->isCLike(); 17260 } 17261 if (CheckForZeroSize) { 17262 bool ZeroSize = true; 17263 bool IsEmpty = true; 17264 unsigned NonBitFields = 0; 17265 for (RecordDecl::field_iterator I = Record->field_begin(), 17266 E = Record->field_end(); 17267 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17268 IsEmpty = false; 17269 if (I->isUnnamedBitfield()) { 17270 if (!I->isZeroLengthBitField(Context)) 17271 ZeroSize = false; 17272 } else { 17273 ++NonBitFields; 17274 QualType FieldType = I->getType(); 17275 if (FieldType->isIncompleteType() || 17276 !Context.getTypeSizeInChars(FieldType).isZero()) 17277 ZeroSize = false; 17278 } 17279 } 17280 17281 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17282 // allowed in C++, but warn if its declaration is inside 17283 // extern "C" block. 17284 if (ZeroSize) { 17285 Diag(RecLoc, getLangOpts().CPlusPlus ? 17286 diag::warn_zero_size_struct_union_in_extern_c : 17287 diag::warn_zero_size_struct_union_compat) 17288 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17289 } 17290 17291 // Structs without named members are extension in C (C99 6.7.2.1p7), 17292 // but are accepted by GCC. 17293 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17294 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17295 diag::ext_no_named_members_in_struct_union) 17296 << Record->isUnion(); 17297 } 17298 } 17299 } else { 17300 ObjCIvarDecl **ClsFields = 17301 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17302 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17303 ID->setEndOfDefinitionLoc(RBrac); 17304 // Add ivar's to class's DeclContext. 17305 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17306 ClsFields[i]->setLexicalDeclContext(ID); 17307 ID->addDecl(ClsFields[i]); 17308 } 17309 // Must enforce the rule that ivars in the base classes may not be 17310 // duplicates. 17311 if (ID->getSuperClass()) 17312 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17313 } else if (ObjCImplementationDecl *IMPDecl = 17314 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17315 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17316 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17317 // Ivar declared in @implementation never belongs to the implementation. 17318 // Only it is in implementation's lexical context. 17319 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17320 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17321 IMPDecl->setIvarLBraceLoc(LBrac); 17322 IMPDecl->setIvarRBraceLoc(RBrac); 17323 } else if (ObjCCategoryDecl *CDecl = 17324 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17325 // case of ivars in class extension; all other cases have been 17326 // reported as errors elsewhere. 17327 // FIXME. Class extension does not have a LocEnd field. 17328 // CDecl->setLocEnd(RBrac); 17329 // Add ivar's to class extension's DeclContext. 17330 // Diagnose redeclaration of private ivars. 17331 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17332 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17333 if (IDecl) { 17334 if (const ObjCIvarDecl *ClsIvar = 17335 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17336 Diag(ClsFields[i]->getLocation(), 17337 diag::err_duplicate_ivar_declaration); 17338 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17339 continue; 17340 } 17341 for (const auto *Ext : IDecl->known_extensions()) { 17342 if (const ObjCIvarDecl *ClsExtIvar 17343 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17344 Diag(ClsFields[i]->getLocation(), 17345 diag::err_duplicate_ivar_declaration); 17346 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17347 continue; 17348 } 17349 } 17350 } 17351 ClsFields[i]->setLexicalDeclContext(CDecl); 17352 CDecl->addDecl(ClsFields[i]); 17353 } 17354 CDecl->setIvarLBraceLoc(LBrac); 17355 CDecl->setIvarRBraceLoc(RBrac); 17356 } 17357 } 17358 } 17359 17360 /// Determine whether the given integral value is representable within 17361 /// the given type T. 17362 static bool isRepresentableIntegerValue(ASTContext &Context, 17363 llvm::APSInt &Value, 17364 QualType T) { 17365 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17366 "Integral type required!"); 17367 unsigned BitWidth = Context.getIntWidth(T); 17368 17369 if (Value.isUnsigned() || Value.isNonNegative()) { 17370 if (T->isSignedIntegerOrEnumerationType()) 17371 --BitWidth; 17372 return Value.getActiveBits() <= BitWidth; 17373 } 17374 return Value.getMinSignedBits() <= BitWidth; 17375 } 17376 17377 // Given an integral type, return the next larger integral type 17378 // (or a NULL type of no such type exists). 17379 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17380 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17381 // enum checking below. 17382 assert((T->isIntegralType(Context) || 17383 T->isEnumeralType()) && "Integral type required!"); 17384 const unsigned NumTypes = 4; 17385 QualType SignedIntegralTypes[NumTypes] = { 17386 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17387 }; 17388 QualType UnsignedIntegralTypes[NumTypes] = { 17389 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17390 Context.UnsignedLongLongTy 17391 }; 17392 17393 unsigned BitWidth = Context.getTypeSize(T); 17394 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17395 : UnsignedIntegralTypes; 17396 for (unsigned I = 0; I != NumTypes; ++I) 17397 if (Context.getTypeSize(Types[I]) > BitWidth) 17398 return Types[I]; 17399 17400 return QualType(); 17401 } 17402 17403 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17404 EnumConstantDecl *LastEnumConst, 17405 SourceLocation IdLoc, 17406 IdentifierInfo *Id, 17407 Expr *Val) { 17408 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17409 llvm::APSInt EnumVal(IntWidth); 17410 QualType EltTy; 17411 17412 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17413 Val = nullptr; 17414 17415 if (Val) 17416 Val = DefaultLvalueConversion(Val).get(); 17417 17418 if (Val) { 17419 if (Enum->isDependentType() || Val->isTypeDependent()) 17420 EltTy = Context.DependentTy; 17421 else { 17422 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17423 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17424 // constant-expression in the enumerator-definition shall be a converted 17425 // constant expression of the underlying type. 17426 EltTy = Enum->getIntegerType(); 17427 ExprResult Converted = 17428 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17429 CCEK_Enumerator); 17430 if (Converted.isInvalid()) 17431 Val = nullptr; 17432 else 17433 Val = Converted.get(); 17434 } else if (!Val->isValueDependent() && 17435 !(Val = VerifyIntegerConstantExpression(Val, 17436 &EnumVal).get())) { 17437 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17438 } else { 17439 if (Enum->isComplete()) { 17440 EltTy = Enum->getIntegerType(); 17441 17442 // In Obj-C and Microsoft mode, require the enumeration value to be 17443 // representable in the underlying type of the enumeration. In C++11, 17444 // we perform a non-narrowing conversion as part of converted constant 17445 // expression checking. 17446 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17447 if (Context.getTargetInfo() 17448 .getTriple() 17449 .isWindowsMSVCEnvironment()) { 17450 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17451 } else { 17452 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17453 } 17454 } 17455 17456 // Cast to the underlying type. 17457 Val = ImpCastExprToType(Val, EltTy, 17458 EltTy->isBooleanType() ? CK_IntegralToBoolean 17459 : CK_IntegralCast) 17460 .get(); 17461 } else if (getLangOpts().CPlusPlus) { 17462 // C++11 [dcl.enum]p5: 17463 // If the underlying type is not fixed, the type of each enumerator 17464 // is the type of its initializing value: 17465 // - If an initializer is specified for an enumerator, the 17466 // initializing value has the same type as the expression. 17467 EltTy = Val->getType(); 17468 } else { 17469 // C99 6.7.2.2p2: 17470 // The expression that defines the value of an enumeration constant 17471 // shall be an integer constant expression that has a value 17472 // representable as an int. 17473 17474 // Complain if the value is not representable in an int. 17475 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17476 Diag(IdLoc, diag::ext_enum_value_not_int) 17477 << EnumVal.toString(10) << Val->getSourceRange() 17478 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17479 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17480 // Force the type of the expression to 'int'. 17481 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17482 } 17483 EltTy = Val->getType(); 17484 } 17485 } 17486 } 17487 } 17488 17489 if (!Val) { 17490 if (Enum->isDependentType()) 17491 EltTy = Context.DependentTy; 17492 else if (!LastEnumConst) { 17493 // C++0x [dcl.enum]p5: 17494 // If the underlying type is not fixed, the type of each enumerator 17495 // is the type of its initializing value: 17496 // - If no initializer is specified for the first enumerator, the 17497 // initializing value has an unspecified integral type. 17498 // 17499 // GCC uses 'int' for its unspecified integral type, as does 17500 // C99 6.7.2.2p3. 17501 if (Enum->isFixed()) { 17502 EltTy = Enum->getIntegerType(); 17503 } 17504 else { 17505 EltTy = Context.IntTy; 17506 } 17507 } else { 17508 // Assign the last value + 1. 17509 EnumVal = LastEnumConst->getInitVal(); 17510 ++EnumVal; 17511 EltTy = LastEnumConst->getType(); 17512 17513 // Check for overflow on increment. 17514 if (EnumVal < LastEnumConst->getInitVal()) { 17515 // C++0x [dcl.enum]p5: 17516 // If the underlying type is not fixed, the type of each enumerator 17517 // is the type of its initializing value: 17518 // 17519 // - Otherwise the type of the initializing value is the same as 17520 // the type of the initializing value of the preceding enumerator 17521 // unless the incremented value is not representable in that type, 17522 // in which case the type is an unspecified integral type 17523 // sufficient to contain the incremented value. If no such type 17524 // exists, the program is ill-formed. 17525 QualType T = getNextLargerIntegralType(Context, EltTy); 17526 if (T.isNull() || Enum->isFixed()) { 17527 // There is no integral type larger enough to represent this 17528 // value. Complain, then allow the value to wrap around. 17529 EnumVal = LastEnumConst->getInitVal(); 17530 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17531 ++EnumVal; 17532 if (Enum->isFixed()) 17533 // When the underlying type is fixed, this is ill-formed. 17534 Diag(IdLoc, diag::err_enumerator_wrapped) 17535 << EnumVal.toString(10) 17536 << EltTy; 17537 else 17538 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17539 << EnumVal.toString(10); 17540 } else { 17541 EltTy = T; 17542 } 17543 17544 // Retrieve the last enumerator's value, extent that type to the 17545 // type that is supposed to be large enough to represent the incremented 17546 // value, then increment. 17547 EnumVal = LastEnumConst->getInitVal(); 17548 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17549 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17550 ++EnumVal; 17551 17552 // If we're not in C++, diagnose the overflow of enumerator values, 17553 // which in C99 means that the enumerator value is not representable in 17554 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17555 // permits enumerator values that are representable in some larger 17556 // integral type. 17557 if (!getLangOpts().CPlusPlus && !T.isNull()) 17558 Diag(IdLoc, diag::warn_enum_value_overflow); 17559 } else if (!getLangOpts().CPlusPlus && 17560 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17561 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17562 Diag(IdLoc, diag::ext_enum_value_not_int) 17563 << EnumVal.toString(10) << 1; 17564 } 17565 } 17566 } 17567 17568 if (!EltTy->isDependentType()) { 17569 // Make the enumerator value match the signedness and size of the 17570 // enumerator's type. 17571 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17572 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17573 } 17574 17575 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17576 Val, EnumVal); 17577 } 17578 17579 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17580 SourceLocation IILoc) { 17581 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17582 !getLangOpts().CPlusPlus) 17583 return SkipBodyInfo(); 17584 17585 // We have an anonymous enum definition. Look up the first enumerator to 17586 // determine if we should merge the definition with an existing one and 17587 // skip the body. 17588 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17589 forRedeclarationInCurContext()); 17590 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17591 if (!PrevECD) 17592 return SkipBodyInfo(); 17593 17594 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17595 NamedDecl *Hidden; 17596 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17597 SkipBodyInfo Skip; 17598 Skip.Previous = Hidden; 17599 return Skip; 17600 } 17601 17602 return SkipBodyInfo(); 17603 } 17604 17605 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17606 SourceLocation IdLoc, IdentifierInfo *Id, 17607 const ParsedAttributesView &Attrs, 17608 SourceLocation EqualLoc, Expr *Val) { 17609 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17610 EnumConstantDecl *LastEnumConst = 17611 cast_or_null<EnumConstantDecl>(lastEnumConst); 17612 17613 // The scope passed in may not be a decl scope. Zip up the scope tree until 17614 // we find one that is. 17615 S = getNonFieldDeclScope(S); 17616 17617 // Verify that there isn't already something declared with this name in this 17618 // scope. 17619 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17620 LookupName(R, S); 17621 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17622 17623 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17624 // Maybe we will complain about the shadowed template parameter. 17625 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17626 // Just pretend that we didn't see the previous declaration. 17627 PrevDecl = nullptr; 17628 } 17629 17630 // C++ [class.mem]p15: 17631 // If T is the name of a class, then each of the following shall have a name 17632 // different from T: 17633 // - every enumerator of every member of class T that is an unscoped 17634 // enumerated type 17635 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17636 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17637 DeclarationNameInfo(Id, IdLoc)); 17638 17639 EnumConstantDecl *New = 17640 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17641 if (!New) 17642 return nullptr; 17643 17644 if (PrevDecl) { 17645 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17646 // Check for other kinds of shadowing not already handled. 17647 CheckShadow(New, PrevDecl, R); 17648 } 17649 17650 // When in C++, we may get a TagDecl with the same name; in this case the 17651 // enum constant will 'hide' the tag. 17652 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17653 "Received TagDecl when not in C++!"); 17654 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17655 if (isa<EnumConstantDecl>(PrevDecl)) 17656 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17657 else 17658 Diag(IdLoc, diag::err_redefinition) << Id; 17659 notePreviousDefinition(PrevDecl, IdLoc); 17660 return nullptr; 17661 } 17662 } 17663 17664 // Process attributes. 17665 ProcessDeclAttributeList(S, New, Attrs); 17666 AddPragmaAttributes(S, New); 17667 17668 // Register this decl in the current scope stack. 17669 New->setAccess(TheEnumDecl->getAccess()); 17670 PushOnScopeChains(New, S); 17671 17672 ActOnDocumentableDecl(New); 17673 17674 return New; 17675 } 17676 17677 // Returns true when the enum initial expression does not trigger the 17678 // duplicate enum warning. A few common cases are exempted as follows: 17679 // Element2 = Element1 17680 // Element2 = Element1 + 1 17681 // Element2 = Element1 - 1 17682 // Where Element2 and Element1 are from the same enum. 17683 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17684 Expr *InitExpr = ECD->getInitExpr(); 17685 if (!InitExpr) 17686 return true; 17687 InitExpr = InitExpr->IgnoreImpCasts(); 17688 17689 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17690 if (!BO->isAdditiveOp()) 17691 return true; 17692 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17693 if (!IL) 17694 return true; 17695 if (IL->getValue() != 1) 17696 return true; 17697 17698 InitExpr = BO->getLHS(); 17699 } 17700 17701 // This checks if the elements are from the same enum. 17702 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17703 if (!DRE) 17704 return true; 17705 17706 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17707 if (!EnumConstant) 17708 return true; 17709 17710 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17711 Enum) 17712 return true; 17713 17714 return false; 17715 } 17716 17717 // Emits a warning when an element is implicitly set a value that 17718 // a previous element has already been set to. 17719 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17720 EnumDecl *Enum, QualType EnumType) { 17721 // Avoid anonymous enums 17722 if (!Enum->getIdentifier()) 17723 return; 17724 17725 // Only check for small enums. 17726 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17727 return; 17728 17729 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17730 return; 17731 17732 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17733 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17734 17735 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17736 17737 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 17738 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17739 17740 // Use int64_t as a key to avoid needing special handling for map keys. 17741 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17742 llvm::APSInt Val = D->getInitVal(); 17743 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17744 }; 17745 17746 DuplicatesVector DupVector; 17747 ValueToVectorMap EnumMap; 17748 17749 // Populate the EnumMap with all values represented by enum constants without 17750 // an initializer. 17751 for (auto *Element : Elements) { 17752 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17753 17754 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17755 // this constant. Skip this enum since it may be ill-formed. 17756 if (!ECD) { 17757 return; 17758 } 17759 17760 // Constants with initalizers are handled in the next loop. 17761 if (ECD->getInitExpr()) 17762 continue; 17763 17764 // Duplicate values are handled in the next loop. 17765 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17766 } 17767 17768 if (EnumMap.size() == 0) 17769 return; 17770 17771 // Create vectors for any values that has duplicates. 17772 for (auto *Element : Elements) { 17773 // The last loop returned if any constant was null. 17774 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17775 if (!ValidDuplicateEnum(ECD, Enum)) 17776 continue; 17777 17778 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17779 if (Iter == EnumMap.end()) 17780 continue; 17781 17782 DeclOrVector& Entry = Iter->second; 17783 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17784 // Ensure constants are different. 17785 if (D == ECD) 17786 continue; 17787 17788 // Create new vector and push values onto it. 17789 auto Vec = std::make_unique<ECDVector>(); 17790 Vec->push_back(D); 17791 Vec->push_back(ECD); 17792 17793 // Update entry to point to the duplicates vector. 17794 Entry = Vec.get(); 17795 17796 // Store the vector somewhere we can consult later for quick emission of 17797 // diagnostics. 17798 DupVector.emplace_back(std::move(Vec)); 17799 continue; 17800 } 17801 17802 ECDVector *Vec = Entry.get<ECDVector*>(); 17803 // Make sure constants are not added more than once. 17804 if (*Vec->begin() == ECD) 17805 continue; 17806 17807 Vec->push_back(ECD); 17808 } 17809 17810 // Emit diagnostics. 17811 for (const auto &Vec : DupVector) { 17812 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 17813 17814 // Emit warning for one enum constant. 17815 auto *FirstECD = Vec->front(); 17816 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 17817 << FirstECD << FirstECD->getInitVal().toString(10) 17818 << FirstECD->getSourceRange(); 17819 17820 // Emit one note for each of the remaining enum constants with 17821 // the same value. 17822 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 17823 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 17824 << ECD << ECD->getInitVal().toString(10) 17825 << ECD->getSourceRange(); 17826 } 17827 } 17828 17829 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 17830 bool AllowMask) const { 17831 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 17832 assert(ED->isCompleteDefinition() && "expected enum definition"); 17833 17834 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 17835 llvm::APInt &FlagBits = R.first->second; 17836 17837 if (R.second) { 17838 for (auto *E : ED->enumerators()) { 17839 const auto &EVal = E->getInitVal(); 17840 // Only single-bit enumerators introduce new flag values. 17841 if (EVal.isPowerOf2()) 17842 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 17843 } 17844 } 17845 17846 // A value is in a flag enum if either its bits are a subset of the enum's 17847 // flag bits (the first condition) or we are allowing masks and the same is 17848 // true of its complement (the second condition). When masks are allowed, we 17849 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 17850 // 17851 // While it's true that any value could be used as a mask, the assumption is 17852 // that a mask will have all of the insignificant bits set. Anything else is 17853 // likely a logic error. 17854 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 17855 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 17856 } 17857 17858 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 17859 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 17860 const ParsedAttributesView &Attrs) { 17861 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 17862 QualType EnumType = Context.getTypeDeclType(Enum); 17863 17864 ProcessDeclAttributeList(S, Enum, Attrs); 17865 17866 if (Enum->isDependentType()) { 17867 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17868 EnumConstantDecl *ECD = 17869 cast_or_null<EnumConstantDecl>(Elements[i]); 17870 if (!ECD) continue; 17871 17872 ECD->setType(EnumType); 17873 } 17874 17875 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 17876 return; 17877 } 17878 17879 // TODO: If the result value doesn't fit in an int, it must be a long or long 17880 // long value. ISO C does not support this, but GCC does as an extension, 17881 // emit a warning. 17882 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17883 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 17884 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 17885 17886 // Verify that all the values are okay, compute the size of the values, and 17887 // reverse the list. 17888 unsigned NumNegativeBits = 0; 17889 unsigned NumPositiveBits = 0; 17890 17891 // Keep track of whether all elements have type int. 17892 bool AllElementsInt = true; 17893 17894 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17895 EnumConstantDecl *ECD = 17896 cast_or_null<EnumConstantDecl>(Elements[i]); 17897 if (!ECD) continue; // Already issued a diagnostic. 17898 17899 const llvm::APSInt &InitVal = ECD->getInitVal(); 17900 17901 // Keep track of the size of positive and negative values. 17902 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 17903 NumPositiveBits = std::max(NumPositiveBits, 17904 (unsigned)InitVal.getActiveBits()); 17905 else 17906 NumNegativeBits = std::max(NumNegativeBits, 17907 (unsigned)InitVal.getMinSignedBits()); 17908 17909 // Keep track of whether every enum element has type int (very common). 17910 if (AllElementsInt) 17911 AllElementsInt = ECD->getType() == Context.IntTy; 17912 } 17913 17914 // Figure out the type that should be used for this enum. 17915 QualType BestType; 17916 unsigned BestWidth; 17917 17918 // C++0x N3000 [conv.prom]p3: 17919 // An rvalue of an unscoped enumeration type whose underlying 17920 // type is not fixed can be converted to an rvalue of the first 17921 // of the following types that can represent all the values of 17922 // the enumeration: int, unsigned int, long int, unsigned long 17923 // int, long long int, or unsigned long long int. 17924 // C99 6.4.4.3p2: 17925 // An identifier declared as an enumeration constant has type int. 17926 // The C99 rule is modified by a gcc extension 17927 QualType BestPromotionType; 17928 17929 bool Packed = Enum->hasAttr<PackedAttr>(); 17930 // -fshort-enums is the equivalent to specifying the packed attribute on all 17931 // enum definitions. 17932 if (LangOpts.ShortEnums) 17933 Packed = true; 17934 17935 // If the enum already has a type because it is fixed or dictated by the 17936 // target, promote that type instead of analyzing the enumerators. 17937 if (Enum->isComplete()) { 17938 BestType = Enum->getIntegerType(); 17939 if (BestType->isPromotableIntegerType()) 17940 BestPromotionType = Context.getPromotedIntegerType(BestType); 17941 else 17942 BestPromotionType = BestType; 17943 17944 BestWidth = Context.getIntWidth(BestType); 17945 } 17946 else if (NumNegativeBits) { 17947 // If there is a negative value, figure out the smallest integer type (of 17948 // int/long/longlong) that fits. 17949 // If it's packed, check also if it fits a char or a short. 17950 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 17951 BestType = Context.SignedCharTy; 17952 BestWidth = CharWidth; 17953 } else if (Packed && NumNegativeBits <= ShortWidth && 17954 NumPositiveBits < ShortWidth) { 17955 BestType = Context.ShortTy; 17956 BestWidth = ShortWidth; 17957 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 17958 BestType = Context.IntTy; 17959 BestWidth = IntWidth; 17960 } else { 17961 BestWidth = Context.getTargetInfo().getLongWidth(); 17962 17963 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 17964 BestType = Context.LongTy; 17965 } else { 17966 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17967 17968 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 17969 Diag(Enum->getLocation(), diag::ext_enum_too_large); 17970 BestType = Context.LongLongTy; 17971 } 17972 } 17973 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 17974 } else { 17975 // If there is no negative value, figure out the smallest type that fits 17976 // all of the enumerator values. 17977 // If it's packed, check also if it fits a char or a short. 17978 if (Packed && NumPositiveBits <= CharWidth) { 17979 BestType = Context.UnsignedCharTy; 17980 BestPromotionType = Context.IntTy; 17981 BestWidth = CharWidth; 17982 } else if (Packed && NumPositiveBits <= ShortWidth) { 17983 BestType = Context.UnsignedShortTy; 17984 BestPromotionType = Context.IntTy; 17985 BestWidth = ShortWidth; 17986 } else if (NumPositiveBits <= IntWidth) { 17987 BestType = Context.UnsignedIntTy; 17988 BestWidth = IntWidth; 17989 BestPromotionType 17990 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17991 ? Context.UnsignedIntTy : Context.IntTy; 17992 } else if (NumPositiveBits <= 17993 (BestWidth = Context.getTargetInfo().getLongWidth())) { 17994 BestType = Context.UnsignedLongTy; 17995 BestPromotionType 17996 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17997 ? Context.UnsignedLongTy : Context.LongTy; 17998 } else { 17999 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18000 assert(NumPositiveBits <= BestWidth && 18001 "How could an initializer get larger than ULL?"); 18002 BestType = Context.UnsignedLongLongTy; 18003 BestPromotionType 18004 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18005 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18006 } 18007 } 18008 18009 // Loop over all of the enumerator constants, changing their types to match 18010 // the type of the enum if needed. 18011 for (auto *D : Elements) { 18012 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18013 if (!ECD) continue; // Already issued a diagnostic. 18014 18015 // Standard C says the enumerators have int type, but we allow, as an 18016 // extension, the enumerators to be larger than int size. If each 18017 // enumerator value fits in an int, type it as an int, otherwise type it the 18018 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18019 // that X has type 'int', not 'unsigned'. 18020 18021 // Determine whether the value fits into an int. 18022 llvm::APSInt InitVal = ECD->getInitVal(); 18023 18024 // If it fits into an integer type, force it. Otherwise force it to match 18025 // the enum decl type. 18026 QualType NewTy; 18027 unsigned NewWidth; 18028 bool NewSign; 18029 if (!getLangOpts().CPlusPlus && 18030 !Enum->isFixed() && 18031 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18032 NewTy = Context.IntTy; 18033 NewWidth = IntWidth; 18034 NewSign = true; 18035 } else if (ECD->getType() == BestType) { 18036 // Already the right type! 18037 if (getLangOpts().CPlusPlus) 18038 // C++ [dcl.enum]p4: Following the closing brace of an 18039 // enum-specifier, each enumerator has the type of its 18040 // enumeration. 18041 ECD->setType(EnumType); 18042 continue; 18043 } else { 18044 NewTy = BestType; 18045 NewWidth = BestWidth; 18046 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18047 } 18048 18049 // Adjust the APSInt value. 18050 InitVal = InitVal.extOrTrunc(NewWidth); 18051 InitVal.setIsSigned(NewSign); 18052 ECD->setInitVal(InitVal); 18053 18054 // Adjust the Expr initializer and type. 18055 if (ECD->getInitExpr() && 18056 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18057 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 18058 CK_IntegralCast, 18059 ECD->getInitExpr(), 18060 /*base paths*/ nullptr, 18061 VK_RValue)); 18062 if (getLangOpts().CPlusPlus) 18063 // C++ [dcl.enum]p4: Following the closing brace of an 18064 // enum-specifier, each enumerator has the type of its 18065 // enumeration. 18066 ECD->setType(EnumType); 18067 else 18068 ECD->setType(NewTy); 18069 } 18070 18071 Enum->completeDefinition(BestType, BestPromotionType, 18072 NumPositiveBits, NumNegativeBits); 18073 18074 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18075 18076 if (Enum->isClosedFlag()) { 18077 for (Decl *D : Elements) { 18078 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18079 if (!ECD) continue; // Already issued a diagnostic. 18080 18081 llvm::APSInt InitVal = ECD->getInitVal(); 18082 if (InitVal != 0 && !InitVal.isPowerOf2() && 18083 !IsValueInFlagEnum(Enum, InitVal, true)) 18084 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18085 << ECD << Enum; 18086 } 18087 } 18088 18089 // Now that the enum type is defined, ensure it's not been underaligned. 18090 if (Enum->hasAttrs()) 18091 CheckAlignasUnderalignment(Enum); 18092 } 18093 18094 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18095 SourceLocation StartLoc, 18096 SourceLocation EndLoc) { 18097 StringLiteral *AsmString = cast<StringLiteral>(expr); 18098 18099 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18100 AsmString, StartLoc, 18101 EndLoc); 18102 CurContext->addDecl(New); 18103 return New; 18104 } 18105 18106 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18107 IdentifierInfo* AliasName, 18108 SourceLocation PragmaLoc, 18109 SourceLocation NameLoc, 18110 SourceLocation AliasNameLoc) { 18111 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18112 LookupOrdinaryName); 18113 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18114 AttributeCommonInfo::AS_Pragma); 18115 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18116 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18117 18118 // If a declaration that: 18119 // 1) declares a function or a variable 18120 // 2) has external linkage 18121 // already exists, add a label attribute to it. 18122 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18123 if (isDeclExternC(PrevDecl)) 18124 PrevDecl->addAttr(Attr); 18125 else 18126 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18127 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18128 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18129 } else 18130 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18131 } 18132 18133 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18134 SourceLocation PragmaLoc, 18135 SourceLocation NameLoc) { 18136 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18137 18138 if (PrevDecl) { 18139 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18140 } else { 18141 (void)WeakUndeclaredIdentifiers.insert( 18142 std::pair<IdentifierInfo*,WeakInfo> 18143 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18144 } 18145 } 18146 18147 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18148 IdentifierInfo* AliasName, 18149 SourceLocation PragmaLoc, 18150 SourceLocation NameLoc, 18151 SourceLocation AliasNameLoc) { 18152 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18153 LookupOrdinaryName); 18154 WeakInfo W = WeakInfo(Name, NameLoc); 18155 18156 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18157 if (!PrevDecl->hasAttr<AliasAttr>()) 18158 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18159 DeclApplyPragmaWeak(TUScope, ND, W); 18160 } else { 18161 (void)WeakUndeclaredIdentifiers.insert( 18162 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18163 } 18164 } 18165 18166 Decl *Sema::getObjCDeclContext() const { 18167 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18168 } 18169 18170 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18171 bool Final) { 18172 // SYCL functions can be template, so we check if they have appropriate 18173 // attribute prior to checking if it is a template. 18174 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18175 return FunctionEmissionStatus::Emitted; 18176 18177 // Templates are emitted when they're instantiated. 18178 if (FD->isDependentContext()) 18179 return FunctionEmissionStatus::TemplateDiscarded; 18180 18181 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; 18182 if (LangOpts.OpenMPIsDevice) { 18183 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18184 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18185 if (DevTy.hasValue()) { 18186 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18187 OMPES = FunctionEmissionStatus::OMPDiscarded; 18188 else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost || 18189 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) { 18190 OMPES = FunctionEmissionStatus::Emitted; 18191 } 18192 } 18193 } else if (LangOpts.OpenMP) { 18194 // In OpenMP 4.5 all the functions are host functions. 18195 if (LangOpts.OpenMP <= 45) { 18196 OMPES = FunctionEmissionStatus::Emitted; 18197 } else { 18198 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18199 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18200 // In OpenMP 5.0 or above, DevTy may be changed later by 18201 // #pragma omp declare target to(*) device_type(*). Therefore DevTy 18202 // having no value does not imply host. The emission status will be 18203 // checked again at the end of compilation unit. 18204 if (DevTy.hasValue()) { 18205 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 18206 OMPES = FunctionEmissionStatus::OMPDiscarded; 18207 } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host || 18208 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) 18209 OMPES = FunctionEmissionStatus::Emitted; 18210 } else if (Final) 18211 OMPES = FunctionEmissionStatus::Emitted; 18212 } 18213 } 18214 if (OMPES == FunctionEmissionStatus::OMPDiscarded || 18215 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) 18216 return OMPES; 18217 18218 if (LangOpts.CUDA) { 18219 // When compiling for device, host functions are never emitted. Similarly, 18220 // when compiling for host, device and global functions are never emitted. 18221 // (Technically, we do emit a host-side stub for global functions, but this 18222 // doesn't count for our purposes here.) 18223 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18224 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18225 return FunctionEmissionStatus::CUDADiscarded; 18226 if (!LangOpts.CUDAIsDevice && 18227 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18228 return FunctionEmissionStatus::CUDADiscarded; 18229 18230 // Check whether this function is externally visible -- if so, it's 18231 // known-emitted. 18232 // 18233 // We have to check the GVA linkage of the function's *definition* -- if we 18234 // only have a declaration, we don't know whether or not the function will 18235 // be emitted, because (say) the definition could include "inline". 18236 FunctionDecl *Def = FD->getDefinition(); 18237 18238 if (Def && 18239 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) 18240 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) 18241 return FunctionEmissionStatus::Emitted; 18242 } 18243 18244 // Otherwise, the function is known-emitted if it's in our set of 18245 // known-emitted functions. 18246 return FunctionEmissionStatus::Unknown; 18247 } 18248 18249 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18250 // Host-side references to a __global__ function refer to the stub, so the 18251 // function itself is never emitted and therefore should not be marked. 18252 // If we have host fn calls kernel fn calls host+device, the HD function 18253 // does not get instantiated on the host. We model this by omitting at the 18254 // call to the kernel from the callgraph. This ensures that, when compiling 18255 // for host, only HD functions actually called from the host get marked as 18256 // known-emitted. 18257 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18258 IdentifyCUDATarget(Callee) == CFT_Global; 18259 } 18260