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 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3914 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3915 continue; 3916 3917 if (!Context.hasSameType(NewArray, 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 // Postpone error emission until we've collected attributes required to 7082 // figure out whether it's a host or device variable and whether the 7083 // error should be ignored. 7084 EmitTLSUnsupportedError = true; 7085 // We still need to mark the variable as TLS so it shows up in AST with 7086 // proper storage class for other tools to use even if we're not going 7087 // to emit any code for it. 7088 NewVD->setTSCSpec(TSCS); 7089 } else 7090 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7091 diag::err_thread_unsupported); 7092 } else 7093 NewVD->setTSCSpec(TSCS); 7094 } 7095 7096 switch (D.getDeclSpec().getConstexprSpecifier()) { 7097 case CSK_unspecified: 7098 break; 7099 7100 case CSK_consteval: 7101 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7102 diag::err_constexpr_wrong_decl_kind) 7103 << D.getDeclSpec().getConstexprSpecifier(); 7104 LLVM_FALLTHROUGH; 7105 7106 case CSK_constexpr: 7107 NewVD->setConstexpr(true); 7108 MaybeAddCUDAConstantAttr(NewVD); 7109 // C++1z [dcl.spec.constexpr]p1: 7110 // A static data member declared with the constexpr specifier is 7111 // implicitly an inline variable. 7112 if (NewVD->isStaticDataMember() && 7113 (getLangOpts().CPlusPlus17 || 7114 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7115 NewVD->setImplicitlyInline(); 7116 break; 7117 7118 case CSK_constinit: 7119 if (!NewVD->hasGlobalStorage()) 7120 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7121 diag::err_constinit_local_variable); 7122 else 7123 NewVD->addAttr(ConstInitAttr::Create( 7124 Context, D.getDeclSpec().getConstexprSpecLoc(), 7125 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7126 break; 7127 } 7128 7129 // C99 6.7.4p3 7130 // An inline definition of a function with external linkage shall 7131 // not contain a definition of a modifiable object with static or 7132 // thread storage duration... 7133 // We only apply this when the function is required to be defined 7134 // elsewhere, i.e. when the function is not 'extern inline'. Note 7135 // that a local variable with thread storage duration still has to 7136 // be marked 'static'. Also note that it's possible to get these 7137 // semantics in C++ using __attribute__((gnu_inline)). 7138 if (SC == SC_Static && S->getFnParent() != nullptr && 7139 !NewVD->getType().isConstQualified()) { 7140 FunctionDecl *CurFD = getCurFunctionDecl(); 7141 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7142 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7143 diag::warn_static_local_in_extern_inline); 7144 MaybeSuggestAddingStaticToDecl(CurFD); 7145 } 7146 } 7147 7148 if (D.getDeclSpec().isModulePrivateSpecified()) { 7149 if (IsVariableTemplateSpecialization) 7150 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7151 << (IsPartialSpecialization ? 1 : 0) 7152 << FixItHint::CreateRemoval( 7153 D.getDeclSpec().getModulePrivateSpecLoc()); 7154 else if (IsMemberSpecialization) 7155 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7156 << 2 7157 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7158 else if (NewVD->hasLocalStorage()) 7159 Diag(NewVD->getLocation(), diag::err_module_private_local) 7160 << 0 << NewVD->getDeclName() 7161 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7162 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7163 else { 7164 NewVD->setModulePrivate(); 7165 if (NewTemplate) 7166 NewTemplate->setModulePrivate(); 7167 for (auto *B : Bindings) 7168 B->setModulePrivate(); 7169 } 7170 } 7171 7172 if (getLangOpts().OpenCL) { 7173 7174 deduceOpenCLAddressSpace(NewVD); 7175 7176 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); 7177 } 7178 7179 // Handle attributes prior to checking for duplicates in MergeVarDecl 7180 ProcessDeclAttributes(S, NewVD, D); 7181 7182 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 7183 if (EmitTLSUnsupportedError && 7184 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7185 (getLangOpts().OpenMPIsDevice && 7186 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7187 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7188 diag::err_thread_unsupported); 7189 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7190 // storage [duration]." 7191 if (SC == SC_None && S->getFnParent() != nullptr && 7192 (NewVD->hasAttr<CUDASharedAttr>() || 7193 NewVD->hasAttr<CUDAConstantAttr>())) { 7194 NewVD->setStorageClass(SC_Static); 7195 } 7196 } 7197 7198 // Ensure that dllimport globals without explicit storage class are treated as 7199 // extern. The storage class is set above using parsed attributes. Now we can 7200 // check the VarDecl itself. 7201 assert(!NewVD->hasAttr<DLLImportAttr>() || 7202 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7203 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7204 7205 // In auto-retain/release, infer strong retension for variables of 7206 // retainable type. 7207 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7208 NewVD->setInvalidDecl(); 7209 7210 // Handle GNU asm-label extension (encoded as an attribute). 7211 if (Expr *E = (Expr*)D.getAsmLabel()) { 7212 // The parser guarantees this is a string. 7213 StringLiteral *SE = cast<StringLiteral>(E); 7214 StringRef Label = SE->getString(); 7215 if (S->getFnParent() != nullptr) { 7216 switch (SC) { 7217 case SC_None: 7218 case SC_Auto: 7219 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7220 break; 7221 case SC_Register: 7222 // Local Named register 7223 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7224 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7225 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7226 break; 7227 case SC_Static: 7228 case SC_Extern: 7229 case SC_PrivateExtern: 7230 break; 7231 } 7232 } else if (SC == SC_Register) { 7233 // Global Named register 7234 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7235 const auto &TI = Context.getTargetInfo(); 7236 bool HasSizeMismatch; 7237 7238 if (!TI.isValidGCCRegisterName(Label)) 7239 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7240 else if (!TI.validateGlobalRegisterVariable(Label, 7241 Context.getTypeSize(R), 7242 HasSizeMismatch)) 7243 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7244 else if (HasSizeMismatch) 7245 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7246 } 7247 7248 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7249 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7250 NewVD->setInvalidDecl(true); 7251 } 7252 } 7253 7254 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7255 /*IsLiteralLabel=*/true, 7256 SE->getStrTokenLoc(0))); 7257 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7258 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7259 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7260 if (I != ExtnameUndeclaredIdentifiers.end()) { 7261 if (isDeclExternC(NewVD)) { 7262 NewVD->addAttr(I->second); 7263 ExtnameUndeclaredIdentifiers.erase(I); 7264 } else 7265 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7266 << /*Variable*/1 << NewVD; 7267 } 7268 } 7269 7270 // Find the shadowed declaration before filtering for scope. 7271 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7272 ? getShadowedDeclaration(NewVD, Previous) 7273 : nullptr; 7274 7275 // Don't consider existing declarations that are in a different 7276 // scope and are out-of-semantic-context declarations (if the new 7277 // declaration has linkage). 7278 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7279 D.getCXXScopeSpec().isNotEmpty() || 7280 IsMemberSpecialization || 7281 IsVariableTemplateSpecialization); 7282 7283 // Check whether the previous declaration is in the same block scope. This 7284 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7285 if (getLangOpts().CPlusPlus && 7286 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7287 NewVD->setPreviousDeclInSameBlockScope( 7288 Previous.isSingleResult() && !Previous.isShadowed() && 7289 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7290 7291 if (!getLangOpts().CPlusPlus) { 7292 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7293 } else { 7294 // If this is an explicit specialization of a static data member, check it. 7295 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7296 CheckMemberSpecialization(NewVD, Previous)) 7297 NewVD->setInvalidDecl(); 7298 7299 // Merge the decl with the existing one if appropriate. 7300 if (!Previous.empty()) { 7301 if (Previous.isSingleResult() && 7302 isa<FieldDecl>(Previous.getFoundDecl()) && 7303 D.getCXXScopeSpec().isSet()) { 7304 // The user tried to define a non-static data member 7305 // out-of-line (C++ [dcl.meaning]p1). 7306 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7307 << D.getCXXScopeSpec().getRange(); 7308 Previous.clear(); 7309 NewVD->setInvalidDecl(); 7310 } 7311 } else if (D.getCXXScopeSpec().isSet()) { 7312 // No previous declaration in the qualifying scope. 7313 Diag(D.getIdentifierLoc(), diag::err_no_member) 7314 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7315 << D.getCXXScopeSpec().getRange(); 7316 NewVD->setInvalidDecl(); 7317 } 7318 7319 if (!IsVariableTemplateSpecialization) 7320 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7321 7322 if (NewTemplate) { 7323 VarTemplateDecl *PrevVarTemplate = 7324 NewVD->getPreviousDecl() 7325 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7326 : nullptr; 7327 7328 // Check the template parameter list of this declaration, possibly 7329 // merging in the template parameter list from the previous variable 7330 // template declaration. 7331 if (CheckTemplateParameterList( 7332 TemplateParams, 7333 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7334 : nullptr, 7335 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7336 DC->isDependentContext()) 7337 ? TPC_ClassTemplateMember 7338 : TPC_VarTemplate)) 7339 NewVD->setInvalidDecl(); 7340 7341 // If we are providing an explicit specialization of a static variable 7342 // template, make a note of that. 7343 if (PrevVarTemplate && 7344 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7345 PrevVarTemplate->setMemberSpecialization(); 7346 } 7347 } 7348 7349 // Diagnose shadowed variables iff this isn't a redeclaration. 7350 if (ShadowedDecl && !D.isRedeclaration()) 7351 CheckShadow(NewVD, ShadowedDecl, Previous); 7352 7353 ProcessPragmaWeak(S, NewVD); 7354 7355 // If this is the first declaration of an extern C variable, update 7356 // the map of such variables. 7357 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7358 isIncompleteDeclExternC(*this, NewVD)) 7359 RegisterLocallyScopedExternCDecl(NewVD, S); 7360 7361 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7362 MangleNumberingContext *MCtx; 7363 Decl *ManglingContextDecl; 7364 std::tie(MCtx, ManglingContextDecl) = 7365 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7366 if (MCtx) { 7367 Context.setManglingNumber( 7368 NewVD, MCtx->getManglingNumber( 7369 NewVD, getMSManglingNumber(getLangOpts(), S))); 7370 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7371 } 7372 } 7373 7374 // Special handling of variable named 'main'. 7375 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7376 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7377 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7378 7379 // C++ [basic.start.main]p3 7380 // A program that declares a variable main at global scope is ill-formed. 7381 if (getLangOpts().CPlusPlus) 7382 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7383 7384 // In C, and external-linkage variable named main results in undefined 7385 // behavior. 7386 else if (NewVD->hasExternalFormalLinkage()) 7387 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7388 } 7389 7390 if (D.isRedeclaration() && !Previous.empty()) { 7391 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7392 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7393 D.isFunctionDefinition()); 7394 } 7395 7396 if (NewTemplate) { 7397 if (NewVD->isInvalidDecl()) 7398 NewTemplate->setInvalidDecl(); 7399 ActOnDocumentableDecl(NewTemplate); 7400 return NewTemplate; 7401 } 7402 7403 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7404 CompleteMemberSpecialization(NewVD, Previous); 7405 7406 return NewVD; 7407 } 7408 7409 /// Enum describing the %select options in diag::warn_decl_shadow. 7410 enum ShadowedDeclKind { 7411 SDK_Local, 7412 SDK_Global, 7413 SDK_StaticMember, 7414 SDK_Field, 7415 SDK_Typedef, 7416 SDK_Using 7417 }; 7418 7419 /// Determine what kind of declaration we're shadowing. 7420 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7421 const DeclContext *OldDC) { 7422 if (isa<TypeAliasDecl>(ShadowedDecl)) 7423 return SDK_Using; 7424 else if (isa<TypedefDecl>(ShadowedDecl)) 7425 return SDK_Typedef; 7426 else if (isa<RecordDecl>(OldDC)) 7427 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7428 7429 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7430 } 7431 7432 /// Return the location of the capture if the given lambda captures the given 7433 /// variable \p VD, or an invalid source location otherwise. 7434 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7435 const VarDecl *VD) { 7436 for (const Capture &Capture : LSI->Captures) { 7437 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7438 return Capture.getLocation(); 7439 } 7440 return SourceLocation(); 7441 } 7442 7443 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7444 const LookupResult &R) { 7445 // Only diagnose if we're shadowing an unambiguous field or variable. 7446 if (R.getResultKind() != LookupResult::Found) 7447 return false; 7448 7449 // Return false if warning is ignored. 7450 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7451 } 7452 7453 /// Return the declaration shadowed by the given variable \p D, or null 7454 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7455 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7456 const LookupResult &R) { 7457 if (!shouldWarnIfShadowedDecl(Diags, R)) 7458 return nullptr; 7459 7460 // Don't diagnose declarations at file scope. 7461 if (D->hasGlobalStorage()) 7462 return nullptr; 7463 7464 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7465 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7466 ? ShadowedDecl 7467 : nullptr; 7468 } 7469 7470 /// Return the declaration shadowed by the given typedef \p D, or null 7471 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7472 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7473 const LookupResult &R) { 7474 // Don't warn if typedef declaration is part of a class 7475 if (D->getDeclContext()->isRecord()) 7476 return nullptr; 7477 7478 if (!shouldWarnIfShadowedDecl(Diags, R)) 7479 return nullptr; 7480 7481 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7482 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7483 } 7484 7485 /// Diagnose variable or built-in function shadowing. Implements 7486 /// -Wshadow. 7487 /// 7488 /// This method is called whenever a VarDecl is added to a "useful" 7489 /// scope. 7490 /// 7491 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7492 /// \param R the lookup of the name 7493 /// 7494 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7495 const LookupResult &R) { 7496 DeclContext *NewDC = D->getDeclContext(); 7497 7498 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7499 // Fields are not shadowed by variables in C++ static methods. 7500 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7501 if (MD->isStatic()) 7502 return; 7503 7504 // Fields shadowed by constructor parameters are a special case. Usually 7505 // the constructor initializes the field with the parameter. 7506 if (isa<CXXConstructorDecl>(NewDC)) 7507 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7508 // Remember that this was shadowed so we can either warn about its 7509 // modification or its existence depending on warning settings. 7510 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7511 return; 7512 } 7513 } 7514 7515 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7516 if (shadowedVar->isExternC()) { 7517 // For shadowing external vars, make sure that we point to the global 7518 // declaration, not a locally scoped extern declaration. 7519 for (auto I : shadowedVar->redecls()) 7520 if (I->isFileVarDecl()) { 7521 ShadowedDecl = I; 7522 break; 7523 } 7524 } 7525 7526 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7527 7528 unsigned WarningDiag = diag::warn_decl_shadow; 7529 SourceLocation CaptureLoc; 7530 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7531 isa<CXXMethodDecl>(NewDC)) { 7532 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7533 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7534 if (RD->getLambdaCaptureDefault() == LCD_None) { 7535 // Try to avoid warnings for lambdas with an explicit capture list. 7536 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7537 // Warn only when the lambda captures the shadowed decl explicitly. 7538 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7539 if (CaptureLoc.isInvalid()) 7540 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7541 } else { 7542 // Remember that this was shadowed so we can avoid the warning if the 7543 // shadowed decl isn't captured and the warning settings allow it. 7544 cast<LambdaScopeInfo>(getCurFunction()) 7545 ->ShadowingDecls.push_back( 7546 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7547 return; 7548 } 7549 } 7550 7551 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7552 // A variable can't shadow a local variable in an enclosing scope, if 7553 // they are separated by a non-capturing declaration context. 7554 for (DeclContext *ParentDC = NewDC; 7555 ParentDC && !ParentDC->Equals(OldDC); 7556 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7557 // Only block literals, captured statements, and lambda expressions 7558 // can capture; other scopes don't. 7559 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7560 !isLambdaCallOperator(ParentDC)) { 7561 return; 7562 } 7563 } 7564 } 7565 } 7566 } 7567 7568 // Only warn about certain kinds of shadowing for class members. 7569 if (NewDC && NewDC->isRecord()) { 7570 // In particular, don't warn about shadowing non-class members. 7571 if (!OldDC->isRecord()) 7572 return; 7573 7574 // TODO: should we warn about static data members shadowing 7575 // static data members from base classes? 7576 7577 // TODO: don't diagnose for inaccessible shadowed members. 7578 // This is hard to do perfectly because we might friend the 7579 // shadowing context, but that's just a false negative. 7580 } 7581 7582 7583 DeclarationName Name = R.getLookupName(); 7584 7585 // Emit warning and note. 7586 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7587 return; 7588 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7589 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7590 if (!CaptureLoc.isInvalid()) 7591 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7592 << Name << /*explicitly*/ 1; 7593 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7594 } 7595 7596 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7597 /// when these variables are captured by the lambda. 7598 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7599 for (const auto &Shadow : LSI->ShadowingDecls) { 7600 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7601 // Try to avoid the warning when the shadowed decl isn't captured. 7602 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7603 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7604 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7605 ? diag::warn_decl_shadow_uncaptured_local 7606 : diag::warn_decl_shadow) 7607 << Shadow.VD->getDeclName() 7608 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7609 if (!CaptureLoc.isInvalid()) 7610 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7611 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7612 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7613 } 7614 } 7615 7616 /// Check -Wshadow without the advantage of a previous lookup. 7617 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7618 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7619 return; 7620 7621 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7622 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7623 LookupName(R, S); 7624 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7625 CheckShadow(D, ShadowedDecl, R); 7626 } 7627 7628 /// Check if 'E', which is an expression that is about to be modified, refers 7629 /// to a constructor parameter that shadows a field. 7630 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7631 // Quickly ignore expressions that can't be shadowing ctor parameters. 7632 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7633 return; 7634 E = E->IgnoreParenImpCasts(); 7635 auto *DRE = dyn_cast<DeclRefExpr>(E); 7636 if (!DRE) 7637 return; 7638 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7639 auto I = ShadowingDecls.find(D); 7640 if (I == ShadowingDecls.end()) 7641 return; 7642 const NamedDecl *ShadowedDecl = I->second; 7643 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7644 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7645 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7646 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7647 7648 // Avoid issuing multiple warnings about the same decl. 7649 ShadowingDecls.erase(I); 7650 } 7651 7652 /// Check for conflict between this global or extern "C" declaration and 7653 /// previous global or extern "C" declarations. This is only used in C++. 7654 template<typename T> 7655 static bool checkGlobalOrExternCConflict( 7656 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7657 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7658 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7659 7660 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7661 // The common case: this global doesn't conflict with any extern "C" 7662 // declaration. 7663 return false; 7664 } 7665 7666 if (Prev) { 7667 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7668 // Both the old and new declarations have C language linkage. This is a 7669 // redeclaration. 7670 Previous.clear(); 7671 Previous.addDecl(Prev); 7672 return true; 7673 } 7674 7675 // This is a global, non-extern "C" declaration, and there is a previous 7676 // non-global extern "C" declaration. Diagnose if this is a variable 7677 // declaration. 7678 if (!isa<VarDecl>(ND)) 7679 return false; 7680 } else { 7681 // The declaration is extern "C". Check for any declaration in the 7682 // translation unit which might conflict. 7683 if (IsGlobal) { 7684 // We have already performed the lookup into the translation unit. 7685 IsGlobal = false; 7686 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7687 I != E; ++I) { 7688 if (isa<VarDecl>(*I)) { 7689 Prev = *I; 7690 break; 7691 } 7692 } 7693 } else { 7694 DeclContext::lookup_result R = 7695 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7696 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7697 I != E; ++I) { 7698 if (isa<VarDecl>(*I)) { 7699 Prev = *I; 7700 break; 7701 } 7702 // FIXME: If we have any other entity with this name in global scope, 7703 // the declaration is ill-formed, but that is a defect: it breaks the 7704 // 'stat' hack, for instance. Only variables can have mangled name 7705 // clashes with extern "C" declarations, so only they deserve a 7706 // diagnostic. 7707 } 7708 } 7709 7710 if (!Prev) 7711 return false; 7712 } 7713 7714 // Use the first declaration's location to ensure we point at something which 7715 // is lexically inside an extern "C" linkage-spec. 7716 assert(Prev && "should have found a previous declaration to diagnose"); 7717 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7718 Prev = FD->getFirstDecl(); 7719 else 7720 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7721 7722 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7723 << IsGlobal << ND; 7724 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7725 << IsGlobal; 7726 return false; 7727 } 7728 7729 /// Apply special rules for handling extern "C" declarations. Returns \c true 7730 /// if we have found that this is a redeclaration of some prior entity. 7731 /// 7732 /// Per C++ [dcl.link]p6: 7733 /// Two declarations [for a function or variable] with C language linkage 7734 /// with the same name that appear in different scopes refer to the same 7735 /// [entity]. An entity with C language linkage shall not be declared with 7736 /// the same name as an entity in global scope. 7737 template<typename T> 7738 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7739 LookupResult &Previous) { 7740 if (!S.getLangOpts().CPlusPlus) { 7741 // In C, when declaring a global variable, look for a corresponding 'extern' 7742 // variable declared in function scope. We don't need this in C++, because 7743 // we find local extern decls in the surrounding file-scope DeclContext. 7744 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7745 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7746 Previous.clear(); 7747 Previous.addDecl(Prev); 7748 return true; 7749 } 7750 } 7751 return false; 7752 } 7753 7754 // A declaration in the translation unit can conflict with an extern "C" 7755 // declaration. 7756 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7757 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7758 7759 // An extern "C" declaration can conflict with a declaration in the 7760 // translation unit or can be a redeclaration of an extern "C" declaration 7761 // in another scope. 7762 if (isIncompleteDeclExternC(S,ND)) 7763 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7764 7765 // Neither global nor extern "C": nothing to do. 7766 return false; 7767 } 7768 7769 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7770 // If the decl is already known invalid, don't check it. 7771 if (NewVD->isInvalidDecl()) 7772 return; 7773 7774 QualType T = NewVD->getType(); 7775 7776 // Defer checking an 'auto' type until its initializer is attached. 7777 if (T->isUndeducedType()) 7778 return; 7779 7780 if (NewVD->hasAttrs()) 7781 CheckAlignasUnderalignment(NewVD); 7782 7783 if (T->isObjCObjectType()) { 7784 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7785 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7786 T = Context.getObjCObjectPointerType(T); 7787 NewVD->setType(T); 7788 } 7789 7790 // Emit an error if an address space was applied to decl with local storage. 7791 // This includes arrays of objects with address space qualifiers, but not 7792 // automatic variables that point to other address spaces. 7793 // ISO/IEC TR 18037 S5.1.2 7794 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7795 T.getAddressSpace() != LangAS::Default) { 7796 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7797 NewVD->setInvalidDecl(); 7798 return; 7799 } 7800 7801 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7802 // scope. 7803 if (getLangOpts().OpenCLVersion == 120 && 7804 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7805 NewVD->isStaticLocal()) { 7806 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7807 NewVD->setInvalidDecl(); 7808 return; 7809 } 7810 7811 if (getLangOpts().OpenCL) { 7812 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7813 if (NewVD->hasAttr<BlocksAttr>()) { 7814 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7815 return; 7816 } 7817 7818 if (T->isBlockPointerType()) { 7819 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7820 // can't use 'extern' storage class. 7821 if (!T.isConstQualified()) { 7822 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7823 << 0 /*const*/; 7824 NewVD->setInvalidDecl(); 7825 return; 7826 } 7827 if (NewVD->hasExternalStorage()) { 7828 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7829 NewVD->setInvalidDecl(); 7830 return; 7831 } 7832 } 7833 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7834 // __constant address space. 7835 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7836 // variables inside a function can also be declared in the global 7837 // address space. 7838 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7839 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7840 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7841 NewVD->hasExternalStorage()) { 7842 if (!T->isSamplerT() && 7843 !(T.getAddressSpace() == LangAS::opencl_constant || 7844 (T.getAddressSpace() == LangAS::opencl_global && 7845 (getLangOpts().OpenCLVersion == 200 || 7846 getLangOpts().OpenCLCPlusPlus)))) { 7847 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7848 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7849 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7850 << Scope << "global or constant"; 7851 else 7852 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7853 << Scope << "constant"; 7854 NewVD->setInvalidDecl(); 7855 return; 7856 } 7857 } else { 7858 if (T.getAddressSpace() == LangAS::opencl_global) { 7859 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7860 << 1 /*is any function*/ << "global"; 7861 NewVD->setInvalidDecl(); 7862 return; 7863 } 7864 if (T.getAddressSpace() == LangAS::opencl_constant || 7865 T.getAddressSpace() == LangAS::opencl_local) { 7866 FunctionDecl *FD = getCurFunctionDecl(); 7867 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7868 // in functions. 7869 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7870 if (T.getAddressSpace() == LangAS::opencl_constant) 7871 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7872 << 0 /*non-kernel only*/ << "constant"; 7873 else 7874 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7875 << 0 /*non-kernel only*/ << "local"; 7876 NewVD->setInvalidDecl(); 7877 return; 7878 } 7879 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7880 // in the outermost scope of a kernel function. 7881 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7882 if (!getCurScope()->isFunctionScope()) { 7883 if (T.getAddressSpace() == LangAS::opencl_constant) 7884 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7885 << "constant"; 7886 else 7887 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7888 << "local"; 7889 NewVD->setInvalidDecl(); 7890 return; 7891 } 7892 } 7893 } else if (T.getAddressSpace() != LangAS::opencl_private && 7894 // If we are parsing a template we didn't deduce an addr 7895 // space yet. 7896 T.getAddressSpace() != LangAS::Default) { 7897 // Do not allow other address spaces on automatic variable. 7898 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7899 NewVD->setInvalidDecl(); 7900 return; 7901 } 7902 } 7903 } 7904 7905 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7906 && !NewVD->hasAttr<BlocksAttr>()) { 7907 if (getLangOpts().getGC() != LangOptions::NonGC) 7908 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7909 else { 7910 assert(!getLangOpts().ObjCAutoRefCount); 7911 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7912 } 7913 } 7914 7915 bool isVM = T->isVariablyModifiedType(); 7916 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7917 NewVD->hasAttr<BlocksAttr>()) 7918 setFunctionHasBranchProtectedScope(); 7919 7920 if ((isVM && NewVD->hasLinkage()) || 7921 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7922 bool SizeIsNegative; 7923 llvm::APSInt Oversized; 7924 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7925 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7926 QualType FixedT; 7927 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7928 FixedT = FixedTInfo->getType(); 7929 else if (FixedTInfo) { 7930 // Type and type-as-written are canonically different. We need to fix up 7931 // both types separately. 7932 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7933 Oversized); 7934 } 7935 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7936 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7937 // FIXME: This won't give the correct result for 7938 // int a[10][n]; 7939 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7940 7941 if (NewVD->isFileVarDecl()) 7942 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7943 << SizeRange; 7944 else if (NewVD->isStaticLocal()) 7945 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7946 << SizeRange; 7947 else 7948 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7949 << SizeRange; 7950 NewVD->setInvalidDecl(); 7951 return; 7952 } 7953 7954 if (!FixedTInfo) { 7955 if (NewVD->isFileVarDecl()) 7956 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7957 else 7958 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7959 NewVD->setInvalidDecl(); 7960 return; 7961 } 7962 7963 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7964 NewVD->setType(FixedT); 7965 NewVD->setTypeSourceInfo(FixedTInfo); 7966 } 7967 7968 if (T->isVoidType()) { 7969 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7970 // of objects and functions. 7971 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7972 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7973 << T; 7974 NewVD->setInvalidDecl(); 7975 return; 7976 } 7977 } 7978 7979 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7980 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7981 NewVD->setInvalidDecl(); 7982 return; 7983 } 7984 7985 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 7986 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 7987 NewVD->setInvalidDecl(); 7988 return; 7989 } 7990 7991 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7992 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7993 NewVD->setInvalidDecl(); 7994 return; 7995 } 7996 7997 if (NewVD->isConstexpr() && !T->isDependentType() && 7998 RequireLiteralType(NewVD->getLocation(), T, 7999 diag::err_constexpr_var_non_literal)) { 8000 NewVD->setInvalidDecl(); 8001 return; 8002 } 8003 } 8004 8005 /// Perform semantic checking on a newly-created variable 8006 /// declaration. 8007 /// 8008 /// This routine performs all of the type-checking required for a 8009 /// variable declaration once it has been built. It is used both to 8010 /// check variables after they have been parsed and their declarators 8011 /// have been translated into a declaration, and to check variables 8012 /// that have been instantiated from a template. 8013 /// 8014 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8015 /// 8016 /// Returns true if the variable declaration is a redeclaration. 8017 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8018 CheckVariableDeclarationType(NewVD); 8019 8020 // If the decl is already known invalid, don't check it. 8021 if (NewVD->isInvalidDecl()) 8022 return false; 8023 8024 // If we did not find anything by this name, look for a non-visible 8025 // extern "C" declaration with the same name. 8026 if (Previous.empty() && 8027 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8028 Previous.setShadowed(); 8029 8030 if (!Previous.empty()) { 8031 MergeVarDecl(NewVD, Previous); 8032 return true; 8033 } 8034 return false; 8035 } 8036 8037 namespace { 8038 struct FindOverriddenMethod { 8039 Sema *S; 8040 CXXMethodDecl *Method; 8041 8042 /// Member lookup function that determines whether a given C++ 8043 /// method overrides a method in a base class, to be used with 8044 /// CXXRecordDecl::lookupInBases(). 8045 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8046 RecordDecl *BaseRecord = 8047 Specifier->getType()->castAs<RecordType>()->getDecl(); 8048 8049 DeclarationName Name = Method->getDeclName(); 8050 8051 // FIXME: Do we care about other names here too? 8052 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8053 // We really want to find the base class destructor here. 8054 QualType T = S->Context.getTypeDeclType(BaseRecord); 8055 CanQualType CT = S->Context.getCanonicalType(T); 8056 8057 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 8058 } 8059 8060 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 8061 Path.Decls = Path.Decls.slice(1)) { 8062 NamedDecl *D = Path.Decls.front(); 8063 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 8064 if (MD->isVirtual() && 8065 !S->IsOverload( 8066 Method, MD, /*UseMemberUsingDeclRules=*/false, 8067 /*ConsiderCudaAttrs=*/true, 8068 // C++2a [class.virtual]p2 does not consider requires clauses 8069 // when overriding. 8070 /*ConsiderRequiresClauses=*/false)) 8071 return true; 8072 } 8073 } 8074 8075 return false; 8076 } 8077 }; 8078 } // end anonymous namespace 8079 8080 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8081 /// and if so, check that it's a valid override and remember it. 8082 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8083 // Look for methods in base classes that this method might override. 8084 CXXBasePaths Paths; 8085 FindOverriddenMethod FOM; 8086 FOM.Method = MD; 8087 FOM.S = this; 8088 bool AddedAny = false; 8089 if (DC->lookupInBases(FOM, Paths)) { 8090 for (auto *I : Paths.found_decls()) { 8091 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 8092 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 8093 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 8094 !CheckOverridingFunctionAttributes(MD, OldMD) && 8095 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 8096 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 8097 AddedAny = true; 8098 } 8099 } 8100 } 8101 } 8102 8103 return AddedAny; 8104 } 8105 8106 namespace { 8107 // Struct for holding all of the extra arguments needed by 8108 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8109 struct ActOnFDArgs { 8110 Scope *S; 8111 Declarator &D; 8112 MultiTemplateParamsArg TemplateParamLists; 8113 bool AddToScope; 8114 }; 8115 } // end anonymous namespace 8116 8117 namespace { 8118 8119 // Callback to only accept typo corrections that have a non-zero edit distance. 8120 // Also only accept corrections that have the same parent decl. 8121 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8122 public: 8123 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8124 CXXRecordDecl *Parent) 8125 : Context(Context), OriginalFD(TypoFD), 8126 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8127 8128 bool ValidateCandidate(const TypoCorrection &candidate) override { 8129 if (candidate.getEditDistance() == 0) 8130 return false; 8131 8132 SmallVector<unsigned, 1> MismatchedParams; 8133 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8134 CDeclEnd = candidate.end(); 8135 CDecl != CDeclEnd; ++CDecl) { 8136 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8137 8138 if (FD && !FD->hasBody() && 8139 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8140 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8141 CXXRecordDecl *Parent = MD->getParent(); 8142 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8143 return true; 8144 } else if (!ExpectedParent) { 8145 return true; 8146 } 8147 } 8148 } 8149 8150 return false; 8151 } 8152 8153 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8154 return std::make_unique<DifferentNameValidatorCCC>(*this); 8155 } 8156 8157 private: 8158 ASTContext &Context; 8159 FunctionDecl *OriginalFD; 8160 CXXRecordDecl *ExpectedParent; 8161 }; 8162 8163 } // end anonymous namespace 8164 8165 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8166 TypoCorrectedFunctionDefinitions.insert(F); 8167 } 8168 8169 /// Generate diagnostics for an invalid function redeclaration. 8170 /// 8171 /// This routine handles generating the diagnostic messages for an invalid 8172 /// function redeclaration, including finding possible similar declarations 8173 /// or performing typo correction if there are no previous declarations with 8174 /// the same name. 8175 /// 8176 /// Returns a NamedDecl iff typo correction was performed and substituting in 8177 /// the new declaration name does not cause new errors. 8178 static NamedDecl *DiagnoseInvalidRedeclaration( 8179 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8180 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8181 DeclarationName Name = NewFD->getDeclName(); 8182 DeclContext *NewDC = NewFD->getDeclContext(); 8183 SmallVector<unsigned, 1> MismatchedParams; 8184 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8185 TypoCorrection Correction; 8186 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8187 unsigned DiagMsg = 8188 IsLocalFriend ? diag::err_no_matching_local_friend : 8189 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8190 diag::err_member_decl_does_not_match; 8191 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8192 IsLocalFriend ? Sema::LookupLocalFriendName 8193 : Sema::LookupOrdinaryName, 8194 Sema::ForVisibleRedeclaration); 8195 8196 NewFD->setInvalidDecl(); 8197 if (IsLocalFriend) 8198 SemaRef.LookupName(Prev, S); 8199 else 8200 SemaRef.LookupQualifiedName(Prev, NewDC); 8201 assert(!Prev.isAmbiguous() && 8202 "Cannot have an ambiguity in previous-declaration lookup"); 8203 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8204 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8205 MD ? MD->getParent() : nullptr); 8206 if (!Prev.empty()) { 8207 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8208 Func != FuncEnd; ++Func) { 8209 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8210 if (FD && 8211 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8212 // Add 1 to the index so that 0 can mean the mismatch didn't 8213 // involve a parameter 8214 unsigned ParamNum = 8215 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8216 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8217 } 8218 } 8219 // If the qualified name lookup yielded nothing, try typo correction 8220 } else if ((Correction = SemaRef.CorrectTypo( 8221 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8222 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8223 IsLocalFriend ? nullptr : NewDC))) { 8224 // Set up everything for the call to ActOnFunctionDeclarator 8225 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8226 ExtraArgs.D.getIdentifierLoc()); 8227 Previous.clear(); 8228 Previous.setLookupName(Correction.getCorrection()); 8229 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8230 CDeclEnd = Correction.end(); 8231 CDecl != CDeclEnd; ++CDecl) { 8232 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8233 if (FD && !FD->hasBody() && 8234 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8235 Previous.addDecl(FD); 8236 } 8237 } 8238 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8239 8240 NamedDecl *Result; 8241 // Retry building the function declaration with the new previous 8242 // declarations, and with errors suppressed. 8243 { 8244 // Trap errors. 8245 Sema::SFINAETrap Trap(SemaRef); 8246 8247 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8248 // pieces need to verify the typo-corrected C++ declaration and hopefully 8249 // eliminate the need for the parameter pack ExtraArgs. 8250 Result = SemaRef.ActOnFunctionDeclarator( 8251 ExtraArgs.S, ExtraArgs.D, 8252 Correction.getCorrectionDecl()->getDeclContext(), 8253 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8254 ExtraArgs.AddToScope); 8255 8256 if (Trap.hasErrorOccurred()) 8257 Result = nullptr; 8258 } 8259 8260 if (Result) { 8261 // Determine which correction we picked. 8262 Decl *Canonical = Result->getCanonicalDecl(); 8263 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8264 I != E; ++I) 8265 if ((*I)->getCanonicalDecl() == Canonical) 8266 Correction.setCorrectionDecl(*I); 8267 8268 // Let Sema know about the correction. 8269 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8270 SemaRef.diagnoseTypo( 8271 Correction, 8272 SemaRef.PDiag(IsLocalFriend 8273 ? diag::err_no_matching_local_friend_suggest 8274 : diag::err_member_decl_does_not_match_suggest) 8275 << Name << NewDC << IsDefinition); 8276 return Result; 8277 } 8278 8279 // Pretend the typo correction never occurred 8280 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8281 ExtraArgs.D.getIdentifierLoc()); 8282 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8283 Previous.clear(); 8284 Previous.setLookupName(Name); 8285 } 8286 8287 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8288 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8289 8290 bool NewFDisConst = false; 8291 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8292 NewFDisConst = NewMD->isConst(); 8293 8294 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8295 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8296 NearMatch != NearMatchEnd; ++NearMatch) { 8297 FunctionDecl *FD = NearMatch->first; 8298 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8299 bool FDisConst = MD && MD->isConst(); 8300 bool IsMember = MD || !IsLocalFriend; 8301 8302 // FIXME: These notes are poorly worded for the local friend case. 8303 if (unsigned Idx = NearMatch->second) { 8304 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8305 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8306 if (Loc.isInvalid()) Loc = FD->getLocation(); 8307 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8308 : diag::note_local_decl_close_param_match) 8309 << Idx << FDParam->getType() 8310 << NewFD->getParamDecl(Idx - 1)->getType(); 8311 } else if (FDisConst != NewFDisConst) { 8312 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8313 << NewFDisConst << FD->getSourceRange().getEnd(); 8314 } else 8315 SemaRef.Diag(FD->getLocation(), 8316 IsMember ? diag::note_member_def_close_match 8317 : diag::note_local_decl_close_match); 8318 } 8319 return nullptr; 8320 } 8321 8322 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8323 switch (D.getDeclSpec().getStorageClassSpec()) { 8324 default: llvm_unreachable("Unknown storage class!"); 8325 case DeclSpec::SCS_auto: 8326 case DeclSpec::SCS_register: 8327 case DeclSpec::SCS_mutable: 8328 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8329 diag::err_typecheck_sclass_func); 8330 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8331 D.setInvalidType(); 8332 break; 8333 case DeclSpec::SCS_unspecified: break; 8334 case DeclSpec::SCS_extern: 8335 if (D.getDeclSpec().isExternInLinkageSpec()) 8336 return SC_None; 8337 return SC_Extern; 8338 case DeclSpec::SCS_static: { 8339 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8340 // C99 6.7.1p5: 8341 // The declaration of an identifier for a function that has 8342 // block scope shall have no explicit storage-class specifier 8343 // other than extern 8344 // See also (C++ [dcl.stc]p4). 8345 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8346 diag::err_static_block_func); 8347 break; 8348 } else 8349 return SC_Static; 8350 } 8351 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8352 } 8353 8354 // No explicit storage class has already been returned 8355 return SC_None; 8356 } 8357 8358 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8359 DeclContext *DC, QualType &R, 8360 TypeSourceInfo *TInfo, 8361 StorageClass SC, 8362 bool &IsVirtualOkay) { 8363 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8364 DeclarationName Name = NameInfo.getName(); 8365 8366 FunctionDecl *NewFD = nullptr; 8367 bool isInline = D.getDeclSpec().isInlineSpecified(); 8368 8369 if (!SemaRef.getLangOpts().CPlusPlus) { 8370 // Determine whether the function was written with a 8371 // prototype. This true when: 8372 // - there is a prototype in the declarator, or 8373 // - the type R of the function is some kind of typedef or other non- 8374 // attributed reference to a type name (which eventually refers to a 8375 // function type). 8376 bool HasPrototype = 8377 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8378 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8379 8380 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8381 R, TInfo, SC, isInline, HasPrototype, 8382 CSK_unspecified, 8383 /*TrailingRequiresClause=*/nullptr); 8384 if (D.isInvalidType()) 8385 NewFD->setInvalidDecl(); 8386 8387 return NewFD; 8388 } 8389 8390 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8391 8392 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8393 if (ConstexprKind == CSK_constinit) { 8394 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8395 diag::err_constexpr_wrong_decl_kind) 8396 << ConstexprKind; 8397 ConstexprKind = CSK_unspecified; 8398 D.getMutableDeclSpec().ClearConstexprSpec(); 8399 } 8400 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8401 8402 // Check that the return type is not an abstract class type. 8403 // For record types, this is done by the AbstractClassUsageDiagnoser once 8404 // the class has been completely parsed. 8405 if (!DC->isRecord() && 8406 SemaRef.RequireNonAbstractType( 8407 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8408 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8409 D.setInvalidType(); 8410 8411 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8412 // This is a C++ constructor declaration. 8413 assert(DC->isRecord() && 8414 "Constructors can only be declared in a member context"); 8415 8416 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8417 return CXXConstructorDecl::Create( 8418 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8419 TInfo, ExplicitSpecifier, isInline, 8420 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8421 TrailingRequiresClause); 8422 8423 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8424 // This is a C++ destructor declaration. 8425 if (DC->isRecord()) { 8426 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8427 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8428 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8429 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8430 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8431 TrailingRequiresClause); 8432 8433 // If the destructor needs an implicit exception specification, set it 8434 // now. FIXME: It'd be nice to be able to create the right type to start 8435 // with, but the type needs to reference the destructor declaration. 8436 if (SemaRef.getLangOpts().CPlusPlus11) 8437 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8438 8439 IsVirtualOkay = true; 8440 return NewDD; 8441 8442 } else { 8443 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8444 D.setInvalidType(); 8445 8446 // Create a FunctionDecl to satisfy the function definition parsing 8447 // code path. 8448 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8449 D.getIdentifierLoc(), Name, R, TInfo, SC, 8450 isInline, 8451 /*hasPrototype=*/true, ConstexprKind, 8452 TrailingRequiresClause); 8453 } 8454 8455 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8456 if (!DC->isRecord()) { 8457 SemaRef.Diag(D.getIdentifierLoc(), 8458 diag::err_conv_function_not_member); 8459 return nullptr; 8460 } 8461 8462 SemaRef.CheckConversionDeclarator(D, R, SC); 8463 if (D.isInvalidType()) 8464 return nullptr; 8465 8466 IsVirtualOkay = true; 8467 return CXXConversionDecl::Create( 8468 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8469 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8470 TrailingRequiresClause); 8471 8472 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8473 if (TrailingRequiresClause) 8474 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8475 diag::err_trailing_requires_clause_on_deduction_guide) 8476 << TrailingRequiresClause->getSourceRange(); 8477 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8478 8479 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8480 ExplicitSpecifier, NameInfo, R, TInfo, 8481 D.getEndLoc()); 8482 } else if (DC->isRecord()) { 8483 // If the name of the function is the same as the name of the record, 8484 // then this must be an invalid constructor that has a return type. 8485 // (The parser checks for a return type and makes the declarator a 8486 // constructor if it has no return type). 8487 if (Name.getAsIdentifierInfo() && 8488 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8489 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8490 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8491 << SourceRange(D.getIdentifierLoc()); 8492 return nullptr; 8493 } 8494 8495 // This is a C++ method declaration. 8496 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8497 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8498 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8499 TrailingRequiresClause); 8500 IsVirtualOkay = !Ret->isStatic(); 8501 return Ret; 8502 } else { 8503 bool isFriend = 8504 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8505 if (!isFriend && SemaRef.CurContext->isRecord()) 8506 return nullptr; 8507 8508 // Determine whether the function was written with a 8509 // prototype. This true when: 8510 // - we're in C++ (where every function has a prototype), 8511 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8512 R, TInfo, SC, isInline, true /*HasPrototype*/, 8513 ConstexprKind, TrailingRequiresClause); 8514 } 8515 } 8516 8517 enum OpenCLParamType { 8518 ValidKernelParam, 8519 PtrPtrKernelParam, 8520 PtrKernelParam, 8521 InvalidAddrSpacePtrKernelParam, 8522 InvalidKernelParam, 8523 RecordKernelParam 8524 }; 8525 8526 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8527 // Size dependent types are just typedefs to normal integer types 8528 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8529 // integers other than by their names. 8530 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8531 8532 // Remove typedefs one by one until we reach a typedef 8533 // for a size dependent type. 8534 QualType DesugaredTy = Ty; 8535 do { 8536 ArrayRef<StringRef> Names(SizeTypeNames); 8537 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8538 if (Names.end() != Match) 8539 return true; 8540 8541 Ty = DesugaredTy; 8542 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8543 } while (DesugaredTy != Ty); 8544 8545 return false; 8546 } 8547 8548 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8549 if (PT->isPointerType()) { 8550 QualType PointeeType = PT->getPointeeType(); 8551 if (PointeeType->isPointerType()) 8552 return PtrPtrKernelParam; 8553 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8554 PointeeType.getAddressSpace() == LangAS::opencl_private || 8555 PointeeType.getAddressSpace() == LangAS::Default) 8556 return InvalidAddrSpacePtrKernelParam; 8557 return PtrKernelParam; 8558 } 8559 8560 // OpenCL v1.2 s6.9.k: 8561 // Arguments to kernel functions in a program cannot be declared with the 8562 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8563 // uintptr_t or a struct and/or union that contain fields declared to be one 8564 // of these built-in scalar types. 8565 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8566 return InvalidKernelParam; 8567 8568 if (PT->isImageType()) 8569 return PtrKernelParam; 8570 8571 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8572 return InvalidKernelParam; 8573 8574 // OpenCL extension spec v1.2 s9.5: 8575 // This extension adds support for half scalar and vector types as built-in 8576 // types that can be used for arithmetic operations, conversions etc. 8577 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8578 return InvalidKernelParam; 8579 8580 if (PT->isRecordType()) 8581 return RecordKernelParam; 8582 8583 // Look into an array argument to check if it has a forbidden type. 8584 if (PT->isArrayType()) { 8585 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8586 // Call ourself to check an underlying type of an array. Since the 8587 // getPointeeOrArrayElementType returns an innermost type which is not an 8588 // array, this recursive call only happens once. 8589 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8590 } 8591 8592 return ValidKernelParam; 8593 } 8594 8595 static void checkIsValidOpenCLKernelParameter( 8596 Sema &S, 8597 Declarator &D, 8598 ParmVarDecl *Param, 8599 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8600 QualType PT = Param->getType(); 8601 8602 // Cache the valid types we encounter to avoid rechecking structs that are 8603 // used again 8604 if (ValidTypes.count(PT.getTypePtr())) 8605 return; 8606 8607 switch (getOpenCLKernelParameterType(S, PT)) { 8608 case PtrPtrKernelParam: 8609 // OpenCL v1.2 s6.9.a: 8610 // A kernel function argument cannot be declared as a 8611 // pointer to a pointer type. 8612 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8613 D.setInvalidType(); 8614 return; 8615 8616 case InvalidAddrSpacePtrKernelParam: 8617 // OpenCL v1.0 s6.5: 8618 // __kernel function arguments declared to be a pointer of a type can point 8619 // to one of the following address spaces only : __global, __local or 8620 // __constant. 8621 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8622 D.setInvalidType(); 8623 return; 8624 8625 // OpenCL v1.2 s6.9.k: 8626 // Arguments to kernel functions in a program cannot be declared with the 8627 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8628 // uintptr_t or a struct and/or union that contain fields declared to be 8629 // one of these built-in scalar types. 8630 8631 case InvalidKernelParam: 8632 // OpenCL v1.2 s6.8 n: 8633 // A kernel function argument cannot be declared 8634 // of event_t type. 8635 // Do not diagnose half type since it is diagnosed as invalid argument 8636 // type for any function elsewhere. 8637 if (!PT->isHalfType()) { 8638 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8639 8640 // Explain what typedefs are involved. 8641 const TypedefType *Typedef = nullptr; 8642 while ((Typedef = PT->getAs<TypedefType>())) { 8643 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8644 // SourceLocation may be invalid for a built-in type. 8645 if (Loc.isValid()) 8646 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8647 PT = Typedef->desugar(); 8648 } 8649 } 8650 8651 D.setInvalidType(); 8652 return; 8653 8654 case PtrKernelParam: 8655 case ValidKernelParam: 8656 ValidTypes.insert(PT.getTypePtr()); 8657 return; 8658 8659 case RecordKernelParam: 8660 break; 8661 } 8662 8663 // Track nested structs we will inspect 8664 SmallVector<const Decl *, 4> VisitStack; 8665 8666 // Track where we are in the nested structs. Items will migrate from 8667 // VisitStack to HistoryStack as we do the DFS for bad field. 8668 SmallVector<const FieldDecl *, 4> HistoryStack; 8669 HistoryStack.push_back(nullptr); 8670 8671 // At this point we already handled everything except of a RecordType or 8672 // an ArrayType of a RecordType. 8673 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8674 const RecordType *RecTy = 8675 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8676 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8677 8678 VisitStack.push_back(RecTy->getDecl()); 8679 assert(VisitStack.back() && "First decl null?"); 8680 8681 do { 8682 const Decl *Next = VisitStack.pop_back_val(); 8683 if (!Next) { 8684 assert(!HistoryStack.empty()); 8685 // Found a marker, we have gone up a level 8686 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8687 ValidTypes.insert(Hist->getType().getTypePtr()); 8688 8689 continue; 8690 } 8691 8692 // Adds everything except the original parameter declaration (which is not a 8693 // field itself) to the history stack. 8694 const RecordDecl *RD; 8695 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8696 HistoryStack.push_back(Field); 8697 8698 QualType FieldTy = Field->getType(); 8699 // Other field types (known to be valid or invalid) are handled while we 8700 // walk around RecordDecl::fields(). 8701 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8702 "Unexpected type."); 8703 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8704 8705 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8706 } else { 8707 RD = cast<RecordDecl>(Next); 8708 } 8709 8710 // Add a null marker so we know when we've gone back up a level 8711 VisitStack.push_back(nullptr); 8712 8713 for (const auto *FD : RD->fields()) { 8714 QualType QT = FD->getType(); 8715 8716 if (ValidTypes.count(QT.getTypePtr())) 8717 continue; 8718 8719 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8720 if (ParamType == ValidKernelParam) 8721 continue; 8722 8723 if (ParamType == RecordKernelParam) { 8724 VisitStack.push_back(FD); 8725 continue; 8726 } 8727 8728 // OpenCL v1.2 s6.9.p: 8729 // Arguments to kernel functions that are declared to be a struct or union 8730 // do not allow OpenCL objects to be passed as elements of the struct or 8731 // union. 8732 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8733 ParamType == InvalidAddrSpacePtrKernelParam) { 8734 S.Diag(Param->getLocation(), 8735 diag::err_record_with_pointers_kernel_param) 8736 << PT->isUnionType() 8737 << PT; 8738 } else { 8739 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8740 } 8741 8742 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8743 << OrigRecDecl->getDeclName(); 8744 8745 // We have an error, now let's go back up through history and show where 8746 // the offending field came from 8747 for (ArrayRef<const FieldDecl *>::const_iterator 8748 I = HistoryStack.begin() + 1, 8749 E = HistoryStack.end(); 8750 I != E; ++I) { 8751 const FieldDecl *OuterField = *I; 8752 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8753 << OuterField->getType(); 8754 } 8755 8756 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8757 << QT->isPointerType() 8758 << QT; 8759 D.setInvalidType(); 8760 return; 8761 } 8762 } while (!VisitStack.empty()); 8763 } 8764 8765 /// Find the DeclContext in which a tag is implicitly declared if we see an 8766 /// elaborated type specifier in the specified context, and lookup finds 8767 /// nothing. 8768 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8769 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8770 DC = DC->getParent(); 8771 return DC; 8772 } 8773 8774 /// Find the Scope in which a tag is implicitly declared if we see an 8775 /// elaborated type specifier in the specified context, and lookup finds 8776 /// nothing. 8777 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8778 while (S->isClassScope() || 8779 (LangOpts.CPlusPlus && 8780 S->isFunctionPrototypeScope()) || 8781 ((S->getFlags() & Scope::DeclScope) == 0) || 8782 (S->getEntity() && S->getEntity()->isTransparentContext())) 8783 S = S->getParent(); 8784 return S; 8785 } 8786 8787 NamedDecl* 8788 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8789 TypeSourceInfo *TInfo, LookupResult &Previous, 8790 MultiTemplateParamsArg TemplateParamListsRef, 8791 bool &AddToScope) { 8792 QualType R = TInfo->getType(); 8793 8794 assert(R->isFunctionType()); 8795 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 8796 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 8797 8798 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8799 for (TemplateParameterList *TPL : TemplateParamListsRef) 8800 TemplateParamLists.push_back(TPL); 8801 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8802 if (!TemplateParamLists.empty() && 8803 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8804 TemplateParamLists.back() = Invented; 8805 else 8806 TemplateParamLists.push_back(Invented); 8807 } 8808 8809 // TODO: consider using NameInfo for diagnostic. 8810 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8811 DeclarationName Name = NameInfo.getName(); 8812 StorageClass SC = getFunctionStorageClass(*this, D); 8813 8814 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8815 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8816 diag::err_invalid_thread) 8817 << DeclSpec::getSpecifierName(TSCS); 8818 8819 if (D.isFirstDeclarationOfMember()) 8820 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8821 D.getIdentifierLoc()); 8822 8823 bool isFriend = false; 8824 FunctionTemplateDecl *FunctionTemplate = nullptr; 8825 bool isMemberSpecialization = false; 8826 bool isFunctionTemplateSpecialization = false; 8827 8828 bool isDependentClassScopeExplicitSpecialization = false; 8829 bool HasExplicitTemplateArgs = false; 8830 TemplateArgumentListInfo TemplateArgs; 8831 8832 bool isVirtualOkay = false; 8833 8834 DeclContext *OriginalDC = DC; 8835 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8836 8837 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8838 isVirtualOkay); 8839 if (!NewFD) return nullptr; 8840 8841 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8842 NewFD->setTopLevelDeclInObjCContainer(); 8843 8844 // Set the lexical context. If this is a function-scope declaration, or has a 8845 // C++ scope specifier, or is the object of a friend declaration, the lexical 8846 // context will be different from the semantic context. 8847 NewFD->setLexicalDeclContext(CurContext); 8848 8849 if (IsLocalExternDecl) 8850 NewFD->setLocalExternDecl(); 8851 8852 if (getLangOpts().CPlusPlus) { 8853 bool isInline = D.getDeclSpec().isInlineSpecified(); 8854 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8855 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8856 isFriend = D.getDeclSpec().isFriendSpecified(); 8857 if (isFriend && !isInline && D.isFunctionDefinition()) { 8858 // C++ [class.friend]p5 8859 // A function can be defined in a friend declaration of a 8860 // class . . . . Such a function is implicitly inline. 8861 NewFD->setImplicitlyInline(); 8862 } 8863 8864 // If this is a method defined in an __interface, and is not a constructor 8865 // or an overloaded operator, then set the pure flag (isVirtual will already 8866 // return true). 8867 if (const CXXRecordDecl *Parent = 8868 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8869 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8870 NewFD->setPure(true); 8871 8872 // C++ [class.union]p2 8873 // A union can have member functions, but not virtual functions. 8874 if (isVirtual && Parent->isUnion()) 8875 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8876 } 8877 8878 SetNestedNameSpecifier(*this, NewFD, D); 8879 isMemberSpecialization = false; 8880 isFunctionTemplateSpecialization = false; 8881 if (D.isInvalidType()) 8882 NewFD->setInvalidDecl(); 8883 8884 // Match up the template parameter lists with the scope specifier, then 8885 // determine whether we have a template or a template specialization. 8886 bool Invalid = false; 8887 TemplateParameterList *TemplateParams = 8888 MatchTemplateParametersToScopeSpecifier( 8889 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8890 D.getCXXScopeSpec(), 8891 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8892 ? D.getName().TemplateId 8893 : nullptr, 8894 TemplateParamLists, isFriend, isMemberSpecialization, 8895 Invalid); 8896 if (TemplateParams) { 8897 if (TemplateParams->size() > 0) { 8898 // This is a function template 8899 8900 // Check that we can declare a template here. 8901 if (CheckTemplateDeclScope(S, TemplateParams)) 8902 NewFD->setInvalidDecl(); 8903 8904 // A destructor cannot be a template. 8905 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8906 Diag(NewFD->getLocation(), diag::err_destructor_template); 8907 NewFD->setInvalidDecl(); 8908 } 8909 8910 // If we're adding a template to a dependent context, we may need to 8911 // rebuilding some of the types used within the template parameter list, 8912 // now that we know what the current instantiation is. 8913 if (DC->isDependentContext()) { 8914 ContextRAII SavedContext(*this, DC); 8915 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8916 Invalid = true; 8917 } 8918 8919 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8920 NewFD->getLocation(), 8921 Name, TemplateParams, 8922 NewFD); 8923 FunctionTemplate->setLexicalDeclContext(CurContext); 8924 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8925 8926 // For source fidelity, store the other template param lists. 8927 if (TemplateParamLists.size() > 1) { 8928 NewFD->setTemplateParameterListsInfo(Context, 8929 ArrayRef<TemplateParameterList *>(TemplateParamLists) 8930 .drop_back(1)); 8931 } 8932 } else { 8933 // This is a function template specialization. 8934 isFunctionTemplateSpecialization = true; 8935 // For source fidelity, store all the template param lists. 8936 if (TemplateParamLists.size() > 0) 8937 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8938 8939 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8940 if (isFriend) { 8941 // We want to remove the "template<>", found here. 8942 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8943 8944 // If we remove the template<> and the name is not a 8945 // template-id, we're actually silently creating a problem: 8946 // the friend declaration will refer to an untemplated decl, 8947 // and clearly the user wants a template specialization. So 8948 // we need to insert '<>' after the name. 8949 SourceLocation InsertLoc; 8950 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8951 InsertLoc = D.getName().getSourceRange().getEnd(); 8952 InsertLoc = getLocForEndOfToken(InsertLoc); 8953 } 8954 8955 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8956 << Name << RemoveRange 8957 << FixItHint::CreateRemoval(RemoveRange) 8958 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8959 } 8960 } 8961 } else { 8962 // All template param lists were matched against the scope specifier: 8963 // this is NOT (an explicit specialization of) a template. 8964 if (TemplateParamLists.size() > 0) 8965 // For source fidelity, store all the template param lists. 8966 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8967 } 8968 8969 if (Invalid) { 8970 NewFD->setInvalidDecl(); 8971 if (FunctionTemplate) 8972 FunctionTemplate->setInvalidDecl(); 8973 } 8974 8975 // C++ [dcl.fct.spec]p5: 8976 // The virtual specifier shall only be used in declarations of 8977 // nonstatic class member functions that appear within a 8978 // member-specification of a class declaration; see 10.3. 8979 // 8980 if (isVirtual && !NewFD->isInvalidDecl()) { 8981 if (!isVirtualOkay) { 8982 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8983 diag::err_virtual_non_function); 8984 } else if (!CurContext->isRecord()) { 8985 // 'virtual' was specified outside of the class. 8986 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8987 diag::err_virtual_out_of_class) 8988 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8989 } else if (NewFD->getDescribedFunctionTemplate()) { 8990 // C++ [temp.mem]p3: 8991 // A member function template shall not be virtual. 8992 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8993 diag::err_virtual_member_function_template) 8994 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8995 } else { 8996 // Okay: Add virtual to the method. 8997 NewFD->setVirtualAsWritten(true); 8998 } 8999 9000 if (getLangOpts().CPlusPlus14 && 9001 NewFD->getReturnType()->isUndeducedType()) 9002 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9003 } 9004 9005 if (getLangOpts().CPlusPlus14 && 9006 (NewFD->isDependentContext() || 9007 (isFriend && CurContext->isDependentContext())) && 9008 NewFD->getReturnType()->isUndeducedType()) { 9009 // If the function template is referenced directly (for instance, as a 9010 // member of the current instantiation), pretend it has a dependent type. 9011 // This is not really justified by the standard, but is the only sane 9012 // thing to do. 9013 // FIXME: For a friend function, we have not marked the function as being 9014 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9015 const FunctionProtoType *FPT = 9016 NewFD->getType()->castAs<FunctionProtoType>(); 9017 QualType Result = 9018 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9019 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9020 FPT->getExtProtoInfo())); 9021 } 9022 9023 // C++ [dcl.fct.spec]p3: 9024 // The inline specifier shall not appear on a block scope function 9025 // declaration. 9026 if (isInline && !NewFD->isInvalidDecl()) { 9027 if (CurContext->isFunctionOrMethod()) { 9028 // 'inline' is not allowed on block scope function declaration. 9029 Diag(D.getDeclSpec().getInlineSpecLoc(), 9030 diag::err_inline_declaration_block_scope) << Name 9031 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9032 } 9033 } 9034 9035 // C++ [dcl.fct.spec]p6: 9036 // The explicit specifier shall be used only in the declaration of a 9037 // constructor or conversion function within its class definition; 9038 // see 12.3.1 and 12.3.2. 9039 if (hasExplicit && !NewFD->isInvalidDecl() && 9040 !isa<CXXDeductionGuideDecl>(NewFD)) { 9041 if (!CurContext->isRecord()) { 9042 // 'explicit' was specified outside of the class. 9043 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9044 diag::err_explicit_out_of_class) 9045 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9046 } else if (!isa<CXXConstructorDecl>(NewFD) && 9047 !isa<CXXConversionDecl>(NewFD)) { 9048 // 'explicit' was specified on a function that wasn't a constructor 9049 // or conversion function. 9050 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9051 diag::err_explicit_non_ctor_or_conv_function) 9052 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9053 } 9054 } 9055 9056 if (ConstexprSpecKind ConstexprKind = 9057 D.getDeclSpec().getConstexprSpecifier()) { 9058 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9059 // are implicitly inline. 9060 NewFD->setImplicitlyInline(); 9061 9062 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9063 // be either constructors or to return a literal type. Therefore, 9064 // destructors cannot be declared constexpr. 9065 if (isa<CXXDestructorDecl>(NewFD) && 9066 (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) { 9067 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9068 << ConstexprKind; 9069 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr); 9070 } 9071 // C++20 [dcl.constexpr]p2: An allocation function, or a 9072 // deallocation function shall not be declared with the consteval 9073 // specifier. 9074 if (ConstexprKind == CSK_consteval && 9075 (NewFD->getOverloadedOperator() == OO_New || 9076 NewFD->getOverloadedOperator() == OO_Array_New || 9077 NewFD->getOverloadedOperator() == OO_Delete || 9078 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9079 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9080 diag::err_invalid_consteval_decl_kind) 9081 << NewFD; 9082 NewFD->setConstexprKind(CSK_constexpr); 9083 } 9084 } 9085 9086 // If __module_private__ was specified, mark the function accordingly. 9087 if (D.getDeclSpec().isModulePrivateSpecified()) { 9088 if (isFunctionTemplateSpecialization) { 9089 SourceLocation ModulePrivateLoc 9090 = D.getDeclSpec().getModulePrivateSpecLoc(); 9091 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9092 << 0 9093 << FixItHint::CreateRemoval(ModulePrivateLoc); 9094 } else { 9095 NewFD->setModulePrivate(); 9096 if (FunctionTemplate) 9097 FunctionTemplate->setModulePrivate(); 9098 } 9099 } 9100 9101 if (isFriend) { 9102 if (FunctionTemplate) { 9103 FunctionTemplate->setObjectOfFriendDecl(); 9104 FunctionTemplate->setAccess(AS_public); 9105 } 9106 NewFD->setObjectOfFriendDecl(); 9107 NewFD->setAccess(AS_public); 9108 } 9109 9110 // If a function is defined as defaulted or deleted, mark it as such now. 9111 // We'll do the relevant checks on defaulted / deleted functions later. 9112 switch (D.getFunctionDefinitionKind()) { 9113 case FDK_Declaration: 9114 case FDK_Definition: 9115 break; 9116 9117 case FDK_Defaulted: 9118 NewFD->setDefaulted(); 9119 break; 9120 9121 case FDK_Deleted: 9122 NewFD->setDeletedAsWritten(); 9123 break; 9124 } 9125 9126 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9127 D.isFunctionDefinition()) { 9128 // C++ [class.mfct]p2: 9129 // A member function may be defined (8.4) in its class definition, in 9130 // which case it is an inline member function (7.1.2) 9131 NewFD->setImplicitlyInline(); 9132 } 9133 9134 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9135 !CurContext->isRecord()) { 9136 // C++ [class.static]p1: 9137 // A data or function member of a class may be declared static 9138 // in a class definition, in which case it is a static member of 9139 // the class. 9140 9141 // Complain about the 'static' specifier if it's on an out-of-line 9142 // member function definition. 9143 9144 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9145 // member function template declaration and class member template 9146 // declaration (MSVC versions before 2015), warn about this. 9147 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9148 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9149 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9150 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9151 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9152 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9153 } 9154 9155 // C++11 [except.spec]p15: 9156 // A deallocation function with no exception-specification is treated 9157 // as if it were specified with noexcept(true). 9158 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9159 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9160 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9161 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9162 NewFD->setType(Context.getFunctionType( 9163 FPT->getReturnType(), FPT->getParamTypes(), 9164 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9165 } 9166 9167 // Filter out previous declarations that don't match the scope. 9168 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9169 D.getCXXScopeSpec().isNotEmpty() || 9170 isMemberSpecialization || 9171 isFunctionTemplateSpecialization); 9172 9173 // Handle GNU asm-label extension (encoded as an attribute). 9174 if (Expr *E = (Expr*) D.getAsmLabel()) { 9175 // The parser guarantees this is a string. 9176 StringLiteral *SE = cast<StringLiteral>(E); 9177 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9178 /*IsLiteralLabel=*/true, 9179 SE->getStrTokenLoc(0))); 9180 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9181 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9182 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9183 if (I != ExtnameUndeclaredIdentifiers.end()) { 9184 if (isDeclExternC(NewFD)) { 9185 NewFD->addAttr(I->second); 9186 ExtnameUndeclaredIdentifiers.erase(I); 9187 } else 9188 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9189 << /*Variable*/0 << NewFD; 9190 } 9191 } 9192 9193 // Copy the parameter declarations from the declarator D to the function 9194 // declaration NewFD, if they are available. First scavenge them into Params. 9195 SmallVector<ParmVarDecl*, 16> Params; 9196 unsigned FTIIdx; 9197 if (D.isFunctionDeclarator(FTIIdx)) { 9198 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9199 9200 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9201 // function that takes no arguments, not a function that takes a 9202 // single void argument. 9203 // We let through "const void" here because Sema::GetTypeForDeclarator 9204 // already checks for that case. 9205 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9206 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9207 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9208 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9209 Param->setDeclContext(NewFD); 9210 Params.push_back(Param); 9211 9212 if (Param->isInvalidDecl()) 9213 NewFD->setInvalidDecl(); 9214 } 9215 } 9216 9217 if (!getLangOpts().CPlusPlus) { 9218 // In C, find all the tag declarations from the prototype and move them 9219 // into the function DeclContext. Remove them from the surrounding tag 9220 // injection context of the function, which is typically but not always 9221 // the TU. 9222 DeclContext *PrototypeTagContext = 9223 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9224 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9225 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9226 9227 // We don't want to reparent enumerators. Look at their parent enum 9228 // instead. 9229 if (!TD) { 9230 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9231 TD = cast<EnumDecl>(ECD->getDeclContext()); 9232 } 9233 if (!TD) 9234 continue; 9235 DeclContext *TagDC = TD->getLexicalDeclContext(); 9236 if (!TagDC->containsDecl(TD)) 9237 continue; 9238 TagDC->removeDecl(TD); 9239 TD->setDeclContext(NewFD); 9240 NewFD->addDecl(TD); 9241 9242 // Preserve the lexical DeclContext if it is not the surrounding tag 9243 // injection context of the FD. In this example, the semantic context of 9244 // E will be f and the lexical context will be S, while both the 9245 // semantic and lexical contexts of S will be f: 9246 // void f(struct S { enum E { a } f; } s); 9247 if (TagDC != PrototypeTagContext) 9248 TD->setLexicalDeclContext(TagDC); 9249 } 9250 } 9251 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9252 // When we're declaring a function with a typedef, typeof, etc as in the 9253 // following example, we'll need to synthesize (unnamed) 9254 // parameters for use in the declaration. 9255 // 9256 // @code 9257 // typedef void fn(int); 9258 // fn f; 9259 // @endcode 9260 9261 // Synthesize a parameter for each argument type. 9262 for (const auto &AI : FT->param_types()) { 9263 ParmVarDecl *Param = 9264 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9265 Param->setScopeInfo(0, Params.size()); 9266 Params.push_back(Param); 9267 } 9268 } else { 9269 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9270 "Should not need args for typedef of non-prototype fn"); 9271 } 9272 9273 // Finally, we know we have the right number of parameters, install them. 9274 NewFD->setParams(Params); 9275 9276 if (D.getDeclSpec().isNoreturnSpecified()) 9277 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9278 D.getDeclSpec().getNoreturnSpecLoc(), 9279 AttributeCommonInfo::AS_Keyword)); 9280 9281 // Functions returning a variably modified type violate C99 6.7.5.2p2 9282 // because all functions have linkage. 9283 if (!NewFD->isInvalidDecl() && 9284 NewFD->getReturnType()->isVariablyModifiedType()) { 9285 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9286 NewFD->setInvalidDecl(); 9287 } 9288 9289 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9290 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9291 !NewFD->hasAttr<SectionAttr>()) 9292 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9293 Context, PragmaClangTextSection.SectionName, 9294 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9295 9296 // Apply an implicit SectionAttr if #pragma code_seg is active. 9297 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9298 !NewFD->hasAttr<SectionAttr>()) { 9299 NewFD->addAttr(SectionAttr::CreateImplicit( 9300 Context, CodeSegStack.CurrentValue->getString(), 9301 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9302 SectionAttr::Declspec_allocate)); 9303 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9304 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9305 ASTContext::PSF_Read, 9306 NewFD)) 9307 NewFD->dropAttr<SectionAttr>(); 9308 } 9309 9310 // Apply an implicit CodeSegAttr from class declspec or 9311 // apply an implicit SectionAttr from #pragma code_seg if active. 9312 if (!NewFD->hasAttr<CodeSegAttr>()) { 9313 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9314 D.isFunctionDefinition())) { 9315 NewFD->addAttr(SAttr); 9316 } 9317 } 9318 9319 // Handle attributes. 9320 ProcessDeclAttributes(S, NewFD, D); 9321 9322 if (getLangOpts().OpenCL) { 9323 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9324 // type declaration will generate a compilation error. 9325 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9326 if (AddressSpace != LangAS::Default) { 9327 Diag(NewFD->getLocation(), 9328 diag::err_opencl_return_value_with_address_space); 9329 NewFD->setInvalidDecl(); 9330 } 9331 } 9332 9333 if (!getLangOpts().CPlusPlus) { 9334 // Perform semantic checking on the function declaration. 9335 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9336 CheckMain(NewFD, D.getDeclSpec()); 9337 9338 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9339 CheckMSVCRTEntryPoint(NewFD); 9340 9341 if (!NewFD->isInvalidDecl()) 9342 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9343 isMemberSpecialization)); 9344 else if (!Previous.empty()) 9345 // Recover gracefully from an invalid redeclaration. 9346 D.setRedeclaration(true); 9347 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9348 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9349 "previous declaration set still overloaded"); 9350 9351 // Diagnose no-prototype function declarations with calling conventions that 9352 // don't support variadic calls. Only do this in C and do it after merging 9353 // possibly prototyped redeclarations. 9354 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9355 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9356 CallingConv CC = FT->getExtInfo().getCC(); 9357 if (!supportsVariadicCall(CC)) { 9358 // Windows system headers sometimes accidentally use stdcall without 9359 // (void) parameters, so we relax this to a warning. 9360 int DiagID = 9361 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9362 Diag(NewFD->getLocation(), DiagID) 9363 << FunctionType::getNameForCallConv(CC); 9364 } 9365 } 9366 9367 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9368 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9369 checkNonTrivialCUnion(NewFD->getReturnType(), 9370 NewFD->getReturnTypeSourceRange().getBegin(), 9371 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9372 } else { 9373 // C++11 [replacement.functions]p3: 9374 // The program's definitions shall not be specified as inline. 9375 // 9376 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9377 // 9378 // Suppress the diagnostic if the function is __attribute__((used)), since 9379 // that forces an external definition to be emitted. 9380 if (D.getDeclSpec().isInlineSpecified() && 9381 NewFD->isReplaceableGlobalAllocationFunction() && 9382 !NewFD->hasAttr<UsedAttr>()) 9383 Diag(D.getDeclSpec().getInlineSpecLoc(), 9384 diag::ext_operator_new_delete_declared_inline) 9385 << NewFD->getDeclName(); 9386 9387 // If the declarator is a template-id, translate the parser's template 9388 // argument list into our AST format. 9389 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9390 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9391 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9392 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9393 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9394 TemplateId->NumArgs); 9395 translateTemplateArguments(TemplateArgsPtr, 9396 TemplateArgs); 9397 9398 HasExplicitTemplateArgs = true; 9399 9400 if (NewFD->isInvalidDecl()) { 9401 HasExplicitTemplateArgs = false; 9402 } else if (FunctionTemplate) { 9403 // Function template with explicit template arguments. 9404 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9405 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9406 9407 HasExplicitTemplateArgs = false; 9408 } else { 9409 assert((isFunctionTemplateSpecialization || 9410 D.getDeclSpec().isFriendSpecified()) && 9411 "should have a 'template<>' for this decl"); 9412 // "friend void foo<>(int);" is an implicit specialization decl. 9413 isFunctionTemplateSpecialization = true; 9414 } 9415 } else if (isFriend && isFunctionTemplateSpecialization) { 9416 // This combination is only possible in a recovery case; the user 9417 // wrote something like: 9418 // template <> friend void foo(int); 9419 // which we're recovering from as if the user had written: 9420 // friend void foo<>(int); 9421 // Go ahead and fake up a template id. 9422 HasExplicitTemplateArgs = true; 9423 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9424 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9425 } 9426 9427 // We do not add HD attributes to specializations here because 9428 // they may have different constexpr-ness compared to their 9429 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9430 // may end up with different effective targets. Instead, a 9431 // specialization inherits its target attributes from its template 9432 // in the CheckFunctionTemplateSpecialization() call below. 9433 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9434 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9435 9436 // If it's a friend (and only if it's a friend), it's possible 9437 // that either the specialized function type or the specialized 9438 // template is dependent, and therefore matching will fail. In 9439 // this case, don't check the specialization yet. 9440 bool InstantiationDependent = false; 9441 if (isFunctionTemplateSpecialization && isFriend && 9442 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9443 TemplateSpecializationType::anyDependentTemplateArguments( 9444 TemplateArgs, 9445 InstantiationDependent))) { 9446 assert(HasExplicitTemplateArgs && 9447 "friend function specialization without template args"); 9448 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9449 Previous)) 9450 NewFD->setInvalidDecl(); 9451 } else if (isFunctionTemplateSpecialization) { 9452 if (CurContext->isDependentContext() && CurContext->isRecord() 9453 && !isFriend) { 9454 isDependentClassScopeExplicitSpecialization = true; 9455 } else if (!NewFD->isInvalidDecl() && 9456 CheckFunctionTemplateSpecialization( 9457 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9458 Previous)) 9459 NewFD->setInvalidDecl(); 9460 9461 // C++ [dcl.stc]p1: 9462 // A storage-class-specifier shall not be specified in an explicit 9463 // specialization (14.7.3) 9464 FunctionTemplateSpecializationInfo *Info = 9465 NewFD->getTemplateSpecializationInfo(); 9466 if (Info && SC != SC_None) { 9467 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9468 Diag(NewFD->getLocation(), 9469 diag::err_explicit_specialization_inconsistent_storage_class) 9470 << SC 9471 << FixItHint::CreateRemoval( 9472 D.getDeclSpec().getStorageClassSpecLoc()); 9473 9474 else 9475 Diag(NewFD->getLocation(), 9476 diag::ext_explicit_specialization_storage_class) 9477 << FixItHint::CreateRemoval( 9478 D.getDeclSpec().getStorageClassSpecLoc()); 9479 } 9480 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9481 if (CheckMemberSpecialization(NewFD, Previous)) 9482 NewFD->setInvalidDecl(); 9483 } 9484 9485 // Perform semantic checking on the function declaration. 9486 if (!isDependentClassScopeExplicitSpecialization) { 9487 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9488 CheckMain(NewFD, D.getDeclSpec()); 9489 9490 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9491 CheckMSVCRTEntryPoint(NewFD); 9492 9493 if (!NewFD->isInvalidDecl()) 9494 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9495 isMemberSpecialization)); 9496 else if (!Previous.empty()) 9497 // Recover gracefully from an invalid redeclaration. 9498 D.setRedeclaration(true); 9499 } 9500 9501 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9502 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9503 "previous declaration set still overloaded"); 9504 9505 NamedDecl *PrincipalDecl = (FunctionTemplate 9506 ? cast<NamedDecl>(FunctionTemplate) 9507 : NewFD); 9508 9509 if (isFriend && NewFD->getPreviousDecl()) { 9510 AccessSpecifier Access = AS_public; 9511 if (!NewFD->isInvalidDecl()) 9512 Access = NewFD->getPreviousDecl()->getAccess(); 9513 9514 NewFD->setAccess(Access); 9515 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9516 } 9517 9518 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9519 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9520 PrincipalDecl->setNonMemberOperator(); 9521 9522 // If we have a function template, check the template parameter 9523 // list. This will check and merge default template arguments. 9524 if (FunctionTemplate) { 9525 FunctionTemplateDecl *PrevTemplate = 9526 FunctionTemplate->getPreviousDecl(); 9527 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9528 PrevTemplate ? PrevTemplate->getTemplateParameters() 9529 : nullptr, 9530 D.getDeclSpec().isFriendSpecified() 9531 ? (D.isFunctionDefinition() 9532 ? TPC_FriendFunctionTemplateDefinition 9533 : TPC_FriendFunctionTemplate) 9534 : (D.getCXXScopeSpec().isSet() && 9535 DC && DC->isRecord() && 9536 DC->isDependentContext()) 9537 ? TPC_ClassTemplateMember 9538 : TPC_FunctionTemplate); 9539 } 9540 9541 if (NewFD->isInvalidDecl()) { 9542 // Ignore all the rest of this. 9543 } else if (!D.isRedeclaration()) { 9544 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9545 AddToScope }; 9546 // Fake up an access specifier if it's supposed to be a class member. 9547 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9548 NewFD->setAccess(AS_public); 9549 9550 // Qualified decls generally require a previous declaration. 9551 if (D.getCXXScopeSpec().isSet()) { 9552 // ...with the major exception of templated-scope or 9553 // dependent-scope friend declarations. 9554 9555 // TODO: we currently also suppress this check in dependent 9556 // contexts because (1) the parameter depth will be off when 9557 // matching friend templates and (2) we might actually be 9558 // selecting a friend based on a dependent factor. But there 9559 // are situations where these conditions don't apply and we 9560 // can actually do this check immediately. 9561 // 9562 // Unless the scope is dependent, it's always an error if qualified 9563 // redeclaration lookup found nothing at all. Diagnose that now; 9564 // nothing will diagnose that error later. 9565 if (isFriend && 9566 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9567 (!Previous.empty() && CurContext->isDependentContext()))) { 9568 // ignore these 9569 } else { 9570 // The user tried to provide an out-of-line definition for a 9571 // function that is a member of a class or namespace, but there 9572 // was no such member function declared (C++ [class.mfct]p2, 9573 // C++ [namespace.memdef]p2). For example: 9574 // 9575 // class X { 9576 // void f() const; 9577 // }; 9578 // 9579 // void X::f() { } // ill-formed 9580 // 9581 // Complain about this problem, and attempt to suggest close 9582 // matches (e.g., those that differ only in cv-qualifiers and 9583 // whether the parameter types are references). 9584 9585 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9586 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9587 AddToScope = ExtraArgs.AddToScope; 9588 return Result; 9589 } 9590 } 9591 9592 // Unqualified local friend declarations are required to resolve 9593 // to something. 9594 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9595 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9596 *this, Previous, NewFD, ExtraArgs, true, S)) { 9597 AddToScope = ExtraArgs.AddToScope; 9598 return Result; 9599 } 9600 } 9601 } else if (!D.isFunctionDefinition() && 9602 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9603 !isFriend && !isFunctionTemplateSpecialization && 9604 !isMemberSpecialization) { 9605 // An out-of-line member function declaration must also be a 9606 // definition (C++ [class.mfct]p2). 9607 // Note that this is not the case for explicit specializations of 9608 // function templates or member functions of class templates, per 9609 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9610 // extension for compatibility with old SWIG code which likes to 9611 // generate them. 9612 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9613 << D.getCXXScopeSpec().getRange(); 9614 } 9615 } 9616 9617 ProcessPragmaWeak(S, NewFD); 9618 checkAttributesAfterMerging(*this, *NewFD); 9619 9620 AddKnownFunctionAttributes(NewFD); 9621 9622 if (NewFD->hasAttr<OverloadableAttr>() && 9623 !NewFD->getType()->getAs<FunctionProtoType>()) { 9624 Diag(NewFD->getLocation(), 9625 diag::err_attribute_overloadable_no_prototype) 9626 << NewFD; 9627 9628 // Turn this into a variadic function with no parameters. 9629 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9630 FunctionProtoType::ExtProtoInfo EPI( 9631 Context.getDefaultCallingConvention(true, false)); 9632 EPI.Variadic = true; 9633 EPI.ExtInfo = FT->getExtInfo(); 9634 9635 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9636 NewFD->setType(R); 9637 } 9638 9639 // If there's a #pragma GCC visibility in scope, and this isn't a class 9640 // member, set the visibility of this function. 9641 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9642 AddPushedVisibilityAttribute(NewFD); 9643 9644 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9645 // marking the function. 9646 AddCFAuditedAttribute(NewFD); 9647 9648 // If this is a function definition, check if we have to apply optnone due to 9649 // a pragma. 9650 if(D.isFunctionDefinition()) 9651 AddRangeBasedOptnone(NewFD); 9652 9653 // If this is the first declaration of an extern C variable, update 9654 // the map of such variables. 9655 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9656 isIncompleteDeclExternC(*this, NewFD)) 9657 RegisterLocallyScopedExternCDecl(NewFD, S); 9658 9659 // Set this FunctionDecl's range up to the right paren. 9660 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9661 9662 if (D.isRedeclaration() && !Previous.empty()) { 9663 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9664 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9665 isMemberSpecialization || 9666 isFunctionTemplateSpecialization, 9667 D.isFunctionDefinition()); 9668 } 9669 9670 if (getLangOpts().CUDA) { 9671 IdentifierInfo *II = NewFD->getIdentifier(); 9672 if (II && II->isStr(getCudaConfigureFuncName()) && 9673 !NewFD->isInvalidDecl() && 9674 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9675 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9676 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9677 << getCudaConfigureFuncName(); 9678 Context.setcudaConfigureCallDecl(NewFD); 9679 } 9680 9681 // Variadic functions, other than a *declaration* of printf, are not allowed 9682 // in device-side CUDA code, unless someone passed 9683 // -fcuda-allow-variadic-functions. 9684 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9685 (NewFD->hasAttr<CUDADeviceAttr>() || 9686 NewFD->hasAttr<CUDAGlobalAttr>()) && 9687 !(II && II->isStr("printf") && NewFD->isExternC() && 9688 !D.isFunctionDefinition())) { 9689 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9690 } 9691 } 9692 9693 MarkUnusedFileScopedDecl(NewFD); 9694 9695 9696 9697 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9698 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9699 if ((getLangOpts().OpenCLVersion >= 120) 9700 && (SC == SC_Static)) { 9701 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9702 D.setInvalidType(); 9703 } 9704 9705 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9706 if (!NewFD->getReturnType()->isVoidType()) { 9707 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9708 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9709 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9710 : FixItHint()); 9711 D.setInvalidType(); 9712 } 9713 9714 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9715 for (auto Param : NewFD->parameters()) 9716 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9717 9718 if (getLangOpts().OpenCLCPlusPlus) { 9719 if (DC->isRecord()) { 9720 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9721 D.setInvalidType(); 9722 } 9723 if (FunctionTemplate) { 9724 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9725 D.setInvalidType(); 9726 } 9727 } 9728 } 9729 9730 if (getLangOpts().CPlusPlus) { 9731 if (FunctionTemplate) { 9732 if (NewFD->isInvalidDecl()) 9733 FunctionTemplate->setInvalidDecl(); 9734 return FunctionTemplate; 9735 } 9736 9737 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9738 CompleteMemberSpecialization(NewFD, Previous); 9739 } 9740 9741 for (const ParmVarDecl *Param : NewFD->parameters()) { 9742 QualType PT = Param->getType(); 9743 9744 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9745 // types. 9746 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9747 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9748 QualType ElemTy = PipeTy->getElementType(); 9749 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9750 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9751 D.setInvalidType(); 9752 } 9753 } 9754 } 9755 } 9756 9757 // Here we have an function template explicit specialization at class scope. 9758 // The actual specialization will be postponed to template instatiation 9759 // time via the ClassScopeFunctionSpecializationDecl node. 9760 if (isDependentClassScopeExplicitSpecialization) { 9761 ClassScopeFunctionSpecializationDecl *NewSpec = 9762 ClassScopeFunctionSpecializationDecl::Create( 9763 Context, CurContext, NewFD->getLocation(), 9764 cast<CXXMethodDecl>(NewFD), 9765 HasExplicitTemplateArgs, TemplateArgs); 9766 CurContext->addDecl(NewSpec); 9767 AddToScope = false; 9768 } 9769 9770 // Diagnose availability attributes. Availability cannot be used on functions 9771 // that are run during load/unload. 9772 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9773 if (NewFD->hasAttr<ConstructorAttr>()) { 9774 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9775 << 1; 9776 NewFD->dropAttr<AvailabilityAttr>(); 9777 } 9778 if (NewFD->hasAttr<DestructorAttr>()) { 9779 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9780 << 2; 9781 NewFD->dropAttr<AvailabilityAttr>(); 9782 } 9783 } 9784 9785 // Diagnose no_builtin attribute on function declaration that are not a 9786 // definition. 9787 // FIXME: We should really be doing this in 9788 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9789 // the FunctionDecl and at this point of the code 9790 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9791 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9792 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9793 switch (D.getFunctionDefinitionKind()) { 9794 case FDK_Defaulted: 9795 case FDK_Deleted: 9796 Diag(NBA->getLocation(), 9797 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9798 << NBA->getSpelling(); 9799 break; 9800 case FDK_Declaration: 9801 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9802 << NBA->getSpelling(); 9803 break; 9804 case FDK_Definition: 9805 break; 9806 } 9807 9808 return NewFD; 9809 } 9810 9811 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9812 /// when __declspec(code_seg) "is applied to a class, all member functions of 9813 /// the class and nested classes -- this includes compiler-generated special 9814 /// member functions -- are put in the specified segment." 9815 /// The actual behavior is a little more complicated. The Microsoft compiler 9816 /// won't check outer classes if there is an active value from #pragma code_seg. 9817 /// The CodeSeg is always applied from the direct parent but only from outer 9818 /// classes when the #pragma code_seg stack is empty. See: 9819 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9820 /// available since MS has removed the page. 9821 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9822 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9823 if (!Method) 9824 return nullptr; 9825 const CXXRecordDecl *Parent = Method->getParent(); 9826 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9827 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9828 NewAttr->setImplicit(true); 9829 return NewAttr; 9830 } 9831 9832 // The Microsoft compiler won't check outer classes for the CodeSeg 9833 // when the #pragma code_seg stack is active. 9834 if (S.CodeSegStack.CurrentValue) 9835 return nullptr; 9836 9837 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9838 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9839 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9840 NewAttr->setImplicit(true); 9841 return NewAttr; 9842 } 9843 } 9844 return nullptr; 9845 } 9846 9847 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9848 /// containing class. Otherwise it will return implicit SectionAttr if the 9849 /// function is a definition and there is an active value on CodeSegStack 9850 /// (from the current #pragma code-seg value). 9851 /// 9852 /// \param FD Function being declared. 9853 /// \param IsDefinition Whether it is a definition or just a declarartion. 9854 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9855 /// nullptr if no attribute should be added. 9856 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9857 bool IsDefinition) { 9858 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9859 return A; 9860 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9861 CodeSegStack.CurrentValue) 9862 return SectionAttr::CreateImplicit( 9863 getASTContext(), CodeSegStack.CurrentValue->getString(), 9864 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9865 SectionAttr::Declspec_allocate); 9866 return nullptr; 9867 } 9868 9869 /// Determines if we can perform a correct type check for \p D as a 9870 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9871 /// best-effort check. 9872 /// 9873 /// \param NewD The new declaration. 9874 /// \param OldD The old declaration. 9875 /// \param NewT The portion of the type of the new declaration to check. 9876 /// \param OldT The portion of the type of the old declaration to check. 9877 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9878 QualType NewT, QualType OldT) { 9879 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9880 return true; 9881 9882 // For dependently-typed local extern declarations and friends, we can't 9883 // perform a correct type check in general until instantiation: 9884 // 9885 // int f(); 9886 // template<typename T> void g() { T f(); } 9887 // 9888 // (valid if g() is only instantiated with T = int). 9889 if (NewT->isDependentType() && 9890 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9891 return false; 9892 9893 // Similarly, if the previous declaration was a dependent local extern 9894 // declaration, we don't really know its type yet. 9895 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9896 return false; 9897 9898 return true; 9899 } 9900 9901 /// Checks if the new declaration declared in dependent context must be 9902 /// put in the same redeclaration chain as the specified declaration. 9903 /// 9904 /// \param D Declaration that is checked. 9905 /// \param PrevDecl Previous declaration found with proper lookup method for the 9906 /// same declaration name. 9907 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9908 /// belongs to. 9909 /// 9910 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9911 if (!D->getLexicalDeclContext()->isDependentContext()) 9912 return true; 9913 9914 // Don't chain dependent friend function definitions until instantiation, to 9915 // permit cases like 9916 // 9917 // void func(); 9918 // template<typename T> class C1 { friend void func() {} }; 9919 // template<typename T> class C2 { friend void func() {} }; 9920 // 9921 // ... which is valid if only one of C1 and C2 is ever instantiated. 9922 // 9923 // FIXME: This need only apply to function definitions. For now, we proxy 9924 // this by checking for a file-scope function. We do not want this to apply 9925 // to friend declarations nominating member functions, because that gets in 9926 // the way of access checks. 9927 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9928 return false; 9929 9930 auto *VD = dyn_cast<ValueDecl>(D); 9931 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 9932 return !VD || !PrevVD || 9933 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 9934 PrevVD->getType()); 9935 } 9936 9937 /// Check the target attribute of the function for MultiVersion 9938 /// validity. 9939 /// 9940 /// Returns true if there was an error, false otherwise. 9941 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9942 const auto *TA = FD->getAttr<TargetAttr>(); 9943 assert(TA && "MultiVersion Candidate requires a target attribute"); 9944 ParsedTargetAttr ParseInfo = TA->parse(); 9945 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9946 enum ErrType { Feature = 0, Architecture = 1 }; 9947 9948 if (!ParseInfo.Architecture.empty() && 9949 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9950 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9951 << Architecture << ParseInfo.Architecture; 9952 return true; 9953 } 9954 9955 for (const auto &Feat : ParseInfo.Features) { 9956 auto BareFeat = StringRef{Feat}.substr(1); 9957 if (Feat[0] == '-') { 9958 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9959 << Feature << ("no-" + BareFeat).str(); 9960 return true; 9961 } 9962 9963 if (!TargetInfo.validateCpuSupports(BareFeat) || 9964 !TargetInfo.isValidFeatureName(BareFeat)) { 9965 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9966 << Feature << BareFeat; 9967 return true; 9968 } 9969 } 9970 return false; 9971 } 9972 9973 // Provide a white-list of attributes that are allowed to be combined with 9974 // multiversion functions. 9975 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 9976 MultiVersionKind MVType) { 9977 switch (Kind) { 9978 default: 9979 return false; 9980 case attr::Used: 9981 return MVType == MultiVersionKind::Target; 9982 } 9983 } 9984 9985 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, 9986 MultiVersionKind MVType) { 9987 for (const Attr *A : FD->attrs()) { 9988 switch (A->getKind()) { 9989 case attr::CPUDispatch: 9990 case attr::CPUSpecific: 9991 if (MVType != MultiVersionKind::CPUDispatch && 9992 MVType != MultiVersionKind::CPUSpecific) 9993 return true; 9994 break; 9995 case attr::Target: 9996 if (MVType != MultiVersionKind::Target) 9997 return true; 9998 break; 9999 default: 10000 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10001 return true; 10002 break; 10003 } 10004 } 10005 return false; 10006 } 10007 10008 bool Sema::areMultiversionVariantFunctionsCompatible( 10009 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10010 const PartialDiagnostic &NoProtoDiagID, 10011 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10012 const PartialDiagnosticAt &NoSupportDiagIDAt, 10013 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10014 bool ConstexprSupported, bool CLinkageMayDiffer) { 10015 enum DoesntSupport { 10016 FuncTemplates = 0, 10017 VirtFuncs = 1, 10018 DeducedReturn = 2, 10019 Constructors = 3, 10020 Destructors = 4, 10021 DeletedFuncs = 5, 10022 DefaultedFuncs = 6, 10023 ConstexprFuncs = 7, 10024 ConstevalFuncs = 8, 10025 }; 10026 enum Different { 10027 CallingConv = 0, 10028 ReturnType = 1, 10029 ConstexprSpec = 2, 10030 InlineSpec = 3, 10031 StorageClass = 4, 10032 Linkage = 5, 10033 }; 10034 10035 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10036 !OldFD->getType()->getAs<FunctionProtoType>()) { 10037 Diag(OldFD->getLocation(), NoProtoDiagID); 10038 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10039 return true; 10040 } 10041 10042 if (NoProtoDiagID.getDiagID() != 0 && 10043 !NewFD->getType()->getAs<FunctionProtoType>()) 10044 return Diag(NewFD->getLocation(), NoProtoDiagID); 10045 10046 if (!TemplatesSupported && 10047 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10048 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10049 << FuncTemplates; 10050 10051 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10052 if (NewCXXFD->isVirtual()) 10053 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10054 << VirtFuncs; 10055 10056 if (isa<CXXConstructorDecl>(NewCXXFD)) 10057 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10058 << Constructors; 10059 10060 if (isa<CXXDestructorDecl>(NewCXXFD)) 10061 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10062 << Destructors; 10063 } 10064 10065 if (NewFD->isDeleted()) 10066 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10067 << DeletedFuncs; 10068 10069 if (NewFD->isDefaulted()) 10070 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10071 << DefaultedFuncs; 10072 10073 if (!ConstexprSupported && NewFD->isConstexpr()) 10074 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10075 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10076 10077 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10078 const auto *NewType = cast<FunctionType>(NewQType); 10079 QualType NewReturnType = NewType->getReturnType(); 10080 10081 if (NewReturnType->isUndeducedType()) 10082 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10083 << DeducedReturn; 10084 10085 // Ensure the return type is identical. 10086 if (OldFD) { 10087 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10088 const auto *OldType = cast<FunctionType>(OldQType); 10089 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10090 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10091 10092 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10093 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10094 10095 QualType OldReturnType = OldType->getReturnType(); 10096 10097 if (OldReturnType != NewReturnType) 10098 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10099 10100 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10101 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10102 10103 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10104 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10105 10106 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10107 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10108 10109 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10110 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10111 10112 if (CheckEquivalentExceptionSpec( 10113 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10114 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10115 return true; 10116 } 10117 return false; 10118 } 10119 10120 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10121 const FunctionDecl *NewFD, 10122 bool CausesMV, 10123 MultiVersionKind MVType) { 10124 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10125 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10126 if (OldFD) 10127 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10128 return true; 10129 } 10130 10131 bool IsCPUSpecificCPUDispatchMVType = 10132 MVType == MultiVersionKind::CPUDispatch || 10133 MVType == MultiVersionKind::CPUSpecific; 10134 10135 // For now, disallow all other attributes. These should be opt-in, but 10136 // an analysis of all of them is a future FIXME. 10137 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { 10138 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) 10139 << IsCPUSpecificCPUDispatchMVType; 10140 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10141 return true; 10142 } 10143 10144 if (HasNonMultiVersionAttributes(NewFD, MVType)) 10145 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) 10146 << IsCPUSpecificCPUDispatchMVType; 10147 10148 // Only allow transition to MultiVersion if it hasn't been used. 10149 if (OldFD && CausesMV && OldFD->isUsed(false)) 10150 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10151 10152 return S.areMultiversionVariantFunctionsCompatible( 10153 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10154 PartialDiagnosticAt(NewFD->getLocation(), 10155 S.PDiag(diag::note_multiversioning_caused_here)), 10156 PartialDiagnosticAt(NewFD->getLocation(), 10157 S.PDiag(diag::err_multiversion_doesnt_support) 10158 << IsCPUSpecificCPUDispatchMVType), 10159 PartialDiagnosticAt(NewFD->getLocation(), 10160 S.PDiag(diag::err_multiversion_diff)), 10161 /*TemplatesSupported=*/false, 10162 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10163 /*CLinkageMayDiffer=*/false); 10164 } 10165 10166 /// Check the validity of a multiversion function declaration that is the 10167 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10168 /// 10169 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10170 /// 10171 /// Returns true if there was an error, false otherwise. 10172 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10173 MultiVersionKind MVType, 10174 const TargetAttr *TA) { 10175 assert(MVType != MultiVersionKind::None && 10176 "Function lacks multiversion attribute"); 10177 10178 // Target only causes MV if it is default, otherwise this is a normal 10179 // function. 10180 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10181 return false; 10182 10183 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10184 FD->setInvalidDecl(); 10185 return true; 10186 } 10187 10188 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10189 FD->setInvalidDecl(); 10190 return true; 10191 } 10192 10193 FD->setIsMultiVersion(); 10194 return false; 10195 } 10196 10197 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10198 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10199 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10200 return true; 10201 } 10202 10203 return false; 10204 } 10205 10206 static bool CheckTargetCausesMultiVersioning( 10207 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10208 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10209 LookupResult &Previous) { 10210 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10211 ParsedTargetAttr NewParsed = NewTA->parse(); 10212 // Sort order doesn't matter, it just needs to be consistent. 10213 llvm::sort(NewParsed.Features); 10214 10215 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10216 // to change, this is a simple redeclaration. 10217 if (!NewTA->isDefaultVersion() && 10218 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10219 return false; 10220 10221 // Otherwise, this decl causes MultiVersioning. 10222 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10223 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10224 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10225 NewFD->setInvalidDecl(); 10226 return true; 10227 } 10228 10229 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10230 MultiVersionKind::Target)) { 10231 NewFD->setInvalidDecl(); 10232 return true; 10233 } 10234 10235 if (CheckMultiVersionValue(S, NewFD)) { 10236 NewFD->setInvalidDecl(); 10237 return true; 10238 } 10239 10240 // If this is 'default', permit the forward declaration. 10241 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10242 Redeclaration = true; 10243 OldDecl = OldFD; 10244 OldFD->setIsMultiVersion(); 10245 NewFD->setIsMultiVersion(); 10246 return false; 10247 } 10248 10249 if (CheckMultiVersionValue(S, OldFD)) { 10250 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10251 NewFD->setInvalidDecl(); 10252 return true; 10253 } 10254 10255 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10256 10257 if (OldParsed == NewParsed) { 10258 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10259 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10260 NewFD->setInvalidDecl(); 10261 return true; 10262 } 10263 10264 for (const auto *FD : OldFD->redecls()) { 10265 const auto *CurTA = FD->getAttr<TargetAttr>(); 10266 // We allow forward declarations before ANY multiversioning attributes, but 10267 // nothing after the fact. 10268 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10269 (!CurTA || CurTA->isInherited())) { 10270 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10271 << 0; 10272 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10273 NewFD->setInvalidDecl(); 10274 return true; 10275 } 10276 } 10277 10278 OldFD->setIsMultiVersion(); 10279 NewFD->setIsMultiVersion(); 10280 Redeclaration = false; 10281 MergeTypeWithPrevious = false; 10282 OldDecl = nullptr; 10283 Previous.clear(); 10284 return false; 10285 } 10286 10287 /// Check the validity of a new function declaration being added to an existing 10288 /// multiversioned declaration collection. 10289 static bool CheckMultiVersionAdditionalDecl( 10290 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10291 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10292 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10293 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10294 LookupResult &Previous) { 10295 10296 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10297 // Disallow mixing of multiversioning types. 10298 if ((OldMVType == MultiVersionKind::Target && 10299 NewMVType != MultiVersionKind::Target) || 10300 (NewMVType == MultiVersionKind::Target && 10301 OldMVType != MultiVersionKind::Target)) { 10302 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10303 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10304 NewFD->setInvalidDecl(); 10305 return true; 10306 } 10307 10308 ParsedTargetAttr NewParsed; 10309 if (NewTA) { 10310 NewParsed = NewTA->parse(); 10311 llvm::sort(NewParsed.Features); 10312 } 10313 10314 bool UseMemberUsingDeclRules = 10315 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10316 10317 // Next, check ALL non-overloads to see if this is a redeclaration of a 10318 // previous member of the MultiVersion set. 10319 for (NamedDecl *ND : Previous) { 10320 FunctionDecl *CurFD = ND->getAsFunction(); 10321 if (!CurFD) 10322 continue; 10323 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10324 continue; 10325 10326 if (NewMVType == MultiVersionKind::Target) { 10327 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10328 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10329 NewFD->setIsMultiVersion(); 10330 Redeclaration = true; 10331 OldDecl = ND; 10332 return false; 10333 } 10334 10335 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10336 if (CurParsed == NewParsed) { 10337 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10338 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10339 NewFD->setInvalidDecl(); 10340 return true; 10341 } 10342 } else { 10343 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10344 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10345 // Handle CPUDispatch/CPUSpecific versions. 10346 // Only 1 CPUDispatch function is allowed, this will make it go through 10347 // the redeclaration errors. 10348 if (NewMVType == MultiVersionKind::CPUDispatch && 10349 CurFD->hasAttr<CPUDispatchAttr>()) { 10350 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10351 std::equal( 10352 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10353 NewCPUDisp->cpus_begin(), 10354 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10355 return Cur->getName() == New->getName(); 10356 })) { 10357 NewFD->setIsMultiVersion(); 10358 Redeclaration = true; 10359 OldDecl = ND; 10360 return false; 10361 } 10362 10363 // If the declarations don't match, this is an error condition. 10364 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10365 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10366 NewFD->setInvalidDecl(); 10367 return true; 10368 } 10369 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10370 10371 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10372 std::equal( 10373 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10374 NewCPUSpec->cpus_begin(), 10375 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10376 return Cur->getName() == New->getName(); 10377 })) { 10378 NewFD->setIsMultiVersion(); 10379 Redeclaration = true; 10380 OldDecl = ND; 10381 return false; 10382 } 10383 10384 // Only 1 version of CPUSpecific is allowed for each CPU. 10385 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10386 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10387 if (CurII == NewII) { 10388 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10389 << NewII; 10390 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10391 NewFD->setInvalidDecl(); 10392 return true; 10393 } 10394 } 10395 } 10396 } 10397 // If the two decls aren't the same MVType, there is no possible error 10398 // condition. 10399 } 10400 } 10401 10402 // Else, this is simply a non-redecl case. Checking the 'value' is only 10403 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10404 // handled in the attribute adding step. 10405 if (NewMVType == MultiVersionKind::Target && 10406 CheckMultiVersionValue(S, NewFD)) { 10407 NewFD->setInvalidDecl(); 10408 return true; 10409 } 10410 10411 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10412 !OldFD->isMultiVersion(), NewMVType)) { 10413 NewFD->setInvalidDecl(); 10414 return true; 10415 } 10416 10417 // Permit forward declarations in the case where these two are compatible. 10418 if (!OldFD->isMultiVersion()) { 10419 OldFD->setIsMultiVersion(); 10420 NewFD->setIsMultiVersion(); 10421 Redeclaration = true; 10422 OldDecl = OldFD; 10423 return false; 10424 } 10425 10426 NewFD->setIsMultiVersion(); 10427 Redeclaration = false; 10428 MergeTypeWithPrevious = false; 10429 OldDecl = nullptr; 10430 Previous.clear(); 10431 return false; 10432 } 10433 10434 10435 /// Check the validity of a mulitversion function declaration. 10436 /// Also sets the multiversion'ness' of the function itself. 10437 /// 10438 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10439 /// 10440 /// Returns true if there was an error, false otherwise. 10441 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10442 bool &Redeclaration, NamedDecl *&OldDecl, 10443 bool &MergeTypeWithPrevious, 10444 LookupResult &Previous) { 10445 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10446 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10447 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10448 10449 // Mixing Multiversioning types is prohibited. 10450 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10451 (NewCPUDisp && NewCPUSpec)) { 10452 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10453 NewFD->setInvalidDecl(); 10454 return true; 10455 } 10456 10457 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10458 10459 // Main isn't allowed to become a multiversion function, however it IS 10460 // permitted to have 'main' be marked with the 'target' optimization hint. 10461 if (NewFD->isMain()) { 10462 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10463 MVType == MultiVersionKind::CPUDispatch || 10464 MVType == MultiVersionKind::CPUSpecific) { 10465 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10466 NewFD->setInvalidDecl(); 10467 return true; 10468 } 10469 return false; 10470 } 10471 10472 if (!OldDecl || !OldDecl->getAsFunction() || 10473 OldDecl->getDeclContext()->getRedeclContext() != 10474 NewFD->getDeclContext()->getRedeclContext()) { 10475 // If there's no previous declaration, AND this isn't attempting to cause 10476 // multiversioning, this isn't an error condition. 10477 if (MVType == MultiVersionKind::None) 10478 return false; 10479 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10480 } 10481 10482 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10483 10484 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10485 return false; 10486 10487 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10488 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10489 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10490 NewFD->setInvalidDecl(); 10491 return true; 10492 } 10493 10494 // Handle the target potentially causes multiversioning case. 10495 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10496 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10497 Redeclaration, OldDecl, 10498 MergeTypeWithPrevious, Previous); 10499 10500 // At this point, we have a multiversion function decl (in OldFD) AND an 10501 // appropriate attribute in the current function decl. Resolve that these are 10502 // still compatible with previous declarations. 10503 return CheckMultiVersionAdditionalDecl( 10504 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10505 OldDecl, MergeTypeWithPrevious, Previous); 10506 } 10507 10508 /// Perform semantic checking of a new function declaration. 10509 /// 10510 /// Performs semantic analysis of the new function declaration 10511 /// NewFD. This routine performs all semantic checking that does not 10512 /// require the actual declarator involved in the declaration, and is 10513 /// used both for the declaration of functions as they are parsed 10514 /// (called via ActOnDeclarator) and for the declaration of functions 10515 /// that have been instantiated via C++ template instantiation (called 10516 /// via InstantiateDecl). 10517 /// 10518 /// \param IsMemberSpecialization whether this new function declaration is 10519 /// a member specialization (that replaces any definition provided by the 10520 /// previous declaration). 10521 /// 10522 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10523 /// 10524 /// \returns true if the function declaration is a redeclaration. 10525 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10526 LookupResult &Previous, 10527 bool IsMemberSpecialization) { 10528 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10529 "Variably modified return types are not handled here"); 10530 10531 // Determine whether the type of this function should be merged with 10532 // a previous visible declaration. This never happens for functions in C++, 10533 // and always happens in C if the previous declaration was visible. 10534 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10535 !Previous.isShadowed(); 10536 10537 bool Redeclaration = false; 10538 NamedDecl *OldDecl = nullptr; 10539 bool MayNeedOverloadableChecks = false; 10540 10541 // Merge or overload the declaration with an existing declaration of 10542 // the same name, if appropriate. 10543 if (!Previous.empty()) { 10544 // Determine whether NewFD is an overload of PrevDecl or 10545 // a declaration that requires merging. If it's an overload, 10546 // there's no more work to do here; we'll just add the new 10547 // function to the scope. 10548 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10549 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10550 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10551 Redeclaration = true; 10552 OldDecl = Candidate; 10553 } 10554 } else { 10555 MayNeedOverloadableChecks = true; 10556 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10557 /*NewIsUsingDecl*/ false)) { 10558 case Ovl_Match: 10559 Redeclaration = true; 10560 break; 10561 10562 case Ovl_NonFunction: 10563 Redeclaration = true; 10564 break; 10565 10566 case Ovl_Overload: 10567 Redeclaration = false; 10568 break; 10569 } 10570 } 10571 } 10572 10573 // Check for a previous extern "C" declaration with this name. 10574 if (!Redeclaration && 10575 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10576 if (!Previous.empty()) { 10577 // This is an extern "C" declaration with the same name as a previous 10578 // declaration, and thus redeclares that entity... 10579 Redeclaration = true; 10580 OldDecl = Previous.getFoundDecl(); 10581 MergeTypeWithPrevious = false; 10582 10583 // ... except in the presence of __attribute__((overloadable)). 10584 if (OldDecl->hasAttr<OverloadableAttr>() || 10585 NewFD->hasAttr<OverloadableAttr>()) { 10586 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10587 MayNeedOverloadableChecks = true; 10588 Redeclaration = false; 10589 OldDecl = nullptr; 10590 } 10591 } 10592 } 10593 } 10594 10595 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10596 MergeTypeWithPrevious, Previous)) 10597 return Redeclaration; 10598 10599 // C++11 [dcl.constexpr]p8: 10600 // A constexpr specifier for a non-static member function that is not 10601 // a constructor declares that member function to be const. 10602 // 10603 // This needs to be delayed until we know whether this is an out-of-line 10604 // definition of a static member function. 10605 // 10606 // This rule is not present in C++1y, so we produce a backwards 10607 // compatibility warning whenever it happens in C++11. 10608 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10609 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10610 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10611 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10612 CXXMethodDecl *OldMD = nullptr; 10613 if (OldDecl) 10614 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10615 if (!OldMD || !OldMD->isStatic()) { 10616 const FunctionProtoType *FPT = 10617 MD->getType()->castAs<FunctionProtoType>(); 10618 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10619 EPI.TypeQuals.addConst(); 10620 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10621 FPT->getParamTypes(), EPI)); 10622 10623 // Warn that we did this, if we're not performing template instantiation. 10624 // In that case, we'll have warned already when the template was defined. 10625 if (!inTemplateInstantiation()) { 10626 SourceLocation AddConstLoc; 10627 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10628 .IgnoreParens().getAs<FunctionTypeLoc>()) 10629 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10630 10631 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10632 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10633 } 10634 } 10635 } 10636 10637 if (Redeclaration) { 10638 // NewFD and OldDecl represent declarations that need to be 10639 // merged. 10640 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10641 NewFD->setInvalidDecl(); 10642 return Redeclaration; 10643 } 10644 10645 Previous.clear(); 10646 Previous.addDecl(OldDecl); 10647 10648 if (FunctionTemplateDecl *OldTemplateDecl = 10649 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10650 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10651 FunctionTemplateDecl *NewTemplateDecl 10652 = NewFD->getDescribedFunctionTemplate(); 10653 assert(NewTemplateDecl && "Template/non-template mismatch"); 10654 10655 // The call to MergeFunctionDecl above may have created some state in 10656 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10657 // can add it as a redeclaration. 10658 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10659 10660 NewFD->setPreviousDeclaration(OldFD); 10661 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10662 if (NewFD->isCXXClassMember()) { 10663 NewFD->setAccess(OldTemplateDecl->getAccess()); 10664 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10665 } 10666 10667 // If this is an explicit specialization of a member that is a function 10668 // template, mark it as a member specialization. 10669 if (IsMemberSpecialization && 10670 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10671 NewTemplateDecl->setMemberSpecialization(); 10672 assert(OldTemplateDecl->isMemberSpecialization()); 10673 // Explicit specializations of a member template do not inherit deleted 10674 // status from the parent member template that they are specializing. 10675 if (OldFD->isDeleted()) { 10676 // FIXME: This assert will not hold in the presence of modules. 10677 assert(OldFD->getCanonicalDecl() == OldFD); 10678 // FIXME: We need an update record for this AST mutation. 10679 OldFD->setDeletedAsWritten(false); 10680 } 10681 } 10682 10683 } else { 10684 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10685 auto *OldFD = cast<FunctionDecl>(OldDecl); 10686 // This needs to happen first so that 'inline' propagates. 10687 NewFD->setPreviousDeclaration(OldFD); 10688 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10689 if (NewFD->isCXXClassMember()) 10690 NewFD->setAccess(OldFD->getAccess()); 10691 } 10692 } 10693 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10694 !NewFD->getAttr<OverloadableAttr>()) { 10695 assert((Previous.empty() || 10696 llvm::any_of(Previous, 10697 [](const NamedDecl *ND) { 10698 return ND->hasAttr<OverloadableAttr>(); 10699 })) && 10700 "Non-redecls shouldn't happen without overloadable present"); 10701 10702 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10703 const auto *FD = dyn_cast<FunctionDecl>(ND); 10704 return FD && !FD->hasAttr<OverloadableAttr>(); 10705 }); 10706 10707 if (OtherUnmarkedIter != Previous.end()) { 10708 Diag(NewFD->getLocation(), 10709 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10710 Diag((*OtherUnmarkedIter)->getLocation(), 10711 diag::note_attribute_overloadable_prev_overload) 10712 << false; 10713 10714 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10715 } 10716 } 10717 10718 // Semantic checking for this function declaration (in isolation). 10719 10720 if (getLangOpts().CPlusPlus) { 10721 // C++-specific checks. 10722 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10723 CheckConstructor(Constructor); 10724 } else if (CXXDestructorDecl *Destructor = 10725 dyn_cast<CXXDestructorDecl>(NewFD)) { 10726 CXXRecordDecl *Record = Destructor->getParent(); 10727 QualType ClassType = Context.getTypeDeclType(Record); 10728 10729 // FIXME: Shouldn't we be able to perform this check even when the class 10730 // type is dependent? Both gcc and edg can handle that. 10731 if (!ClassType->isDependentType()) { 10732 DeclarationName Name 10733 = Context.DeclarationNames.getCXXDestructorName( 10734 Context.getCanonicalType(ClassType)); 10735 if (NewFD->getDeclName() != Name) { 10736 Diag(NewFD->getLocation(), diag::err_destructor_name); 10737 NewFD->setInvalidDecl(); 10738 return Redeclaration; 10739 } 10740 } 10741 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10742 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10743 CheckDeductionGuideTemplate(TD); 10744 10745 // A deduction guide is not on the list of entities that can be 10746 // explicitly specialized. 10747 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10748 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10749 << /*explicit specialization*/ 1; 10750 } 10751 10752 // Find any virtual functions that this function overrides. 10753 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10754 if (!Method->isFunctionTemplateSpecialization() && 10755 !Method->getDescribedFunctionTemplate() && 10756 Method->isCanonicalDecl()) { 10757 AddOverriddenMethods(Method->getParent(), Method); 10758 } 10759 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10760 // C++2a [class.virtual]p6 10761 // A virtual method shall not have a requires-clause. 10762 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10763 diag::err_constrained_virtual_method); 10764 10765 if (Method->isStatic()) 10766 checkThisInStaticMemberFunctionType(Method); 10767 } 10768 10769 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 10770 ActOnConversionDeclarator(Conversion); 10771 10772 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10773 if (NewFD->isOverloadedOperator() && 10774 CheckOverloadedOperatorDeclaration(NewFD)) { 10775 NewFD->setInvalidDecl(); 10776 return Redeclaration; 10777 } 10778 10779 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10780 if (NewFD->getLiteralIdentifier() && 10781 CheckLiteralOperatorDeclaration(NewFD)) { 10782 NewFD->setInvalidDecl(); 10783 return Redeclaration; 10784 } 10785 10786 // In C++, check default arguments now that we have merged decls. Unless 10787 // the lexical context is the class, because in this case this is done 10788 // during delayed parsing anyway. 10789 if (!CurContext->isRecord()) 10790 CheckCXXDefaultArguments(NewFD); 10791 10792 // If this function declares a builtin function, check the type of this 10793 // declaration against the expected type for the builtin. 10794 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10795 ASTContext::GetBuiltinTypeError Error; 10796 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 10797 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10798 // If the type of the builtin differs only in its exception 10799 // specification, that's OK. 10800 // FIXME: If the types do differ in this way, it would be better to 10801 // retain the 'noexcept' form of the type. 10802 if (!T.isNull() && 10803 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10804 NewFD->getType())) 10805 // The type of this function differs from the type of the builtin, 10806 // so forget about the builtin entirely. 10807 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10808 } 10809 10810 // If this function is declared as being extern "C", then check to see if 10811 // the function returns a UDT (class, struct, or union type) that is not C 10812 // compatible, and if it does, warn the user. 10813 // But, issue any diagnostic on the first declaration only. 10814 if (Previous.empty() && NewFD->isExternC()) { 10815 QualType R = NewFD->getReturnType(); 10816 if (R->isIncompleteType() && !R->isVoidType()) 10817 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10818 << NewFD << R; 10819 else if (!R.isPODType(Context) && !R->isVoidType() && 10820 !R->isObjCObjectPointerType()) 10821 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10822 } 10823 10824 // C++1z [dcl.fct]p6: 10825 // [...] whether the function has a non-throwing exception-specification 10826 // [is] part of the function type 10827 // 10828 // This results in an ABI break between C++14 and C++17 for functions whose 10829 // declared type includes an exception-specification in a parameter or 10830 // return type. (Exception specifications on the function itself are OK in 10831 // most cases, and exception specifications are not permitted in most other 10832 // contexts where they could make it into a mangling.) 10833 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10834 auto HasNoexcept = [&](QualType T) -> bool { 10835 // Strip off declarator chunks that could be between us and a function 10836 // type. We don't need to look far, exception specifications are very 10837 // restricted prior to C++17. 10838 if (auto *RT = T->getAs<ReferenceType>()) 10839 T = RT->getPointeeType(); 10840 else if (T->isAnyPointerType()) 10841 T = T->getPointeeType(); 10842 else if (auto *MPT = T->getAs<MemberPointerType>()) 10843 T = MPT->getPointeeType(); 10844 if (auto *FPT = T->getAs<FunctionProtoType>()) 10845 if (FPT->isNothrow()) 10846 return true; 10847 return false; 10848 }; 10849 10850 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10851 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10852 for (QualType T : FPT->param_types()) 10853 AnyNoexcept |= HasNoexcept(T); 10854 if (AnyNoexcept) 10855 Diag(NewFD->getLocation(), 10856 diag::warn_cxx17_compat_exception_spec_in_signature) 10857 << NewFD; 10858 } 10859 10860 if (!Redeclaration && LangOpts.CUDA) 10861 checkCUDATargetOverload(NewFD, Previous); 10862 } 10863 return Redeclaration; 10864 } 10865 10866 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10867 // C++11 [basic.start.main]p3: 10868 // A program that [...] declares main to be inline, static or 10869 // constexpr is ill-formed. 10870 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10871 // appear in a declaration of main. 10872 // static main is not an error under C99, but we should warn about it. 10873 // We accept _Noreturn main as an extension. 10874 if (FD->getStorageClass() == SC_Static) 10875 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10876 ? diag::err_static_main : diag::warn_static_main) 10877 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10878 if (FD->isInlineSpecified()) 10879 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10880 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10881 if (DS.isNoreturnSpecified()) { 10882 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10883 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10884 Diag(NoreturnLoc, diag::ext_noreturn_main); 10885 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10886 << FixItHint::CreateRemoval(NoreturnRange); 10887 } 10888 if (FD->isConstexpr()) { 10889 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10890 << FD->isConsteval() 10891 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10892 FD->setConstexprKind(CSK_unspecified); 10893 } 10894 10895 if (getLangOpts().OpenCL) { 10896 Diag(FD->getLocation(), diag::err_opencl_no_main) 10897 << FD->hasAttr<OpenCLKernelAttr>(); 10898 FD->setInvalidDecl(); 10899 return; 10900 } 10901 10902 QualType T = FD->getType(); 10903 assert(T->isFunctionType() && "function decl is not of function type"); 10904 const FunctionType* FT = T->castAs<FunctionType>(); 10905 10906 // Set default calling convention for main() 10907 if (FT->getCallConv() != CC_C) { 10908 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10909 FD->setType(QualType(FT, 0)); 10910 T = Context.getCanonicalType(FD->getType()); 10911 } 10912 10913 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10914 // In C with GNU extensions we allow main() to have non-integer return 10915 // type, but we should warn about the extension, and we disable the 10916 // implicit-return-zero rule. 10917 10918 // GCC in C mode accepts qualified 'int'. 10919 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10920 FD->setHasImplicitReturnZero(true); 10921 else { 10922 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10923 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10924 if (RTRange.isValid()) 10925 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10926 << FixItHint::CreateReplacement(RTRange, "int"); 10927 } 10928 } else { 10929 // In C and C++, main magically returns 0 if you fall off the end; 10930 // set the flag which tells us that. 10931 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 10932 10933 // All the standards say that main() should return 'int'. 10934 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 10935 FD->setHasImplicitReturnZero(true); 10936 else { 10937 // Otherwise, this is just a flat-out error. 10938 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10939 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 10940 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 10941 : FixItHint()); 10942 FD->setInvalidDecl(true); 10943 } 10944 } 10945 10946 // Treat protoless main() as nullary. 10947 if (isa<FunctionNoProtoType>(FT)) return; 10948 10949 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 10950 unsigned nparams = FTP->getNumParams(); 10951 assert(FD->getNumParams() == nparams); 10952 10953 bool HasExtraParameters = (nparams > 3); 10954 10955 if (FTP->isVariadic()) { 10956 Diag(FD->getLocation(), diag::ext_variadic_main); 10957 // FIXME: if we had information about the location of the ellipsis, we 10958 // could add a FixIt hint to remove it as a parameter. 10959 } 10960 10961 // Darwin passes an undocumented fourth argument of type char**. If 10962 // other platforms start sprouting these, the logic below will start 10963 // getting shifty. 10964 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 10965 HasExtraParameters = false; 10966 10967 if (HasExtraParameters) { 10968 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 10969 FD->setInvalidDecl(true); 10970 nparams = 3; 10971 } 10972 10973 // FIXME: a lot of the following diagnostics would be improved 10974 // if we had some location information about types. 10975 10976 QualType CharPP = 10977 Context.getPointerType(Context.getPointerType(Context.CharTy)); 10978 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 10979 10980 for (unsigned i = 0; i < nparams; ++i) { 10981 QualType AT = FTP->getParamType(i); 10982 10983 bool mismatch = true; 10984 10985 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 10986 mismatch = false; 10987 else if (Expected[i] == CharPP) { 10988 // As an extension, the following forms are okay: 10989 // char const ** 10990 // char const * const * 10991 // char * const * 10992 10993 QualifierCollector qs; 10994 const PointerType* PT; 10995 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 10996 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 10997 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 10998 Context.CharTy)) { 10999 qs.removeConst(); 11000 mismatch = !qs.empty(); 11001 } 11002 } 11003 11004 if (mismatch) { 11005 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11006 // TODO: suggest replacing given type with expected type 11007 FD->setInvalidDecl(true); 11008 } 11009 } 11010 11011 if (nparams == 1 && !FD->isInvalidDecl()) { 11012 Diag(FD->getLocation(), diag::warn_main_one_arg); 11013 } 11014 11015 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11016 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11017 FD->setInvalidDecl(); 11018 } 11019 } 11020 11021 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11022 QualType T = FD->getType(); 11023 assert(T->isFunctionType() && "function decl is not of function type"); 11024 const FunctionType *FT = T->castAs<FunctionType>(); 11025 11026 // Set an implicit return of 'zero' if the function can return some integral, 11027 // enumeration, pointer or nullptr type. 11028 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11029 FT->getReturnType()->isAnyPointerType() || 11030 FT->getReturnType()->isNullPtrType()) 11031 // DllMain is exempt because a return value of zero means it failed. 11032 if (FD->getName() != "DllMain") 11033 FD->setHasImplicitReturnZero(true); 11034 11035 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11036 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11037 FD->setInvalidDecl(); 11038 } 11039 } 11040 11041 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11042 // FIXME: Need strict checking. In C89, we need to check for 11043 // any assignment, increment, decrement, function-calls, or 11044 // commas outside of a sizeof. In C99, it's the same list, 11045 // except that the aforementioned are allowed in unevaluated 11046 // expressions. Everything else falls under the 11047 // "may accept other forms of constant expressions" exception. 11048 // (We never end up here for C++, so the constant expression 11049 // rules there don't matter.) 11050 const Expr *Culprit; 11051 if (Init->isConstantInitializer(Context, false, &Culprit)) 11052 return false; 11053 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11054 << Culprit->getSourceRange(); 11055 return true; 11056 } 11057 11058 namespace { 11059 // Visits an initialization expression to see if OrigDecl is evaluated in 11060 // its own initialization and throws a warning if it does. 11061 class SelfReferenceChecker 11062 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11063 Sema &S; 11064 Decl *OrigDecl; 11065 bool isRecordType; 11066 bool isPODType; 11067 bool isReferenceType; 11068 11069 bool isInitList; 11070 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11071 11072 public: 11073 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11074 11075 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11076 S(S), OrigDecl(OrigDecl) { 11077 isPODType = false; 11078 isRecordType = false; 11079 isReferenceType = false; 11080 isInitList = false; 11081 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11082 isPODType = VD->getType().isPODType(S.Context); 11083 isRecordType = VD->getType()->isRecordType(); 11084 isReferenceType = VD->getType()->isReferenceType(); 11085 } 11086 } 11087 11088 // For most expressions, just call the visitor. For initializer lists, 11089 // track the index of the field being initialized since fields are 11090 // initialized in order allowing use of previously initialized fields. 11091 void CheckExpr(Expr *E) { 11092 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11093 if (!InitList) { 11094 Visit(E); 11095 return; 11096 } 11097 11098 // Track and increment the index here. 11099 isInitList = true; 11100 InitFieldIndex.push_back(0); 11101 for (auto Child : InitList->children()) { 11102 CheckExpr(cast<Expr>(Child)); 11103 ++InitFieldIndex.back(); 11104 } 11105 InitFieldIndex.pop_back(); 11106 } 11107 11108 // Returns true if MemberExpr is checked and no further checking is needed. 11109 // Returns false if additional checking is required. 11110 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11111 llvm::SmallVector<FieldDecl*, 4> Fields; 11112 Expr *Base = E; 11113 bool ReferenceField = false; 11114 11115 // Get the field members used. 11116 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11117 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11118 if (!FD) 11119 return false; 11120 Fields.push_back(FD); 11121 if (FD->getType()->isReferenceType()) 11122 ReferenceField = true; 11123 Base = ME->getBase()->IgnoreParenImpCasts(); 11124 } 11125 11126 // Keep checking only if the base Decl is the same. 11127 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11128 if (!DRE || DRE->getDecl() != OrigDecl) 11129 return false; 11130 11131 // A reference field can be bound to an unininitialized field. 11132 if (CheckReference && !ReferenceField) 11133 return true; 11134 11135 // Convert FieldDecls to their index number. 11136 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11137 for (const FieldDecl *I : llvm::reverse(Fields)) 11138 UsedFieldIndex.push_back(I->getFieldIndex()); 11139 11140 // See if a warning is needed by checking the first difference in index 11141 // numbers. If field being used has index less than the field being 11142 // initialized, then the use is safe. 11143 for (auto UsedIter = UsedFieldIndex.begin(), 11144 UsedEnd = UsedFieldIndex.end(), 11145 OrigIter = InitFieldIndex.begin(), 11146 OrigEnd = InitFieldIndex.end(); 11147 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11148 if (*UsedIter < *OrigIter) 11149 return true; 11150 if (*UsedIter > *OrigIter) 11151 break; 11152 } 11153 11154 // TODO: Add a different warning which will print the field names. 11155 HandleDeclRefExpr(DRE); 11156 return true; 11157 } 11158 11159 // For most expressions, the cast is directly above the DeclRefExpr. 11160 // For conditional operators, the cast can be outside the conditional 11161 // operator if both expressions are DeclRefExpr's. 11162 void HandleValue(Expr *E) { 11163 E = E->IgnoreParens(); 11164 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11165 HandleDeclRefExpr(DRE); 11166 return; 11167 } 11168 11169 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11170 Visit(CO->getCond()); 11171 HandleValue(CO->getTrueExpr()); 11172 HandleValue(CO->getFalseExpr()); 11173 return; 11174 } 11175 11176 if (BinaryConditionalOperator *BCO = 11177 dyn_cast<BinaryConditionalOperator>(E)) { 11178 Visit(BCO->getCond()); 11179 HandleValue(BCO->getFalseExpr()); 11180 return; 11181 } 11182 11183 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11184 HandleValue(OVE->getSourceExpr()); 11185 return; 11186 } 11187 11188 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11189 if (BO->getOpcode() == BO_Comma) { 11190 Visit(BO->getLHS()); 11191 HandleValue(BO->getRHS()); 11192 return; 11193 } 11194 } 11195 11196 if (isa<MemberExpr>(E)) { 11197 if (isInitList) { 11198 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11199 false /*CheckReference*/)) 11200 return; 11201 } 11202 11203 Expr *Base = E->IgnoreParenImpCasts(); 11204 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11205 // Check for static member variables and don't warn on them. 11206 if (!isa<FieldDecl>(ME->getMemberDecl())) 11207 return; 11208 Base = ME->getBase()->IgnoreParenImpCasts(); 11209 } 11210 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11211 HandleDeclRefExpr(DRE); 11212 return; 11213 } 11214 11215 Visit(E); 11216 } 11217 11218 // Reference types not handled in HandleValue are handled here since all 11219 // uses of references are bad, not just r-value uses. 11220 void VisitDeclRefExpr(DeclRefExpr *E) { 11221 if (isReferenceType) 11222 HandleDeclRefExpr(E); 11223 } 11224 11225 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11226 if (E->getCastKind() == CK_LValueToRValue) { 11227 HandleValue(E->getSubExpr()); 11228 return; 11229 } 11230 11231 Inherited::VisitImplicitCastExpr(E); 11232 } 11233 11234 void VisitMemberExpr(MemberExpr *E) { 11235 if (isInitList) { 11236 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11237 return; 11238 } 11239 11240 // Don't warn on arrays since they can be treated as pointers. 11241 if (E->getType()->canDecayToPointerType()) return; 11242 11243 // Warn when a non-static method call is followed by non-static member 11244 // field accesses, which is followed by a DeclRefExpr. 11245 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11246 bool Warn = (MD && !MD->isStatic()); 11247 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11248 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11249 if (!isa<FieldDecl>(ME->getMemberDecl())) 11250 Warn = false; 11251 Base = ME->getBase()->IgnoreParenImpCasts(); 11252 } 11253 11254 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11255 if (Warn) 11256 HandleDeclRefExpr(DRE); 11257 return; 11258 } 11259 11260 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11261 // Visit that expression. 11262 Visit(Base); 11263 } 11264 11265 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11266 Expr *Callee = E->getCallee(); 11267 11268 if (isa<UnresolvedLookupExpr>(Callee)) 11269 return Inherited::VisitCXXOperatorCallExpr(E); 11270 11271 Visit(Callee); 11272 for (auto Arg: E->arguments()) 11273 HandleValue(Arg->IgnoreParenImpCasts()); 11274 } 11275 11276 void VisitUnaryOperator(UnaryOperator *E) { 11277 // For POD record types, addresses of its own members are well-defined. 11278 if (E->getOpcode() == UO_AddrOf && isRecordType && 11279 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11280 if (!isPODType) 11281 HandleValue(E->getSubExpr()); 11282 return; 11283 } 11284 11285 if (E->isIncrementDecrementOp()) { 11286 HandleValue(E->getSubExpr()); 11287 return; 11288 } 11289 11290 Inherited::VisitUnaryOperator(E); 11291 } 11292 11293 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11294 11295 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11296 if (E->getConstructor()->isCopyConstructor()) { 11297 Expr *ArgExpr = E->getArg(0); 11298 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11299 if (ILE->getNumInits() == 1) 11300 ArgExpr = ILE->getInit(0); 11301 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11302 if (ICE->getCastKind() == CK_NoOp) 11303 ArgExpr = ICE->getSubExpr(); 11304 HandleValue(ArgExpr); 11305 return; 11306 } 11307 Inherited::VisitCXXConstructExpr(E); 11308 } 11309 11310 void VisitCallExpr(CallExpr *E) { 11311 // Treat std::move as a use. 11312 if (E->isCallToStdMove()) { 11313 HandleValue(E->getArg(0)); 11314 return; 11315 } 11316 11317 Inherited::VisitCallExpr(E); 11318 } 11319 11320 void VisitBinaryOperator(BinaryOperator *E) { 11321 if (E->isCompoundAssignmentOp()) { 11322 HandleValue(E->getLHS()); 11323 Visit(E->getRHS()); 11324 return; 11325 } 11326 11327 Inherited::VisitBinaryOperator(E); 11328 } 11329 11330 // A custom visitor for BinaryConditionalOperator is needed because the 11331 // regular visitor would check the condition and true expression separately 11332 // but both point to the same place giving duplicate diagnostics. 11333 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11334 Visit(E->getCond()); 11335 Visit(E->getFalseExpr()); 11336 } 11337 11338 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11339 Decl* ReferenceDecl = DRE->getDecl(); 11340 if (OrigDecl != ReferenceDecl) return; 11341 unsigned diag; 11342 if (isReferenceType) { 11343 diag = diag::warn_uninit_self_reference_in_reference_init; 11344 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11345 diag = diag::warn_static_self_reference_in_init; 11346 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11347 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11348 DRE->getDecl()->getType()->isRecordType()) { 11349 diag = diag::warn_uninit_self_reference_in_init; 11350 } else { 11351 // Local variables will be handled by the CFG analysis. 11352 return; 11353 } 11354 11355 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11356 S.PDiag(diag) 11357 << DRE->getDecl() << OrigDecl->getLocation() 11358 << DRE->getSourceRange()); 11359 } 11360 }; 11361 11362 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11363 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11364 bool DirectInit) { 11365 // Parameters arguments are occassionially constructed with itself, 11366 // for instance, in recursive functions. Skip them. 11367 if (isa<ParmVarDecl>(OrigDecl)) 11368 return; 11369 11370 E = E->IgnoreParens(); 11371 11372 // Skip checking T a = a where T is not a record or reference type. 11373 // Doing so is a way to silence uninitialized warnings. 11374 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11375 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11376 if (ICE->getCastKind() == CK_LValueToRValue) 11377 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11378 if (DRE->getDecl() == OrigDecl) 11379 return; 11380 11381 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11382 } 11383 } // end anonymous namespace 11384 11385 namespace { 11386 // Simple wrapper to add the name of a variable or (if no variable is 11387 // available) a DeclarationName into a diagnostic. 11388 struct VarDeclOrName { 11389 VarDecl *VDecl; 11390 DeclarationName Name; 11391 11392 friend const Sema::SemaDiagnosticBuilder & 11393 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11394 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11395 } 11396 }; 11397 } // end anonymous namespace 11398 11399 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11400 DeclarationName Name, QualType Type, 11401 TypeSourceInfo *TSI, 11402 SourceRange Range, bool DirectInit, 11403 Expr *Init) { 11404 bool IsInitCapture = !VDecl; 11405 assert((!VDecl || !VDecl->isInitCapture()) && 11406 "init captures are expected to be deduced prior to initialization"); 11407 11408 VarDeclOrName VN{VDecl, Name}; 11409 11410 DeducedType *Deduced = Type->getContainedDeducedType(); 11411 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11412 11413 // C++11 [dcl.spec.auto]p3 11414 if (!Init) { 11415 assert(VDecl && "no init for init capture deduction?"); 11416 11417 // Except for class argument deduction, and then for an initializing 11418 // declaration only, i.e. no static at class scope or extern. 11419 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11420 VDecl->hasExternalStorage() || 11421 VDecl->isStaticDataMember()) { 11422 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11423 << VDecl->getDeclName() << Type; 11424 return QualType(); 11425 } 11426 } 11427 11428 ArrayRef<Expr*> DeduceInits; 11429 if (Init) 11430 DeduceInits = Init; 11431 11432 if (DirectInit) { 11433 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11434 DeduceInits = PL->exprs(); 11435 } 11436 11437 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11438 assert(VDecl && "non-auto type for init capture deduction?"); 11439 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11440 InitializationKind Kind = InitializationKind::CreateForInit( 11441 VDecl->getLocation(), DirectInit, Init); 11442 // FIXME: Initialization should not be taking a mutable list of inits. 11443 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11444 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11445 InitsCopy); 11446 } 11447 11448 if (DirectInit) { 11449 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11450 DeduceInits = IL->inits(); 11451 } 11452 11453 // Deduction only works if we have exactly one source expression. 11454 if (DeduceInits.empty()) { 11455 // It isn't possible to write this directly, but it is possible to 11456 // end up in this situation with "auto x(some_pack...);" 11457 Diag(Init->getBeginLoc(), IsInitCapture 11458 ? diag::err_init_capture_no_expression 11459 : diag::err_auto_var_init_no_expression) 11460 << VN << Type << Range; 11461 return QualType(); 11462 } 11463 11464 if (DeduceInits.size() > 1) { 11465 Diag(DeduceInits[1]->getBeginLoc(), 11466 IsInitCapture ? diag::err_init_capture_multiple_expressions 11467 : diag::err_auto_var_init_multiple_expressions) 11468 << VN << Type << Range; 11469 return QualType(); 11470 } 11471 11472 Expr *DeduceInit = DeduceInits[0]; 11473 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11474 Diag(Init->getBeginLoc(), IsInitCapture 11475 ? diag::err_init_capture_paren_braces 11476 : diag::err_auto_var_init_paren_braces) 11477 << isa<InitListExpr>(Init) << VN << Type << Range; 11478 return QualType(); 11479 } 11480 11481 // Expressions default to 'id' when we're in a debugger. 11482 bool DefaultedAnyToId = false; 11483 if (getLangOpts().DebuggerCastResultToId && 11484 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11485 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11486 if (Result.isInvalid()) { 11487 return QualType(); 11488 } 11489 Init = Result.get(); 11490 DefaultedAnyToId = true; 11491 } 11492 11493 // C++ [dcl.decomp]p1: 11494 // If the assignment-expression [...] has array type A and no ref-qualifier 11495 // is present, e has type cv A 11496 if (VDecl && isa<DecompositionDecl>(VDecl) && 11497 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11498 DeduceInit->getType()->isConstantArrayType()) 11499 return Context.getQualifiedType(DeduceInit->getType(), 11500 Type.getQualifiers()); 11501 11502 QualType DeducedType; 11503 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11504 if (!IsInitCapture) 11505 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11506 else if (isa<InitListExpr>(Init)) 11507 Diag(Range.getBegin(), 11508 diag::err_init_capture_deduction_failure_from_init_list) 11509 << VN 11510 << (DeduceInit->getType().isNull() ? TSI->getType() 11511 : DeduceInit->getType()) 11512 << DeduceInit->getSourceRange(); 11513 else 11514 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11515 << VN << TSI->getType() 11516 << (DeduceInit->getType().isNull() ? TSI->getType() 11517 : DeduceInit->getType()) 11518 << DeduceInit->getSourceRange(); 11519 } 11520 11521 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11522 // 'id' instead of a specific object type prevents most of our usual 11523 // checks. 11524 // We only want to warn outside of template instantiations, though: 11525 // inside a template, the 'id' could have come from a parameter. 11526 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11527 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11528 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11529 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11530 } 11531 11532 return DeducedType; 11533 } 11534 11535 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11536 Expr *Init) { 11537 assert(!Init || !Init->containsErrors()); 11538 QualType DeducedType = deduceVarTypeFromInitializer( 11539 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11540 VDecl->getSourceRange(), DirectInit, Init); 11541 if (DeducedType.isNull()) { 11542 VDecl->setInvalidDecl(); 11543 return true; 11544 } 11545 11546 VDecl->setType(DeducedType); 11547 assert(VDecl->isLinkageValid()); 11548 11549 // In ARC, infer lifetime. 11550 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11551 VDecl->setInvalidDecl(); 11552 11553 if (getLangOpts().OpenCL) 11554 deduceOpenCLAddressSpace(VDecl); 11555 11556 // If this is a redeclaration, check that the type we just deduced matches 11557 // the previously declared type. 11558 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11559 // We never need to merge the type, because we cannot form an incomplete 11560 // array of auto, nor deduce such a type. 11561 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11562 } 11563 11564 // Check the deduced type is valid for a variable declaration. 11565 CheckVariableDeclarationType(VDecl); 11566 return VDecl->isInvalidDecl(); 11567 } 11568 11569 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11570 SourceLocation Loc) { 11571 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11572 Init = EWC->getSubExpr(); 11573 11574 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11575 Init = CE->getSubExpr(); 11576 11577 QualType InitType = Init->getType(); 11578 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11579 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11580 "shouldn't be called if type doesn't have a non-trivial C struct"); 11581 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11582 for (auto I : ILE->inits()) { 11583 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11584 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11585 continue; 11586 SourceLocation SL = I->getExprLoc(); 11587 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11588 } 11589 return; 11590 } 11591 11592 if (isa<ImplicitValueInitExpr>(Init)) { 11593 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11594 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11595 NTCUK_Init); 11596 } else { 11597 // Assume all other explicit initializers involving copying some existing 11598 // object. 11599 // TODO: ignore any explicit initializers where we can guarantee 11600 // copy-elision. 11601 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11602 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11603 } 11604 } 11605 11606 namespace { 11607 11608 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11609 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11610 // in the source code or implicitly by the compiler if it is in a union 11611 // defined in a system header and has non-trivial ObjC ownership 11612 // qualifications. We don't want those fields to participate in determining 11613 // whether the containing union is non-trivial. 11614 return FD->hasAttr<UnavailableAttr>(); 11615 } 11616 11617 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11618 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11619 void> { 11620 using Super = 11621 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11622 void>; 11623 11624 DiagNonTrivalCUnionDefaultInitializeVisitor( 11625 QualType OrigTy, SourceLocation OrigLoc, 11626 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11627 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11628 11629 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11630 const FieldDecl *FD, bool InNonTrivialUnion) { 11631 if (const auto *AT = S.Context.getAsArrayType(QT)) 11632 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11633 InNonTrivialUnion); 11634 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11635 } 11636 11637 void visitARCStrong(QualType QT, const FieldDecl *FD, 11638 bool InNonTrivialUnion) { 11639 if (InNonTrivialUnion) 11640 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11641 << 1 << 0 << QT << FD->getName(); 11642 } 11643 11644 void visitARCWeak(QualType QT, const FieldDecl *FD, 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 visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11651 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11652 if (RD->isUnion()) { 11653 if (OrigLoc.isValid()) { 11654 bool IsUnion = false; 11655 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11656 IsUnion = OrigRD->isUnion(); 11657 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11658 << 0 << OrigTy << IsUnion << UseContext; 11659 // Reset OrigLoc so that this diagnostic is emitted only once. 11660 OrigLoc = SourceLocation(); 11661 } 11662 InNonTrivialUnion = true; 11663 } 11664 11665 if (InNonTrivialUnion) 11666 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11667 << 0 << 0 << QT.getUnqualifiedType() << ""; 11668 11669 for (const FieldDecl *FD : RD->fields()) 11670 if (!shouldIgnoreForRecordTriviality(FD)) 11671 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11672 } 11673 11674 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11675 11676 // The non-trivial C union type or the struct/union type that contains a 11677 // non-trivial C union. 11678 QualType OrigTy; 11679 SourceLocation OrigLoc; 11680 Sema::NonTrivialCUnionContext UseContext; 11681 Sema &S; 11682 }; 11683 11684 struct DiagNonTrivalCUnionDestructedTypeVisitor 11685 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11686 using Super = 11687 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11688 11689 DiagNonTrivalCUnionDestructedTypeVisitor( 11690 QualType OrigTy, SourceLocation OrigLoc, 11691 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11692 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11693 11694 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11695 const FieldDecl *FD, bool InNonTrivialUnion) { 11696 if (const auto *AT = S.Context.getAsArrayType(QT)) 11697 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11698 InNonTrivialUnion); 11699 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11700 } 11701 11702 void visitARCStrong(QualType QT, const FieldDecl *FD, 11703 bool InNonTrivialUnion) { 11704 if (InNonTrivialUnion) 11705 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11706 << 1 << 1 << QT << FD->getName(); 11707 } 11708 11709 void visitARCWeak(QualType QT, const FieldDecl *FD, 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 visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11716 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11717 if (RD->isUnion()) { 11718 if (OrigLoc.isValid()) { 11719 bool IsUnion = false; 11720 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11721 IsUnion = OrigRD->isUnion(); 11722 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11723 << 1 << OrigTy << IsUnion << UseContext; 11724 // Reset OrigLoc so that this diagnostic is emitted only once. 11725 OrigLoc = SourceLocation(); 11726 } 11727 InNonTrivialUnion = true; 11728 } 11729 11730 if (InNonTrivialUnion) 11731 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11732 << 0 << 1 << QT.getUnqualifiedType() << ""; 11733 11734 for (const FieldDecl *FD : RD->fields()) 11735 if (!shouldIgnoreForRecordTriviality(FD)) 11736 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11737 } 11738 11739 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11740 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11741 bool InNonTrivialUnion) {} 11742 11743 // The non-trivial C union type or the struct/union type that contains a 11744 // non-trivial C union. 11745 QualType OrigTy; 11746 SourceLocation OrigLoc; 11747 Sema::NonTrivialCUnionContext UseContext; 11748 Sema &S; 11749 }; 11750 11751 struct DiagNonTrivalCUnionCopyVisitor 11752 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11753 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11754 11755 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11756 Sema::NonTrivialCUnionContext UseContext, 11757 Sema &S) 11758 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11759 11760 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11761 const FieldDecl *FD, bool InNonTrivialUnion) { 11762 if (const auto *AT = S.Context.getAsArrayType(QT)) 11763 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11764 InNonTrivialUnion); 11765 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11766 } 11767 11768 void visitARCStrong(QualType QT, const FieldDecl *FD, 11769 bool InNonTrivialUnion) { 11770 if (InNonTrivialUnion) 11771 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11772 << 1 << 2 << QT << FD->getName(); 11773 } 11774 11775 void visitARCWeak(QualType QT, const FieldDecl *FD, 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 visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11782 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11783 if (RD->isUnion()) { 11784 if (OrigLoc.isValid()) { 11785 bool IsUnion = false; 11786 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11787 IsUnion = OrigRD->isUnion(); 11788 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11789 << 2 << OrigTy << IsUnion << UseContext; 11790 // Reset OrigLoc so that this diagnostic is emitted only once. 11791 OrigLoc = SourceLocation(); 11792 } 11793 InNonTrivialUnion = true; 11794 } 11795 11796 if (InNonTrivialUnion) 11797 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11798 << 0 << 2 << QT.getUnqualifiedType() << ""; 11799 11800 for (const FieldDecl *FD : RD->fields()) 11801 if (!shouldIgnoreForRecordTriviality(FD)) 11802 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11803 } 11804 11805 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 11806 const FieldDecl *FD, bool InNonTrivialUnion) {} 11807 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11808 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 11809 bool InNonTrivialUnion) {} 11810 11811 // The non-trivial C union type or the struct/union type that contains a 11812 // non-trivial C union. 11813 QualType OrigTy; 11814 SourceLocation OrigLoc; 11815 Sema::NonTrivialCUnionContext UseContext; 11816 Sema &S; 11817 }; 11818 11819 } // namespace 11820 11821 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 11822 NonTrivialCUnionContext UseContext, 11823 unsigned NonTrivialKind) { 11824 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11825 QT.hasNonTrivialToPrimitiveDestructCUnion() || 11826 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 11827 "shouldn't be called if type doesn't have a non-trivial C union"); 11828 11829 if ((NonTrivialKind & NTCUK_Init) && 11830 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11831 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 11832 .visit(QT, nullptr, false); 11833 if ((NonTrivialKind & NTCUK_Destruct) && 11834 QT.hasNonTrivialToPrimitiveDestructCUnion()) 11835 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 11836 .visit(QT, nullptr, false); 11837 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 11838 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 11839 .visit(QT, nullptr, false); 11840 } 11841 11842 /// AddInitializerToDecl - Adds the initializer Init to the 11843 /// declaration dcl. If DirectInit is true, this is C++ direct 11844 /// initialization rather than copy initialization. 11845 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11846 // If there is no declaration, there was an error parsing it. Just ignore 11847 // the initializer. 11848 if (!RealDecl || RealDecl->isInvalidDecl()) { 11849 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11850 return; 11851 } 11852 11853 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11854 // Pure-specifiers are handled in ActOnPureSpecifier. 11855 Diag(Method->getLocation(), diag::err_member_function_initialization) 11856 << Method->getDeclName() << Init->getSourceRange(); 11857 Method->setInvalidDecl(); 11858 return; 11859 } 11860 11861 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 11862 if (!VDecl) { 11863 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 11864 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 11865 RealDecl->setInvalidDecl(); 11866 return; 11867 } 11868 11869 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11870 if (VDecl->getType()->isUndeducedType()) { 11871 // Attempt typo correction early so that the type of the init expression can 11872 // be deduced based on the chosen correction if the original init contains a 11873 // TypoExpr. 11874 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11875 if (!Res.isUsable()) { 11876 // There are unresolved typos in Init, just drop them. 11877 // FIXME: improve the recovery strategy to preserve the Init. 11878 RealDecl->setInvalidDecl(); 11879 return; 11880 } 11881 if (Res.get()->containsErrors()) { 11882 // Invalidate the decl as we don't know the type for recovery-expr yet. 11883 RealDecl->setInvalidDecl(); 11884 VDecl->setInit(Res.get()); 11885 return; 11886 } 11887 Init = Res.get(); 11888 11889 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11890 return; 11891 } 11892 11893 // dllimport cannot be used on variable definitions. 11894 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11895 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11896 VDecl->setInvalidDecl(); 11897 return; 11898 } 11899 11900 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11901 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11902 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11903 VDecl->setInvalidDecl(); 11904 return; 11905 } 11906 11907 if (!VDecl->getType()->isDependentType()) { 11908 // A definition must end up with a complete type, which means it must be 11909 // complete with the restriction that an array type might be completed by 11910 // the initializer; note that later code assumes this restriction. 11911 QualType BaseDeclType = VDecl->getType(); 11912 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 11913 BaseDeclType = Array->getElementType(); 11914 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 11915 diag::err_typecheck_decl_incomplete_type)) { 11916 RealDecl->setInvalidDecl(); 11917 return; 11918 } 11919 11920 // The variable can not have an abstract class type. 11921 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 11922 diag::err_abstract_type_in_decl, 11923 AbstractVariableType)) 11924 VDecl->setInvalidDecl(); 11925 } 11926 11927 // If adding the initializer will turn this declaration into a definition, 11928 // and we already have a definition for this variable, diagnose or otherwise 11929 // handle the situation. 11930 VarDecl *Def; 11931 if ((Def = VDecl->getDefinition()) && Def != VDecl && 11932 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 11933 !VDecl->isThisDeclarationADemotedDefinition() && 11934 checkVarDeclRedefinition(Def, VDecl)) 11935 return; 11936 11937 if (getLangOpts().CPlusPlus) { 11938 // C++ [class.static.data]p4 11939 // If a static data member is of const integral or const 11940 // enumeration type, its declaration in the class definition can 11941 // specify a constant-initializer which shall be an integral 11942 // constant expression (5.19). In that case, the member can appear 11943 // in integral constant expressions. The member shall still be 11944 // defined in a namespace scope if it is used in the program and the 11945 // namespace scope definition shall not contain an initializer. 11946 // 11947 // We already performed a redefinition check above, but for static 11948 // data members we also need to check whether there was an in-class 11949 // declaration with an initializer. 11950 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 11951 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 11952 << VDecl->getDeclName(); 11953 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 11954 diag::note_previous_initializer) 11955 << 0; 11956 return; 11957 } 11958 11959 if (VDecl->hasLocalStorage()) 11960 setFunctionHasBranchProtectedScope(); 11961 11962 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 11963 VDecl->setInvalidDecl(); 11964 return; 11965 } 11966 } 11967 11968 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 11969 // a kernel function cannot be initialized." 11970 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 11971 Diag(VDecl->getLocation(), diag::err_local_cant_init); 11972 VDecl->setInvalidDecl(); 11973 return; 11974 } 11975 11976 // The LoaderUninitialized attribute acts as a definition (of undef). 11977 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 11978 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 11979 VDecl->setInvalidDecl(); 11980 return; 11981 } 11982 11983 // Get the decls type and save a reference for later, since 11984 // CheckInitializerTypes may change it. 11985 QualType DclT = VDecl->getType(), SavT = DclT; 11986 11987 // Expressions default to 'id' when we're in a debugger 11988 // and we are assigning it to a variable of Objective-C pointer type. 11989 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 11990 Init->getType() == Context.UnknownAnyTy) { 11991 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11992 if (Result.isInvalid()) { 11993 VDecl->setInvalidDecl(); 11994 return; 11995 } 11996 Init = Result.get(); 11997 } 11998 11999 // Perform the initialization. 12000 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12001 if (!VDecl->isInvalidDecl()) { 12002 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12003 InitializationKind Kind = InitializationKind::CreateForInit( 12004 VDecl->getLocation(), DirectInit, Init); 12005 12006 MultiExprArg Args = Init; 12007 if (CXXDirectInit) 12008 Args = MultiExprArg(CXXDirectInit->getExprs(), 12009 CXXDirectInit->getNumExprs()); 12010 12011 // Try to correct any TypoExprs in the initialization arguments. 12012 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12013 ExprResult Res = CorrectDelayedTyposInExpr( 12014 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 12015 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12016 return Init.Failed() ? ExprError() : E; 12017 }); 12018 if (Res.isInvalid()) { 12019 VDecl->setInvalidDecl(); 12020 } else if (Res.get() != Args[Idx]) { 12021 Args[Idx] = Res.get(); 12022 } 12023 } 12024 if (VDecl->isInvalidDecl()) 12025 return; 12026 12027 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12028 /*TopLevelOfInitList=*/false, 12029 /*TreatUnavailableAsInvalid=*/false); 12030 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12031 if (Result.isInvalid()) { 12032 // If the provied initializer fails to initialize the var decl, 12033 // we attach a recovery expr for better recovery. 12034 auto RecoveryExpr = 12035 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12036 if (RecoveryExpr.get()) 12037 VDecl->setInit(RecoveryExpr.get()); 12038 return; 12039 } 12040 12041 Init = Result.getAs<Expr>(); 12042 } 12043 12044 // Check for self-references within variable initializers. 12045 // Variables declared within a function/method body (except for references) 12046 // are handled by a dataflow analysis. 12047 // This is undefined behavior in C++, but valid in C. 12048 if (getLangOpts().CPlusPlus) { 12049 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12050 VDecl->getType()->isReferenceType()) { 12051 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12052 } 12053 } 12054 12055 // If the type changed, it means we had an incomplete type that was 12056 // completed by the initializer. For example: 12057 // int ary[] = { 1, 3, 5 }; 12058 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12059 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12060 VDecl->setType(DclT); 12061 12062 if (!VDecl->isInvalidDecl()) { 12063 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12064 12065 if (VDecl->hasAttr<BlocksAttr>()) 12066 checkRetainCycles(VDecl, Init); 12067 12068 // It is safe to assign a weak reference into a strong variable. 12069 // Although this code can still have problems: 12070 // id x = self.weakProp; 12071 // id y = self.weakProp; 12072 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12073 // paths through the function. This should be revisited if 12074 // -Wrepeated-use-of-weak is made flow-sensitive. 12075 if (FunctionScopeInfo *FSI = getCurFunction()) 12076 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12077 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12078 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12079 Init->getBeginLoc())) 12080 FSI->markSafeWeakUse(Init); 12081 } 12082 12083 // The initialization is usually a full-expression. 12084 // 12085 // FIXME: If this is a braced initialization of an aggregate, it is not 12086 // an expression, and each individual field initializer is a separate 12087 // full-expression. For instance, in: 12088 // 12089 // struct Temp { ~Temp(); }; 12090 // struct S { S(Temp); }; 12091 // struct T { S a, b; } t = { Temp(), Temp() } 12092 // 12093 // we should destroy the first Temp before constructing the second. 12094 ExprResult Result = 12095 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12096 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12097 if (Result.isInvalid()) { 12098 VDecl->setInvalidDecl(); 12099 return; 12100 } 12101 Init = Result.get(); 12102 12103 // Attach the initializer to the decl. 12104 VDecl->setInit(Init); 12105 12106 if (VDecl->isLocalVarDecl()) { 12107 // Don't check the initializer if the declaration is malformed. 12108 if (VDecl->isInvalidDecl()) { 12109 // do nothing 12110 12111 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12112 // This is true even in C++ for OpenCL. 12113 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12114 CheckForConstantInitializer(Init, DclT); 12115 12116 // Otherwise, C++ does not restrict the initializer. 12117 } else if (getLangOpts().CPlusPlus) { 12118 // do nothing 12119 12120 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12121 // static storage duration shall be constant expressions or string literals. 12122 } else if (VDecl->getStorageClass() == SC_Static) { 12123 CheckForConstantInitializer(Init, DclT); 12124 12125 // C89 is stricter than C99 for aggregate initializers. 12126 // C89 6.5.7p3: All the expressions [...] in an initializer list 12127 // for an object that has aggregate or union type shall be 12128 // constant expressions. 12129 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12130 isa<InitListExpr>(Init)) { 12131 const Expr *Culprit; 12132 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12133 Diag(Culprit->getExprLoc(), 12134 diag::ext_aggregate_init_not_constant) 12135 << Culprit->getSourceRange(); 12136 } 12137 } 12138 12139 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12140 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12141 if (VDecl->hasLocalStorage()) 12142 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12143 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12144 VDecl->getLexicalDeclContext()->isRecord()) { 12145 // This is an in-class initialization for a static data member, e.g., 12146 // 12147 // struct S { 12148 // static const int value = 17; 12149 // }; 12150 12151 // C++ [class.mem]p4: 12152 // A member-declarator can contain a constant-initializer only 12153 // if it declares a static member (9.4) of const integral or 12154 // const enumeration type, see 9.4.2. 12155 // 12156 // C++11 [class.static.data]p3: 12157 // If a non-volatile non-inline const static data member is of integral 12158 // or enumeration type, its declaration in the class definition can 12159 // specify a brace-or-equal-initializer in which every initializer-clause 12160 // that is an assignment-expression is a constant expression. A static 12161 // data member of literal type can be declared in the class definition 12162 // with the constexpr specifier; if so, its declaration shall specify a 12163 // brace-or-equal-initializer in which every initializer-clause that is 12164 // an assignment-expression is a constant expression. 12165 12166 // Do nothing on dependent types. 12167 if (DclT->isDependentType()) { 12168 12169 // Allow any 'static constexpr' members, whether or not they are of literal 12170 // type. We separately check that every constexpr variable is of literal 12171 // type. 12172 } else if (VDecl->isConstexpr()) { 12173 12174 // Require constness. 12175 } else if (!DclT.isConstQualified()) { 12176 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12177 << Init->getSourceRange(); 12178 VDecl->setInvalidDecl(); 12179 12180 // We allow integer constant expressions in all cases. 12181 } else if (DclT->isIntegralOrEnumerationType()) { 12182 // Check whether the expression is a constant expression. 12183 SourceLocation Loc; 12184 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12185 // In C++11, a non-constexpr const static data member with an 12186 // in-class initializer cannot be volatile. 12187 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12188 else if (Init->isValueDependent()) 12189 ; // Nothing to check. 12190 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12191 ; // Ok, it's an ICE! 12192 else if (Init->getType()->isScopedEnumeralType() && 12193 Init->isCXX11ConstantExpr(Context)) 12194 ; // Ok, it is a scoped-enum constant expression. 12195 else if (Init->isEvaluatable(Context)) { 12196 // If we can constant fold the initializer through heroics, accept it, 12197 // but report this as a use of an extension for -pedantic. 12198 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12199 << Init->getSourceRange(); 12200 } else { 12201 // Otherwise, this is some crazy unknown case. Report the issue at the 12202 // location provided by the isIntegerConstantExpr failed check. 12203 Diag(Loc, diag::err_in_class_initializer_non_constant) 12204 << Init->getSourceRange(); 12205 VDecl->setInvalidDecl(); 12206 } 12207 12208 // We allow foldable floating-point constants as an extension. 12209 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12210 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12211 // it anyway and provide a fixit to add the 'constexpr'. 12212 if (getLangOpts().CPlusPlus11) { 12213 Diag(VDecl->getLocation(), 12214 diag::ext_in_class_initializer_float_type_cxx11) 12215 << DclT << Init->getSourceRange(); 12216 Diag(VDecl->getBeginLoc(), 12217 diag::note_in_class_initializer_float_type_cxx11) 12218 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12219 } else { 12220 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12221 << DclT << Init->getSourceRange(); 12222 12223 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12224 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12225 << Init->getSourceRange(); 12226 VDecl->setInvalidDecl(); 12227 } 12228 } 12229 12230 // Suggest adding 'constexpr' in C++11 for literal types. 12231 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12232 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12233 << DclT << Init->getSourceRange() 12234 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12235 VDecl->setConstexpr(true); 12236 12237 } else { 12238 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12239 << DclT << Init->getSourceRange(); 12240 VDecl->setInvalidDecl(); 12241 } 12242 } else if (VDecl->isFileVarDecl()) { 12243 // In C, extern is typically used to avoid tentative definitions when 12244 // declaring variables in headers, but adding an intializer makes it a 12245 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12246 // In C++, extern is often used to give implictly static const variables 12247 // external linkage, so don't warn in that case. If selectany is present, 12248 // this might be header code intended for C and C++ inclusion, so apply the 12249 // C++ rules. 12250 if (VDecl->getStorageClass() == SC_Extern && 12251 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12252 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12253 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12254 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12255 Diag(VDecl->getLocation(), diag::warn_extern_init); 12256 12257 // In Microsoft C++ mode, a const variable defined in namespace scope has 12258 // external linkage by default if the variable is declared with 12259 // __declspec(dllexport). 12260 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12261 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12262 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12263 VDecl->setStorageClass(SC_Extern); 12264 12265 // C99 6.7.8p4. All file scoped initializers need to be constant. 12266 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12267 CheckForConstantInitializer(Init, DclT); 12268 } 12269 12270 QualType InitType = Init->getType(); 12271 if (!InitType.isNull() && 12272 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12273 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12274 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12275 12276 // We will represent direct-initialization similarly to copy-initialization: 12277 // int x(1); -as-> int x = 1; 12278 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12279 // 12280 // Clients that want to distinguish between the two forms, can check for 12281 // direct initializer using VarDecl::getInitStyle(). 12282 // A major benefit is that clients that don't particularly care about which 12283 // exactly form was it (like the CodeGen) can handle both cases without 12284 // special case code. 12285 12286 // C++ 8.5p11: 12287 // The form of initialization (using parentheses or '=') is generally 12288 // insignificant, but does matter when the entity being initialized has a 12289 // class type. 12290 if (CXXDirectInit) { 12291 assert(DirectInit && "Call-style initializer must be direct init."); 12292 VDecl->setInitStyle(VarDecl::CallInit); 12293 } else if (DirectInit) { 12294 // This must be list-initialization. No other way is direct-initialization. 12295 VDecl->setInitStyle(VarDecl::ListInit); 12296 } 12297 12298 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12299 DeclsToCheckForDeferredDiags.push_back(VDecl); 12300 CheckCompleteVariableDeclaration(VDecl); 12301 } 12302 12303 /// ActOnInitializerError - Given that there was an error parsing an 12304 /// initializer for the given declaration, try to return to some form 12305 /// of sanity. 12306 void Sema::ActOnInitializerError(Decl *D) { 12307 // Our main concern here is re-establishing invariants like "a 12308 // variable's type is either dependent or complete". 12309 if (!D || D->isInvalidDecl()) return; 12310 12311 VarDecl *VD = dyn_cast<VarDecl>(D); 12312 if (!VD) return; 12313 12314 // Bindings are not usable if we can't make sense of the initializer. 12315 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12316 for (auto *BD : DD->bindings()) 12317 BD->setInvalidDecl(); 12318 12319 // Auto types are meaningless if we can't make sense of the initializer. 12320 if (VD->getType()->isUndeducedType()) { 12321 D->setInvalidDecl(); 12322 return; 12323 } 12324 12325 QualType Ty = VD->getType(); 12326 if (Ty->isDependentType()) return; 12327 12328 // Require a complete type. 12329 if (RequireCompleteType(VD->getLocation(), 12330 Context.getBaseElementType(Ty), 12331 diag::err_typecheck_decl_incomplete_type)) { 12332 VD->setInvalidDecl(); 12333 return; 12334 } 12335 12336 // Require a non-abstract type. 12337 if (RequireNonAbstractType(VD->getLocation(), Ty, 12338 diag::err_abstract_type_in_decl, 12339 AbstractVariableType)) { 12340 VD->setInvalidDecl(); 12341 return; 12342 } 12343 12344 // Don't bother complaining about constructors or destructors, 12345 // though. 12346 } 12347 12348 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12349 // If there is no declaration, there was an error parsing it. Just ignore it. 12350 if (!RealDecl) 12351 return; 12352 12353 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12354 QualType Type = Var->getType(); 12355 12356 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12357 if (isa<DecompositionDecl>(RealDecl)) { 12358 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12359 Var->setInvalidDecl(); 12360 return; 12361 } 12362 12363 if (Type->isUndeducedType() && 12364 DeduceVariableDeclarationType(Var, false, nullptr)) 12365 return; 12366 12367 // C++11 [class.static.data]p3: A static data member can be declared with 12368 // the constexpr specifier; if so, its declaration shall specify 12369 // a brace-or-equal-initializer. 12370 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12371 // the definition of a variable [...] or the declaration of a static data 12372 // member. 12373 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12374 !Var->isThisDeclarationADemotedDefinition()) { 12375 if (Var->isStaticDataMember()) { 12376 // C++1z removes the relevant rule; the in-class declaration is always 12377 // a definition there. 12378 if (!getLangOpts().CPlusPlus17 && 12379 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12380 Diag(Var->getLocation(), 12381 diag::err_constexpr_static_mem_var_requires_init) 12382 << Var->getDeclName(); 12383 Var->setInvalidDecl(); 12384 return; 12385 } 12386 } else { 12387 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12388 Var->setInvalidDecl(); 12389 return; 12390 } 12391 } 12392 12393 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12394 // be initialized. 12395 if (!Var->isInvalidDecl() && 12396 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12397 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12398 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12399 Var->setInvalidDecl(); 12400 return; 12401 } 12402 12403 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12404 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12405 if (!RD->hasTrivialDefaultConstructor()) { 12406 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12407 Var->setInvalidDecl(); 12408 return; 12409 } 12410 } 12411 if (Var->getStorageClass() == SC_Extern) { 12412 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12413 << Var; 12414 Var->setInvalidDecl(); 12415 return; 12416 } 12417 } 12418 12419 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12420 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12421 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12422 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12423 NTCUC_DefaultInitializedObject, NTCUK_Init); 12424 12425 12426 switch (DefKind) { 12427 case VarDecl::Definition: 12428 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12429 break; 12430 12431 // We have an out-of-line definition of a static data member 12432 // that has an in-class initializer, so we type-check this like 12433 // a declaration. 12434 // 12435 LLVM_FALLTHROUGH; 12436 12437 case VarDecl::DeclarationOnly: 12438 // It's only a declaration. 12439 12440 // Block scope. C99 6.7p7: If an identifier for an object is 12441 // declared with no linkage (C99 6.2.2p6), the type for the 12442 // object shall be complete. 12443 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12444 !Var->hasLinkage() && !Var->isInvalidDecl() && 12445 RequireCompleteType(Var->getLocation(), Type, 12446 diag::err_typecheck_decl_incomplete_type)) 12447 Var->setInvalidDecl(); 12448 12449 // Make sure that the type is not abstract. 12450 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12451 RequireNonAbstractType(Var->getLocation(), Type, 12452 diag::err_abstract_type_in_decl, 12453 AbstractVariableType)) 12454 Var->setInvalidDecl(); 12455 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12456 Var->getStorageClass() == SC_PrivateExtern) { 12457 Diag(Var->getLocation(), diag::warn_private_extern); 12458 Diag(Var->getLocation(), diag::note_private_extern); 12459 } 12460 12461 if (Context.getTargetInfo().allowDebugInfoForExternalVar() && 12462 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12463 ExternalDeclarations.push_back(Var); 12464 12465 return; 12466 12467 case VarDecl::TentativeDefinition: 12468 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12469 // object that has file scope without an initializer, and without a 12470 // storage-class specifier or with the storage-class specifier "static", 12471 // constitutes a tentative definition. Note: A tentative definition with 12472 // external linkage is valid (C99 6.2.2p5). 12473 if (!Var->isInvalidDecl()) { 12474 if (const IncompleteArrayType *ArrayT 12475 = Context.getAsIncompleteArrayType(Type)) { 12476 if (RequireCompleteSizedType( 12477 Var->getLocation(), ArrayT->getElementType(), 12478 diag::err_array_incomplete_or_sizeless_type)) 12479 Var->setInvalidDecl(); 12480 } else if (Var->getStorageClass() == SC_Static) { 12481 // C99 6.9.2p3: If the declaration of an identifier for an object is 12482 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12483 // declared type shall not be an incomplete type. 12484 // NOTE: code such as the following 12485 // static struct s; 12486 // struct s { int a; }; 12487 // is accepted by gcc. Hence here we issue a warning instead of 12488 // an error and we do not invalidate the static declaration. 12489 // NOTE: to avoid multiple warnings, only check the first declaration. 12490 if (Var->isFirstDecl()) 12491 RequireCompleteType(Var->getLocation(), Type, 12492 diag::ext_typecheck_decl_incomplete_type); 12493 } 12494 } 12495 12496 // Record the tentative definition; we're done. 12497 if (!Var->isInvalidDecl()) 12498 TentativeDefinitions.push_back(Var); 12499 return; 12500 } 12501 12502 // Provide a specific diagnostic for uninitialized variable 12503 // definitions with incomplete array type. 12504 if (Type->isIncompleteArrayType()) { 12505 Diag(Var->getLocation(), 12506 diag::err_typecheck_incomplete_array_needs_initializer); 12507 Var->setInvalidDecl(); 12508 return; 12509 } 12510 12511 // Provide a specific diagnostic for uninitialized variable 12512 // definitions with reference type. 12513 if (Type->isReferenceType()) { 12514 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12515 << Var->getDeclName() 12516 << SourceRange(Var->getLocation(), Var->getLocation()); 12517 Var->setInvalidDecl(); 12518 return; 12519 } 12520 12521 // Do not attempt to type-check the default initializer for a 12522 // variable with dependent type. 12523 if (Type->isDependentType()) 12524 return; 12525 12526 if (Var->isInvalidDecl()) 12527 return; 12528 12529 if (!Var->hasAttr<AliasAttr>()) { 12530 if (RequireCompleteType(Var->getLocation(), 12531 Context.getBaseElementType(Type), 12532 diag::err_typecheck_decl_incomplete_type)) { 12533 Var->setInvalidDecl(); 12534 return; 12535 } 12536 } else { 12537 return; 12538 } 12539 12540 // The variable can not have an abstract class type. 12541 if (RequireNonAbstractType(Var->getLocation(), Type, 12542 diag::err_abstract_type_in_decl, 12543 AbstractVariableType)) { 12544 Var->setInvalidDecl(); 12545 return; 12546 } 12547 12548 // Check for jumps past the implicit initializer. C++0x 12549 // clarifies that this applies to a "variable with automatic 12550 // storage duration", not a "local variable". 12551 // C++11 [stmt.dcl]p3 12552 // A program that jumps from a point where a variable with automatic 12553 // storage duration is not in scope to a point where it is in scope is 12554 // ill-formed unless the variable has scalar type, class type with a 12555 // trivial default constructor and a trivial destructor, a cv-qualified 12556 // version of one of these types, or an array of one of the preceding 12557 // types and is declared without an initializer. 12558 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12559 if (const RecordType *Record 12560 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12561 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12562 // Mark the function (if we're in one) for further checking even if the 12563 // looser rules of C++11 do not require such checks, so that we can 12564 // diagnose incompatibilities with C++98. 12565 if (!CXXRecord->isPOD()) 12566 setFunctionHasBranchProtectedScope(); 12567 } 12568 } 12569 // In OpenCL, we can't initialize objects in the __local address space, 12570 // even implicitly, so don't synthesize an implicit initializer. 12571 if (getLangOpts().OpenCL && 12572 Var->getType().getAddressSpace() == LangAS::opencl_local) 12573 return; 12574 // C++03 [dcl.init]p9: 12575 // If no initializer is specified for an object, and the 12576 // object is of (possibly cv-qualified) non-POD class type (or 12577 // array thereof), the object shall be default-initialized; if 12578 // the object is of const-qualified type, the underlying class 12579 // type shall have a user-declared default 12580 // constructor. Otherwise, if no initializer is specified for 12581 // a non- static object, the object and its subobjects, if 12582 // any, have an indeterminate initial value); if the object 12583 // or any of its subobjects are of const-qualified type, the 12584 // program is ill-formed. 12585 // C++0x [dcl.init]p11: 12586 // If no initializer is specified for an object, the object is 12587 // default-initialized; [...]. 12588 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12589 InitializationKind Kind 12590 = InitializationKind::CreateDefault(Var->getLocation()); 12591 12592 InitializationSequence InitSeq(*this, Entity, Kind, None); 12593 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12594 12595 if (Init.get()) { 12596 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12597 // This is important for template substitution. 12598 Var->setInitStyle(VarDecl::CallInit); 12599 } else if (Init.isInvalid()) { 12600 // If default-init fails, attach a recovery-expr initializer to track 12601 // that initialization was attempted and failed. 12602 auto RecoveryExpr = 12603 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12604 if (RecoveryExpr.get()) 12605 Var->setInit(RecoveryExpr.get()); 12606 } 12607 12608 CheckCompleteVariableDeclaration(Var); 12609 } 12610 } 12611 12612 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12613 // If there is no declaration, there was an error parsing it. Ignore it. 12614 if (!D) 12615 return; 12616 12617 VarDecl *VD = dyn_cast<VarDecl>(D); 12618 if (!VD) { 12619 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12620 D->setInvalidDecl(); 12621 return; 12622 } 12623 12624 VD->setCXXForRangeDecl(true); 12625 12626 // for-range-declaration cannot be given a storage class specifier. 12627 int Error = -1; 12628 switch (VD->getStorageClass()) { 12629 case SC_None: 12630 break; 12631 case SC_Extern: 12632 Error = 0; 12633 break; 12634 case SC_Static: 12635 Error = 1; 12636 break; 12637 case SC_PrivateExtern: 12638 Error = 2; 12639 break; 12640 case SC_Auto: 12641 Error = 3; 12642 break; 12643 case SC_Register: 12644 Error = 4; 12645 break; 12646 } 12647 if (Error != -1) { 12648 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12649 << VD->getDeclName() << Error; 12650 D->setInvalidDecl(); 12651 } 12652 } 12653 12654 StmtResult 12655 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12656 IdentifierInfo *Ident, 12657 ParsedAttributes &Attrs, 12658 SourceLocation AttrEnd) { 12659 // C++1y [stmt.iter]p1: 12660 // A range-based for statement of the form 12661 // for ( for-range-identifier : for-range-initializer ) statement 12662 // is equivalent to 12663 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12664 DeclSpec DS(Attrs.getPool().getFactory()); 12665 12666 const char *PrevSpec; 12667 unsigned DiagID; 12668 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12669 getPrintingPolicy()); 12670 12671 Declarator D(DS, DeclaratorContext::ForContext); 12672 D.SetIdentifier(Ident, IdentLoc); 12673 D.takeAttributes(Attrs, AttrEnd); 12674 12675 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12676 IdentLoc); 12677 Decl *Var = ActOnDeclarator(S, D); 12678 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12679 FinalizeDeclaration(Var); 12680 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12681 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12682 } 12683 12684 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12685 if (var->isInvalidDecl()) return; 12686 12687 if (getLangOpts().OpenCL) { 12688 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12689 // initialiser 12690 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12691 !var->hasInit()) { 12692 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12693 << 1 /*Init*/; 12694 var->setInvalidDecl(); 12695 return; 12696 } 12697 } 12698 12699 // In Objective-C, don't allow jumps past the implicit initialization of a 12700 // local retaining variable. 12701 if (getLangOpts().ObjC && 12702 var->hasLocalStorage()) { 12703 switch (var->getType().getObjCLifetime()) { 12704 case Qualifiers::OCL_None: 12705 case Qualifiers::OCL_ExplicitNone: 12706 case Qualifiers::OCL_Autoreleasing: 12707 break; 12708 12709 case Qualifiers::OCL_Weak: 12710 case Qualifiers::OCL_Strong: 12711 setFunctionHasBranchProtectedScope(); 12712 break; 12713 } 12714 } 12715 12716 if (var->hasLocalStorage() && 12717 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12718 setFunctionHasBranchProtectedScope(); 12719 12720 // Warn about externally-visible variables being defined without a 12721 // prior declaration. We only want to do this for global 12722 // declarations, but we also specifically need to avoid doing it for 12723 // class members because the linkage of an anonymous class can 12724 // change if it's later given a typedef name. 12725 if (var->isThisDeclarationADefinition() && 12726 var->getDeclContext()->getRedeclContext()->isFileContext() && 12727 var->isExternallyVisible() && var->hasLinkage() && 12728 !var->isInline() && !var->getDescribedVarTemplate() && 12729 !isa<VarTemplatePartialSpecializationDecl>(var) && 12730 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12731 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12732 var->getLocation())) { 12733 // Find a previous declaration that's not a definition. 12734 VarDecl *prev = var->getPreviousDecl(); 12735 while (prev && prev->isThisDeclarationADefinition()) 12736 prev = prev->getPreviousDecl(); 12737 12738 if (!prev) { 12739 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12740 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12741 << /* variable */ 0; 12742 } 12743 } 12744 12745 // Cache the result of checking for constant initialization. 12746 Optional<bool> CacheHasConstInit; 12747 const Expr *CacheCulprit = nullptr; 12748 auto checkConstInit = [&]() mutable { 12749 if (!CacheHasConstInit) 12750 CacheHasConstInit = var->getInit()->isConstantInitializer( 12751 Context, var->getType()->isReferenceType(), &CacheCulprit); 12752 return *CacheHasConstInit; 12753 }; 12754 12755 if (var->getTLSKind() == VarDecl::TLS_Static) { 12756 if (var->getType().isDestructedType()) { 12757 // GNU C++98 edits for __thread, [basic.start.term]p3: 12758 // The type of an object with thread storage duration shall not 12759 // have a non-trivial destructor. 12760 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12761 if (getLangOpts().CPlusPlus11) 12762 Diag(var->getLocation(), diag::note_use_thread_local); 12763 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12764 if (!checkConstInit()) { 12765 // GNU C++98 edits for __thread, [basic.start.init]p4: 12766 // An object of thread storage duration shall not require dynamic 12767 // initialization. 12768 // FIXME: Need strict checking here. 12769 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12770 << CacheCulprit->getSourceRange(); 12771 if (getLangOpts().CPlusPlus11) 12772 Diag(var->getLocation(), diag::note_use_thread_local); 12773 } 12774 } 12775 } 12776 12777 // Apply section attributes and pragmas to global variables. 12778 bool GlobalStorage = var->hasGlobalStorage(); 12779 if (GlobalStorage && var->isThisDeclarationADefinition() && 12780 !inTemplateInstantiation()) { 12781 PragmaStack<StringLiteral *> *Stack = nullptr; 12782 int SectionFlags = ASTContext::PSF_Read; 12783 if (var->getType().isConstQualified()) 12784 Stack = &ConstSegStack; 12785 else if (!var->getInit()) { 12786 Stack = &BSSSegStack; 12787 SectionFlags |= ASTContext::PSF_Write; 12788 } else { 12789 Stack = &DataSegStack; 12790 SectionFlags |= ASTContext::PSF_Write; 12791 } 12792 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 12793 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 12794 SectionFlags |= ASTContext::PSF_Implicit; 12795 UnifySection(SA->getName(), SectionFlags, var); 12796 } else if (Stack->CurrentValue) { 12797 SectionFlags |= ASTContext::PSF_Implicit; 12798 auto SectionName = Stack->CurrentValue->getString(); 12799 var->addAttr(SectionAttr::CreateImplicit( 12800 Context, SectionName, Stack->CurrentPragmaLocation, 12801 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 12802 if (UnifySection(SectionName, SectionFlags, var)) 12803 var->dropAttr<SectionAttr>(); 12804 } 12805 12806 // Apply the init_seg attribute if this has an initializer. If the 12807 // initializer turns out to not be dynamic, we'll end up ignoring this 12808 // attribute. 12809 if (CurInitSeg && var->getInit()) 12810 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 12811 CurInitSegLoc, 12812 AttributeCommonInfo::AS_Pragma)); 12813 } 12814 12815 // All the following checks are C++ only. 12816 if (!getLangOpts().CPlusPlus) { 12817 // If this variable must be emitted, add it as an initializer for the 12818 // current module. 12819 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12820 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12821 return; 12822 } 12823 12824 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 12825 CheckCompleteDecompositionDeclaration(DD); 12826 12827 QualType type = var->getType(); 12828 if (type->isDependentType()) return; 12829 12830 if (var->hasAttr<BlocksAttr>()) 12831 getCurFunction()->addByrefBlockVar(var); 12832 12833 Expr *Init = var->getInit(); 12834 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 12835 QualType baseType = Context.getBaseElementType(type); 12836 12837 if (Init && !Init->isValueDependent()) { 12838 if (var->isConstexpr()) { 12839 SmallVector<PartialDiagnosticAt, 8> Notes; 12840 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 12841 SourceLocation DiagLoc = var->getLocation(); 12842 // If the note doesn't add any useful information other than a source 12843 // location, fold it into the primary diagnostic. 12844 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12845 diag::note_invalid_subexpr_in_const_expr) { 12846 DiagLoc = Notes[0].first; 12847 Notes.clear(); 12848 } 12849 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 12850 << var << Init->getSourceRange(); 12851 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12852 Diag(Notes[I].first, Notes[I].second); 12853 } 12854 } else if (var->mightBeUsableInConstantExpressions(Context)) { 12855 // Check whether the initializer of a const variable of integral or 12856 // enumeration type is an ICE now, since we can't tell whether it was 12857 // initialized by a constant expression if we check later. 12858 var->checkInitIsICE(); 12859 } 12860 12861 // Don't emit further diagnostics about constexpr globals since they 12862 // were just diagnosed. 12863 if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) { 12864 // FIXME: Need strict checking in C++03 here. 12865 bool DiagErr = getLangOpts().CPlusPlus11 12866 ? !var->checkInitIsICE() : !checkConstInit(); 12867 if (DiagErr) { 12868 auto *Attr = var->getAttr<ConstInitAttr>(); 12869 Diag(var->getLocation(), diag::err_require_constant_init_failed) 12870 << Init->getSourceRange(); 12871 Diag(Attr->getLocation(), 12872 diag::note_declared_required_constant_init_here) 12873 << Attr->getRange() << Attr->isConstinit(); 12874 if (getLangOpts().CPlusPlus11) { 12875 APValue Value; 12876 SmallVector<PartialDiagnosticAt, 8> Notes; 12877 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 12878 for (auto &it : Notes) 12879 Diag(it.first, it.second); 12880 } else { 12881 Diag(CacheCulprit->getExprLoc(), 12882 diag::note_invalid_subexpr_in_const_expr) 12883 << CacheCulprit->getSourceRange(); 12884 } 12885 } 12886 } 12887 else if (!var->isConstexpr() && IsGlobal && 12888 !getDiagnostics().isIgnored(diag::warn_global_constructor, 12889 var->getLocation())) { 12890 // Warn about globals which don't have a constant initializer. Don't 12891 // warn about globals with a non-trivial destructor because we already 12892 // warned about them. 12893 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 12894 if (!(RD && !RD->hasTrivialDestructor())) { 12895 if (!checkConstInit()) 12896 Diag(var->getLocation(), diag::warn_global_constructor) 12897 << Init->getSourceRange(); 12898 } 12899 } 12900 } 12901 12902 // Require the destructor. 12903 if (const RecordType *recordType = baseType->getAs<RecordType>()) 12904 FinalizeVarWithDestructor(var, recordType); 12905 12906 // If this variable must be emitted, add it as an initializer for the current 12907 // module. 12908 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12909 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12910 } 12911 12912 /// Determines if a variable's alignment is dependent. 12913 static bool hasDependentAlignment(VarDecl *VD) { 12914 if (VD->getType()->isDependentType()) 12915 return true; 12916 for (auto *I : VD->specific_attrs<AlignedAttr>()) 12917 if (I->isAlignmentDependent()) 12918 return true; 12919 return false; 12920 } 12921 12922 /// Check if VD needs to be dllexport/dllimport due to being in a 12923 /// dllexport/import function. 12924 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 12925 assert(VD->isStaticLocal()); 12926 12927 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12928 12929 // Find outermost function when VD is in lambda function. 12930 while (FD && !getDLLAttr(FD) && 12931 !FD->hasAttr<DLLExportStaticLocalAttr>() && 12932 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 12933 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 12934 } 12935 12936 if (!FD) 12937 return; 12938 12939 // Static locals inherit dll attributes from their function. 12940 if (Attr *A = getDLLAttr(FD)) { 12941 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 12942 NewAttr->setInherited(true); 12943 VD->addAttr(NewAttr); 12944 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 12945 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 12946 NewAttr->setInherited(true); 12947 VD->addAttr(NewAttr); 12948 12949 // Export this function to enforce exporting this static variable even 12950 // if it is not used in this compilation unit. 12951 if (!FD->hasAttr<DLLExportAttr>()) 12952 FD->addAttr(NewAttr); 12953 12954 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 12955 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 12956 NewAttr->setInherited(true); 12957 VD->addAttr(NewAttr); 12958 } 12959 } 12960 12961 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 12962 /// any semantic actions necessary after any initializer has been attached. 12963 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 12964 // Note that we are no longer parsing the initializer for this declaration. 12965 ParsingInitForAutoVars.erase(ThisDecl); 12966 12967 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 12968 if (!VD) 12969 return; 12970 12971 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 12972 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 12973 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 12974 if (PragmaClangBSSSection.Valid) 12975 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 12976 Context, PragmaClangBSSSection.SectionName, 12977 PragmaClangBSSSection.PragmaLocation, 12978 AttributeCommonInfo::AS_Pragma)); 12979 if (PragmaClangDataSection.Valid) 12980 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 12981 Context, PragmaClangDataSection.SectionName, 12982 PragmaClangDataSection.PragmaLocation, 12983 AttributeCommonInfo::AS_Pragma)); 12984 if (PragmaClangRodataSection.Valid) 12985 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 12986 Context, PragmaClangRodataSection.SectionName, 12987 PragmaClangRodataSection.PragmaLocation, 12988 AttributeCommonInfo::AS_Pragma)); 12989 if (PragmaClangRelroSection.Valid) 12990 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 12991 Context, PragmaClangRelroSection.SectionName, 12992 PragmaClangRelroSection.PragmaLocation, 12993 AttributeCommonInfo::AS_Pragma)); 12994 } 12995 12996 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 12997 for (auto *BD : DD->bindings()) { 12998 FinalizeDeclaration(BD); 12999 } 13000 } 13001 13002 checkAttributesAfterMerging(*this, *VD); 13003 13004 // Perform TLS alignment check here after attributes attached to the variable 13005 // which may affect the alignment have been processed. Only perform the check 13006 // if the target has a maximum TLS alignment (zero means no constraints). 13007 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13008 // Protect the check so that it's not performed on dependent types and 13009 // dependent alignments (we can't determine the alignment in that case). 13010 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 13011 !VD->isInvalidDecl()) { 13012 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13013 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13014 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13015 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13016 << (unsigned)MaxAlignChars.getQuantity(); 13017 } 13018 } 13019 } 13020 13021 if (VD->isStaticLocal()) { 13022 CheckStaticLocalForDllExport(VD); 13023 13024 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 13025 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 13026 // function, only __shared__ variables or variables without any device 13027 // memory qualifiers may be declared with static storage class. 13028 // Note: It is unclear how a function-scope non-const static variable 13029 // without device memory qualifier is implemented, therefore only static 13030 // const variable without device memory qualifier is allowed. 13031 [&]() { 13032 if (!getLangOpts().CUDA) 13033 return; 13034 if (VD->hasAttr<CUDASharedAttr>()) 13035 return; 13036 if (VD->getType().isConstQualified() && 13037 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 13038 return; 13039 if (CUDADiagIfDeviceCode(VD->getLocation(), 13040 diag::err_device_static_local_var) 13041 << CurrentCUDATarget()) 13042 VD->setInvalidDecl(); 13043 }(); 13044 } 13045 } 13046 13047 // Perform check for initializers of device-side global variables. 13048 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13049 // 7.5). We must also apply the same checks to all __shared__ 13050 // variables whether they are local or not. CUDA also allows 13051 // constant initializers for __constant__ and __device__ variables. 13052 if (getLangOpts().CUDA) 13053 checkAllowedCUDAInitializer(VD); 13054 13055 // Grab the dllimport or dllexport attribute off of the VarDecl. 13056 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13057 13058 // Imported static data members cannot be defined out-of-line. 13059 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13060 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13061 VD->isThisDeclarationADefinition()) { 13062 // We allow definitions of dllimport class template static data members 13063 // with a warning. 13064 CXXRecordDecl *Context = 13065 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13066 bool IsClassTemplateMember = 13067 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13068 Context->getDescribedClassTemplate(); 13069 13070 Diag(VD->getLocation(), 13071 IsClassTemplateMember 13072 ? diag::warn_attribute_dllimport_static_field_definition 13073 : diag::err_attribute_dllimport_static_field_definition); 13074 Diag(IA->getLocation(), diag::note_attribute); 13075 if (!IsClassTemplateMember) 13076 VD->setInvalidDecl(); 13077 } 13078 } 13079 13080 // dllimport/dllexport variables cannot be thread local, their TLS index 13081 // isn't exported with the variable. 13082 if (DLLAttr && VD->getTLSKind()) { 13083 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13084 if (F && getDLLAttr(F)) { 13085 assert(VD->isStaticLocal()); 13086 // But if this is a static local in a dlimport/dllexport function, the 13087 // function will never be inlined, which means the var would never be 13088 // imported, so having it marked import/export is safe. 13089 } else { 13090 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13091 << DLLAttr; 13092 VD->setInvalidDecl(); 13093 } 13094 } 13095 13096 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13097 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13098 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 13099 VD->dropAttr<UsedAttr>(); 13100 } 13101 } 13102 13103 const DeclContext *DC = VD->getDeclContext(); 13104 // If there's a #pragma GCC visibility in scope, and this isn't a class 13105 // member, set the visibility of this variable. 13106 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13107 AddPushedVisibilityAttribute(VD); 13108 13109 // FIXME: Warn on unused var template partial specializations. 13110 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13111 MarkUnusedFileScopedDecl(VD); 13112 13113 // Now we have parsed the initializer and can update the table of magic 13114 // tag values. 13115 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13116 !VD->getType()->isIntegralOrEnumerationType()) 13117 return; 13118 13119 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13120 const Expr *MagicValueExpr = VD->getInit(); 13121 if (!MagicValueExpr) { 13122 continue; 13123 } 13124 llvm::APSInt MagicValueInt; 13125 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 13126 Diag(I->getRange().getBegin(), 13127 diag::err_type_tag_for_datatype_not_ice) 13128 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13129 continue; 13130 } 13131 if (MagicValueInt.getActiveBits() > 64) { 13132 Diag(I->getRange().getBegin(), 13133 diag::err_type_tag_for_datatype_too_large) 13134 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13135 continue; 13136 } 13137 uint64_t MagicValue = MagicValueInt.getZExtValue(); 13138 RegisterTypeTagForDatatype(I->getArgumentKind(), 13139 MagicValue, 13140 I->getMatchingCType(), 13141 I->getLayoutCompatible(), 13142 I->getMustBeNull()); 13143 } 13144 } 13145 13146 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13147 auto *VD = dyn_cast<VarDecl>(DD); 13148 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13149 } 13150 13151 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13152 ArrayRef<Decl *> Group) { 13153 SmallVector<Decl*, 8> Decls; 13154 13155 if (DS.isTypeSpecOwned()) 13156 Decls.push_back(DS.getRepAsDecl()); 13157 13158 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13159 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13160 bool DiagnosedMultipleDecomps = false; 13161 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13162 bool DiagnosedNonDeducedAuto = false; 13163 13164 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13165 if (Decl *D = Group[i]) { 13166 // For declarators, there are some additional syntactic-ish checks we need 13167 // to perform. 13168 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13169 if (!FirstDeclaratorInGroup) 13170 FirstDeclaratorInGroup = DD; 13171 if (!FirstDecompDeclaratorInGroup) 13172 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13173 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13174 !hasDeducedAuto(DD)) 13175 FirstNonDeducedAutoInGroup = DD; 13176 13177 if (FirstDeclaratorInGroup != DD) { 13178 // A decomposition declaration cannot be combined with any other 13179 // declaration in the same group. 13180 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13181 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13182 diag::err_decomp_decl_not_alone) 13183 << FirstDeclaratorInGroup->getSourceRange() 13184 << DD->getSourceRange(); 13185 DiagnosedMultipleDecomps = true; 13186 } 13187 13188 // A declarator that uses 'auto' in any way other than to declare a 13189 // variable with a deduced type cannot be combined with any other 13190 // declarator in the same group. 13191 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13192 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13193 diag::err_auto_non_deduced_not_alone) 13194 << FirstNonDeducedAutoInGroup->getType() 13195 ->hasAutoForTrailingReturnType() 13196 << FirstDeclaratorInGroup->getSourceRange() 13197 << DD->getSourceRange(); 13198 DiagnosedNonDeducedAuto = true; 13199 } 13200 } 13201 } 13202 13203 Decls.push_back(D); 13204 } 13205 } 13206 13207 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13208 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13209 handleTagNumbering(Tag, S); 13210 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13211 getLangOpts().CPlusPlus) 13212 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13213 } 13214 } 13215 13216 return BuildDeclaratorGroup(Decls); 13217 } 13218 13219 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13220 /// group, performing any necessary semantic checking. 13221 Sema::DeclGroupPtrTy 13222 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13223 // C++14 [dcl.spec.auto]p7: (DR1347) 13224 // If the type that replaces the placeholder type is not the same in each 13225 // deduction, the program is ill-formed. 13226 if (Group.size() > 1) { 13227 QualType Deduced; 13228 VarDecl *DeducedDecl = nullptr; 13229 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13230 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13231 if (!D || D->isInvalidDecl()) 13232 break; 13233 DeducedType *DT = D->getType()->getContainedDeducedType(); 13234 if (!DT || DT->getDeducedType().isNull()) 13235 continue; 13236 if (Deduced.isNull()) { 13237 Deduced = DT->getDeducedType(); 13238 DeducedDecl = D; 13239 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13240 auto *AT = dyn_cast<AutoType>(DT); 13241 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13242 diag::err_auto_different_deductions) 13243 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13244 << DeducedDecl->getDeclName() << DT->getDeducedType() 13245 << D->getDeclName(); 13246 if (DeducedDecl->hasInit()) 13247 Dia << DeducedDecl->getInit()->getSourceRange(); 13248 if (D->getInit()) 13249 Dia << D->getInit()->getSourceRange(); 13250 D->setInvalidDecl(); 13251 break; 13252 } 13253 } 13254 } 13255 13256 ActOnDocumentableDecls(Group); 13257 13258 return DeclGroupPtrTy::make( 13259 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13260 } 13261 13262 void Sema::ActOnDocumentableDecl(Decl *D) { 13263 ActOnDocumentableDecls(D); 13264 } 13265 13266 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13267 // Don't parse the comment if Doxygen diagnostics are ignored. 13268 if (Group.empty() || !Group[0]) 13269 return; 13270 13271 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13272 Group[0]->getLocation()) && 13273 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13274 Group[0]->getLocation())) 13275 return; 13276 13277 if (Group.size() >= 2) { 13278 // This is a decl group. Normally it will contain only declarations 13279 // produced from declarator list. But in case we have any definitions or 13280 // additional declaration references: 13281 // 'typedef struct S {} S;' 13282 // 'typedef struct S *S;' 13283 // 'struct S *pS;' 13284 // FinalizeDeclaratorGroup adds these as separate declarations. 13285 Decl *MaybeTagDecl = Group[0]; 13286 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13287 Group = Group.slice(1); 13288 } 13289 } 13290 13291 // FIMXE: We assume every Decl in the group is in the same file. 13292 // This is false when preprocessor constructs the group from decls in 13293 // different files (e. g. macros or #include). 13294 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13295 } 13296 13297 /// Common checks for a parameter-declaration that should apply to both function 13298 /// parameters and non-type template parameters. 13299 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13300 // Check that there are no default arguments inside the type of this 13301 // parameter. 13302 if (getLangOpts().CPlusPlus) 13303 CheckExtraCXXDefaultArguments(D); 13304 13305 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13306 if (D.getCXXScopeSpec().isSet()) { 13307 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13308 << D.getCXXScopeSpec().getRange(); 13309 } 13310 13311 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13312 // simple identifier except [...irrelevant cases...]. 13313 switch (D.getName().getKind()) { 13314 case UnqualifiedIdKind::IK_Identifier: 13315 break; 13316 13317 case UnqualifiedIdKind::IK_OperatorFunctionId: 13318 case UnqualifiedIdKind::IK_ConversionFunctionId: 13319 case UnqualifiedIdKind::IK_LiteralOperatorId: 13320 case UnqualifiedIdKind::IK_ConstructorName: 13321 case UnqualifiedIdKind::IK_DestructorName: 13322 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13323 case UnqualifiedIdKind::IK_DeductionGuideName: 13324 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13325 << GetNameForDeclarator(D).getName(); 13326 break; 13327 13328 case UnqualifiedIdKind::IK_TemplateId: 13329 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13330 // GetNameForDeclarator would not produce a useful name in this case. 13331 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13332 break; 13333 } 13334 } 13335 13336 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13337 /// to introduce parameters into function prototype scope. 13338 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13339 const DeclSpec &DS = D.getDeclSpec(); 13340 13341 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13342 13343 // C++03 [dcl.stc]p2 also permits 'auto'. 13344 StorageClass SC = SC_None; 13345 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13346 SC = SC_Register; 13347 // In C++11, the 'register' storage class specifier is deprecated. 13348 // In C++17, it is not allowed, but we tolerate it as an extension. 13349 if (getLangOpts().CPlusPlus11) { 13350 Diag(DS.getStorageClassSpecLoc(), 13351 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13352 : diag::warn_deprecated_register) 13353 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13354 } 13355 } else if (getLangOpts().CPlusPlus && 13356 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13357 SC = SC_Auto; 13358 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13359 Diag(DS.getStorageClassSpecLoc(), 13360 diag::err_invalid_storage_class_in_func_decl); 13361 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13362 } 13363 13364 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13365 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13366 << DeclSpec::getSpecifierName(TSCS); 13367 if (DS.isInlineSpecified()) 13368 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13369 << getLangOpts().CPlusPlus17; 13370 if (DS.hasConstexprSpecifier()) 13371 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13372 << 0 << D.getDeclSpec().getConstexprSpecifier(); 13373 13374 DiagnoseFunctionSpecifiers(DS); 13375 13376 CheckFunctionOrTemplateParamDeclarator(S, D); 13377 13378 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13379 QualType parmDeclType = TInfo->getType(); 13380 13381 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13382 IdentifierInfo *II = D.getIdentifier(); 13383 if (II) { 13384 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13385 ForVisibleRedeclaration); 13386 LookupName(R, S); 13387 if (R.isSingleResult()) { 13388 NamedDecl *PrevDecl = R.getFoundDecl(); 13389 if (PrevDecl->isTemplateParameter()) { 13390 // Maybe we will complain about the shadowed template parameter. 13391 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13392 // Just pretend that we didn't see the previous declaration. 13393 PrevDecl = nullptr; 13394 } else if (S->isDeclScope(PrevDecl)) { 13395 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13396 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13397 13398 // Recover by removing the name 13399 II = nullptr; 13400 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13401 D.setInvalidType(true); 13402 } 13403 } 13404 } 13405 13406 // Temporarily put parameter variables in the translation unit, not 13407 // the enclosing context. This prevents them from accidentally 13408 // looking like class members in C++. 13409 ParmVarDecl *New = 13410 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13411 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13412 13413 if (D.isInvalidType()) 13414 New->setInvalidDecl(); 13415 13416 assert(S->isFunctionPrototypeScope()); 13417 assert(S->getFunctionPrototypeDepth() >= 1); 13418 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13419 S->getNextFunctionPrototypeIndex()); 13420 13421 // Add the parameter declaration into this scope. 13422 S->AddDecl(New); 13423 if (II) 13424 IdResolver.AddDecl(New); 13425 13426 ProcessDeclAttributes(S, New, D); 13427 13428 if (D.getDeclSpec().isModulePrivateSpecified()) 13429 Diag(New->getLocation(), diag::err_module_private_local) 13430 << 1 << New->getDeclName() 13431 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13432 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13433 13434 if (New->hasAttr<BlocksAttr>()) { 13435 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13436 } 13437 13438 if (getLangOpts().OpenCL) 13439 deduceOpenCLAddressSpace(New); 13440 13441 return New; 13442 } 13443 13444 /// Synthesizes a variable for a parameter arising from a 13445 /// typedef. 13446 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13447 SourceLocation Loc, 13448 QualType T) { 13449 /* FIXME: setting StartLoc == Loc. 13450 Would it be worth to modify callers so as to provide proper source 13451 location for the unnamed parameters, embedding the parameter's type? */ 13452 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13453 T, Context.getTrivialTypeSourceInfo(T, Loc), 13454 SC_None, nullptr); 13455 Param->setImplicit(); 13456 return Param; 13457 } 13458 13459 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13460 // Don't diagnose unused-parameter errors in template instantiations; we 13461 // will already have done so in the template itself. 13462 if (inTemplateInstantiation()) 13463 return; 13464 13465 for (const ParmVarDecl *Parameter : Parameters) { 13466 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13467 !Parameter->hasAttr<UnusedAttr>()) { 13468 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13469 << Parameter->getDeclName(); 13470 } 13471 } 13472 } 13473 13474 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13475 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13476 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13477 return; 13478 13479 // Warn if the return value is pass-by-value and larger than the specified 13480 // threshold. 13481 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13482 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13483 if (Size > LangOpts.NumLargeByValueCopy) 13484 Diag(D->getLocation(), diag::warn_return_value_size) 13485 << D->getDeclName() << Size; 13486 } 13487 13488 // Warn if any parameter is pass-by-value and larger than the specified 13489 // threshold. 13490 for (const ParmVarDecl *Parameter : Parameters) { 13491 QualType T = Parameter->getType(); 13492 if (T->isDependentType() || !T.isPODType(Context)) 13493 continue; 13494 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13495 if (Size > LangOpts.NumLargeByValueCopy) 13496 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13497 << Parameter->getDeclName() << Size; 13498 } 13499 } 13500 13501 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13502 SourceLocation NameLoc, IdentifierInfo *Name, 13503 QualType T, TypeSourceInfo *TSInfo, 13504 StorageClass SC) { 13505 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13506 if (getLangOpts().ObjCAutoRefCount && 13507 T.getObjCLifetime() == Qualifiers::OCL_None && 13508 T->isObjCLifetimeType()) { 13509 13510 Qualifiers::ObjCLifetime lifetime; 13511 13512 // Special cases for arrays: 13513 // - if it's const, use __unsafe_unretained 13514 // - otherwise, it's an error 13515 if (T->isArrayType()) { 13516 if (!T.isConstQualified()) { 13517 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13518 DelayedDiagnostics.add( 13519 sema::DelayedDiagnostic::makeForbiddenType( 13520 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13521 else 13522 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13523 << TSInfo->getTypeLoc().getSourceRange(); 13524 } 13525 lifetime = Qualifiers::OCL_ExplicitNone; 13526 } else { 13527 lifetime = T->getObjCARCImplicitLifetime(); 13528 } 13529 T = Context.getLifetimeQualifiedType(T, lifetime); 13530 } 13531 13532 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13533 Context.getAdjustedParameterType(T), 13534 TSInfo, SC, nullptr); 13535 13536 // Make a note if we created a new pack in the scope of a lambda, so that 13537 // we know that references to that pack must also be expanded within the 13538 // lambda scope. 13539 if (New->isParameterPack()) 13540 if (auto *LSI = getEnclosingLambda()) 13541 LSI->LocalPacks.push_back(New); 13542 13543 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13544 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13545 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13546 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13547 13548 // Parameters can not be abstract class types. 13549 // For record types, this is done by the AbstractClassUsageDiagnoser once 13550 // the class has been completely parsed. 13551 if (!CurContext->isRecord() && 13552 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13553 AbstractParamType)) 13554 New->setInvalidDecl(); 13555 13556 // Parameter declarators cannot be interface types. All ObjC objects are 13557 // passed by reference. 13558 if (T->isObjCObjectType()) { 13559 SourceLocation TypeEndLoc = 13560 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13561 Diag(NameLoc, 13562 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13563 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13564 T = Context.getObjCObjectPointerType(T); 13565 New->setType(T); 13566 } 13567 13568 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13569 // duration shall not be qualified by an address-space qualifier." 13570 // Since all parameters have automatic store duration, they can not have 13571 // an address space. 13572 if (T.getAddressSpace() != LangAS::Default && 13573 // OpenCL allows function arguments declared to be an array of a type 13574 // to be qualified with an address space. 13575 !(getLangOpts().OpenCL && 13576 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13577 Diag(NameLoc, diag::err_arg_with_address_space); 13578 New->setInvalidDecl(); 13579 } 13580 13581 return New; 13582 } 13583 13584 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13585 SourceLocation LocAfterDecls) { 13586 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13587 13588 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13589 // for a K&R function. 13590 if (!FTI.hasPrototype) { 13591 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13592 --i; 13593 if (FTI.Params[i].Param == nullptr) { 13594 SmallString<256> Code; 13595 llvm::raw_svector_ostream(Code) 13596 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13597 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13598 << FTI.Params[i].Ident 13599 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13600 13601 // Implicitly declare the argument as type 'int' for lack of a better 13602 // type. 13603 AttributeFactory attrs; 13604 DeclSpec DS(attrs); 13605 const char* PrevSpec; // unused 13606 unsigned DiagID; // unused 13607 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13608 DiagID, Context.getPrintingPolicy()); 13609 // Use the identifier location for the type source range. 13610 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13611 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13612 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 13613 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13614 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13615 } 13616 } 13617 } 13618 } 13619 13620 Decl * 13621 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13622 MultiTemplateParamsArg TemplateParameterLists, 13623 SkipBodyInfo *SkipBody) { 13624 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13625 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13626 Scope *ParentScope = FnBodyScope->getParent(); 13627 13628 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 13629 // we define a non-templated function definition, we will create a declaration 13630 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 13631 // The base function declaration will have the equivalent of an `omp declare 13632 // variant` annotation which specifies the mangled definition as a 13633 // specialization function under the OpenMP context defined as part of the 13634 // `omp begin declare variant`. 13635 FunctionDecl *BaseFD = nullptr; 13636 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope() && 13637 TemplateParameterLists.empty()) 13638 BaseFD = ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 13639 ParentScope, D); 13640 13641 D.setFunctionDefinitionKind(FDK_Definition); 13642 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13643 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13644 13645 if (BaseFD) 13646 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 13647 cast<FunctionDecl>(Dcl), BaseFD); 13648 13649 return Dcl; 13650 } 13651 13652 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13653 Consumer.HandleInlineFunctionDefinition(D); 13654 } 13655 13656 static bool 13657 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13658 const FunctionDecl *&PossiblePrototype) { 13659 // Don't warn about invalid declarations. 13660 if (FD->isInvalidDecl()) 13661 return false; 13662 13663 // Or declarations that aren't global. 13664 if (!FD->isGlobal()) 13665 return false; 13666 13667 // Don't warn about C++ member functions. 13668 if (isa<CXXMethodDecl>(FD)) 13669 return false; 13670 13671 // Don't warn about 'main'. 13672 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13673 if (IdentifierInfo *II = FD->getIdentifier()) 13674 if (II->isStr("main")) 13675 return false; 13676 13677 // Don't warn about inline functions. 13678 if (FD->isInlined()) 13679 return false; 13680 13681 // Don't warn about function templates. 13682 if (FD->getDescribedFunctionTemplate()) 13683 return false; 13684 13685 // Don't warn about function template specializations. 13686 if (FD->isFunctionTemplateSpecialization()) 13687 return false; 13688 13689 // Don't warn for OpenCL kernels. 13690 if (FD->hasAttr<OpenCLKernelAttr>()) 13691 return false; 13692 13693 // Don't warn on explicitly deleted functions. 13694 if (FD->isDeleted()) 13695 return false; 13696 13697 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13698 Prev; Prev = Prev->getPreviousDecl()) { 13699 // Ignore any declarations that occur in function or method 13700 // scope, because they aren't visible from the header. 13701 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13702 continue; 13703 13704 PossiblePrototype = Prev; 13705 return Prev->getType()->isFunctionNoProtoType(); 13706 } 13707 13708 return true; 13709 } 13710 13711 void 13712 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13713 const FunctionDecl *EffectiveDefinition, 13714 SkipBodyInfo *SkipBody) { 13715 const FunctionDecl *Definition = EffectiveDefinition; 13716 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 13717 // If this is a friend function defined in a class template, it does not 13718 // have a body until it is used, nevertheless it is a definition, see 13719 // [temp.inst]p2: 13720 // 13721 // ... for the purpose of determining whether an instantiated redeclaration 13722 // is valid according to [basic.def.odr] and [class.mem], a declaration that 13723 // corresponds to a definition in the template is considered to be a 13724 // definition. 13725 // 13726 // The following code must produce redefinition error: 13727 // 13728 // template<typename T> struct C20 { friend void func_20() {} }; 13729 // C20<int> c20i; 13730 // void func_20() {} 13731 // 13732 for (auto I : FD->redecls()) { 13733 if (I != FD && !I->isInvalidDecl() && 13734 I->getFriendObjectKind() != Decl::FOK_None) { 13735 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 13736 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13737 // A merged copy of the same function, instantiated as a member of 13738 // the same class, is OK. 13739 if (declaresSameEntity(OrigFD, Original) && 13740 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 13741 cast<Decl>(FD->getLexicalDeclContext()))) 13742 continue; 13743 } 13744 13745 if (Original->isThisDeclarationADefinition()) { 13746 Definition = I; 13747 break; 13748 } 13749 } 13750 } 13751 } 13752 } 13753 13754 if (!Definition) 13755 // Similar to friend functions a friend function template may be a 13756 // definition and do not have a body if it is instantiated in a class 13757 // template. 13758 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 13759 for (auto I : FTD->redecls()) { 13760 auto D = cast<FunctionTemplateDecl>(I); 13761 if (D != FTD) { 13762 assert(!D->isThisDeclarationADefinition() && 13763 "More than one definition in redeclaration chain"); 13764 if (D->getFriendObjectKind() != Decl::FOK_None) 13765 if (FunctionTemplateDecl *FT = 13766 D->getInstantiatedFromMemberTemplate()) { 13767 if (FT->isThisDeclarationADefinition()) { 13768 Definition = D->getTemplatedDecl(); 13769 break; 13770 } 13771 } 13772 } 13773 } 13774 } 13775 13776 if (!Definition) 13777 return; 13778 13779 if (canRedefineFunction(Definition, getLangOpts())) 13780 return; 13781 13782 // Don't emit an error when this is redefinition of a typo-corrected 13783 // definition. 13784 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13785 return; 13786 13787 // If we don't have a visible definition of the function, and it's inline or 13788 // a template, skip the new definition. 13789 if (SkipBody && !hasVisibleDefinition(Definition) && 13790 (Definition->getFormalLinkage() == InternalLinkage || 13791 Definition->isInlined() || 13792 Definition->getDescribedFunctionTemplate() || 13793 Definition->getNumTemplateParameterLists())) { 13794 SkipBody->ShouldSkip = true; 13795 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 13796 if (auto *TD = Definition->getDescribedFunctionTemplate()) 13797 makeMergedDefinitionVisible(TD); 13798 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 13799 return; 13800 } 13801 13802 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 13803 Definition->getStorageClass() == SC_Extern) 13804 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 13805 << FD->getDeclName() << getLangOpts().CPlusPlus; 13806 else 13807 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 13808 13809 Diag(Definition->getLocation(), diag::note_previous_definition); 13810 FD->setInvalidDecl(); 13811 } 13812 13813 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 13814 Sema &S) { 13815 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 13816 13817 LambdaScopeInfo *LSI = S.PushLambdaScope(); 13818 LSI->CallOperator = CallOperator; 13819 LSI->Lambda = LambdaClass; 13820 LSI->ReturnType = CallOperator->getReturnType(); 13821 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 13822 13823 if (LCD == LCD_None) 13824 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 13825 else if (LCD == LCD_ByCopy) 13826 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 13827 else if (LCD == LCD_ByRef) 13828 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 13829 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 13830 13831 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 13832 LSI->Mutable = !CallOperator->isConst(); 13833 13834 // Add the captures to the LSI so they can be noted as already 13835 // captured within tryCaptureVar. 13836 auto I = LambdaClass->field_begin(); 13837 for (const auto &C : LambdaClass->captures()) { 13838 if (C.capturesVariable()) { 13839 VarDecl *VD = C.getCapturedVar(); 13840 if (VD->isInitCapture()) 13841 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 13842 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 13843 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 13844 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 13845 /*EllipsisLoc*/C.isPackExpansion() 13846 ? C.getEllipsisLoc() : SourceLocation(), 13847 I->getType(), /*Invalid*/false); 13848 13849 } else if (C.capturesThis()) { 13850 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 13851 C.getCaptureKind() == LCK_StarThis); 13852 } else { 13853 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 13854 I->getType()); 13855 } 13856 ++I; 13857 } 13858 } 13859 13860 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 13861 SkipBodyInfo *SkipBody) { 13862 if (!D) { 13863 // Parsing the function declaration failed in some way. Push on a fake scope 13864 // anyway so we can try to parse the function body. 13865 PushFunctionScope(); 13866 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13867 return D; 13868 } 13869 13870 FunctionDecl *FD = nullptr; 13871 13872 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 13873 FD = FunTmpl->getTemplatedDecl(); 13874 else 13875 FD = cast<FunctionDecl>(D); 13876 13877 // Do not push if it is a lambda because one is already pushed when building 13878 // the lambda in ActOnStartOfLambdaDefinition(). 13879 if (!isLambdaCallOperator(FD)) 13880 PushExpressionEvaluationContext( 13881 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 13882 : ExprEvalContexts.back().Context); 13883 13884 // Check for defining attributes before the check for redefinition. 13885 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 13886 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 13887 FD->dropAttr<AliasAttr>(); 13888 FD->setInvalidDecl(); 13889 } 13890 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 13891 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 13892 FD->dropAttr<IFuncAttr>(); 13893 FD->setInvalidDecl(); 13894 } 13895 13896 // See if this is a redefinition. If 'will have body' is already set, then 13897 // these checks were already performed when it was set. 13898 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 13899 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 13900 13901 // If we're skipping the body, we're done. Don't enter the scope. 13902 if (SkipBody && SkipBody->ShouldSkip) 13903 return D; 13904 } 13905 13906 // Mark this function as "will have a body eventually". This lets users to 13907 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 13908 // this function. 13909 FD->setWillHaveBody(); 13910 13911 // If we are instantiating a generic lambda call operator, push 13912 // a LambdaScopeInfo onto the function stack. But use the information 13913 // that's already been calculated (ActOnLambdaExpr) to prime the current 13914 // LambdaScopeInfo. 13915 // When the template operator is being specialized, the LambdaScopeInfo, 13916 // has to be properly restored so that tryCaptureVariable doesn't try 13917 // and capture any new variables. In addition when calculating potential 13918 // captures during transformation of nested lambdas, it is necessary to 13919 // have the LSI properly restored. 13920 if (isGenericLambdaCallOperatorSpecialization(FD)) { 13921 assert(inTemplateInstantiation() && 13922 "There should be an active template instantiation on the stack " 13923 "when instantiating a generic lambda!"); 13924 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 13925 } else { 13926 // Enter a new function scope 13927 PushFunctionScope(); 13928 } 13929 13930 // Builtin functions cannot be defined. 13931 if (unsigned BuiltinID = FD->getBuiltinID()) { 13932 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 13933 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 13934 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 13935 FD->setInvalidDecl(); 13936 } 13937 } 13938 13939 // The return type of a function definition must be complete 13940 // (C99 6.9.1p3, C++ [dcl.fct]p6). 13941 QualType ResultType = FD->getReturnType(); 13942 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 13943 !FD->isInvalidDecl() && 13944 RequireCompleteType(FD->getLocation(), ResultType, 13945 diag::err_func_def_incomplete_result)) 13946 FD->setInvalidDecl(); 13947 13948 if (FnBodyScope) 13949 PushDeclContext(FnBodyScope, FD); 13950 13951 // Check the validity of our function parameters 13952 CheckParmsForFunctionDef(FD->parameters(), 13953 /*CheckParameterNames=*/true); 13954 13955 // Add non-parameter declarations already in the function to the current 13956 // scope. 13957 if (FnBodyScope) { 13958 for (Decl *NPD : FD->decls()) { 13959 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 13960 if (!NonParmDecl) 13961 continue; 13962 assert(!isa<ParmVarDecl>(NonParmDecl) && 13963 "parameters should not be in newly created FD yet"); 13964 13965 // If the decl has a name, make it accessible in the current scope. 13966 if (NonParmDecl->getDeclName()) 13967 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 13968 13969 // Similarly, dive into enums and fish their constants out, making them 13970 // accessible in this scope. 13971 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 13972 for (auto *EI : ED->enumerators()) 13973 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 13974 } 13975 } 13976 } 13977 13978 // Introduce our parameters into the function scope 13979 for (auto Param : FD->parameters()) { 13980 Param->setOwningFunction(FD); 13981 13982 // If this has an identifier, add it to the scope stack. 13983 if (Param->getIdentifier() && FnBodyScope) { 13984 CheckShadow(FnBodyScope, Param); 13985 13986 PushOnScopeChains(Param, FnBodyScope); 13987 } 13988 } 13989 13990 // Ensure that the function's exception specification is instantiated. 13991 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 13992 ResolveExceptionSpec(D->getLocation(), FPT); 13993 13994 // dllimport cannot be applied to non-inline function definitions. 13995 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 13996 !FD->isTemplateInstantiation()) { 13997 assert(!FD->hasAttr<DLLExportAttr>()); 13998 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 13999 FD->setInvalidDecl(); 14000 return D; 14001 } 14002 // We want to attach documentation to original Decl (which might be 14003 // a function template). 14004 ActOnDocumentableDecl(D); 14005 if (getCurLexicalContext()->isObjCContainer() && 14006 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14007 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14008 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14009 14010 return D; 14011 } 14012 14013 /// Given the set of return statements within a function body, 14014 /// compute the variables that are subject to the named return value 14015 /// optimization. 14016 /// 14017 /// Each of the variables that is subject to the named return value 14018 /// optimization will be marked as NRVO variables in the AST, and any 14019 /// return statement that has a marked NRVO variable as its NRVO candidate can 14020 /// use the named return value optimization. 14021 /// 14022 /// This function applies a very simplistic algorithm for NRVO: if every return 14023 /// statement in the scope of a variable has the same NRVO candidate, that 14024 /// candidate is an NRVO variable. 14025 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14026 ReturnStmt **Returns = Scope->Returns.data(); 14027 14028 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14029 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14030 if (!NRVOCandidate->isNRVOVariable()) 14031 Returns[I]->setNRVOCandidate(nullptr); 14032 } 14033 } 14034 } 14035 14036 bool Sema::canDelayFunctionBody(const Declarator &D) { 14037 // We can't delay parsing the body of a constexpr function template (yet). 14038 if (D.getDeclSpec().hasConstexprSpecifier()) 14039 return false; 14040 14041 // We can't delay parsing the body of a function template with a deduced 14042 // return type (yet). 14043 if (D.getDeclSpec().hasAutoTypeSpec()) { 14044 // If the placeholder introduces a non-deduced trailing return type, 14045 // we can still delay parsing it. 14046 if (D.getNumTypeObjects()) { 14047 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14048 if (Outer.Kind == DeclaratorChunk::Function && 14049 Outer.Fun.hasTrailingReturnType()) { 14050 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14051 return Ty.isNull() || !Ty->isUndeducedType(); 14052 } 14053 } 14054 return false; 14055 } 14056 14057 return true; 14058 } 14059 14060 bool Sema::canSkipFunctionBody(Decl *D) { 14061 // We cannot skip the body of a function (or function template) which is 14062 // constexpr, since we may need to evaluate its body in order to parse the 14063 // rest of the file. 14064 // We cannot skip the body of a function with an undeduced return type, 14065 // because any callers of that function need to know the type. 14066 if (const FunctionDecl *FD = D->getAsFunction()) { 14067 if (FD->isConstexpr()) 14068 return false; 14069 // We can't simply call Type::isUndeducedType here, because inside template 14070 // auto can be deduced to a dependent type, which is not considered 14071 // "undeduced". 14072 if (FD->getReturnType()->getContainedDeducedType()) 14073 return false; 14074 } 14075 return Consumer.shouldSkipFunctionBody(D); 14076 } 14077 14078 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14079 if (!Decl) 14080 return nullptr; 14081 if (FunctionDecl *FD = Decl->getAsFunction()) 14082 FD->setHasSkippedBody(); 14083 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14084 MD->setHasSkippedBody(); 14085 return Decl; 14086 } 14087 14088 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14089 return ActOnFinishFunctionBody(D, BodyArg, false); 14090 } 14091 14092 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14093 /// body. 14094 class ExitFunctionBodyRAII { 14095 public: 14096 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14097 ~ExitFunctionBodyRAII() { 14098 if (!IsLambda) 14099 S.PopExpressionEvaluationContext(); 14100 } 14101 14102 private: 14103 Sema &S; 14104 bool IsLambda = false; 14105 }; 14106 14107 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14108 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14109 14110 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14111 if (EscapeInfo.count(BD)) 14112 return EscapeInfo[BD]; 14113 14114 bool R = false; 14115 const BlockDecl *CurBD = BD; 14116 14117 do { 14118 R = !CurBD->doesNotEscape(); 14119 if (R) 14120 break; 14121 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14122 } while (CurBD); 14123 14124 return EscapeInfo[BD] = R; 14125 }; 14126 14127 // If the location where 'self' is implicitly retained is inside a escaping 14128 // block, emit a diagnostic. 14129 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14130 S.ImplicitlyRetainedSelfLocs) 14131 if (IsOrNestedInEscapingBlock(P.second)) 14132 S.Diag(P.first, diag::warn_implicitly_retains_self) 14133 << FixItHint::CreateInsertion(P.first, "self->"); 14134 } 14135 14136 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14137 bool IsInstantiation) { 14138 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14139 14140 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14141 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14142 14143 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) 14144 CheckCompletedCoroutineBody(FD, Body); 14145 14146 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14147 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14148 // meant to pop the context added in ActOnStartOfFunctionDef(). 14149 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14150 14151 if (FD) { 14152 FD->setBody(Body); 14153 FD->setWillHaveBody(false); 14154 14155 if (getLangOpts().CPlusPlus14) { 14156 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14157 FD->getReturnType()->isUndeducedType()) { 14158 // If the function has a deduced result type but contains no 'return' 14159 // statements, the result type as written must be exactly 'auto', and 14160 // the deduced result type is 'void'. 14161 if (!FD->getReturnType()->getAs<AutoType>()) { 14162 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14163 << FD->getReturnType(); 14164 FD->setInvalidDecl(); 14165 } else { 14166 // Substitute 'void' for the 'auto' in the type. 14167 TypeLoc ResultType = getReturnTypeLoc(FD); 14168 Context.adjustDeducedFunctionResultType( 14169 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14170 } 14171 } 14172 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14173 // In C++11, we don't use 'auto' deduction rules for lambda call 14174 // operators because we don't support return type deduction. 14175 auto *LSI = getCurLambda(); 14176 if (LSI->HasImplicitReturnType) { 14177 deduceClosureReturnType(*LSI); 14178 14179 // C++11 [expr.prim.lambda]p4: 14180 // [...] if there are no return statements in the compound-statement 14181 // [the deduced type is] the type void 14182 QualType RetType = 14183 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14184 14185 // Update the return type to the deduced type. 14186 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14187 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14188 Proto->getExtProtoInfo())); 14189 } 14190 } 14191 14192 // If the function implicitly returns zero (like 'main') or is naked, 14193 // don't complain about missing return statements. 14194 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14195 WP.disableCheckFallThrough(); 14196 14197 // MSVC permits the use of pure specifier (=0) on function definition, 14198 // defined at class scope, warn about this non-standard construct. 14199 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14200 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14201 14202 if (!FD->isInvalidDecl()) { 14203 // Don't diagnose unused parameters of defaulted or deleted functions. 14204 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14205 DiagnoseUnusedParameters(FD->parameters()); 14206 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14207 FD->getReturnType(), FD); 14208 14209 // If this is a structor, we need a vtable. 14210 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14211 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14212 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14213 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14214 14215 // Try to apply the named return value optimization. We have to check 14216 // if we can do this here because lambdas keep return statements around 14217 // to deduce an implicit return type. 14218 if (FD->getReturnType()->isRecordType() && 14219 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14220 computeNRVO(Body, getCurFunction()); 14221 } 14222 14223 // GNU warning -Wmissing-prototypes: 14224 // Warn if a global function is defined without a previous 14225 // prototype declaration. This warning is issued even if the 14226 // definition itself provides a prototype. The aim is to detect 14227 // global functions that fail to be declared in header files. 14228 const FunctionDecl *PossiblePrototype = nullptr; 14229 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14230 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14231 14232 if (PossiblePrototype) { 14233 // We found a declaration that is not a prototype, 14234 // but that could be a zero-parameter prototype 14235 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14236 TypeLoc TL = TI->getTypeLoc(); 14237 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14238 Diag(PossiblePrototype->getLocation(), 14239 diag::note_declaration_not_a_prototype) 14240 << (FD->getNumParams() != 0) 14241 << (FD->getNumParams() == 0 14242 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14243 : FixItHint{}); 14244 } 14245 } else { 14246 // Returns true if the token beginning at this Loc is `const`. 14247 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14248 const LangOptions &LangOpts) { 14249 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14250 if (LocInfo.first.isInvalid()) 14251 return false; 14252 14253 bool Invalid = false; 14254 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14255 if (Invalid) 14256 return false; 14257 14258 if (LocInfo.second > Buffer.size()) 14259 return false; 14260 14261 const char *LexStart = Buffer.data() + LocInfo.second; 14262 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14263 14264 return StartTok.consume_front("const") && 14265 (StartTok.empty() || isWhitespace(StartTok[0]) || 14266 StartTok.startswith("/*") || StartTok.startswith("//")); 14267 }; 14268 14269 auto findBeginLoc = [&]() { 14270 // If the return type has `const` qualifier, we want to insert 14271 // `static` before `const` (and not before the typename). 14272 if ((FD->getReturnType()->isAnyPointerType() && 14273 FD->getReturnType()->getPointeeType().isConstQualified()) || 14274 FD->getReturnType().isConstQualified()) { 14275 // But only do this if we can determine where the `const` is. 14276 14277 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14278 getLangOpts())) 14279 14280 return FD->getBeginLoc(); 14281 } 14282 return FD->getTypeSpecStartLoc(); 14283 }; 14284 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14285 << /* function */ 1 14286 << (FD->getStorageClass() == SC_None 14287 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14288 : FixItHint{}); 14289 } 14290 14291 // GNU warning -Wstrict-prototypes 14292 // Warn if K&R function is defined without a previous declaration. 14293 // This warning is issued only if the definition itself does not provide 14294 // a prototype. Only K&R definitions do not provide a prototype. 14295 if (!FD->hasWrittenPrototype()) { 14296 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14297 TypeLoc TL = TI->getTypeLoc(); 14298 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14299 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14300 } 14301 } 14302 14303 // Warn on CPUDispatch with an actual body. 14304 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14305 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14306 if (!CmpndBody->body_empty()) 14307 Diag(CmpndBody->body_front()->getBeginLoc(), 14308 diag::warn_dispatch_body_ignored); 14309 14310 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14311 const CXXMethodDecl *KeyFunction; 14312 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14313 MD->isVirtual() && 14314 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14315 MD == KeyFunction->getCanonicalDecl()) { 14316 // Update the key-function state if necessary for this ABI. 14317 if (FD->isInlined() && 14318 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14319 Context.setNonKeyFunction(MD); 14320 14321 // If the newly-chosen key function is already defined, then we 14322 // need to mark the vtable as used retroactively. 14323 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14324 const FunctionDecl *Definition; 14325 if (KeyFunction && KeyFunction->isDefined(Definition)) 14326 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14327 } else { 14328 // We just defined they key function; mark the vtable as used. 14329 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14330 } 14331 } 14332 } 14333 14334 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14335 "Function parsing confused"); 14336 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14337 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14338 MD->setBody(Body); 14339 if (!MD->isInvalidDecl()) { 14340 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14341 MD->getReturnType(), MD); 14342 14343 if (Body) 14344 computeNRVO(Body, getCurFunction()); 14345 } 14346 if (getCurFunction()->ObjCShouldCallSuper) { 14347 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14348 << MD->getSelector().getAsString(); 14349 getCurFunction()->ObjCShouldCallSuper = false; 14350 } 14351 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 14352 const ObjCMethodDecl *InitMethod = nullptr; 14353 bool isDesignated = 14354 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14355 assert(isDesignated && InitMethod); 14356 (void)isDesignated; 14357 14358 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14359 auto IFace = MD->getClassInterface(); 14360 if (!IFace) 14361 return false; 14362 auto SuperD = IFace->getSuperClass(); 14363 if (!SuperD) 14364 return false; 14365 return SuperD->getIdentifier() == 14366 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14367 }; 14368 // Don't issue this warning for unavailable inits or direct subclasses 14369 // of NSObject. 14370 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14371 Diag(MD->getLocation(), 14372 diag::warn_objc_designated_init_missing_super_call); 14373 Diag(InitMethod->getLocation(), 14374 diag::note_objc_designated_init_marked_here); 14375 } 14376 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 14377 } 14378 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 14379 // Don't issue this warning for unavaialable inits. 14380 if (!MD->isUnavailable()) 14381 Diag(MD->getLocation(), 14382 diag::warn_objc_secondary_init_missing_init_call); 14383 getCurFunction()->ObjCWarnForNoInitDelegation = false; 14384 } 14385 14386 diagnoseImplicitlyRetainedSelf(*this); 14387 } else { 14388 // Parsing the function declaration failed in some way. Pop the fake scope 14389 // we pushed on. 14390 PopFunctionScopeInfo(ActivePolicy, dcl); 14391 return nullptr; 14392 } 14393 14394 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14395 DiagnoseUnguardedAvailabilityViolations(dcl); 14396 14397 assert(!getCurFunction()->ObjCShouldCallSuper && 14398 "This should only be set for ObjC methods, which should have been " 14399 "handled in the block above."); 14400 14401 // Verify and clean out per-function state. 14402 if (Body && (!FD || !FD->isDefaulted())) { 14403 // C++ constructors that have function-try-blocks can't have return 14404 // statements in the handlers of that block. (C++ [except.handle]p14) 14405 // Verify this. 14406 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14407 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14408 14409 // Verify that gotos and switch cases don't jump into scopes illegally. 14410 if (getCurFunction()->NeedsScopeChecking() && 14411 !PP.isCodeCompletionEnabled()) 14412 DiagnoseInvalidJumps(Body); 14413 14414 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14415 if (!Destructor->getParent()->isDependentType()) 14416 CheckDestructor(Destructor); 14417 14418 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14419 Destructor->getParent()); 14420 } 14421 14422 // If any errors have occurred, clear out any temporaries that may have 14423 // been leftover. This ensures that these temporaries won't be picked up for 14424 // deletion in some later function. 14425 if (getDiagnostics().hasUncompilableErrorOccurred() || 14426 getDiagnostics().getSuppressAllDiagnostics()) { 14427 DiscardCleanupsInEvaluationContext(); 14428 } 14429 if (!getDiagnostics().hasUncompilableErrorOccurred() && 14430 !isa<FunctionTemplateDecl>(dcl)) { 14431 // Since the body is valid, issue any analysis-based warnings that are 14432 // enabled. 14433 ActivePolicy = &WP; 14434 } 14435 14436 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14437 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14438 FD->setInvalidDecl(); 14439 14440 if (FD && FD->hasAttr<NakedAttr>()) { 14441 for (const Stmt *S : Body->children()) { 14442 // Allow local register variables without initializer as they don't 14443 // require prologue. 14444 bool RegisterVariables = false; 14445 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14446 for (const auto *Decl : DS->decls()) { 14447 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14448 RegisterVariables = 14449 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14450 if (!RegisterVariables) 14451 break; 14452 } 14453 } 14454 } 14455 if (RegisterVariables) 14456 continue; 14457 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14458 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14459 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14460 FD->setInvalidDecl(); 14461 break; 14462 } 14463 } 14464 } 14465 14466 assert(ExprCleanupObjects.size() == 14467 ExprEvalContexts.back().NumCleanupObjects && 14468 "Leftover temporaries in function"); 14469 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14470 assert(MaybeODRUseExprs.empty() && 14471 "Leftover expressions for odr-use checking"); 14472 } 14473 14474 if (!IsInstantiation) 14475 PopDeclContext(); 14476 14477 PopFunctionScopeInfo(ActivePolicy, dcl); 14478 // If any errors have occurred, clear out any temporaries that may have 14479 // been leftover. This ensures that these temporaries won't be picked up for 14480 // deletion in some later function. 14481 if (getDiagnostics().hasUncompilableErrorOccurred()) { 14482 DiscardCleanupsInEvaluationContext(); 14483 } 14484 14485 if (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice) { 14486 auto ES = getEmissionStatus(FD); 14487 if (ES == Sema::FunctionEmissionStatus::Emitted || 14488 ES == Sema::FunctionEmissionStatus::Unknown) 14489 DeclsToCheckForDeferredDiags.push_back(FD); 14490 } 14491 14492 return dcl; 14493 } 14494 14495 /// When we finish delayed parsing of an attribute, we must attach it to the 14496 /// relevant Decl. 14497 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14498 ParsedAttributes &Attrs) { 14499 // Always attach attributes to the underlying decl. 14500 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14501 D = TD->getTemplatedDecl(); 14502 ProcessDeclAttributeList(S, D, Attrs); 14503 14504 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14505 if (Method->isStatic()) 14506 checkThisInStaticMemberFunctionAttributes(Method); 14507 } 14508 14509 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14510 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14511 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14512 IdentifierInfo &II, Scope *S) { 14513 // Find the scope in which the identifier is injected and the corresponding 14514 // DeclContext. 14515 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14516 // In that case, we inject the declaration into the translation unit scope 14517 // instead. 14518 Scope *BlockScope = S; 14519 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14520 BlockScope = BlockScope->getParent(); 14521 14522 Scope *ContextScope = BlockScope; 14523 while (!ContextScope->getEntity()) 14524 ContextScope = ContextScope->getParent(); 14525 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14526 14527 // Before we produce a declaration for an implicitly defined 14528 // function, see whether there was a locally-scoped declaration of 14529 // this name as a function or variable. If so, use that 14530 // (non-visible) declaration, and complain about it. 14531 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14532 if (ExternCPrev) { 14533 // We still need to inject the function into the enclosing block scope so 14534 // that later (non-call) uses can see it. 14535 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14536 14537 // C89 footnote 38: 14538 // If in fact it is not defined as having type "function returning int", 14539 // the behavior is undefined. 14540 if (!isa<FunctionDecl>(ExternCPrev) || 14541 !Context.typesAreCompatible( 14542 cast<FunctionDecl>(ExternCPrev)->getType(), 14543 Context.getFunctionNoProtoType(Context.IntTy))) { 14544 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14545 << ExternCPrev << !getLangOpts().C99; 14546 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14547 return ExternCPrev; 14548 } 14549 } 14550 14551 // Extension in C99. Legal in C90, but warn about it. 14552 unsigned diag_id; 14553 if (II.getName().startswith("__builtin_")) 14554 diag_id = diag::warn_builtin_unknown; 14555 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14556 else if (getLangOpts().OpenCL) 14557 diag_id = diag::err_opencl_implicit_function_decl; 14558 else if (getLangOpts().C99) 14559 diag_id = diag::ext_implicit_function_decl; 14560 else 14561 diag_id = diag::warn_implicit_function_decl; 14562 Diag(Loc, diag_id) << &II; 14563 14564 // If we found a prior declaration of this function, don't bother building 14565 // another one. We've already pushed that one into scope, so there's nothing 14566 // more to do. 14567 if (ExternCPrev) 14568 return ExternCPrev; 14569 14570 // Because typo correction is expensive, only do it if the implicit 14571 // function declaration is going to be treated as an error. 14572 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14573 TypoCorrection Corrected; 14574 DeclFilterCCC<FunctionDecl> CCC{}; 14575 if (S && (Corrected = 14576 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14577 S, nullptr, CCC, CTK_NonError))) 14578 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14579 /*ErrorRecovery*/false); 14580 } 14581 14582 // Set a Declarator for the implicit definition: int foo(); 14583 const char *Dummy; 14584 AttributeFactory attrFactory; 14585 DeclSpec DS(attrFactory); 14586 unsigned DiagID; 14587 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14588 Context.getPrintingPolicy()); 14589 (void)Error; // Silence warning. 14590 assert(!Error && "Error setting up implicit decl!"); 14591 SourceLocation NoLoc; 14592 Declarator D(DS, DeclaratorContext::BlockContext); 14593 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14594 /*IsAmbiguous=*/false, 14595 /*LParenLoc=*/NoLoc, 14596 /*Params=*/nullptr, 14597 /*NumParams=*/0, 14598 /*EllipsisLoc=*/NoLoc, 14599 /*RParenLoc=*/NoLoc, 14600 /*RefQualifierIsLvalueRef=*/true, 14601 /*RefQualifierLoc=*/NoLoc, 14602 /*MutableLoc=*/NoLoc, EST_None, 14603 /*ESpecRange=*/SourceRange(), 14604 /*Exceptions=*/nullptr, 14605 /*ExceptionRanges=*/nullptr, 14606 /*NumExceptions=*/0, 14607 /*NoexceptExpr=*/nullptr, 14608 /*ExceptionSpecTokens=*/nullptr, 14609 /*DeclsInPrototype=*/None, Loc, 14610 Loc, D), 14611 std::move(DS.getAttributes()), SourceLocation()); 14612 D.SetIdentifier(&II, Loc); 14613 14614 // Insert this function into the enclosing block scope. 14615 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14616 FD->setImplicit(); 14617 14618 AddKnownFunctionAttributes(FD); 14619 14620 return FD; 14621 } 14622 14623 /// If this function is a C++ replaceable global allocation function 14624 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14625 /// adds any function attributes that we know a priori based on the standard. 14626 /// 14627 /// We need to check for duplicate attributes both here and where user-written 14628 /// attributes are applied to declarations. 14629 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14630 FunctionDecl *FD) { 14631 if (FD->isInvalidDecl()) 14632 return; 14633 14634 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14635 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14636 return; 14637 14638 Optional<unsigned> AlignmentParam; 14639 bool IsNothrow = false; 14640 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14641 return; 14642 14643 // C++2a [basic.stc.dynamic.allocation]p4: 14644 // An allocation function that has a non-throwing exception specification 14645 // indicates failure by returning a null pointer value. Any other allocation 14646 // function never returns a null pointer value and indicates failure only by 14647 // throwing an exception [...] 14648 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14649 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14650 14651 // C++2a [basic.stc.dynamic.allocation]p2: 14652 // An allocation function attempts to allocate the requested amount of 14653 // storage. [...] If the request succeeds, the value returned by a 14654 // replaceable allocation function is a [...] pointer value p0 different 14655 // from any previously returned value p1 [...] 14656 // 14657 // However, this particular information is being added in codegen, 14658 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14659 14660 // C++2a [basic.stc.dynamic.allocation]p2: 14661 // An allocation function attempts to allocate the requested amount of 14662 // storage. If it is successful, it returns the address of the start of a 14663 // block of storage whose length in bytes is at least as large as the 14664 // requested size. 14665 if (!FD->hasAttr<AllocSizeAttr>()) { 14666 FD->addAttr(AllocSizeAttr::CreateImplicit( 14667 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14668 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14669 } 14670 14671 // C++2a [basic.stc.dynamic.allocation]p3: 14672 // For an allocation function [...], the pointer returned on a successful 14673 // call shall represent the address of storage that is aligned as follows: 14674 // (3.1) If the allocation function takes an argument of type 14675 // std::align_val_t, the storage will have the alignment 14676 // specified by the value of this argument. 14677 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14678 FD->addAttr(AllocAlignAttr::CreateImplicit( 14679 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14680 } 14681 14682 // FIXME: 14683 // C++2a [basic.stc.dynamic.allocation]p3: 14684 // For an allocation function [...], the pointer returned on a successful 14685 // call shall represent the address of storage that is aligned as follows: 14686 // (3.2) Otherwise, if the allocation function is named operator new[], 14687 // the storage is aligned for any object that does not have 14688 // new-extended alignment ([basic.align]) and is no larger than the 14689 // requested size. 14690 // (3.3) Otherwise, the storage is aligned for any object that does not 14691 // have new-extended alignment and is of the requested size. 14692 } 14693 14694 /// Adds any function attributes that we know a priori based on 14695 /// the declaration of this function. 14696 /// 14697 /// These attributes can apply both to implicitly-declared builtins 14698 /// (like __builtin___printf_chk) or to library-declared functions 14699 /// like NSLog or printf. 14700 /// 14701 /// We need to check for duplicate attributes both here and where user-written 14702 /// attributes are applied to declarations. 14703 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14704 if (FD->isInvalidDecl()) 14705 return; 14706 14707 // If this is a built-in function, map its builtin attributes to 14708 // actual attributes. 14709 if (unsigned BuiltinID = FD->getBuiltinID()) { 14710 // Handle printf-formatting attributes. 14711 unsigned FormatIdx; 14712 bool HasVAListArg; 14713 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14714 if (!FD->hasAttr<FormatAttr>()) { 14715 const char *fmt = "printf"; 14716 unsigned int NumParams = FD->getNumParams(); 14717 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14718 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14719 fmt = "NSString"; 14720 FD->addAttr(FormatAttr::CreateImplicit(Context, 14721 &Context.Idents.get(fmt), 14722 FormatIdx+1, 14723 HasVAListArg ? 0 : FormatIdx+2, 14724 FD->getLocation())); 14725 } 14726 } 14727 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14728 HasVAListArg)) { 14729 if (!FD->hasAttr<FormatAttr>()) 14730 FD->addAttr(FormatAttr::CreateImplicit(Context, 14731 &Context.Idents.get("scanf"), 14732 FormatIdx+1, 14733 HasVAListArg ? 0 : FormatIdx+2, 14734 FD->getLocation())); 14735 } 14736 14737 // Handle automatically recognized callbacks. 14738 SmallVector<int, 4> Encoding; 14739 if (!FD->hasAttr<CallbackAttr>() && 14740 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14741 FD->addAttr(CallbackAttr::CreateImplicit( 14742 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14743 14744 // Mark const if we don't care about errno and that is the only thing 14745 // preventing the function from being const. This allows IRgen to use LLVM 14746 // intrinsics for such functions. 14747 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14748 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14749 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14750 14751 // We make "fma" on some platforms const because we know it does not set 14752 // errno in those environments even though it could set errno based on the 14753 // C standard. 14754 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14755 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14756 !FD->hasAttr<ConstAttr>()) { 14757 switch (BuiltinID) { 14758 case Builtin::BI__builtin_fma: 14759 case Builtin::BI__builtin_fmaf: 14760 case Builtin::BI__builtin_fmal: 14761 case Builtin::BIfma: 14762 case Builtin::BIfmaf: 14763 case Builtin::BIfmal: 14764 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14765 break; 14766 default: 14767 break; 14768 } 14769 } 14770 14771 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14772 !FD->hasAttr<ReturnsTwiceAttr>()) 14773 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 14774 FD->getLocation())); 14775 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 14776 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14777 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 14778 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 14779 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 14780 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14781 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 14782 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 14783 // Add the appropriate attribute, depending on the CUDA compilation mode 14784 // and which target the builtin belongs to. For example, during host 14785 // compilation, aux builtins are __device__, while the rest are __host__. 14786 if (getLangOpts().CUDAIsDevice != 14787 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 14788 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 14789 else 14790 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 14791 } 14792 } 14793 14794 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 14795 14796 // If C++ exceptions are enabled but we are told extern "C" functions cannot 14797 // throw, add an implicit nothrow attribute to any extern "C" function we come 14798 // across. 14799 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 14800 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 14801 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 14802 if (!FPT || FPT->getExceptionSpecType() == EST_None) 14803 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14804 } 14805 14806 IdentifierInfo *Name = FD->getIdentifier(); 14807 if (!Name) 14808 return; 14809 if ((!getLangOpts().CPlusPlus && 14810 FD->getDeclContext()->isTranslationUnit()) || 14811 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 14812 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 14813 LinkageSpecDecl::lang_c)) { 14814 // Okay: this could be a libc/libm/Objective-C function we know 14815 // about. 14816 } else 14817 return; 14818 14819 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 14820 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 14821 // target-specific builtins, perhaps? 14822 if (!FD->hasAttr<FormatAttr>()) 14823 FD->addAttr(FormatAttr::CreateImplicit(Context, 14824 &Context.Idents.get("printf"), 2, 14825 Name->isStr("vasprintf") ? 0 : 3, 14826 FD->getLocation())); 14827 } 14828 14829 if (Name->isStr("__CFStringMakeConstantString")) { 14830 // We already have a __builtin___CFStringMakeConstantString, 14831 // but builds that use -fno-constant-cfstrings don't go through that. 14832 if (!FD->hasAttr<FormatArgAttr>()) 14833 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 14834 FD->getLocation())); 14835 } 14836 } 14837 14838 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 14839 TypeSourceInfo *TInfo) { 14840 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 14841 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 14842 14843 if (!TInfo) { 14844 assert(D.isInvalidType() && "no declarator info for valid type"); 14845 TInfo = Context.getTrivialTypeSourceInfo(T); 14846 } 14847 14848 // Scope manipulation handled by caller. 14849 TypedefDecl *NewTD = 14850 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 14851 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 14852 14853 // Bail out immediately if we have an invalid declaration. 14854 if (D.isInvalidType()) { 14855 NewTD->setInvalidDecl(); 14856 return NewTD; 14857 } 14858 14859 if (D.getDeclSpec().isModulePrivateSpecified()) { 14860 if (CurContext->isFunctionOrMethod()) 14861 Diag(NewTD->getLocation(), diag::err_module_private_local) 14862 << 2 << NewTD->getDeclName() 14863 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 14864 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 14865 else 14866 NewTD->setModulePrivate(); 14867 } 14868 14869 // C++ [dcl.typedef]p8: 14870 // If the typedef declaration defines an unnamed class (or 14871 // enum), the first typedef-name declared by the declaration 14872 // to be that class type (or enum type) is used to denote the 14873 // class type (or enum type) for linkage purposes only. 14874 // We need to check whether the type was declared in the declaration. 14875 switch (D.getDeclSpec().getTypeSpecType()) { 14876 case TST_enum: 14877 case TST_struct: 14878 case TST_interface: 14879 case TST_union: 14880 case TST_class: { 14881 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 14882 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 14883 break; 14884 } 14885 14886 default: 14887 break; 14888 } 14889 14890 return NewTD; 14891 } 14892 14893 /// Check that this is a valid underlying type for an enum declaration. 14894 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 14895 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 14896 QualType T = TI->getType(); 14897 14898 if (T->isDependentType()) 14899 return false; 14900 14901 // This doesn't use 'isIntegralType' despite the error message mentioning 14902 // integral type because isIntegralType would also allow enum types in C. 14903 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 14904 if (BT->isInteger()) 14905 return false; 14906 14907 if (T->isExtIntType()) 14908 return false; 14909 14910 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 14911 } 14912 14913 /// Check whether this is a valid redeclaration of a previous enumeration. 14914 /// \return true if the redeclaration was invalid. 14915 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 14916 QualType EnumUnderlyingTy, bool IsFixed, 14917 const EnumDecl *Prev) { 14918 if (IsScoped != Prev->isScoped()) { 14919 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 14920 << Prev->isScoped(); 14921 Diag(Prev->getLocation(), diag::note_previous_declaration); 14922 return true; 14923 } 14924 14925 if (IsFixed && Prev->isFixed()) { 14926 if (!EnumUnderlyingTy->isDependentType() && 14927 !Prev->getIntegerType()->isDependentType() && 14928 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 14929 Prev->getIntegerType())) { 14930 // TODO: Highlight the underlying type of the redeclaration. 14931 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 14932 << EnumUnderlyingTy << Prev->getIntegerType(); 14933 Diag(Prev->getLocation(), diag::note_previous_declaration) 14934 << Prev->getIntegerTypeRange(); 14935 return true; 14936 } 14937 } else if (IsFixed != Prev->isFixed()) { 14938 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 14939 << Prev->isFixed(); 14940 Diag(Prev->getLocation(), diag::note_previous_declaration); 14941 return true; 14942 } 14943 14944 return false; 14945 } 14946 14947 /// Get diagnostic %select index for tag kind for 14948 /// redeclaration diagnostic message. 14949 /// WARNING: Indexes apply to particular diagnostics only! 14950 /// 14951 /// \returns diagnostic %select index. 14952 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 14953 switch (Tag) { 14954 case TTK_Struct: return 0; 14955 case TTK_Interface: return 1; 14956 case TTK_Class: return 2; 14957 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 14958 } 14959 } 14960 14961 /// Determine if tag kind is a class-key compatible with 14962 /// class for redeclaration (class, struct, or __interface). 14963 /// 14964 /// \returns true iff the tag kind is compatible. 14965 static bool isClassCompatTagKind(TagTypeKind Tag) 14966 { 14967 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 14968 } 14969 14970 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 14971 TagTypeKind TTK) { 14972 if (isa<TypedefDecl>(PrevDecl)) 14973 return NTK_Typedef; 14974 else if (isa<TypeAliasDecl>(PrevDecl)) 14975 return NTK_TypeAlias; 14976 else if (isa<ClassTemplateDecl>(PrevDecl)) 14977 return NTK_Template; 14978 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 14979 return NTK_TypeAliasTemplate; 14980 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 14981 return NTK_TemplateTemplateArgument; 14982 switch (TTK) { 14983 case TTK_Struct: 14984 case TTK_Interface: 14985 case TTK_Class: 14986 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 14987 case TTK_Union: 14988 return NTK_NonUnion; 14989 case TTK_Enum: 14990 return NTK_NonEnum; 14991 } 14992 llvm_unreachable("invalid TTK"); 14993 } 14994 14995 /// Determine whether a tag with a given kind is acceptable 14996 /// as a redeclaration of the given tag declaration. 14997 /// 14998 /// \returns true if the new tag kind is acceptable, false otherwise. 14999 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15000 TagTypeKind NewTag, bool isDefinition, 15001 SourceLocation NewTagLoc, 15002 const IdentifierInfo *Name) { 15003 // C++ [dcl.type.elab]p3: 15004 // The class-key or enum keyword present in the 15005 // elaborated-type-specifier shall agree in kind with the 15006 // declaration to which the name in the elaborated-type-specifier 15007 // refers. This rule also applies to the form of 15008 // elaborated-type-specifier that declares a class-name or 15009 // friend class since it can be construed as referring to the 15010 // definition of the class. Thus, in any 15011 // elaborated-type-specifier, the enum keyword shall be used to 15012 // refer to an enumeration (7.2), the union class-key shall be 15013 // used to refer to a union (clause 9), and either the class or 15014 // struct class-key shall be used to refer to a class (clause 9) 15015 // declared using the class or struct class-key. 15016 TagTypeKind OldTag = Previous->getTagKind(); 15017 if (OldTag != NewTag && 15018 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15019 return false; 15020 15021 // Tags are compatible, but we might still want to warn on mismatched tags. 15022 // Non-class tags can't be mismatched at this point. 15023 if (!isClassCompatTagKind(NewTag)) 15024 return true; 15025 15026 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15027 // by our warning analysis. We don't want to warn about mismatches with (eg) 15028 // declarations in system headers that are designed to be specialized, but if 15029 // a user asks us to warn, we should warn if their code contains mismatched 15030 // declarations. 15031 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15032 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15033 Loc); 15034 }; 15035 if (IsIgnoredLoc(NewTagLoc)) 15036 return true; 15037 15038 auto IsIgnored = [&](const TagDecl *Tag) { 15039 return IsIgnoredLoc(Tag->getLocation()); 15040 }; 15041 while (IsIgnored(Previous)) { 15042 Previous = Previous->getPreviousDecl(); 15043 if (!Previous) 15044 return true; 15045 OldTag = Previous->getTagKind(); 15046 } 15047 15048 bool isTemplate = false; 15049 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15050 isTemplate = Record->getDescribedClassTemplate(); 15051 15052 if (inTemplateInstantiation()) { 15053 if (OldTag != NewTag) { 15054 // In a template instantiation, do not offer fix-its for tag mismatches 15055 // since they usually mess up the template instead of fixing the problem. 15056 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15057 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15058 << getRedeclDiagFromTagKind(OldTag); 15059 // FIXME: Note previous location? 15060 } 15061 return true; 15062 } 15063 15064 if (isDefinition) { 15065 // On definitions, check all previous tags and issue a fix-it for each 15066 // one that doesn't match the current tag. 15067 if (Previous->getDefinition()) { 15068 // Don't suggest fix-its for redefinitions. 15069 return true; 15070 } 15071 15072 bool previousMismatch = false; 15073 for (const TagDecl *I : Previous->redecls()) { 15074 if (I->getTagKind() != NewTag) { 15075 // Ignore previous declarations for which the warning was disabled. 15076 if (IsIgnored(I)) 15077 continue; 15078 15079 if (!previousMismatch) { 15080 previousMismatch = true; 15081 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15082 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15083 << getRedeclDiagFromTagKind(I->getTagKind()); 15084 } 15085 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15086 << getRedeclDiagFromTagKind(NewTag) 15087 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15088 TypeWithKeyword::getTagTypeKindName(NewTag)); 15089 } 15090 } 15091 return true; 15092 } 15093 15094 // Identify the prevailing tag kind: this is the kind of the definition (if 15095 // there is a non-ignored definition), or otherwise the kind of the prior 15096 // (non-ignored) declaration. 15097 const TagDecl *PrevDef = Previous->getDefinition(); 15098 if (PrevDef && IsIgnored(PrevDef)) 15099 PrevDef = nullptr; 15100 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15101 if (Redecl->getTagKind() != NewTag) { 15102 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15103 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15104 << getRedeclDiagFromTagKind(OldTag); 15105 Diag(Redecl->getLocation(), diag::note_previous_use); 15106 15107 // If there is a previous definition, suggest a fix-it. 15108 if (PrevDef) { 15109 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15110 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15111 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15112 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15113 } 15114 } 15115 15116 return true; 15117 } 15118 15119 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15120 /// from an outer enclosing namespace or file scope inside a friend declaration. 15121 /// This should provide the commented out code in the following snippet: 15122 /// namespace N { 15123 /// struct X; 15124 /// namespace M { 15125 /// struct Y { friend struct /*N::*/ X; }; 15126 /// } 15127 /// } 15128 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15129 SourceLocation NameLoc) { 15130 // While the decl is in a namespace, do repeated lookup of that name and see 15131 // if we get the same namespace back. If we do not, continue until 15132 // translation unit scope, at which point we have a fully qualified NNS. 15133 SmallVector<IdentifierInfo *, 4> Namespaces; 15134 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15135 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15136 // This tag should be declared in a namespace, which can only be enclosed by 15137 // other namespaces. Bail if there's an anonymous namespace in the chain. 15138 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15139 if (!Namespace || Namespace->isAnonymousNamespace()) 15140 return FixItHint(); 15141 IdentifierInfo *II = Namespace->getIdentifier(); 15142 Namespaces.push_back(II); 15143 NamedDecl *Lookup = SemaRef.LookupSingleName( 15144 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15145 if (Lookup == Namespace) 15146 break; 15147 } 15148 15149 // Once we have all the namespaces, reverse them to go outermost first, and 15150 // build an NNS. 15151 SmallString<64> Insertion; 15152 llvm::raw_svector_ostream OS(Insertion); 15153 if (DC->isTranslationUnit()) 15154 OS << "::"; 15155 std::reverse(Namespaces.begin(), Namespaces.end()); 15156 for (auto *II : Namespaces) 15157 OS << II->getName() << "::"; 15158 return FixItHint::CreateInsertion(NameLoc, Insertion); 15159 } 15160 15161 /// Determine whether a tag originally declared in context \p OldDC can 15162 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15163 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15164 /// using-declaration). 15165 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15166 DeclContext *NewDC) { 15167 OldDC = OldDC->getRedeclContext(); 15168 NewDC = NewDC->getRedeclContext(); 15169 15170 if (OldDC->Equals(NewDC)) 15171 return true; 15172 15173 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15174 // encloses the other). 15175 if (S.getLangOpts().MSVCCompat && 15176 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15177 return true; 15178 15179 return false; 15180 } 15181 15182 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15183 /// former case, Name will be non-null. In the later case, Name will be null. 15184 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15185 /// reference/declaration/definition of a tag. 15186 /// 15187 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15188 /// trailing-type-specifier) other than one in an alias-declaration. 15189 /// 15190 /// \param SkipBody If non-null, will be set to indicate if the caller should 15191 /// skip the definition of this tag and treat it as if it were a declaration. 15192 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15193 SourceLocation KWLoc, CXXScopeSpec &SS, 15194 IdentifierInfo *Name, SourceLocation NameLoc, 15195 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15196 SourceLocation ModulePrivateLoc, 15197 MultiTemplateParamsArg TemplateParameterLists, 15198 bool &OwnedDecl, bool &IsDependent, 15199 SourceLocation ScopedEnumKWLoc, 15200 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15201 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15202 SkipBodyInfo *SkipBody) { 15203 // If this is not a definition, it must have a name. 15204 IdentifierInfo *OrigName = Name; 15205 assert((Name != nullptr || TUK == TUK_Definition) && 15206 "Nameless record must be a definition!"); 15207 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15208 15209 OwnedDecl = false; 15210 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15211 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15212 15213 // FIXME: Check member specializations more carefully. 15214 bool isMemberSpecialization = false; 15215 bool Invalid = false; 15216 15217 // We only need to do this matching if we have template parameters 15218 // or a scope specifier, which also conveniently avoids this work 15219 // for non-C++ cases. 15220 if (TemplateParameterLists.size() > 0 || 15221 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15222 if (TemplateParameterList *TemplateParams = 15223 MatchTemplateParametersToScopeSpecifier( 15224 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15225 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15226 if (Kind == TTK_Enum) { 15227 Diag(KWLoc, diag::err_enum_template); 15228 return nullptr; 15229 } 15230 15231 if (TemplateParams->size() > 0) { 15232 // This is a declaration or definition of a class template (which may 15233 // be a member of another template). 15234 15235 if (Invalid) 15236 return nullptr; 15237 15238 OwnedDecl = false; 15239 DeclResult Result = CheckClassTemplate( 15240 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15241 AS, ModulePrivateLoc, 15242 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15243 TemplateParameterLists.data(), SkipBody); 15244 return Result.get(); 15245 } else { 15246 // The "template<>" header is extraneous. 15247 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15248 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15249 isMemberSpecialization = true; 15250 } 15251 } 15252 } 15253 15254 // Figure out the underlying type if this a enum declaration. We need to do 15255 // this early, because it's needed to detect if this is an incompatible 15256 // redeclaration. 15257 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15258 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15259 15260 if (Kind == TTK_Enum) { 15261 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15262 // No underlying type explicitly specified, or we failed to parse the 15263 // type, default to int. 15264 EnumUnderlying = Context.IntTy.getTypePtr(); 15265 } else if (UnderlyingType.get()) { 15266 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15267 // integral type; any cv-qualification is ignored. 15268 TypeSourceInfo *TI = nullptr; 15269 GetTypeFromParser(UnderlyingType.get(), &TI); 15270 EnumUnderlying = TI; 15271 15272 if (CheckEnumUnderlyingType(TI)) 15273 // Recover by falling back to int. 15274 EnumUnderlying = Context.IntTy.getTypePtr(); 15275 15276 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15277 UPPC_FixedUnderlyingType)) 15278 EnumUnderlying = Context.IntTy.getTypePtr(); 15279 15280 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15281 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15282 // of 'int'. However, if this is an unfixed forward declaration, don't set 15283 // the underlying type unless the user enables -fms-compatibility. This 15284 // makes unfixed forward declared enums incomplete and is more conforming. 15285 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15286 EnumUnderlying = Context.IntTy.getTypePtr(); 15287 } 15288 } 15289 15290 DeclContext *SearchDC = CurContext; 15291 DeclContext *DC = CurContext; 15292 bool isStdBadAlloc = false; 15293 bool isStdAlignValT = false; 15294 15295 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15296 if (TUK == TUK_Friend || TUK == TUK_Reference) 15297 Redecl = NotForRedeclaration; 15298 15299 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15300 /// implemented asks for structural equivalence checking, the returned decl 15301 /// here is passed back to the parser, allowing the tag body to be parsed. 15302 auto createTagFromNewDecl = [&]() -> TagDecl * { 15303 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15304 // If there is an identifier, use the location of the identifier as the 15305 // location of the decl, otherwise use the location of the struct/union 15306 // keyword. 15307 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15308 TagDecl *New = nullptr; 15309 15310 if (Kind == TTK_Enum) { 15311 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15312 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15313 // If this is an undefined enum, bail. 15314 if (TUK != TUK_Definition && !Invalid) 15315 return nullptr; 15316 if (EnumUnderlying) { 15317 EnumDecl *ED = cast<EnumDecl>(New); 15318 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15319 ED->setIntegerTypeSourceInfo(TI); 15320 else 15321 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15322 ED->setPromotionType(ED->getIntegerType()); 15323 } 15324 } else { // struct/union 15325 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15326 nullptr); 15327 } 15328 15329 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15330 // Add alignment attributes if necessary; these attributes are checked 15331 // when the ASTContext lays out the structure. 15332 // 15333 // It is important for implementing the correct semantics that this 15334 // happen here (in ActOnTag). The #pragma pack stack is 15335 // maintained as a result of parser callbacks which can occur at 15336 // many points during the parsing of a struct declaration (because 15337 // the #pragma tokens are effectively skipped over during the 15338 // parsing of the struct). 15339 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15340 AddAlignmentAttributesForRecord(RD); 15341 AddMsStructLayoutForRecord(RD); 15342 } 15343 } 15344 New->setLexicalDeclContext(CurContext); 15345 return New; 15346 }; 15347 15348 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15349 if (Name && SS.isNotEmpty()) { 15350 // We have a nested-name tag ('struct foo::bar'). 15351 15352 // Check for invalid 'foo::'. 15353 if (SS.isInvalid()) { 15354 Name = nullptr; 15355 goto CreateNewDecl; 15356 } 15357 15358 // If this is a friend or a reference to a class in a dependent 15359 // context, don't try to make a decl for it. 15360 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15361 DC = computeDeclContext(SS, false); 15362 if (!DC) { 15363 IsDependent = true; 15364 return nullptr; 15365 } 15366 } else { 15367 DC = computeDeclContext(SS, true); 15368 if (!DC) { 15369 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15370 << SS.getRange(); 15371 return nullptr; 15372 } 15373 } 15374 15375 if (RequireCompleteDeclContext(SS, DC)) 15376 return nullptr; 15377 15378 SearchDC = DC; 15379 // Look-up name inside 'foo::'. 15380 LookupQualifiedName(Previous, DC); 15381 15382 if (Previous.isAmbiguous()) 15383 return nullptr; 15384 15385 if (Previous.empty()) { 15386 // Name lookup did not find anything. However, if the 15387 // nested-name-specifier refers to the current instantiation, 15388 // and that current instantiation has any dependent base 15389 // classes, we might find something at instantiation time: treat 15390 // this as a dependent elaborated-type-specifier. 15391 // But this only makes any sense for reference-like lookups. 15392 if (Previous.wasNotFoundInCurrentInstantiation() && 15393 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15394 IsDependent = true; 15395 return nullptr; 15396 } 15397 15398 // A tag 'foo::bar' must already exist. 15399 Diag(NameLoc, diag::err_not_tag_in_scope) 15400 << Kind << Name << DC << SS.getRange(); 15401 Name = nullptr; 15402 Invalid = true; 15403 goto CreateNewDecl; 15404 } 15405 } else if (Name) { 15406 // C++14 [class.mem]p14: 15407 // If T is the name of a class, then each of the following shall have a 15408 // name different from T: 15409 // -- every member of class T that is itself a type 15410 if (TUK != TUK_Reference && TUK != TUK_Friend && 15411 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15412 return nullptr; 15413 15414 // If this is a named struct, check to see if there was a previous forward 15415 // declaration or definition. 15416 // FIXME: We're looking into outer scopes here, even when we 15417 // shouldn't be. Doing so can result in ambiguities that we 15418 // shouldn't be diagnosing. 15419 LookupName(Previous, S); 15420 15421 // When declaring or defining a tag, ignore ambiguities introduced 15422 // by types using'ed into this scope. 15423 if (Previous.isAmbiguous() && 15424 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15425 LookupResult::Filter F = Previous.makeFilter(); 15426 while (F.hasNext()) { 15427 NamedDecl *ND = F.next(); 15428 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15429 SearchDC->getRedeclContext())) 15430 F.erase(); 15431 } 15432 F.done(); 15433 } 15434 15435 // C++11 [namespace.memdef]p3: 15436 // If the name in a friend declaration is neither qualified nor 15437 // a template-id and the declaration is a function or an 15438 // elaborated-type-specifier, the lookup to determine whether 15439 // the entity has been previously declared shall not consider 15440 // any scopes outside the innermost enclosing namespace. 15441 // 15442 // MSVC doesn't implement the above rule for types, so a friend tag 15443 // declaration may be a redeclaration of a type declared in an enclosing 15444 // scope. They do implement this rule for friend functions. 15445 // 15446 // Does it matter that this should be by scope instead of by 15447 // semantic context? 15448 if (!Previous.empty() && TUK == TUK_Friend) { 15449 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15450 LookupResult::Filter F = Previous.makeFilter(); 15451 bool FriendSawTagOutsideEnclosingNamespace = false; 15452 while (F.hasNext()) { 15453 NamedDecl *ND = F.next(); 15454 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15455 if (DC->isFileContext() && 15456 !EnclosingNS->Encloses(ND->getDeclContext())) { 15457 if (getLangOpts().MSVCCompat) 15458 FriendSawTagOutsideEnclosingNamespace = true; 15459 else 15460 F.erase(); 15461 } 15462 } 15463 F.done(); 15464 15465 // Diagnose this MSVC extension in the easy case where lookup would have 15466 // unambiguously found something outside the enclosing namespace. 15467 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15468 NamedDecl *ND = Previous.getFoundDecl(); 15469 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15470 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15471 } 15472 } 15473 15474 // Note: there used to be some attempt at recovery here. 15475 if (Previous.isAmbiguous()) 15476 return nullptr; 15477 15478 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15479 // FIXME: This makes sure that we ignore the contexts associated 15480 // with C structs, unions, and enums when looking for a matching 15481 // tag declaration or definition. See the similar lookup tweak 15482 // in Sema::LookupName; is there a better way to deal with this? 15483 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15484 SearchDC = SearchDC->getParent(); 15485 } 15486 } 15487 15488 if (Previous.isSingleResult() && 15489 Previous.getFoundDecl()->isTemplateParameter()) { 15490 // Maybe we will complain about the shadowed template parameter. 15491 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15492 // Just pretend that we didn't see the previous declaration. 15493 Previous.clear(); 15494 } 15495 15496 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15497 DC->Equals(getStdNamespace())) { 15498 if (Name->isStr("bad_alloc")) { 15499 // This is a declaration of or a reference to "std::bad_alloc". 15500 isStdBadAlloc = true; 15501 15502 // If std::bad_alloc has been implicitly declared (but made invisible to 15503 // name lookup), fill in this implicit declaration as the previous 15504 // declaration, so that the declarations get chained appropriately. 15505 if (Previous.empty() && StdBadAlloc) 15506 Previous.addDecl(getStdBadAlloc()); 15507 } else if (Name->isStr("align_val_t")) { 15508 isStdAlignValT = true; 15509 if (Previous.empty() && StdAlignValT) 15510 Previous.addDecl(getStdAlignValT()); 15511 } 15512 } 15513 15514 // If we didn't find a previous declaration, and this is a reference 15515 // (or friend reference), move to the correct scope. In C++, we 15516 // also need to do a redeclaration lookup there, just in case 15517 // there's a shadow friend decl. 15518 if (Name && Previous.empty() && 15519 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15520 if (Invalid) goto CreateNewDecl; 15521 assert(SS.isEmpty()); 15522 15523 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15524 // C++ [basic.scope.pdecl]p5: 15525 // -- for an elaborated-type-specifier of the form 15526 // 15527 // class-key identifier 15528 // 15529 // if the elaborated-type-specifier is used in the 15530 // decl-specifier-seq or parameter-declaration-clause of a 15531 // function defined in namespace scope, the identifier is 15532 // declared as a class-name in the namespace that contains 15533 // the declaration; otherwise, except as a friend 15534 // declaration, the identifier is declared in the smallest 15535 // non-class, non-function-prototype scope that contains the 15536 // declaration. 15537 // 15538 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15539 // C structs and unions. 15540 // 15541 // It is an error in C++ to declare (rather than define) an enum 15542 // type, including via an elaborated type specifier. We'll 15543 // diagnose that later; for now, declare the enum in the same 15544 // scope as we would have picked for any other tag type. 15545 // 15546 // GNU C also supports this behavior as part of its incomplete 15547 // enum types extension, while GNU C++ does not. 15548 // 15549 // Find the context where we'll be declaring the tag. 15550 // FIXME: We would like to maintain the current DeclContext as the 15551 // lexical context, 15552 SearchDC = getTagInjectionContext(SearchDC); 15553 15554 // Find the scope where we'll be declaring the tag. 15555 S = getTagInjectionScope(S, getLangOpts()); 15556 } else { 15557 assert(TUK == TUK_Friend); 15558 // C++ [namespace.memdef]p3: 15559 // If a friend declaration in a non-local class first declares a 15560 // class or function, the friend class or function is a member of 15561 // the innermost enclosing namespace. 15562 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15563 } 15564 15565 // In C++, we need to do a redeclaration lookup to properly 15566 // diagnose some problems. 15567 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15568 // hidden declaration so that we don't get ambiguity errors when using a 15569 // type declared by an elaborated-type-specifier. In C that is not correct 15570 // and we should instead merge compatible types found by lookup. 15571 if (getLangOpts().CPlusPlus) { 15572 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15573 LookupQualifiedName(Previous, SearchDC); 15574 } else { 15575 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15576 LookupName(Previous, S); 15577 } 15578 } 15579 15580 // If we have a known previous declaration to use, then use it. 15581 if (Previous.empty() && SkipBody && SkipBody->Previous) 15582 Previous.addDecl(SkipBody->Previous); 15583 15584 if (!Previous.empty()) { 15585 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15586 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15587 15588 // It's okay to have a tag decl in the same scope as a typedef 15589 // which hides a tag decl in the same scope. Finding this 15590 // insanity with a redeclaration lookup can only actually happen 15591 // in C++. 15592 // 15593 // This is also okay for elaborated-type-specifiers, which is 15594 // technically forbidden by the current standard but which is 15595 // okay according to the likely resolution of an open issue; 15596 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15597 if (getLangOpts().CPlusPlus) { 15598 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15599 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15600 TagDecl *Tag = TT->getDecl(); 15601 if (Tag->getDeclName() == Name && 15602 Tag->getDeclContext()->getRedeclContext() 15603 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15604 PrevDecl = Tag; 15605 Previous.clear(); 15606 Previous.addDecl(Tag); 15607 Previous.resolveKind(); 15608 } 15609 } 15610 } 15611 } 15612 15613 // If this is a redeclaration of a using shadow declaration, it must 15614 // declare a tag in the same context. In MSVC mode, we allow a 15615 // redefinition if either context is within the other. 15616 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15617 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15618 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15619 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15620 !(OldTag && isAcceptableTagRedeclContext( 15621 *this, OldTag->getDeclContext(), SearchDC))) { 15622 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15623 Diag(Shadow->getTargetDecl()->getLocation(), 15624 diag::note_using_decl_target); 15625 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15626 << 0; 15627 // Recover by ignoring the old declaration. 15628 Previous.clear(); 15629 goto CreateNewDecl; 15630 } 15631 } 15632 15633 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15634 // If this is a use of a previous tag, or if the tag is already declared 15635 // in the same scope (so that the definition/declaration completes or 15636 // rementions the tag), reuse the decl. 15637 if (TUK == TUK_Reference || TUK == TUK_Friend || 15638 isDeclInScope(DirectPrevDecl, SearchDC, S, 15639 SS.isNotEmpty() || isMemberSpecialization)) { 15640 // Make sure that this wasn't declared as an enum and now used as a 15641 // struct or something similar. 15642 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15643 TUK == TUK_Definition, KWLoc, 15644 Name)) { 15645 bool SafeToContinue 15646 = (PrevTagDecl->getTagKind() != TTK_Enum && 15647 Kind != TTK_Enum); 15648 if (SafeToContinue) 15649 Diag(KWLoc, diag::err_use_with_wrong_tag) 15650 << Name 15651 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15652 PrevTagDecl->getKindName()); 15653 else 15654 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15655 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15656 15657 if (SafeToContinue) 15658 Kind = PrevTagDecl->getTagKind(); 15659 else { 15660 // Recover by making this an anonymous redefinition. 15661 Name = nullptr; 15662 Previous.clear(); 15663 Invalid = true; 15664 } 15665 } 15666 15667 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15668 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15669 if (TUK == TUK_Reference || TUK == TUK_Friend) 15670 return PrevTagDecl; 15671 15672 QualType EnumUnderlyingTy; 15673 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15674 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15675 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15676 EnumUnderlyingTy = QualType(T, 0); 15677 15678 // All conflicts with previous declarations are recovered by 15679 // returning the previous declaration, unless this is a definition, 15680 // in which case we want the caller to bail out. 15681 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15682 ScopedEnum, EnumUnderlyingTy, 15683 IsFixed, PrevEnum)) 15684 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15685 } 15686 15687 // C++11 [class.mem]p1: 15688 // A member shall not be declared twice in the member-specification, 15689 // except that a nested class or member class template can be declared 15690 // and then later defined. 15691 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15692 S->isDeclScope(PrevDecl)) { 15693 Diag(NameLoc, diag::ext_member_redeclared); 15694 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15695 } 15696 15697 if (!Invalid) { 15698 // If this is a use, just return the declaration we found, unless 15699 // we have attributes. 15700 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15701 if (!Attrs.empty()) { 15702 // FIXME: Diagnose these attributes. For now, we create a new 15703 // declaration to hold them. 15704 } else if (TUK == TUK_Reference && 15705 (PrevTagDecl->getFriendObjectKind() == 15706 Decl::FOK_Undeclared || 15707 PrevDecl->getOwningModule() != getCurrentModule()) && 15708 SS.isEmpty()) { 15709 // This declaration is a reference to an existing entity, but 15710 // has different visibility from that entity: it either makes 15711 // a friend visible or it makes a type visible in a new module. 15712 // In either case, create a new declaration. We only do this if 15713 // the declaration would have meant the same thing if no prior 15714 // declaration were found, that is, if it was found in the same 15715 // scope where we would have injected a declaration. 15716 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15717 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15718 return PrevTagDecl; 15719 // This is in the injected scope, create a new declaration in 15720 // that scope. 15721 S = getTagInjectionScope(S, getLangOpts()); 15722 } else { 15723 return PrevTagDecl; 15724 } 15725 } 15726 15727 // Diagnose attempts to redefine a tag. 15728 if (TUK == TUK_Definition) { 15729 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15730 // If we're defining a specialization and the previous definition 15731 // is from an implicit instantiation, don't emit an error 15732 // here; we'll catch this in the general case below. 15733 bool IsExplicitSpecializationAfterInstantiation = false; 15734 if (isMemberSpecialization) { 15735 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15736 IsExplicitSpecializationAfterInstantiation = 15737 RD->getTemplateSpecializationKind() != 15738 TSK_ExplicitSpecialization; 15739 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15740 IsExplicitSpecializationAfterInstantiation = 15741 ED->getTemplateSpecializationKind() != 15742 TSK_ExplicitSpecialization; 15743 } 15744 15745 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15746 // not keep more that one definition around (merge them). However, 15747 // ensure the decl passes the structural compatibility check in 15748 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15749 NamedDecl *Hidden = nullptr; 15750 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15751 // There is a definition of this tag, but it is not visible. We 15752 // explicitly make use of C++'s one definition rule here, and 15753 // assume that this definition is identical to the hidden one 15754 // we already have. Make the existing definition visible and 15755 // use it in place of this one. 15756 if (!getLangOpts().CPlusPlus) { 15757 // Postpone making the old definition visible until after we 15758 // complete parsing the new one and do the structural 15759 // comparison. 15760 SkipBody->CheckSameAsPrevious = true; 15761 SkipBody->New = createTagFromNewDecl(); 15762 SkipBody->Previous = Def; 15763 return Def; 15764 } else { 15765 SkipBody->ShouldSkip = true; 15766 SkipBody->Previous = Def; 15767 makeMergedDefinitionVisible(Hidden); 15768 // Carry on and handle it like a normal definition. We'll 15769 // skip starting the definitiion later. 15770 } 15771 } else if (!IsExplicitSpecializationAfterInstantiation) { 15772 // A redeclaration in function prototype scope in C isn't 15773 // visible elsewhere, so merely issue a warning. 15774 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 15775 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 15776 else 15777 Diag(NameLoc, diag::err_redefinition) << Name; 15778 notePreviousDefinition(Def, 15779 NameLoc.isValid() ? NameLoc : KWLoc); 15780 // If this is a redefinition, recover by making this 15781 // struct be anonymous, which will make any later 15782 // references get the previous definition. 15783 Name = nullptr; 15784 Previous.clear(); 15785 Invalid = true; 15786 } 15787 } else { 15788 // If the type is currently being defined, complain 15789 // about a nested redefinition. 15790 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 15791 if (TD->isBeingDefined()) { 15792 Diag(NameLoc, diag::err_nested_redefinition) << Name; 15793 Diag(PrevTagDecl->getLocation(), 15794 diag::note_previous_definition); 15795 Name = nullptr; 15796 Previous.clear(); 15797 Invalid = true; 15798 } 15799 } 15800 15801 // Okay, this is definition of a previously declared or referenced 15802 // tag. We're going to create a new Decl for it. 15803 } 15804 15805 // Okay, we're going to make a redeclaration. If this is some kind 15806 // of reference, make sure we build the redeclaration in the same DC 15807 // as the original, and ignore the current access specifier. 15808 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15809 SearchDC = PrevTagDecl->getDeclContext(); 15810 AS = AS_none; 15811 } 15812 } 15813 // If we get here we have (another) forward declaration or we 15814 // have a definition. Just create a new decl. 15815 15816 } else { 15817 // If we get here, this is a definition of a new tag type in a nested 15818 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 15819 // new decl/type. We set PrevDecl to NULL so that the entities 15820 // have distinct types. 15821 Previous.clear(); 15822 } 15823 // If we get here, we're going to create a new Decl. If PrevDecl 15824 // is non-NULL, it's a definition of the tag declared by 15825 // PrevDecl. If it's NULL, we have a new definition. 15826 15827 // Otherwise, PrevDecl is not a tag, but was found with tag 15828 // lookup. This is only actually possible in C++, where a few 15829 // things like templates still live in the tag namespace. 15830 } else { 15831 // Use a better diagnostic if an elaborated-type-specifier 15832 // found the wrong kind of type on the first 15833 // (non-redeclaration) lookup. 15834 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 15835 !Previous.isForRedeclaration()) { 15836 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15837 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 15838 << Kind; 15839 Diag(PrevDecl->getLocation(), diag::note_declared_at); 15840 Invalid = true; 15841 15842 // Otherwise, only diagnose if the declaration is in scope. 15843 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 15844 SS.isNotEmpty() || isMemberSpecialization)) { 15845 // do nothing 15846 15847 // Diagnose implicit declarations introduced by elaborated types. 15848 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 15849 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15850 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 15851 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15852 Invalid = true; 15853 15854 // Otherwise it's a declaration. Call out a particularly common 15855 // case here. 15856 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15857 unsigned Kind = 0; 15858 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 15859 Diag(NameLoc, diag::err_tag_definition_of_typedef) 15860 << Name << Kind << TND->getUnderlyingType(); 15861 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15862 Invalid = true; 15863 15864 // Otherwise, diagnose. 15865 } else { 15866 // The tag name clashes with something else in the target scope, 15867 // issue an error and recover by making this tag be anonymous. 15868 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 15869 notePreviousDefinition(PrevDecl, NameLoc); 15870 Name = nullptr; 15871 Invalid = true; 15872 } 15873 15874 // The existing declaration isn't relevant to us; we're in a 15875 // new scope, so clear out the previous declaration. 15876 Previous.clear(); 15877 } 15878 } 15879 15880 CreateNewDecl: 15881 15882 TagDecl *PrevDecl = nullptr; 15883 if (Previous.isSingleResult()) 15884 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 15885 15886 // If there is an identifier, use the location of the identifier as the 15887 // location of the decl, otherwise use the location of the struct/union 15888 // keyword. 15889 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15890 15891 // Otherwise, create a new declaration. If there is a previous 15892 // declaration of the same entity, the two will be linked via 15893 // PrevDecl. 15894 TagDecl *New; 15895 15896 if (Kind == TTK_Enum) { 15897 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15898 // enum X { A, B, C } D; D should chain to X. 15899 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 15900 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 15901 ScopedEnumUsesClassTag, IsFixed); 15902 15903 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 15904 StdAlignValT = cast<EnumDecl>(New); 15905 15906 // If this is an undefined enum, warn. 15907 if (TUK != TUK_Definition && !Invalid) { 15908 TagDecl *Def; 15909 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 15910 // C++0x: 7.2p2: opaque-enum-declaration. 15911 // Conflicts are diagnosed above. Do nothing. 15912 } 15913 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 15914 Diag(Loc, diag::ext_forward_ref_enum_def) 15915 << New; 15916 Diag(Def->getLocation(), diag::note_previous_definition); 15917 } else { 15918 unsigned DiagID = diag::ext_forward_ref_enum; 15919 if (getLangOpts().MSVCCompat) 15920 DiagID = diag::ext_ms_forward_ref_enum; 15921 else if (getLangOpts().CPlusPlus) 15922 DiagID = diag::err_forward_ref_enum; 15923 Diag(Loc, DiagID); 15924 } 15925 } 15926 15927 if (EnumUnderlying) { 15928 EnumDecl *ED = cast<EnumDecl>(New); 15929 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15930 ED->setIntegerTypeSourceInfo(TI); 15931 else 15932 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 15933 ED->setPromotionType(ED->getIntegerType()); 15934 assert(ED->isComplete() && "enum with type should be complete"); 15935 } 15936 } else { 15937 // struct/union/class 15938 15939 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15940 // struct X { int A; } D; D should chain to X. 15941 if (getLangOpts().CPlusPlus) { 15942 // FIXME: Look for a way to use RecordDecl for simple structs. 15943 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15944 cast_or_null<CXXRecordDecl>(PrevDecl)); 15945 15946 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 15947 StdBadAlloc = cast<CXXRecordDecl>(New); 15948 } else 15949 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15950 cast_or_null<RecordDecl>(PrevDecl)); 15951 } 15952 15953 // C++11 [dcl.type]p3: 15954 // A type-specifier-seq shall not define a class or enumeration [...]. 15955 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 15956 TUK == TUK_Definition) { 15957 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 15958 << Context.getTagDeclType(New); 15959 Invalid = true; 15960 } 15961 15962 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 15963 DC->getDeclKind() == Decl::Enum) { 15964 Diag(New->getLocation(), diag::err_type_defined_in_enum) 15965 << Context.getTagDeclType(New); 15966 Invalid = true; 15967 } 15968 15969 // Maybe add qualifier info. 15970 if (SS.isNotEmpty()) { 15971 if (SS.isSet()) { 15972 // If this is either a declaration or a definition, check the 15973 // nested-name-specifier against the current context. 15974 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 15975 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 15976 isMemberSpecialization)) 15977 Invalid = true; 15978 15979 New->setQualifierInfo(SS.getWithLocInContext(Context)); 15980 if (TemplateParameterLists.size() > 0) { 15981 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 15982 } 15983 } 15984 else 15985 Invalid = true; 15986 } 15987 15988 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15989 // Add alignment attributes if necessary; these attributes are checked when 15990 // the ASTContext lays out the structure. 15991 // 15992 // It is important for implementing the correct semantics that this 15993 // happen here (in ActOnTag). The #pragma pack stack is 15994 // maintained as a result of parser callbacks which can occur at 15995 // many points during the parsing of a struct declaration (because 15996 // the #pragma tokens are effectively skipped over during the 15997 // parsing of the struct). 15998 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15999 AddAlignmentAttributesForRecord(RD); 16000 AddMsStructLayoutForRecord(RD); 16001 } 16002 } 16003 16004 if (ModulePrivateLoc.isValid()) { 16005 if (isMemberSpecialization) 16006 Diag(New->getLocation(), diag::err_module_private_specialization) 16007 << 2 16008 << FixItHint::CreateRemoval(ModulePrivateLoc); 16009 // __module_private__ does not apply to local classes. However, we only 16010 // diagnose this as an error when the declaration specifiers are 16011 // freestanding. Here, we just ignore the __module_private__. 16012 else if (!SearchDC->isFunctionOrMethod()) 16013 New->setModulePrivate(); 16014 } 16015 16016 // If this is a specialization of a member class (of a class template), 16017 // check the specialization. 16018 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16019 Invalid = true; 16020 16021 // If we're declaring or defining a tag in function prototype scope in C, 16022 // note that this type can only be used within the function and add it to 16023 // the list of decls to inject into the function definition scope. 16024 if ((Name || Kind == TTK_Enum) && 16025 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16026 if (getLangOpts().CPlusPlus) { 16027 // C++ [dcl.fct]p6: 16028 // Types shall not be defined in return or parameter types. 16029 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16030 Diag(Loc, diag::err_type_defined_in_param_type) 16031 << Name; 16032 Invalid = true; 16033 } 16034 } else if (!PrevDecl) { 16035 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16036 } 16037 } 16038 16039 if (Invalid) 16040 New->setInvalidDecl(); 16041 16042 // Set the lexical context. If the tag has a C++ scope specifier, the 16043 // lexical context will be different from the semantic context. 16044 New->setLexicalDeclContext(CurContext); 16045 16046 // Mark this as a friend decl if applicable. 16047 // In Microsoft mode, a friend declaration also acts as a forward 16048 // declaration so we always pass true to setObjectOfFriendDecl to make 16049 // the tag name visible. 16050 if (TUK == TUK_Friend) 16051 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16052 16053 // Set the access specifier. 16054 if (!Invalid && SearchDC->isRecord()) 16055 SetMemberAccessSpecifier(New, PrevDecl, AS); 16056 16057 if (PrevDecl) 16058 CheckRedeclarationModuleOwnership(New, PrevDecl); 16059 16060 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16061 New->startDefinition(); 16062 16063 ProcessDeclAttributeList(S, New, Attrs); 16064 AddPragmaAttributes(S, New); 16065 16066 // If this has an identifier, add it to the scope stack. 16067 if (TUK == TUK_Friend) { 16068 // We might be replacing an existing declaration in the lookup tables; 16069 // if so, borrow its access specifier. 16070 if (PrevDecl) 16071 New->setAccess(PrevDecl->getAccess()); 16072 16073 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16074 DC->makeDeclVisibleInContext(New); 16075 if (Name) // can be null along some error paths 16076 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16077 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16078 } else if (Name) { 16079 S = getNonFieldDeclScope(S); 16080 PushOnScopeChains(New, S, true); 16081 } else { 16082 CurContext->addDecl(New); 16083 } 16084 16085 // If this is the C FILE type, notify the AST context. 16086 if (IdentifierInfo *II = New->getIdentifier()) 16087 if (!New->isInvalidDecl() && 16088 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16089 II->isStr("FILE")) 16090 Context.setFILEDecl(New); 16091 16092 if (PrevDecl) 16093 mergeDeclAttributes(New, PrevDecl); 16094 16095 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16096 inferGslOwnerPointerAttribute(CXXRD); 16097 16098 // If there's a #pragma GCC visibility in scope, set the visibility of this 16099 // record. 16100 AddPushedVisibilityAttribute(New); 16101 16102 if (isMemberSpecialization && !New->isInvalidDecl()) 16103 CompleteMemberSpecialization(New, Previous); 16104 16105 OwnedDecl = true; 16106 // In C++, don't return an invalid declaration. We can't recover well from 16107 // the cases where we make the type anonymous. 16108 if (Invalid && getLangOpts().CPlusPlus) { 16109 if (New->isBeingDefined()) 16110 if (auto RD = dyn_cast<RecordDecl>(New)) 16111 RD->completeDefinition(); 16112 return nullptr; 16113 } else if (SkipBody && SkipBody->ShouldSkip) { 16114 return SkipBody->Previous; 16115 } else { 16116 return New; 16117 } 16118 } 16119 16120 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16121 AdjustDeclIfTemplate(TagD); 16122 TagDecl *Tag = cast<TagDecl>(TagD); 16123 16124 // Enter the tag context. 16125 PushDeclContext(S, Tag); 16126 16127 ActOnDocumentableDecl(TagD); 16128 16129 // If there's a #pragma GCC visibility in scope, set the visibility of this 16130 // record. 16131 AddPushedVisibilityAttribute(Tag); 16132 } 16133 16134 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16135 SkipBodyInfo &SkipBody) { 16136 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16137 return false; 16138 16139 // Make the previous decl visible. 16140 makeMergedDefinitionVisible(SkipBody.Previous); 16141 return true; 16142 } 16143 16144 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16145 assert(isa<ObjCContainerDecl>(IDecl) && 16146 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16147 DeclContext *OCD = cast<DeclContext>(IDecl); 16148 assert(getContainingDC(OCD) == CurContext && 16149 "The next DeclContext should be lexically contained in the current one."); 16150 CurContext = OCD; 16151 return IDecl; 16152 } 16153 16154 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16155 SourceLocation FinalLoc, 16156 bool IsFinalSpelledSealed, 16157 SourceLocation LBraceLoc) { 16158 AdjustDeclIfTemplate(TagD); 16159 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16160 16161 FieldCollector->StartClass(); 16162 16163 if (!Record->getIdentifier()) 16164 return; 16165 16166 if (FinalLoc.isValid()) 16167 Record->addAttr(FinalAttr::Create( 16168 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16169 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16170 16171 // C++ [class]p2: 16172 // [...] The class-name is also inserted into the scope of the 16173 // class itself; this is known as the injected-class-name. For 16174 // purposes of access checking, the injected-class-name is treated 16175 // as if it were a public member name. 16176 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16177 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16178 Record->getLocation(), Record->getIdentifier(), 16179 /*PrevDecl=*/nullptr, 16180 /*DelayTypeCreation=*/true); 16181 Context.getTypeDeclType(InjectedClassName, Record); 16182 InjectedClassName->setImplicit(); 16183 InjectedClassName->setAccess(AS_public); 16184 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16185 InjectedClassName->setDescribedClassTemplate(Template); 16186 PushOnScopeChains(InjectedClassName, S); 16187 assert(InjectedClassName->isInjectedClassName() && 16188 "Broken injected-class-name"); 16189 } 16190 16191 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16192 SourceRange BraceRange) { 16193 AdjustDeclIfTemplate(TagD); 16194 TagDecl *Tag = cast<TagDecl>(TagD); 16195 Tag->setBraceRange(BraceRange); 16196 16197 // Make sure we "complete" the definition even it is invalid. 16198 if (Tag->isBeingDefined()) { 16199 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16200 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16201 RD->completeDefinition(); 16202 } 16203 16204 if (isa<CXXRecordDecl>(Tag)) { 16205 FieldCollector->FinishClass(); 16206 } 16207 16208 // Exit this scope of this tag's definition. 16209 PopDeclContext(); 16210 16211 if (getCurLexicalContext()->isObjCContainer() && 16212 Tag->getDeclContext()->isFileContext()) 16213 Tag->setTopLevelDeclInObjCContainer(); 16214 16215 // Notify the consumer that we've defined a tag. 16216 if (!Tag->isInvalidDecl()) 16217 Consumer.HandleTagDeclDefinition(Tag); 16218 } 16219 16220 void Sema::ActOnObjCContainerFinishDefinition() { 16221 // Exit this scope of this interface definition. 16222 PopDeclContext(); 16223 } 16224 16225 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16226 assert(DC == CurContext && "Mismatch of container contexts"); 16227 OriginalLexicalContext = DC; 16228 ActOnObjCContainerFinishDefinition(); 16229 } 16230 16231 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16232 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16233 OriginalLexicalContext = nullptr; 16234 } 16235 16236 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16237 AdjustDeclIfTemplate(TagD); 16238 TagDecl *Tag = cast<TagDecl>(TagD); 16239 Tag->setInvalidDecl(); 16240 16241 // Make sure we "complete" the definition even it is invalid. 16242 if (Tag->isBeingDefined()) { 16243 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16244 RD->completeDefinition(); 16245 } 16246 16247 // We're undoing ActOnTagStartDefinition here, not 16248 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16249 // the FieldCollector. 16250 16251 PopDeclContext(); 16252 } 16253 16254 // Note that FieldName may be null for anonymous bitfields. 16255 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16256 IdentifierInfo *FieldName, 16257 QualType FieldTy, bool IsMsStruct, 16258 Expr *BitWidth, bool *ZeroWidth) { 16259 assert(BitWidth); 16260 if (BitWidth->containsErrors()) 16261 return ExprError(); 16262 16263 // Default to true; that shouldn't confuse checks for emptiness 16264 if (ZeroWidth) 16265 *ZeroWidth = true; 16266 16267 // C99 6.7.2.1p4 - verify the field type. 16268 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16269 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16270 // Handle incomplete and sizeless types with a specific error. 16271 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16272 diag::err_field_incomplete_or_sizeless)) 16273 return ExprError(); 16274 if (FieldName) 16275 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16276 << FieldName << FieldTy << BitWidth->getSourceRange(); 16277 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16278 << FieldTy << BitWidth->getSourceRange(); 16279 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16280 UPPC_BitFieldWidth)) 16281 return ExprError(); 16282 16283 // If the bit-width is type- or value-dependent, don't try to check 16284 // it now. 16285 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16286 return BitWidth; 16287 16288 llvm::APSInt Value; 16289 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 16290 if (ICE.isInvalid()) 16291 return ICE; 16292 BitWidth = ICE.get(); 16293 16294 if (Value != 0 && ZeroWidth) 16295 *ZeroWidth = false; 16296 16297 // Zero-width bitfield is ok for anonymous field. 16298 if (Value == 0 && FieldName) 16299 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16300 16301 if (Value.isSigned() && Value.isNegative()) { 16302 if (FieldName) 16303 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16304 << FieldName << Value.toString(10); 16305 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16306 << Value.toString(10); 16307 } 16308 16309 if (!FieldTy->isDependentType()) { 16310 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16311 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16312 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16313 16314 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16315 // ABI. 16316 bool CStdConstraintViolation = 16317 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16318 bool MSBitfieldViolation = 16319 Value.ugt(TypeStorageSize) && 16320 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16321 if (CStdConstraintViolation || MSBitfieldViolation) { 16322 unsigned DiagWidth = 16323 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16324 if (FieldName) 16325 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16326 << FieldName << (unsigned)Value.getZExtValue() 16327 << !CStdConstraintViolation << DiagWidth; 16328 16329 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16330 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 16331 << DiagWidth; 16332 } 16333 16334 // Warn on types where the user might conceivably expect to get all 16335 // specified bits as value bits: that's all integral types other than 16336 // 'bool'. 16337 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 16338 if (FieldName) 16339 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16340 << FieldName << (unsigned)Value.getZExtValue() 16341 << (unsigned)TypeWidth; 16342 else 16343 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 16344 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 16345 } 16346 } 16347 16348 return BitWidth; 16349 } 16350 16351 /// ActOnField - Each field of a C struct/union is passed into this in order 16352 /// to create a FieldDecl object for it. 16353 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16354 Declarator &D, Expr *BitfieldWidth) { 16355 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16356 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16357 /*InitStyle=*/ICIS_NoInit, AS_public); 16358 return Res; 16359 } 16360 16361 /// HandleField - Analyze a field of a C struct or a C++ data member. 16362 /// 16363 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16364 SourceLocation DeclStart, 16365 Declarator &D, Expr *BitWidth, 16366 InClassInitStyle InitStyle, 16367 AccessSpecifier AS) { 16368 if (D.isDecompositionDeclarator()) { 16369 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16370 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16371 << Decomp.getSourceRange(); 16372 return nullptr; 16373 } 16374 16375 IdentifierInfo *II = D.getIdentifier(); 16376 SourceLocation Loc = DeclStart; 16377 if (II) Loc = D.getIdentifierLoc(); 16378 16379 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16380 QualType T = TInfo->getType(); 16381 if (getLangOpts().CPlusPlus) { 16382 CheckExtraCXXDefaultArguments(D); 16383 16384 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16385 UPPC_DataMemberType)) { 16386 D.setInvalidType(); 16387 T = Context.IntTy; 16388 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16389 } 16390 } 16391 16392 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16393 16394 if (D.getDeclSpec().isInlineSpecified()) 16395 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16396 << getLangOpts().CPlusPlus17; 16397 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16398 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16399 diag::err_invalid_thread) 16400 << DeclSpec::getSpecifierName(TSCS); 16401 16402 // Check to see if this name was declared as a member previously 16403 NamedDecl *PrevDecl = nullptr; 16404 LookupResult Previous(*this, II, Loc, LookupMemberName, 16405 ForVisibleRedeclaration); 16406 LookupName(Previous, S); 16407 switch (Previous.getResultKind()) { 16408 case LookupResult::Found: 16409 case LookupResult::FoundUnresolvedValue: 16410 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16411 break; 16412 16413 case LookupResult::FoundOverloaded: 16414 PrevDecl = Previous.getRepresentativeDecl(); 16415 break; 16416 16417 case LookupResult::NotFound: 16418 case LookupResult::NotFoundInCurrentInstantiation: 16419 case LookupResult::Ambiguous: 16420 break; 16421 } 16422 Previous.suppressDiagnostics(); 16423 16424 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16425 // Maybe we will complain about the shadowed template parameter. 16426 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16427 // Just pretend that we didn't see the previous declaration. 16428 PrevDecl = nullptr; 16429 } 16430 16431 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16432 PrevDecl = nullptr; 16433 16434 bool Mutable 16435 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16436 SourceLocation TSSL = D.getBeginLoc(); 16437 FieldDecl *NewFD 16438 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16439 TSSL, AS, PrevDecl, &D); 16440 16441 if (NewFD->isInvalidDecl()) 16442 Record->setInvalidDecl(); 16443 16444 if (D.getDeclSpec().isModulePrivateSpecified()) 16445 NewFD->setModulePrivate(); 16446 16447 if (NewFD->isInvalidDecl() && PrevDecl) { 16448 // Don't introduce NewFD into scope; there's already something 16449 // with the same name in the same scope. 16450 } else if (II) { 16451 PushOnScopeChains(NewFD, S); 16452 } else 16453 Record->addDecl(NewFD); 16454 16455 return NewFD; 16456 } 16457 16458 /// Build a new FieldDecl and check its well-formedness. 16459 /// 16460 /// This routine builds a new FieldDecl given the fields name, type, 16461 /// record, etc. \p PrevDecl should refer to any previous declaration 16462 /// with the same name and in the same scope as the field to be 16463 /// created. 16464 /// 16465 /// \returns a new FieldDecl. 16466 /// 16467 /// \todo The Declarator argument is a hack. It will be removed once 16468 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16469 TypeSourceInfo *TInfo, 16470 RecordDecl *Record, SourceLocation Loc, 16471 bool Mutable, Expr *BitWidth, 16472 InClassInitStyle InitStyle, 16473 SourceLocation TSSL, 16474 AccessSpecifier AS, NamedDecl *PrevDecl, 16475 Declarator *D) { 16476 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16477 bool InvalidDecl = false; 16478 if (D) InvalidDecl = D->isInvalidType(); 16479 16480 // If we receive a broken type, recover by assuming 'int' and 16481 // marking this declaration as invalid. 16482 if (T.isNull()) { 16483 InvalidDecl = true; 16484 T = Context.IntTy; 16485 } 16486 16487 QualType EltTy = Context.getBaseElementType(T); 16488 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16489 if (RequireCompleteSizedType(Loc, EltTy, 16490 diag::err_field_incomplete_or_sizeless)) { 16491 // Fields of incomplete type force their record to be invalid. 16492 Record->setInvalidDecl(); 16493 InvalidDecl = true; 16494 } else { 16495 NamedDecl *Def; 16496 EltTy->isIncompleteType(&Def); 16497 if (Def && Def->isInvalidDecl()) { 16498 Record->setInvalidDecl(); 16499 InvalidDecl = true; 16500 } 16501 } 16502 } 16503 16504 // TR 18037 does not allow fields to be declared with address space 16505 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16506 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16507 Diag(Loc, diag::err_field_with_address_space); 16508 Record->setInvalidDecl(); 16509 InvalidDecl = true; 16510 } 16511 16512 if (LangOpts.OpenCL) { 16513 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16514 // used as structure or union field: image, sampler, event or block types. 16515 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16516 T->isBlockPointerType()) { 16517 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16518 Record->setInvalidDecl(); 16519 InvalidDecl = true; 16520 } 16521 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16522 if (BitWidth) { 16523 Diag(Loc, diag::err_opencl_bitfields); 16524 InvalidDecl = true; 16525 } 16526 } 16527 16528 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16529 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16530 T.hasQualifiers()) { 16531 InvalidDecl = true; 16532 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16533 } 16534 16535 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16536 // than a variably modified type. 16537 if (!InvalidDecl && T->isVariablyModifiedType()) { 16538 bool SizeIsNegative; 16539 llvm::APSInt Oversized; 16540 16541 TypeSourceInfo *FixedTInfo = 16542 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 16543 SizeIsNegative, 16544 Oversized); 16545 if (FixedTInfo) { 16546 Diag(Loc, diag::warn_illegal_constant_array_size); 16547 TInfo = FixedTInfo; 16548 T = FixedTInfo->getType(); 16549 } else { 16550 if (SizeIsNegative) 16551 Diag(Loc, diag::err_typecheck_negative_array_size); 16552 else if (Oversized.getBoolValue()) 16553 Diag(Loc, diag::err_array_too_large) 16554 << Oversized.toString(10); 16555 else 16556 Diag(Loc, diag::err_typecheck_field_variable_size); 16557 InvalidDecl = true; 16558 } 16559 } 16560 16561 // Fields can not have abstract class types 16562 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16563 diag::err_abstract_type_in_decl, 16564 AbstractFieldType)) 16565 InvalidDecl = true; 16566 16567 bool ZeroWidth = false; 16568 if (InvalidDecl) 16569 BitWidth = nullptr; 16570 // If this is declared as a bit-field, check the bit-field. 16571 if (BitWidth) { 16572 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16573 &ZeroWidth).get(); 16574 if (!BitWidth) { 16575 InvalidDecl = true; 16576 BitWidth = nullptr; 16577 ZeroWidth = false; 16578 } 16579 16580 // Only data members can have in-class initializers. 16581 if (BitWidth && !II && InitStyle) { 16582 Diag(Loc, diag::err_anon_bitfield_init); 16583 InvalidDecl = true; 16584 BitWidth = nullptr; 16585 ZeroWidth = false; 16586 } 16587 } 16588 16589 // Check that 'mutable' is consistent with the type of the declaration. 16590 if (!InvalidDecl && Mutable) { 16591 unsigned DiagID = 0; 16592 if (T->isReferenceType()) 16593 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16594 : diag::err_mutable_reference; 16595 else if (T.isConstQualified()) 16596 DiagID = diag::err_mutable_const; 16597 16598 if (DiagID) { 16599 SourceLocation ErrLoc = Loc; 16600 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16601 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16602 Diag(ErrLoc, DiagID); 16603 if (DiagID != diag::ext_mutable_reference) { 16604 Mutable = false; 16605 InvalidDecl = true; 16606 } 16607 } 16608 } 16609 16610 // C++11 [class.union]p8 (DR1460): 16611 // At most one variant member of a union may have a 16612 // brace-or-equal-initializer. 16613 if (InitStyle != ICIS_NoInit) 16614 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16615 16616 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16617 BitWidth, Mutable, InitStyle); 16618 if (InvalidDecl) 16619 NewFD->setInvalidDecl(); 16620 16621 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16622 Diag(Loc, diag::err_duplicate_member) << II; 16623 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16624 NewFD->setInvalidDecl(); 16625 } 16626 16627 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16628 if (Record->isUnion()) { 16629 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16630 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16631 if (RDecl->getDefinition()) { 16632 // C++ [class.union]p1: An object of a class with a non-trivial 16633 // constructor, a non-trivial copy constructor, a non-trivial 16634 // destructor, or a non-trivial copy assignment operator 16635 // cannot be a member of a union, nor can an array of such 16636 // objects. 16637 if (CheckNontrivialField(NewFD)) 16638 NewFD->setInvalidDecl(); 16639 } 16640 } 16641 16642 // C++ [class.union]p1: If a union contains a member of reference type, 16643 // the program is ill-formed, except when compiling with MSVC extensions 16644 // enabled. 16645 if (EltTy->isReferenceType()) { 16646 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16647 diag::ext_union_member_of_reference_type : 16648 diag::err_union_member_of_reference_type) 16649 << NewFD->getDeclName() << EltTy; 16650 if (!getLangOpts().MicrosoftExt) 16651 NewFD->setInvalidDecl(); 16652 } 16653 } 16654 } 16655 16656 // FIXME: We need to pass in the attributes given an AST 16657 // representation, not a parser representation. 16658 if (D) { 16659 // FIXME: The current scope is almost... but not entirely... correct here. 16660 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16661 16662 if (NewFD->hasAttrs()) 16663 CheckAlignasUnderalignment(NewFD); 16664 } 16665 16666 // In auto-retain/release, infer strong retension for fields of 16667 // retainable type. 16668 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16669 NewFD->setInvalidDecl(); 16670 16671 if (T.isObjCGCWeak()) 16672 Diag(Loc, diag::warn_attribute_weak_on_field); 16673 16674 NewFD->setAccess(AS); 16675 return NewFD; 16676 } 16677 16678 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16679 assert(FD); 16680 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16681 16682 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16683 return false; 16684 16685 QualType EltTy = Context.getBaseElementType(FD->getType()); 16686 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16687 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16688 if (RDecl->getDefinition()) { 16689 // We check for copy constructors before constructors 16690 // because otherwise we'll never get complaints about 16691 // copy constructors. 16692 16693 CXXSpecialMember member = CXXInvalid; 16694 // We're required to check for any non-trivial constructors. Since the 16695 // implicit default constructor is suppressed if there are any 16696 // user-declared constructors, we just need to check that there is a 16697 // trivial default constructor and a trivial copy constructor. (We don't 16698 // worry about move constructors here, since this is a C++98 check.) 16699 if (RDecl->hasNonTrivialCopyConstructor()) 16700 member = CXXCopyConstructor; 16701 else if (!RDecl->hasTrivialDefaultConstructor()) 16702 member = CXXDefaultConstructor; 16703 else if (RDecl->hasNonTrivialCopyAssignment()) 16704 member = CXXCopyAssignment; 16705 else if (RDecl->hasNonTrivialDestructor()) 16706 member = CXXDestructor; 16707 16708 if (member != CXXInvalid) { 16709 if (!getLangOpts().CPlusPlus11 && 16710 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16711 // Objective-C++ ARC: it is an error to have a non-trivial field of 16712 // a union. However, system headers in Objective-C programs 16713 // occasionally have Objective-C lifetime objects within unions, 16714 // and rather than cause the program to fail, we make those 16715 // members unavailable. 16716 SourceLocation Loc = FD->getLocation(); 16717 if (getSourceManager().isInSystemHeader(Loc)) { 16718 if (!FD->hasAttr<UnavailableAttr>()) 16719 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16720 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16721 return false; 16722 } 16723 } 16724 16725 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16726 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16727 diag::err_illegal_union_or_anon_struct_member) 16728 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16729 DiagnoseNontrivial(RDecl, member); 16730 return !getLangOpts().CPlusPlus11; 16731 } 16732 } 16733 } 16734 16735 return false; 16736 } 16737 16738 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16739 /// AST enum value. 16740 static ObjCIvarDecl::AccessControl 16741 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16742 switch (ivarVisibility) { 16743 default: llvm_unreachable("Unknown visitibility kind"); 16744 case tok::objc_private: return ObjCIvarDecl::Private; 16745 case tok::objc_public: return ObjCIvarDecl::Public; 16746 case tok::objc_protected: return ObjCIvarDecl::Protected; 16747 case tok::objc_package: return ObjCIvarDecl::Package; 16748 } 16749 } 16750 16751 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16752 /// in order to create an IvarDecl object for it. 16753 Decl *Sema::ActOnIvar(Scope *S, 16754 SourceLocation DeclStart, 16755 Declarator &D, Expr *BitfieldWidth, 16756 tok::ObjCKeywordKind Visibility) { 16757 16758 IdentifierInfo *II = D.getIdentifier(); 16759 Expr *BitWidth = (Expr*)BitfieldWidth; 16760 SourceLocation Loc = DeclStart; 16761 if (II) Loc = D.getIdentifierLoc(); 16762 16763 // FIXME: Unnamed fields can be handled in various different ways, for 16764 // example, unnamed unions inject all members into the struct namespace! 16765 16766 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16767 QualType T = TInfo->getType(); 16768 16769 if (BitWidth) { 16770 // 6.7.2.1p3, 6.7.2.1p4 16771 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16772 if (!BitWidth) 16773 D.setInvalidType(); 16774 } else { 16775 // Not a bitfield. 16776 16777 // validate II. 16778 16779 } 16780 if (T->isReferenceType()) { 16781 Diag(Loc, diag::err_ivar_reference_type); 16782 D.setInvalidType(); 16783 } 16784 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16785 // than a variably modified type. 16786 else if (T->isVariablyModifiedType()) { 16787 Diag(Loc, diag::err_typecheck_ivar_variable_size); 16788 D.setInvalidType(); 16789 } 16790 16791 // Get the visibility (access control) for this ivar. 16792 ObjCIvarDecl::AccessControl ac = 16793 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 16794 : ObjCIvarDecl::None; 16795 // Must set ivar's DeclContext to its enclosing interface. 16796 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 16797 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 16798 return nullptr; 16799 ObjCContainerDecl *EnclosingContext; 16800 if (ObjCImplementationDecl *IMPDecl = 16801 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16802 if (LangOpts.ObjCRuntime.isFragile()) { 16803 // Case of ivar declared in an implementation. Context is that of its class. 16804 EnclosingContext = IMPDecl->getClassInterface(); 16805 assert(EnclosingContext && "Implementation has no class interface!"); 16806 } 16807 else 16808 EnclosingContext = EnclosingDecl; 16809 } else { 16810 if (ObjCCategoryDecl *CDecl = 16811 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16812 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 16813 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 16814 return nullptr; 16815 } 16816 } 16817 EnclosingContext = EnclosingDecl; 16818 } 16819 16820 // Construct the decl. 16821 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 16822 DeclStart, Loc, II, T, 16823 TInfo, ac, (Expr *)BitfieldWidth); 16824 16825 if (II) { 16826 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 16827 ForVisibleRedeclaration); 16828 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 16829 && !isa<TagDecl>(PrevDecl)) { 16830 Diag(Loc, diag::err_duplicate_member) << II; 16831 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16832 NewID->setInvalidDecl(); 16833 } 16834 } 16835 16836 // Process attributes attached to the ivar. 16837 ProcessDeclAttributes(S, NewID, D); 16838 16839 if (D.isInvalidType()) 16840 NewID->setInvalidDecl(); 16841 16842 // In ARC, infer 'retaining' for ivars of retainable type. 16843 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 16844 NewID->setInvalidDecl(); 16845 16846 if (D.getDeclSpec().isModulePrivateSpecified()) 16847 NewID->setModulePrivate(); 16848 16849 if (II) { 16850 // FIXME: When interfaces are DeclContexts, we'll need to add 16851 // these to the interface. 16852 S->AddDecl(NewID); 16853 IdResolver.AddDecl(NewID); 16854 } 16855 16856 if (LangOpts.ObjCRuntime.isNonFragile() && 16857 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 16858 Diag(Loc, diag::warn_ivars_in_interface); 16859 16860 return NewID; 16861 } 16862 16863 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 16864 /// class and class extensions. For every class \@interface and class 16865 /// extension \@interface, if the last ivar is a bitfield of any type, 16866 /// then add an implicit `char :0` ivar to the end of that interface. 16867 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 16868 SmallVectorImpl<Decl *> &AllIvarDecls) { 16869 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 16870 return; 16871 16872 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 16873 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 16874 16875 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 16876 return; 16877 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 16878 if (!ID) { 16879 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 16880 if (!CD->IsClassExtension()) 16881 return; 16882 } 16883 // No need to add this to end of @implementation. 16884 else 16885 return; 16886 } 16887 // All conditions are met. Add a new bitfield to the tail end of ivars. 16888 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 16889 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 16890 16891 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 16892 DeclLoc, DeclLoc, nullptr, 16893 Context.CharTy, 16894 Context.getTrivialTypeSourceInfo(Context.CharTy, 16895 DeclLoc), 16896 ObjCIvarDecl::Private, BW, 16897 true); 16898 AllIvarDecls.push_back(Ivar); 16899 } 16900 16901 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 16902 ArrayRef<Decl *> Fields, SourceLocation LBrac, 16903 SourceLocation RBrac, 16904 const ParsedAttributesView &Attrs) { 16905 assert(EnclosingDecl && "missing record or interface decl"); 16906 16907 // If this is an Objective-C @implementation or category and we have 16908 // new fields here we should reset the layout of the interface since 16909 // it will now change. 16910 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 16911 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 16912 switch (DC->getKind()) { 16913 default: break; 16914 case Decl::ObjCCategory: 16915 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 16916 break; 16917 case Decl::ObjCImplementation: 16918 Context. 16919 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 16920 break; 16921 } 16922 } 16923 16924 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 16925 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 16926 16927 // Start counting up the number of named members; make sure to include 16928 // members of anonymous structs and unions in the total. 16929 unsigned NumNamedMembers = 0; 16930 if (Record) { 16931 for (const auto *I : Record->decls()) { 16932 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 16933 if (IFD->getDeclName()) 16934 ++NumNamedMembers; 16935 } 16936 } 16937 16938 // Verify that all the fields are okay. 16939 SmallVector<FieldDecl*, 32> RecFields; 16940 16941 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 16942 i != end; ++i) { 16943 FieldDecl *FD = cast<FieldDecl>(*i); 16944 16945 // Get the type for the field. 16946 const Type *FDTy = FD->getType().getTypePtr(); 16947 16948 if (!FD->isAnonymousStructOrUnion()) { 16949 // Remember all fields written by the user. 16950 RecFields.push_back(FD); 16951 } 16952 16953 // If the field is already invalid for some reason, don't emit more 16954 // diagnostics about it. 16955 if (FD->isInvalidDecl()) { 16956 EnclosingDecl->setInvalidDecl(); 16957 continue; 16958 } 16959 16960 // C99 6.7.2.1p2: 16961 // A structure or union shall not contain a member with 16962 // incomplete or function type (hence, a structure shall not 16963 // contain an instance of itself, but may contain a pointer to 16964 // an instance of itself), except that the last member of a 16965 // structure with more than one named member may have incomplete 16966 // array type; such a structure (and any union containing, 16967 // possibly recursively, a member that is such a structure) 16968 // shall not be a member of a structure or an element of an 16969 // array. 16970 bool IsLastField = (i + 1 == Fields.end()); 16971 if (FDTy->isFunctionType()) { 16972 // Field declared as a function. 16973 Diag(FD->getLocation(), diag::err_field_declared_as_function) 16974 << FD->getDeclName(); 16975 FD->setInvalidDecl(); 16976 EnclosingDecl->setInvalidDecl(); 16977 continue; 16978 } else if (FDTy->isIncompleteArrayType() && 16979 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 16980 if (Record) { 16981 // Flexible array member. 16982 // Microsoft and g++ is more permissive regarding flexible array. 16983 // It will accept flexible array in union and also 16984 // as the sole element of a struct/class. 16985 unsigned DiagID = 0; 16986 if (!Record->isUnion() && !IsLastField) { 16987 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 16988 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 16989 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 16990 FD->setInvalidDecl(); 16991 EnclosingDecl->setInvalidDecl(); 16992 continue; 16993 } else if (Record->isUnion()) 16994 DiagID = getLangOpts().MicrosoftExt 16995 ? diag::ext_flexible_array_union_ms 16996 : getLangOpts().CPlusPlus 16997 ? diag::ext_flexible_array_union_gnu 16998 : diag::err_flexible_array_union; 16999 else if (NumNamedMembers < 1) 17000 DiagID = getLangOpts().MicrosoftExt 17001 ? diag::ext_flexible_array_empty_aggregate_ms 17002 : getLangOpts().CPlusPlus 17003 ? diag::ext_flexible_array_empty_aggregate_gnu 17004 : diag::err_flexible_array_empty_aggregate; 17005 17006 if (DiagID) 17007 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17008 << Record->getTagKind(); 17009 // While the layout of types that contain virtual bases is not specified 17010 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17011 // virtual bases after the derived members. This would make a flexible 17012 // array member declared at the end of an object not adjacent to the end 17013 // of the type. 17014 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17015 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17016 << FD->getDeclName() << Record->getTagKind(); 17017 if (!getLangOpts().C99) 17018 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17019 << FD->getDeclName() << Record->getTagKind(); 17020 17021 // If the element type has a non-trivial destructor, we would not 17022 // implicitly destroy the elements, so disallow it for now. 17023 // 17024 // FIXME: GCC allows this. We should probably either implicitly delete 17025 // the destructor of the containing class, or just allow this. 17026 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17027 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17028 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17029 << FD->getDeclName() << FD->getType(); 17030 FD->setInvalidDecl(); 17031 EnclosingDecl->setInvalidDecl(); 17032 continue; 17033 } 17034 // Okay, we have a legal flexible array member at the end of the struct. 17035 Record->setHasFlexibleArrayMember(true); 17036 } else { 17037 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17038 // unless they are followed by another ivar. That check is done 17039 // elsewhere, after synthesized ivars are known. 17040 } 17041 } else if (!FDTy->isDependentType() && 17042 RequireCompleteSizedType( 17043 FD->getLocation(), FD->getType(), 17044 diag::err_field_incomplete_or_sizeless)) { 17045 // Incomplete type 17046 FD->setInvalidDecl(); 17047 EnclosingDecl->setInvalidDecl(); 17048 continue; 17049 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17050 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17051 // A type which contains a flexible array member is considered to be a 17052 // flexible array member. 17053 Record->setHasFlexibleArrayMember(true); 17054 if (!Record->isUnion()) { 17055 // If this is a struct/class and this is not the last element, reject 17056 // it. Note that GCC supports variable sized arrays in the middle of 17057 // structures. 17058 if (!IsLastField) 17059 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17060 << FD->getDeclName() << FD->getType(); 17061 else { 17062 // We support flexible arrays at the end of structs in 17063 // other structs as an extension. 17064 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17065 << FD->getDeclName(); 17066 } 17067 } 17068 } 17069 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17070 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17071 diag::err_abstract_type_in_decl, 17072 AbstractIvarType)) { 17073 // Ivars can not have abstract class types 17074 FD->setInvalidDecl(); 17075 } 17076 if (Record && FDTTy->getDecl()->hasObjectMember()) 17077 Record->setHasObjectMember(true); 17078 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17079 Record->setHasVolatileMember(true); 17080 } else if (FDTy->isObjCObjectType()) { 17081 /// A field cannot be an Objective-c object 17082 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17083 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17084 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17085 FD->setType(T); 17086 } else if (Record && Record->isUnion() && 17087 FD->getType().hasNonTrivialObjCLifetime() && 17088 getSourceManager().isInSystemHeader(FD->getLocation()) && 17089 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17090 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17091 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17092 // For backward compatibility, fields of C unions declared in system 17093 // headers that have non-trivial ObjC ownership qualifications are marked 17094 // as unavailable unless the qualifier is explicit and __strong. This can 17095 // break ABI compatibility between programs compiled with ARC and MRR, but 17096 // is a better option than rejecting programs using those unions under 17097 // ARC. 17098 FD->addAttr(UnavailableAttr::CreateImplicit( 17099 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17100 FD->getLocation())); 17101 } else if (getLangOpts().ObjC && 17102 getLangOpts().getGC() != LangOptions::NonGC && Record && 17103 !Record->hasObjectMember()) { 17104 if (FD->getType()->isObjCObjectPointerType() || 17105 FD->getType().isObjCGCStrong()) 17106 Record->setHasObjectMember(true); 17107 else if (Context.getAsArrayType(FD->getType())) { 17108 QualType BaseType = Context.getBaseElementType(FD->getType()); 17109 if (BaseType->isRecordType() && 17110 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17111 Record->setHasObjectMember(true); 17112 else if (BaseType->isObjCObjectPointerType() || 17113 BaseType.isObjCGCStrong()) 17114 Record->setHasObjectMember(true); 17115 } 17116 } 17117 17118 if (Record && !getLangOpts().CPlusPlus && 17119 !shouldIgnoreForRecordTriviality(FD)) { 17120 QualType FT = FD->getType(); 17121 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17122 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17123 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17124 Record->isUnion()) 17125 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17126 } 17127 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17128 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17129 Record->setNonTrivialToPrimitiveCopy(true); 17130 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17131 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17132 } 17133 if (FT.isDestructedType()) { 17134 Record->setNonTrivialToPrimitiveDestroy(true); 17135 Record->setParamDestroyedInCallee(true); 17136 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17137 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17138 } 17139 17140 if (const auto *RT = FT->getAs<RecordType>()) { 17141 if (RT->getDecl()->getArgPassingRestrictions() == 17142 RecordDecl::APK_CanNeverPassInRegs) 17143 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17144 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17145 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17146 } 17147 17148 if (Record && FD->getType().isVolatileQualified()) 17149 Record->setHasVolatileMember(true); 17150 // Keep track of the number of named members. 17151 if (FD->getIdentifier()) 17152 ++NumNamedMembers; 17153 } 17154 17155 // Okay, we successfully defined 'Record'. 17156 if (Record) { 17157 bool Completed = false; 17158 if (CXXRecord) { 17159 if (!CXXRecord->isInvalidDecl()) { 17160 // Set access bits correctly on the directly-declared conversions. 17161 for (CXXRecordDecl::conversion_iterator 17162 I = CXXRecord->conversion_begin(), 17163 E = CXXRecord->conversion_end(); I != E; ++I) 17164 I.setAccess((*I)->getAccess()); 17165 } 17166 17167 if (!CXXRecord->isDependentType()) { 17168 // Add any implicitly-declared members to this class. 17169 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17170 17171 if (!CXXRecord->isInvalidDecl()) { 17172 // If we have virtual base classes, we may end up finding multiple 17173 // final overriders for a given virtual function. Check for this 17174 // problem now. 17175 if (CXXRecord->getNumVBases()) { 17176 CXXFinalOverriderMap FinalOverriders; 17177 CXXRecord->getFinalOverriders(FinalOverriders); 17178 17179 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17180 MEnd = FinalOverriders.end(); 17181 M != MEnd; ++M) { 17182 for (OverridingMethods::iterator SO = M->second.begin(), 17183 SOEnd = M->second.end(); 17184 SO != SOEnd; ++SO) { 17185 assert(SO->second.size() > 0 && 17186 "Virtual function without overriding functions?"); 17187 if (SO->second.size() == 1) 17188 continue; 17189 17190 // C++ [class.virtual]p2: 17191 // In a derived class, if a virtual member function of a base 17192 // class subobject has more than one final overrider the 17193 // program is ill-formed. 17194 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17195 << (const NamedDecl *)M->first << Record; 17196 Diag(M->first->getLocation(), 17197 diag::note_overridden_virtual_function); 17198 for (OverridingMethods::overriding_iterator 17199 OM = SO->second.begin(), 17200 OMEnd = SO->second.end(); 17201 OM != OMEnd; ++OM) 17202 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17203 << (const NamedDecl *)M->first << OM->Method->getParent(); 17204 17205 Record->setInvalidDecl(); 17206 } 17207 } 17208 CXXRecord->completeDefinition(&FinalOverriders); 17209 Completed = true; 17210 } 17211 } 17212 } 17213 } 17214 17215 if (!Completed) 17216 Record->completeDefinition(); 17217 17218 // Handle attributes before checking the layout. 17219 ProcessDeclAttributeList(S, Record, Attrs); 17220 17221 // We may have deferred checking for a deleted destructor. Check now. 17222 if (CXXRecord) { 17223 auto *Dtor = CXXRecord->getDestructor(); 17224 if (Dtor && Dtor->isImplicit() && 17225 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17226 CXXRecord->setImplicitDestructorIsDeleted(); 17227 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17228 } 17229 } 17230 17231 if (Record->hasAttrs()) { 17232 CheckAlignasUnderalignment(Record); 17233 17234 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17235 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17236 IA->getRange(), IA->getBestCase(), 17237 IA->getInheritanceModel()); 17238 } 17239 17240 // Check if the structure/union declaration is a type that can have zero 17241 // size in C. For C this is a language extension, for C++ it may cause 17242 // compatibility problems. 17243 bool CheckForZeroSize; 17244 if (!getLangOpts().CPlusPlus) { 17245 CheckForZeroSize = true; 17246 } else { 17247 // For C++ filter out types that cannot be referenced in C code. 17248 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17249 CheckForZeroSize = 17250 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17251 !CXXRecord->isDependentType() && 17252 CXXRecord->isCLike(); 17253 } 17254 if (CheckForZeroSize) { 17255 bool ZeroSize = true; 17256 bool IsEmpty = true; 17257 unsigned NonBitFields = 0; 17258 for (RecordDecl::field_iterator I = Record->field_begin(), 17259 E = Record->field_end(); 17260 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17261 IsEmpty = false; 17262 if (I->isUnnamedBitfield()) { 17263 if (!I->isZeroLengthBitField(Context)) 17264 ZeroSize = false; 17265 } else { 17266 ++NonBitFields; 17267 QualType FieldType = I->getType(); 17268 if (FieldType->isIncompleteType() || 17269 !Context.getTypeSizeInChars(FieldType).isZero()) 17270 ZeroSize = false; 17271 } 17272 } 17273 17274 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17275 // allowed in C++, but warn if its declaration is inside 17276 // extern "C" block. 17277 if (ZeroSize) { 17278 Diag(RecLoc, getLangOpts().CPlusPlus ? 17279 diag::warn_zero_size_struct_union_in_extern_c : 17280 diag::warn_zero_size_struct_union_compat) 17281 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17282 } 17283 17284 // Structs without named members are extension in C (C99 6.7.2.1p7), 17285 // but are accepted by GCC. 17286 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17287 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17288 diag::ext_no_named_members_in_struct_union) 17289 << Record->isUnion(); 17290 } 17291 } 17292 } else { 17293 ObjCIvarDecl **ClsFields = 17294 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17295 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17296 ID->setEndOfDefinitionLoc(RBrac); 17297 // Add ivar's to class's DeclContext. 17298 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17299 ClsFields[i]->setLexicalDeclContext(ID); 17300 ID->addDecl(ClsFields[i]); 17301 } 17302 // Must enforce the rule that ivars in the base classes may not be 17303 // duplicates. 17304 if (ID->getSuperClass()) 17305 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17306 } else if (ObjCImplementationDecl *IMPDecl = 17307 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17308 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17309 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17310 // Ivar declared in @implementation never belongs to the implementation. 17311 // Only it is in implementation's lexical context. 17312 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17313 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17314 IMPDecl->setIvarLBraceLoc(LBrac); 17315 IMPDecl->setIvarRBraceLoc(RBrac); 17316 } else if (ObjCCategoryDecl *CDecl = 17317 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17318 // case of ivars in class extension; all other cases have been 17319 // reported as errors elsewhere. 17320 // FIXME. Class extension does not have a LocEnd field. 17321 // CDecl->setLocEnd(RBrac); 17322 // Add ivar's to class extension's DeclContext. 17323 // Diagnose redeclaration of private ivars. 17324 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17325 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17326 if (IDecl) { 17327 if (const ObjCIvarDecl *ClsIvar = 17328 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17329 Diag(ClsFields[i]->getLocation(), 17330 diag::err_duplicate_ivar_declaration); 17331 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17332 continue; 17333 } 17334 for (const auto *Ext : IDecl->known_extensions()) { 17335 if (const ObjCIvarDecl *ClsExtIvar 17336 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17337 Diag(ClsFields[i]->getLocation(), 17338 diag::err_duplicate_ivar_declaration); 17339 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17340 continue; 17341 } 17342 } 17343 } 17344 ClsFields[i]->setLexicalDeclContext(CDecl); 17345 CDecl->addDecl(ClsFields[i]); 17346 } 17347 CDecl->setIvarLBraceLoc(LBrac); 17348 CDecl->setIvarRBraceLoc(RBrac); 17349 } 17350 } 17351 } 17352 17353 /// Determine whether the given integral value is representable within 17354 /// the given type T. 17355 static bool isRepresentableIntegerValue(ASTContext &Context, 17356 llvm::APSInt &Value, 17357 QualType T) { 17358 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17359 "Integral type required!"); 17360 unsigned BitWidth = Context.getIntWidth(T); 17361 17362 if (Value.isUnsigned() || Value.isNonNegative()) { 17363 if (T->isSignedIntegerOrEnumerationType()) 17364 --BitWidth; 17365 return Value.getActiveBits() <= BitWidth; 17366 } 17367 return Value.getMinSignedBits() <= BitWidth; 17368 } 17369 17370 // Given an integral type, return the next larger integral type 17371 // (or a NULL type of no such type exists). 17372 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17373 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17374 // enum checking below. 17375 assert((T->isIntegralType(Context) || 17376 T->isEnumeralType()) && "Integral type required!"); 17377 const unsigned NumTypes = 4; 17378 QualType SignedIntegralTypes[NumTypes] = { 17379 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17380 }; 17381 QualType UnsignedIntegralTypes[NumTypes] = { 17382 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17383 Context.UnsignedLongLongTy 17384 }; 17385 17386 unsigned BitWidth = Context.getTypeSize(T); 17387 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17388 : UnsignedIntegralTypes; 17389 for (unsigned I = 0; I != NumTypes; ++I) 17390 if (Context.getTypeSize(Types[I]) > BitWidth) 17391 return Types[I]; 17392 17393 return QualType(); 17394 } 17395 17396 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17397 EnumConstantDecl *LastEnumConst, 17398 SourceLocation IdLoc, 17399 IdentifierInfo *Id, 17400 Expr *Val) { 17401 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17402 llvm::APSInt EnumVal(IntWidth); 17403 QualType EltTy; 17404 17405 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17406 Val = nullptr; 17407 17408 if (Val) 17409 Val = DefaultLvalueConversion(Val).get(); 17410 17411 if (Val) { 17412 if (Enum->isDependentType() || Val->isTypeDependent()) 17413 EltTy = Context.DependentTy; 17414 else { 17415 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17416 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17417 // constant-expression in the enumerator-definition shall be a converted 17418 // constant expression of the underlying type. 17419 EltTy = Enum->getIntegerType(); 17420 ExprResult Converted = 17421 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17422 CCEK_Enumerator); 17423 if (Converted.isInvalid()) 17424 Val = nullptr; 17425 else 17426 Val = Converted.get(); 17427 } else if (!Val->isValueDependent() && 17428 !(Val = VerifyIntegerConstantExpression(Val, 17429 &EnumVal).get())) { 17430 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17431 } else { 17432 if (Enum->isComplete()) { 17433 EltTy = Enum->getIntegerType(); 17434 17435 // In Obj-C and Microsoft mode, require the enumeration value to be 17436 // representable in the underlying type of the enumeration. In C++11, 17437 // we perform a non-narrowing conversion as part of converted constant 17438 // expression checking. 17439 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17440 if (Context.getTargetInfo() 17441 .getTriple() 17442 .isWindowsMSVCEnvironment()) { 17443 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17444 } else { 17445 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17446 } 17447 } 17448 17449 // Cast to the underlying type. 17450 Val = ImpCastExprToType(Val, EltTy, 17451 EltTy->isBooleanType() ? CK_IntegralToBoolean 17452 : CK_IntegralCast) 17453 .get(); 17454 } else if (getLangOpts().CPlusPlus) { 17455 // C++11 [dcl.enum]p5: 17456 // If the underlying type is not fixed, the type of each enumerator 17457 // is the type of its initializing value: 17458 // - If an initializer is specified for an enumerator, the 17459 // initializing value has the same type as the expression. 17460 EltTy = Val->getType(); 17461 } else { 17462 // C99 6.7.2.2p2: 17463 // The expression that defines the value of an enumeration constant 17464 // shall be an integer constant expression that has a value 17465 // representable as an int. 17466 17467 // Complain if the value is not representable in an int. 17468 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17469 Diag(IdLoc, diag::ext_enum_value_not_int) 17470 << EnumVal.toString(10) << Val->getSourceRange() 17471 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17472 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17473 // Force the type of the expression to 'int'. 17474 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17475 } 17476 EltTy = Val->getType(); 17477 } 17478 } 17479 } 17480 } 17481 17482 if (!Val) { 17483 if (Enum->isDependentType()) 17484 EltTy = Context.DependentTy; 17485 else if (!LastEnumConst) { 17486 // C++0x [dcl.enum]p5: 17487 // If the underlying type is not fixed, the type of each enumerator 17488 // is the type of its initializing value: 17489 // - If no initializer is specified for the first enumerator, the 17490 // initializing value has an unspecified integral type. 17491 // 17492 // GCC uses 'int' for its unspecified integral type, as does 17493 // C99 6.7.2.2p3. 17494 if (Enum->isFixed()) { 17495 EltTy = Enum->getIntegerType(); 17496 } 17497 else { 17498 EltTy = Context.IntTy; 17499 } 17500 } else { 17501 // Assign the last value + 1. 17502 EnumVal = LastEnumConst->getInitVal(); 17503 ++EnumVal; 17504 EltTy = LastEnumConst->getType(); 17505 17506 // Check for overflow on increment. 17507 if (EnumVal < LastEnumConst->getInitVal()) { 17508 // C++0x [dcl.enum]p5: 17509 // If the underlying type is not fixed, the type of each enumerator 17510 // is the type of its initializing value: 17511 // 17512 // - Otherwise the type of the initializing value is the same as 17513 // the type of the initializing value of the preceding enumerator 17514 // unless the incremented value is not representable in that type, 17515 // in which case the type is an unspecified integral type 17516 // sufficient to contain the incremented value. If no such type 17517 // exists, the program is ill-formed. 17518 QualType T = getNextLargerIntegralType(Context, EltTy); 17519 if (T.isNull() || Enum->isFixed()) { 17520 // There is no integral type larger enough to represent this 17521 // value. Complain, then allow the value to wrap around. 17522 EnumVal = LastEnumConst->getInitVal(); 17523 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17524 ++EnumVal; 17525 if (Enum->isFixed()) 17526 // When the underlying type is fixed, this is ill-formed. 17527 Diag(IdLoc, diag::err_enumerator_wrapped) 17528 << EnumVal.toString(10) 17529 << EltTy; 17530 else 17531 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17532 << EnumVal.toString(10); 17533 } else { 17534 EltTy = T; 17535 } 17536 17537 // Retrieve the last enumerator's value, extent that type to the 17538 // type that is supposed to be large enough to represent the incremented 17539 // value, then increment. 17540 EnumVal = LastEnumConst->getInitVal(); 17541 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17542 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17543 ++EnumVal; 17544 17545 // If we're not in C++, diagnose the overflow of enumerator values, 17546 // which in C99 means that the enumerator value is not representable in 17547 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17548 // permits enumerator values that are representable in some larger 17549 // integral type. 17550 if (!getLangOpts().CPlusPlus && !T.isNull()) 17551 Diag(IdLoc, diag::warn_enum_value_overflow); 17552 } else if (!getLangOpts().CPlusPlus && 17553 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17554 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17555 Diag(IdLoc, diag::ext_enum_value_not_int) 17556 << EnumVal.toString(10) << 1; 17557 } 17558 } 17559 } 17560 17561 if (!EltTy->isDependentType()) { 17562 // Make the enumerator value match the signedness and size of the 17563 // enumerator's type. 17564 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17565 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17566 } 17567 17568 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17569 Val, EnumVal); 17570 } 17571 17572 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17573 SourceLocation IILoc) { 17574 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17575 !getLangOpts().CPlusPlus) 17576 return SkipBodyInfo(); 17577 17578 // We have an anonymous enum definition. Look up the first enumerator to 17579 // determine if we should merge the definition with an existing one and 17580 // skip the body. 17581 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17582 forRedeclarationInCurContext()); 17583 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17584 if (!PrevECD) 17585 return SkipBodyInfo(); 17586 17587 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17588 NamedDecl *Hidden; 17589 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17590 SkipBodyInfo Skip; 17591 Skip.Previous = Hidden; 17592 return Skip; 17593 } 17594 17595 return SkipBodyInfo(); 17596 } 17597 17598 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17599 SourceLocation IdLoc, IdentifierInfo *Id, 17600 const ParsedAttributesView &Attrs, 17601 SourceLocation EqualLoc, Expr *Val) { 17602 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17603 EnumConstantDecl *LastEnumConst = 17604 cast_or_null<EnumConstantDecl>(lastEnumConst); 17605 17606 // The scope passed in may not be a decl scope. Zip up the scope tree until 17607 // we find one that is. 17608 S = getNonFieldDeclScope(S); 17609 17610 // Verify that there isn't already something declared with this name in this 17611 // scope. 17612 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17613 LookupName(R, S); 17614 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17615 17616 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17617 // Maybe we will complain about the shadowed template parameter. 17618 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17619 // Just pretend that we didn't see the previous declaration. 17620 PrevDecl = nullptr; 17621 } 17622 17623 // C++ [class.mem]p15: 17624 // If T is the name of a class, then each of the following shall have a name 17625 // different from T: 17626 // - every enumerator of every member of class T that is an unscoped 17627 // enumerated type 17628 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17629 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17630 DeclarationNameInfo(Id, IdLoc)); 17631 17632 EnumConstantDecl *New = 17633 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17634 if (!New) 17635 return nullptr; 17636 17637 if (PrevDecl) { 17638 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17639 // Check for other kinds of shadowing not already handled. 17640 CheckShadow(New, PrevDecl, R); 17641 } 17642 17643 // When in C++, we may get a TagDecl with the same name; in this case the 17644 // enum constant will 'hide' the tag. 17645 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17646 "Received TagDecl when not in C++!"); 17647 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17648 if (isa<EnumConstantDecl>(PrevDecl)) 17649 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17650 else 17651 Diag(IdLoc, diag::err_redefinition) << Id; 17652 notePreviousDefinition(PrevDecl, IdLoc); 17653 return nullptr; 17654 } 17655 } 17656 17657 // Process attributes. 17658 ProcessDeclAttributeList(S, New, Attrs); 17659 AddPragmaAttributes(S, New); 17660 17661 // Register this decl in the current scope stack. 17662 New->setAccess(TheEnumDecl->getAccess()); 17663 PushOnScopeChains(New, S); 17664 17665 ActOnDocumentableDecl(New); 17666 17667 return New; 17668 } 17669 17670 // Returns true when the enum initial expression does not trigger the 17671 // duplicate enum warning. A few common cases are exempted as follows: 17672 // Element2 = Element1 17673 // Element2 = Element1 + 1 17674 // Element2 = Element1 - 1 17675 // Where Element2 and Element1 are from the same enum. 17676 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17677 Expr *InitExpr = ECD->getInitExpr(); 17678 if (!InitExpr) 17679 return true; 17680 InitExpr = InitExpr->IgnoreImpCasts(); 17681 17682 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17683 if (!BO->isAdditiveOp()) 17684 return true; 17685 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17686 if (!IL) 17687 return true; 17688 if (IL->getValue() != 1) 17689 return true; 17690 17691 InitExpr = BO->getLHS(); 17692 } 17693 17694 // This checks if the elements are from the same enum. 17695 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17696 if (!DRE) 17697 return true; 17698 17699 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17700 if (!EnumConstant) 17701 return true; 17702 17703 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17704 Enum) 17705 return true; 17706 17707 return false; 17708 } 17709 17710 // Emits a warning when an element is implicitly set a value that 17711 // a previous element has already been set to. 17712 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17713 EnumDecl *Enum, QualType EnumType) { 17714 // Avoid anonymous enums 17715 if (!Enum->getIdentifier()) 17716 return; 17717 17718 // Only check for small enums. 17719 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17720 return; 17721 17722 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17723 return; 17724 17725 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17726 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17727 17728 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17729 17730 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 17731 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17732 17733 // Use int64_t as a key to avoid needing special handling for map keys. 17734 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17735 llvm::APSInt Val = D->getInitVal(); 17736 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17737 }; 17738 17739 DuplicatesVector DupVector; 17740 ValueToVectorMap EnumMap; 17741 17742 // Populate the EnumMap with all values represented by enum constants without 17743 // an initializer. 17744 for (auto *Element : Elements) { 17745 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17746 17747 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17748 // this constant. Skip this enum since it may be ill-formed. 17749 if (!ECD) { 17750 return; 17751 } 17752 17753 // Constants with initalizers are handled in the next loop. 17754 if (ECD->getInitExpr()) 17755 continue; 17756 17757 // Duplicate values are handled in the next loop. 17758 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17759 } 17760 17761 if (EnumMap.size() == 0) 17762 return; 17763 17764 // Create vectors for any values that has duplicates. 17765 for (auto *Element : Elements) { 17766 // The last loop returned if any constant was null. 17767 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17768 if (!ValidDuplicateEnum(ECD, Enum)) 17769 continue; 17770 17771 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17772 if (Iter == EnumMap.end()) 17773 continue; 17774 17775 DeclOrVector& Entry = Iter->second; 17776 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17777 // Ensure constants are different. 17778 if (D == ECD) 17779 continue; 17780 17781 // Create new vector and push values onto it. 17782 auto Vec = std::make_unique<ECDVector>(); 17783 Vec->push_back(D); 17784 Vec->push_back(ECD); 17785 17786 // Update entry to point to the duplicates vector. 17787 Entry = Vec.get(); 17788 17789 // Store the vector somewhere we can consult later for quick emission of 17790 // diagnostics. 17791 DupVector.emplace_back(std::move(Vec)); 17792 continue; 17793 } 17794 17795 ECDVector *Vec = Entry.get<ECDVector*>(); 17796 // Make sure constants are not added more than once. 17797 if (*Vec->begin() == ECD) 17798 continue; 17799 17800 Vec->push_back(ECD); 17801 } 17802 17803 // Emit diagnostics. 17804 for (const auto &Vec : DupVector) { 17805 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 17806 17807 // Emit warning for one enum constant. 17808 auto *FirstECD = Vec->front(); 17809 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 17810 << FirstECD << FirstECD->getInitVal().toString(10) 17811 << FirstECD->getSourceRange(); 17812 17813 // Emit one note for each of the remaining enum constants with 17814 // the same value. 17815 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 17816 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 17817 << ECD << ECD->getInitVal().toString(10) 17818 << ECD->getSourceRange(); 17819 } 17820 } 17821 17822 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 17823 bool AllowMask) const { 17824 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 17825 assert(ED->isCompleteDefinition() && "expected enum definition"); 17826 17827 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 17828 llvm::APInt &FlagBits = R.first->second; 17829 17830 if (R.second) { 17831 for (auto *E : ED->enumerators()) { 17832 const auto &EVal = E->getInitVal(); 17833 // Only single-bit enumerators introduce new flag values. 17834 if (EVal.isPowerOf2()) 17835 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 17836 } 17837 } 17838 17839 // A value is in a flag enum if either its bits are a subset of the enum's 17840 // flag bits (the first condition) or we are allowing masks and the same is 17841 // true of its complement (the second condition). When masks are allowed, we 17842 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 17843 // 17844 // While it's true that any value could be used as a mask, the assumption is 17845 // that a mask will have all of the insignificant bits set. Anything else is 17846 // likely a logic error. 17847 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 17848 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 17849 } 17850 17851 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 17852 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 17853 const ParsedAttributesView &Attrs) { 17854 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 17855 QualType EnumType = Context.getTypeDeclType(Enum); 17856 17857 ProcessDeclAttributeList(S, Enum, Attrs); 17858 17859 if (Enum->isDependentType()) { 17860 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17861 EnumConstantDecl *ECD = 17862 cast_or_null<EnumConstantDecl>(Elements[i]); 17863 if (!ECD) continue; 17864 17865 ECD->setType(EnumType); 17866 } 17867 17868 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 17869 return; 17870 } 17871 17872 // TODO: If the result value doesn't fit in an int, it must be a long or long 17873 // long value. ISO C does not support this, but GCC does as an extension, 17874 // emit a warning. 17875 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17876 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 17877 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 17878 17879 // Verify that all the values are okay, compute the size of the values, and 17880 // reverse the list. 17881 unsigned NumNegativeBits = 0; 17882 unsigned NumPositiveBits = 0; 17883 17884 // Keep track of whether all elements have type int. 17885 bool AllElementsInt = true; 17886 17887 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17888 EnumConstantDecl *ECD = 17889 cast_or_null<EnumConstantDecl>(Elements[i]); 17890 if (!ECD) continue; // Already issued a diagnostic. 17891 17892 const llvm::APSInt &InitVal = ECD->getInitVal(); 17893 17894 // Keep track of the size of positive and negative values. 17895 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 17896 NumPositiveBits = std::max(NumPositiveBits, 17897 (unsigned)InitVal.getActiveBits()); 17898 else 17899 NumNegativeBits = std::max(NumNegativeBits, 17900 (unsigned)InitVal.getMinSignedBits()); 17901 17902 // Keep track of whether every enum element has type int (very common). 17903 if (AllElementsInt) 17904 AllElementsInt = ECD->getType() == Context.IntTy; 17905 } 17906 17907 // Figure out the type that should be used for this enum. 17908 QualType BestType; 17909 unsigned BestWidth; 17910 17911 // C++0x N3000 [conv.prom]p3: 17912 // An rvalue of an unscoped enumeration type whose underlying 17913 // type is not fixed can be converted to an rvalue of the first 17914 // of the following types that can represent all the values of 17915 // the enumeration: int, unsigned int, long int, unsigned long 17916 // int, long long int, or unsigned long long int. 17917 // C99 6.4.4.3p2: 17918 // An identifier declared as an enumeration constant has type int. 17919 // The C99 rule is modified by a gcc extension 17920 QualType BestPromotionType; 17921 17922 bool Packed = Enum->hasAttr<PackedAttr>(); 17923 // -fshort-enums is the equivalent to specifying the packed attribute on all 17924 // enum definitions. 17925 if (LangOpts.ShortEnums) 17926 Packed = true; 17927 17928 // If the enum already has a type because it is fixed or dictated by the 17929 // target, promote that type instead of analyzing the enumerators. 17930 if (Enum->isComplete()) { 17931 BestType = Enum->getIntegerType(); 17932 if (BestType->isPromotableIntegerType()) 17933 BestPromotionType = Context.getPromotedIntegerType(BestType); 17934 else 17935 BestPromotionType = BestType; 17936 17937 BestWidth = Context.getIntWidth(BestType); 17938 } 17939 else if (NumNegativeBits) { 17940 // If there is a negative value, figure out the smallest integer type (of 17941 // int/long/longlong) that fits. 17942 // If it's packed, check also if it fits a char or a short. 17943 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 17944 BestType = Context.SignedCharTy; 17945 BestWidth = CharWidth; 17946 } else if (Packed && NumNegativeBits <= ShortWidth && 17947 NumPositiveBits < ShortWidth) { 17948 BestType = Context.ShortTy; 17949 BestWidth = ShortWidth; 17950 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 17951 BestType = Context.IntTy; 17952 BestWidth = IntWidth; 17953 } else { 17954 BestWidth = Context.getTargetInfo().getLongWidth(); 17955 17956 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 17957 BestType = Context.LongTy; 17958 } else { 17959 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17960 17961 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 17962 Diag(Enum->getLocation(), diag::ext_enum_too_large); 17963 BestType = Context.LongLongTy; 17964 } 17965 } 17966 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 17967 } else { 17968 // If there is no negative value, figure out the smallest type that fits 17969 // all of the enumerator values. 17970 // If it's packed, check also if it fits a char or a short. 17971 if (Packed && NumPositiveBits <= CharWidth) { 17972 BestType = Context.UnsignedCharTy; 17973 BestPromotionType = Context.IntTy; 17974 BestWidth = CharWidth; 17975 } else if (Packed && NumPositiveBits <= ShortWidth) { 17976 BestType = Context.UnsignedShortTy; 17977 BestPromotionType = Context.IntTy; 17978 BestWidth = ShortWidth; 17979 } else if (NumPositiveBits <= IntWidth) { 17980 BestType = Context.UnsignedIntTy; 17981 BestWidth = IntWidth; 17982 BestPromotionType 17983 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17984 ? Context.UnsignedIntTy : Context.IntTy; 17985 } else if (NumPositiveBits <= 17986 (BestWidth = Context.getTargetInfo().getLongWidth())) { 17987 BestType = Context.UnsignedLongTy; 17988 BestPromotionType 17989 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17990 ? Context.UnsignedLongTy : Context.LongTy; 17991 } else { 17992 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17993 assert(NumPositiveBits <= BestWidth && 17994 "How could an initializer get larger than ULL?"); 17995 BestType = Context.UnsignedLongLongTy; 17996 BestPromotionType 17997 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17998 ? Context.UnsignedLongLongTy : Context.LongLongTy; 17999 } 18000 } 18001 18002 // Loop over all of the enumerator constants, changing their types to match 18003 // the type of the enum if needed. 18004 for (auto *D : Elements) { 18005 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18006 if (!ECD) continue; // Already issued a diagnostic. 18007 18008 // Standard C says the enumerators have int type, but we allow, as an 18009 // extension, the enumerators to be larger than int size. If each 18010 // enumerator value fits in an int, type it as an int, otherwise type it the 18011 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18012 // that X has type 'int', not 'unsigned'. 18013 18014 // Determine whether the value fits into an int. 18015 llvm::APSInt InitVal = ECD->getInitVal(); 18016 18017 // If it fits into an integer type, force it. Otherwise force it to match 18018 // the enum decl type. 18019 QualType NewTy; 18020 unsigned NewWidth; 18021 bool NewSign; 18022 if (!getLangOpts().CPlusPlus && 18023 !Enum->isFixed() && 18024 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18025 NewTy = Context.IntTy; 18026 NewWidth = IntWidth; 18027 NewSign = true; 18028 } else if (ECD->getType() == BestType) { 18029 // Already the right type! 18030 if (getLangOpts().CPlusPlus) 18031 // C++ [dcl.enum]p4: Following the closing brace of an 18032 // enum-specifier, each enumerator has the type of its 18033 // enumeration. 18034 ECD->setType(EnumType); 18035 continue; 18036 } else { 18037 NewTy = BestType; 18038 NewWidth = BestWidth; 18039 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18040 } 18041 18042 // Adjust the APSInt value. 18043 InitVal = InitVal.extOrTrunc(NewWidth); 18044 InitVal.setIsSigned(NewSign); 18045 ECD->setInitVal(InitVal); 18046 18047 // Adjust the Expr initializer and type. 18048 if (ECD->getInitExpr() && 18049 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18050 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 18051 CK_IntegralCast, 18052 ECD->getInitExpr(), 18053 /*base paths*/ nullptr, 18054 VK_RValue)); 18055 if (getLangOpts().CPlusPlus) 18056 // C++ [dcl.enum]p4: Following the closing brace of an 18057 // enum-specifier, each enumerator has the type of its 18058 // enumeration. 18059 ECD->setType(EnumType); 18060 else 18061 ECD->setType(NewTy); 18062 } 18063 18064 Enum->completeDefinition(BestType, BestPromotionType, 18065 NumPositiveBits, NumNegativeBits); 18066 18067 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18068 18069 if (Enum->isClosedFlag()) { 18070 for (Decl *D : Elements) { 18071 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18072 if (!ECD) continue; // Already issued a diagnostic. 18073 18074 llvm::APSInt InitVal = ECD->getInitVal(); 18075 if (InitVal != 0 && !InitVal.isPowerOf2() && 18076 !IsValueInFlagEnum(Enum, InitVal, true)) 18077 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18078 << ECD << Enum; 18079 } 18080 } 18081 18082 // Now that the enum type is defined, ensure it's not been underaligned. 18083 if (Enum->hasAttrs()) 18084 CheckAlignasUnderalignment(Enum); 18085 } 18086 18087 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18088 SourceLocation StartLoc, 18089 SourceLocation EndLoc) { 18090 StringLiteral *AsmString = cast<StringLiteral>(expr); 18091 18092 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18093 AsmString, StartLoc, 18094 EndLoc); 18095 CurContext->addDecl(New); 18096 return New; 18097 } 18098 18099 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18100 IdentifierInfo* AliasName, 18101 SourceLocation PragmaLoc, 18102 SourceLocation NameLoc, 18103 SourceLocation AliasNameLoc) { 18104 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18105 LookupOrdinaryName); 18106 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18107 AttributeCommonInfo::AS_Pragma); 18108 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18109 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18110 18111 // If a declaration that: 18112 // 1) declares a function or a variable 18113 // 2) has external linkage 18114 // already exists, add a label attribute to it. 18115 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18116 if (isDeclExternC(PrevDecl)) 18117 PrevDecl->addAttr(Attr); 18118 else 18119 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18120 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18121 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18122 } else 18123 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18124 } 18125 18126 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18127 SourceLocation PragmaLoc, 18128 SourceLocation NameLoc) { 18129 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18130 18131 if (PrevDecl) { 18132 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18133 } else { 18134 (void)WeakUndeclaredIdentifiers.insert( 18135 std::pair<IdentifierInfo*,WeakInfo> 18136 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18137 } 18138 } 18139 18140 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18141 IdentifierInfo* AliasName, 18142 SourceLocation PragmaLoc, 18143 SourceLocation NameLoc, 18144 SourceLocation AliasNameLoc) { 18145 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18146 LookupOrdinaryName); 18147 WeakInfo W = WeakInfo(Name, NameLoc); 18148 18149 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18150 if (!PrevDecl->hasAttr<AliasAttr>()) 18151 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18152 DeclApplyPragmaWeak(TUScope, ND, W); 18153 } else { 18154 (void)WeakUndeclaredIdentifiers.insert( 18155 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18156 } 18157 } 18158 18159 Decl *Sema::getObjCDeclContext() const { 18160 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18161 } 18162 18163 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18164 bool Final) { 18165 // SYCL functions can be template, so we check if they have appropriate 18166 // attribute prior to checking if it is a template. 18167 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18168 return FunctionEmissionStatus::Emitted; 18169 18170 // Templates are emitted when they're instantiated. 18171 if (FD->isDependentContext()) 18172 return FunctionEmissionStatus::TemplateDiscarded; 18173 18174 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; 18175 if (LangOpts.OpenMPIsDevice) { 18176 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18177 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18178 if (DevTy.hasValue()) { 18179 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18180 OMPES = FunctionEmissionStatus::OMPDiscarded; 18181 else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost || 18182 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) { 18183 OMPES = FunctionEmissionStatus::Emitted; 18184 } 18185 } 18186 } else if (LangOpts.OpenMP) { 18187 // In OpenMP 4.5 all the functions are host functions. 18188 if (LangOpts.OpenMP <= 45) { 18189 OMPES = FunctionEmissionStatus::Emitted; 18190 } else { 18191 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18192 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18193 // In OpenMP 5.0 or above, DevTy may be changed later by 18194 // #pragma omp declare target to(*) device_type(*). Therefore DevTy 18195 // having no value does not imply host. The emission status will be 18196 // checked again at the end of compilation unit. 18197 if (DevTy.hasValue()) { 18198 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 18199 OMPES = FunctionEmissionStatus::OMPDiscarded; 18200 } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host || 18201 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) 18202 OMPES = FunctionEmissionStatus::Emitted; 18203 } else if (Final) 18204 OMPES = FunctionEmissionStatus::Emitted; 18205 } 18206 } 18207 if (OMPES == FunctionEmissionStatus::OMPDiscarded || 18208 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) 18209 return OMPES; 18210 18211 if (LangOpts.CUDA) { 18212 // When compiling for device, host functions are never emitted. Similarly, 18213 // when compiling for host, device and global functions are never emitted. 18214 // (Technically, we do emit a host-side stub for global functions, but this 18215 // doesn't count for our purposes here.) 18216 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18217 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18218 return FunctionEmissionStatus::CUDADiscarded; 18219 if (!LangOpts.CUDAIsDevice && 18220 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18221 return FunctionEmissionStatus::CUDADiscarded; 18222 18223 // Check whether this function is externally visible -- if so, it's 18224 // known-emitted. 18225 // 18226 // We have to check the GVA linkage of the function's *definition* -- if we 18227 // only have a declaration, we don't know whether or not the function will 18228 // be emitted, because (say) the definition could include "inline". 18229 FunctionDecl *Def = FD->getDefinition(); 18230 18231 if (Def && 18232 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) 18233 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) 18234 return FunctionEmissionStatus::Emitted; 18235 } 18236 18237 // Otherwise, the function is known-emitted if it's in our set of 18238 // known-emitted functions. 18239 return FunctionEmissionStatus::Unknown; 18240 } 18241 18242 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18243 // Host-side references to a __global__ function refer to the stub, so the 18244 // function itself is never emitted and therefore should not be marked. 18245 // If we have host fn calls kernel fn calls host+device, the HD function 18246 // does not get instantiated on the host. We model this by omitting at the 18247 // call to the kernel from the callgraph. This ensures that, when compiling 18248 // for host, only HD functions actually called from the host get marked as 18249 // known-emitted. 18250 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18251 IdentifyCUDATarget(Callee) == CFT_Global; 18252 } 18253