1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TypeLocBuilder.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/CommentDiagnostic.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/NonTrivialTypeVisitor.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 36 #include "clang/Sema/CXXFieldCollector.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaInternal.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/ADT/SmallString.h" 47 #include "llvm/ADT/Triple.h" 48 #include <algorithm> 49 #include <cstring> 50 #include <functional> 51 #include <unordered_map> 52 53 using namespace clang; 54 using namespace sema; 55 56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 57 if (OwnedType) { 58 Decl *Group[2] = { OwnedType, Ptr }; 59 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 60 } 61 62 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 63 } 64 65 namespace { 66 67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 68 public: 69 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 70 bool AllowTemplates = false, 71 bool AllowNonTemplates = true) 72 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 73 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 74 WantExpressionKeywords = false; 75 WantCXXNamedCasts = false; 76 WantRemainingKeywords = false; 77 } 78 79 bool ValidateCandidate(const TypoCorrection &candidate) override { 80 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 81 if (!AllowInvalidDecl && ND->isInvalidDecl()) 82 return false; 83 84 if (getAsTypeTemplateDecl(ND)) 85 return AllowTemplates; 86 87 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 88 if (!IsType) 89 return false; 90 91 if (AllowNonTemplates) 92 return true; 93 94 // An injected-class-name of a class template (specialization) is valid 95 // as a template or as a non-template. 96 if (AllowTemplates) { 97 auto *RD = dyn_cast<CXXRecordDecl>(ND); 98 if (!RD || !RD->isInjectedClassName()) 99 return false; 100 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 101 return RD->getDescribedClassTemplate() || 102 isa<ClassTemplateSpecializationDecl>(RD); 103 } 104 105 return false; 106 } 107 108 return !WantClassName && candidate.isKeyword(); 109 } 110 111 std::unique_ptr<CorrectionCandidateCallback> clone() override { 112 return std::make_unique<TypeNameValidatorCCC>(*this); 113 } 114 115 private: 116 bool AllowInvalidDecl; 117 bool WantClassName; 118 bool AllowTemplates; 119 bool AllowNonTemplates; 120 }; 121 122 } // end anonymous namespace 123 124 /// Determine whether the token kind starts a simple-type-specifier. 125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 126 switch (Kind) { 127 // FIXME: Take into account the current language when deciding whether a 128 // token kind is a valid type specifier 129 case tok::kw_short: 130 case tok::kw_long: 131 case tok::kw___int64: 132 case tok::kw___int128: 133 case tok::kw_signed: 134 case tok::kw_unsigned: 135 case tok::kw_void: 136 case tok::kw_char: 137 case tok::kw_int: 138 case tok::kw_half: 139 case tok::kw_float: 140 case tok::kw_double: 141 case tok::kw___bf16: 142 case tok::kw__Float16: 143 case tok::kw___float128: 144 case tok::kw_wchar_t: 145 case tok::kw_bool: 146 case tok::kw___underlying_type: 147 case tok::kw___auto_type: 148 return true; 149 150 case tok::annot_typename: 151 case tok::kw_char16_t: 152 case tok::kw_char32_t: 153 case tok::kw_typeof: 154 case tok::annot_decltype: 155 case tok::kw_decltype: 156 return getLangOpts().CPlusPlus; 157 158 case tok::kw_char8_t: 159 return getLangOpts().Char8; 160 161 default: 162 break; 163 } 164 165 return false; 166 } 167 168 namespace { 169 enum class UnqualifiedTypeNameLookupResult { 170 NotFound, 171 FoundNonType, 172 FoundType 173 }; 174 } // end anonymous namespace 175 176 /// Tries to perform unqualified lookup of the type decls in bases for 177 /// dependent class. 178 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 179 /// type decl, \a FoundType if only type decls are found. 180 static UnqualifiedTypeNameLookupResult 181 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 182 SourceLocation NameLoc, 183 const CXXRecordDecl *RD) { 184 if (!RD->hasDefinition()) 185 return UnqualifiedTypeNameLookupResult::NotFound; 186 // Look for type decls in base classes. 187 UnqualifiedTypeNameLookupResult FoundTypeDecl = 188 UnqualifiedTypeNameLookupResult::NotFound; 189 for (const auto &Base : RD->bases()) { 190 const CXXRecordDecl *BaseRD = nullptr; 191 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 192 BaseRD = BaseTT->getAsCXXRecordDecl(); 193 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 194 // Look for type decls in dependent base classes that have known primary 195 // templates. 196 if (!TST || !TST->isDependentType()) 197 continue; 198 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 199 if (!TD) 200 continue; 201 if (auto *BasePrimaryTemplate = 202 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 204 BaseRD = BasePrimaryTemplate; 205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 206 if (const ClassTemplatePartialSpecializationDecl *PS = 207 CTD->findPartialSpecialization(Base.getType())) 208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 209 BaseRD = PS; 210 } 211 } 212 } 213 if (BaseRD) { 214 for (NamedDecl *ND : BaseRD->lookup(&II)) { 215 if (!isa<TypeDecl>(ND)) 216 return UnqualifiedTypeNameLookupResult::FoundNonType; 217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 218 } 219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 221 case UnqualifiedTypeNameLookupResult::FoundNonType: 222 return UnqualifiedTypeNameLookupResult::FoundNonType; 223 case UnqualifiedTypeNameLookupResult::FoundType: 224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 225 break; 226 case UnqualifiedTypeNameLookupResult::NotFound: 227 break; 228 } 229 } 230 } 231 } 232 233 return FoundTypeDecl; 234 } 235 236 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 237 const IdentifierInfo &II, 238 SourceLocation NameLoc) { 239 // Lookup in the parent class template context, if any. 240 const CXXRecordDecl *RD = nullptr; 241 UnqualifiedTypeNameLookupResult FoundTypeDecl = 242 UnqualifiedTypeNameLookupResult::NotFound; 243 for (DeclContext *DC = S.CurContext; 244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 245 DC = DC->getParent()) { 246 // Look for type decls in dependent base classes that have known primary 247 // templates. 248 RD = dyn_cast<CXXRecordDecl>(DC); 249 if (RD && RD->getDescribedClassTemplate()) 250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 251 } 252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 253 return nullptr; 254 255 // We found some types in dependent base classes. Recover as if the user 256 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 257 // lookup during template instantiation. 258 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II; 259 260 ASTContext &Context = S.Context; 261 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 262 cast<Type>(Context.getRecordType(RD))); 263 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 264 265 CXXScopeSpec SS; 266 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 267 268 TypeLocBuilder Builder; 269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 270 DepTL.setNameLoc(NameLoc); 271 DepTL.setElaboratedKeywordLoc(SourceLocation()); 272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 273 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 274 } 275 276 /// If the identifier refers to a type name within this scope, 277 /// return the declaration of that type. 278 /// 279 /// This routine performs ordinary name lookup of the identifier II 280 /// within the given scope, with optional C++ scope specifier SS, to 281 /// determine whether the name refers to a type. If so, returns an 282 /// opaque pointer (actually a QualType) corresponding to that 283 /// type. Otherwise, returns NULL. 284 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 285 Scope *S, CXXScopeSpec *SS, 286 bool isClassName, bool HasTrailingDot, 287 ParsedType ObjectTypePtr, 288 bool IsCtorOrDtorName, 289 bool WantNontrivialTypeSourceInfo, 290 bool IsClassTemplateDeductionContext, 291 IdentifierInfo **CorrectedII) { 292 // FIXME: Consider allowing this outside C++1z mode as an extension. 293 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 294 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 295 !isClassName && !HasTrailingDot; 296 297 // Determine where we will perform name lookup. 298 DeclContext *LookupCtx = nullptr; 299 if (ObjectTypePtr) { 300 QualType ObjectType = ObjectTypePtr.get(); 301 if (ObjectType->isRecordType()) 302 LookupCtx = computeDeclContext(ObjectType); 303 } else if (SS && SS->isNotEmpty()) { 304 LookupCtx = computeDeclContext(*SS, false); 305 306 if (!LookupCtx) { 307 if (isDependentScopeSpecifier(*SS)) { 308 // C++ [temp.res]p3: 309 // A qualified-id that refers to a type and in which the 310 // nested-name-specifier depends on a template-parameter (14.6.2) 311 // shall be prefixed by the keyword typename to indicate that the 312 // qualified-id denotes a type, forming an 313 // elaborated-type-specifier (7.1.5.3). 314 // 315 // We therefore do not perform any name lookup if the result would 316 // refer to a member of an unknown specialization. 317 if (!isClassName && !IsCtorOrDtorName) 318 return nullptr; 319 320 // We know from the grammar that this name refers to a type, 321 // so build a dependent node to describe the type. 322 if (WantNontrivialTypeSourceInfo) 323 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 324 325 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 326 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 327 II, NameLoc); 328 return ParsedType::make(T); 329 } 330 331 return nullptr; 332 } 333 334 if (!LookupCtx->isDependentContext() && 335 RequireCompleteDeclContext(*SS, LookupCtx)) 336 return nullptr; 337 } 338 339 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 340 // lookup for class-names. 341 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 342 LookupOrdinaryName; 343 LookupResult Result(*this, &II, NameLoc, Kind); 344 if (LookupCtx) { 345 // Perform "qualified" name lookup into the declaration context we 346 // computed, which is either the type of the base of a member access 347 // expression or the declaration context associated with a prior 348 // nested-name-specifier. 349 LookupQualifiedName(Result, LookupCtx); 350 351 if (ObjectTypePtr && Result.empty()) { 352 // C++ [basic.lookup.classref]p3: 353 // If the unqualified-id is ~type-name, the type-name is looked up 354 // in the context of the entire postfix-expression. If the type T of 355 // the object expression is of a class type C, the type-name is also 356 // looked up in the scope of class C. At least one of the lookups shall 357 // find a name that refers to (possibly cv-qualified) T. 358 LookupName(Result, S); 359 } 360 } else { 361 // Perform unqualified name lookup. 362 LookupName(Result, S); 363 364 // For unqualified lookup in a class template in MSVC mode, look into 365 // dependent base classes where the primary class template is known. 366 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 367 if (ParsedType TypeInBase = 368 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 369 return TypeInBase; 370 } 371 } 372 373 NamedDecl *IIDecl = nullptr; 374 switch (Result.getResultKind()) { 375 case LookupResult::NotFound: 376 case LookupResult::NotFoundInCurrentInstantiation: 377 if (CorrectedII) { 378 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 379 AllowDeducedTemplate); 380 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 381 S, SS, CCC, CTK_ErrorRecovery); 382 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 383 TemplateTy Template; 384 bool MemberOfUnknownSpecialization; 385 UnqualifiedId TemplateName; 386 TemplateName.setIdentifier(NewII, NameLoc); 387 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 388 CXXScopeSpec NewSS, *NewSSPtr = SS; 389 if (SS && NNS) { 390 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 391 NewSSPtr = &NewSS; 392 } 393 if (Correction && (NNS || NewII != &II) && 394 // Ignore a correction to a template type as the to-be-corrected 395 // identifier is not a template (typo correction for template names 396 // is handled elsewhere). 397 !(getLangOpts().CPlusPlus && NewSSPtr && 398 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 399 Template, MemberOfUnknownSpecialization))) { 400 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 401 isClassName, HasTrailingDot, ObjectTypePtr, 402 IsCtorOrDtorName, 403 WantNontrivialTypeSourceInfo, 404 IsClassTemplateDeductionContext); 405 if (Ty) { 406 diagnoseTypo(Correction, 407 PDiag(diag::err_unknown_type_or_class_name_suggest) 408 << Result.getLookupName() << isClassName); 409 if (SS && NNS) 410 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 411 *CorrectedII = NewII; 412 return Ty; 413 } 414 } 415 } 416 // If typo correction failed or was not performed, fall through 417 LLVM_FALLTHROUGH; 418 case LookupResult::FoundOverloaded: 419 case LookupResult::FoundUnresolvedValue: 420 Result.suppressDiagnostics(); 421 return nullptr; 422 423 case LookupResult::Ambiguous: 424 // Recover from type-hiding ambiguities by hiding the type. We'll 425 // do the lookup again when looking for an object, and we can 426 // diagnose the error then. If we don't do this, then the error 427 // about hiding the type will be immediately followed by an error 428 // that only makes sense if the identifier was treated like a type. 429 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 430 Result.suppressDiagnostics(); 431 return nullptr; 432 } 433 434 // Look to see if we have a type anywhere in the list of results. 435 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 436 Res != ResEnd; ++Res) { 437 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 438 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 439 if (!IIDecl || (*Res)->getLocation() < IIDecl->getLocation()) 440 IIDecl = *Res; 441 } 442 } 443 444 if (!IIDecl) { 445 // None of the entities we found is a type, so there is no way 446 // to even assume that the result is a type. In this case, don't 447 // complain about the ambiguity. The parser will either try to 448 // perform this lookup again (e.g., as an object name), which 449 // will produce the ambiguity, or will complain that it expected 450 // a type name. 451 Result.suppressDiagnostics(); 452 return nullptr; 453 } 454 455 // We found a type within the ambiguous lookup; diagnose the 456 // ambiguity and then return that type. This might be the right 457 // answer, or it might not be, but it suppresses any attempt to 458 // perform the name lookup again. 459 break; 460 461 case LookupResult::Found: 462 IIDecl = Result.getFoundDecl(); 463 break; 464 } 465 466 assert(IIDecl && "Didn't find decl"); 467 468 QualType T; 469 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 470 // C++ [class.qual]p2: A lookup that would find the injected-class-name 471 // instead names the constructors of the class, except when naming a class. 472 // This is ill-formed when we're not actually forming a ctor or dtor name. 473 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 474 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 475 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 476 FoundRD->isInjectedClassName() && 477 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 478 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 479 << &II << /*Type*/1; 480 481 DiagnoseUseOfDecl(IIDecl, NameLoc); 482 483 T = Context.getTypeDeclType(TD); 484 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 485 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 486 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 487 if (!HasTrailingDot) 488 T = Context.getObjCInterfaceType(IDecl); 489 } else if (AllowDeducedTemplate) { 490 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 491 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 492 QualType(), false); 493 } 494 495 if (T.isNull()) { 496 // If it's not plausibly a type, suppress diagnostics. 497 Result.suppressDiagnostics(); 498 return nullptr; 499 } 500 501 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 502 // constructor or destructor name (in such a case, the scope specifier 503 // will be attached to the enclosing Expr or Decl node). 504 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 505 !isa<ObjCInterfaceDecl>(IIDecl)) { 506 if (WantNontrivialTypeSourceInfo) { 507 // Construct a type with type-source information. 508 TypeLocBuilder Builder; 509 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 510 511 T = getElaboratedType(ETK_None, *SS, T); 512 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 513 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 514 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 515 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 516 } else { 517 T = getElaboratedType(ETK_None, *SS, T); 518 } 519 } 520 521 return ParsedType::make(T); 522 } 523 524 // Builds a fake NNS for the given decl context. 525 static NestedNameSpecifier * 526 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 527 for (;; DC = DC->getLookupParent()) { 528 DC = DC->getPrimaryContext(); 529 auto *ND = dyn_cast<NamespaceDecl>(DC); 530 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 531 return NestedNameSpecifier::Create(Context, nullptr, ND); 532 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 533 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 534 RD->getTypeForDecl()); 535 else if (isa<TranslationUnitDecl>(DC)) 536 return NestedNameSpecifier::GlobalSpecifier(Context); 537 } 538 llvm_unreachable("something isn't in TU scope?"); 539 } 540 541 /// Find the parent class with dependent bases of the innermost enclosing method 542 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 543 /// up allowing unqualified dependent type names at class-level, which MSVC 544 /// correctly rejects. 545 static const CXXRecordDecl * 546 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 547 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 548 DC = DC->getPrimaryContext(); 549 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 550 if (MD->getParent()->hasAnyDependentBases()) 551 return MD->getParent(); 552 } 553 return nullptr; 554 } 555 556 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 557 SourceLocation NameLoc, 558 bool IsTemplateTypeArg) { 559 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 560 561 NestedNameSpecifier *NNS = nullptr; 562 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 563 // If we weren't able to parse a default template argument, delay lookup 564 // until instantiation time by making a non-dependent DependentTypeName. We 565 // pretend we saw a NestedNameSpecifier referring to the current scope, and 566 // lookup is retried. 567 // FIXME: This hurts our diagnostic quality, since we get errors like "no 568 // type named 'Foo' in 'current_namespace'" when the user didn't write any 569 // name specifiers. 570 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 571 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 572 } else if (const CXXRecordDecl *RD = 573 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 574 // Build a DependentNameType that will perform lookup into RD at 575 // instantiation time. 576 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 577 RD->getTypeForDecl()); 578 579 // Diagnose that this identifier was undeclared, and retry the lookup during 580 // template instantiation. 581 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 582 << RD; 583 } else { 584 // This is not a situation that we should recover from. 585 return ParsedType(); 586 } 587 588 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 589 590 // Build type location information. We synthesized the qualifier, so we have 591 // to build a fake NestedNameSpecifierLoc. 592 NestedNameSpecifierLocBuilder NNSLocBuilder; 593 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 594 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 595 596 TypeLocBuilder Builder; 597 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 598 DepTL.setNameLoc(NameLoc); 599 DepTL.setElaboratedKeywordLoc(SourceLocation()); 600 DepTL.setQualifierLoc(QualifierLoc); 601 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 602 } 603 604 /// isTagName() - This method is called *for error recovery purposes only* 605 /// to determine if the specified name is a valid tag name ("struct foo"). If 606 /// so, this returns the TST for the tag corresponding to it (TST_enum, 607 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 608 /// cases in C where the user forgot to specify the tag. 609 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 610 // Do a tag name lookup in this scope. 611 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 612 LookupName(R, S, false); 613 R.suppressDiagnostics(); 614 if (R.getResultKind() == LookupResult::Found) 615 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 616 switch (TD->getTagKind()) { 617 case TTK_Struct: return DeclSpec::TST_struct; 618 case TTK_Interface: return DeclSpec::TST_interface; 619 case TTK_Union: return DeclSpec::TST_union; 620 case TTK_Class: return DeclSpec::TST_class; 621 case TTK_Enum: return DeclSpec::TST_enum; 622 } 623 } 624 625 return DeclSpec::TST_unspecified; 626 } 627 628 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 629 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 630 /// then downgrade the missing typename error to a warning. 631 /// This is needed for MSVC compatibility; Example: 632 /// @code 633 /// template<class T> class A { 634 /// public: 635 /// typedef int TYPE; 636 /// }; 637 /// template<class T> class B : public A<T> { 638 /// public: 639 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 640 /// }; 641 /// @endcode 642 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 643 if (CurContext->isRecord()) { 644 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 645 return true; 646 647 const Type *Ty = SS->getScopeRep()->getAsType(); 648 649 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 650 for (const auto &Base : RD->bases()) 651 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 652 return true; 653 return S->isFunctionPrototypeScope(); 654 } 655 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 656 } 657 658 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 659 SourceLocation IILoc, 660 Scope *S, 661 CXXScopeSpec *SS, 662 ParsedType &SuggestedType, 663 bool IsTemplateName) { 664 // Don't report typename errors for editor placeholders. 665 if (II->isEditorPlaceholder()) 666 return; 667 // We don't have anything to suggest (yet). 668 SuggestedType = nullptr; 669 670 // There may have been a typo in the name of the type. Look up typo 671 // results, in case we have something that we can suggest. 672 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 673 /*AllowTemplates=*/IsTemplateName, 674 /*AllowNonTemplates=*/!IsTemplateName); 675 if (TypoCorrection Corrected = 676 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 677 CCC, CTK_ErrorRecovery)) { 678 // FIXME: Support error recovery for the template-name case. 679 bool CanRecover = !IsTemplateName; 680 if (Corrected.isKeyword()) { 681 // We corrected to a keyword. 682 diagnoseTypo(Corrected, 683 PDiag(IsTemplateName ? diag::err_no_template_suggest 684 : diag::err_unknown_typename_suggest) 685 << II); 686 II = Corrected.getCorrectionAsIdentifierInfo(); 687 } else { 688 // We found a similarly-named type or interface; suggest that. 689 if (!SS || !SS->isSet()) { 690 diagnoseTypo(Corrected, 691 PDiag(IsTemplateName ? diag::err_no_template_suggest 692 : diag::err_unknown_typename_suggest) 693 << II, CanRecover); 694 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 695 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 696 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 697 II->getName().equals(CorrectedStr); 698 diagnoseTypo(Corrected, 699 PDiag(IsTemplateName 700 ? diag::err_no_member_template_suggest 701 : diag::err_unknown_nested_typename_suggest) 702 << II << DC << DroppedSpecifier << SS->getRange(), 703 CanRecover); 704 } else { 705 llvm_unreachable("could not have corrected a typo here"); 706 } 707 708 if (!CanRecover) 709 return; 710 711 CXXScopeSpec tmpSS; 712 if (Corrected.getCorrectionSpecifier()) 713 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 714 SourceRange(IILoc)); 715 // FIXME: Support class template argument deduction here. 716 SuggestedType = 717 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 718 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 719 /*IsCtorOrDtorName=*/false, 720 /*WantNontrivialTypeSourceInfo=*/true); 721 } 722 return; 723 } 724 725 if (getLangOpts().CPlusPlus && !IsTemplateName) { 726 // See if II is a class template that the user forgot to pass arguments to. 727 UnqualifiedId Name; 728 Name.setIdentifier(II, IILoc); 729 CXXScopeSpec EmptySS; 730 TemplateTy TemplateResult; 731 bool MemberOfUnknownSpecialization; 732 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 733 Name, nullptr, true, TemplateResult, 734 MemberOfUnknownSpecialization) == TNK_Type_template) { 735 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 736 return; 737 } 738 } 739 740 // FIXME: Should we move the logic that tries to recover from a missing tag 741 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 742 743 if (!SS || (!SS->isSet() && !SS->isInvalid())) 744 Diag(IILoc, IsTemplateName ? diag::err_no_template 745 : diag::err_unknown_typename) 746 << II; 747 else if (DeclContext *DC = computeDeclContext(*SS, false)) 748 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 749 : diag::err_typename_nested_not_found) 750 << II << DC << SS->getRange(); 751 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { 752 SuggestedType = 753 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); 754 } else if (isDependentScopeSpecifier(*SS)) { 755 unsigned DiagID = diag::err_typename_missing; 756 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 757 DiagID = diag::ext_typename_missing; 758 759 Diag(SS->getRange().getBegin(), DiagID) 760 << SS->getScopeRep() << II->getName() 761 << SourceRange(SS->getRange().getBegin(), IILoc) 762 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 763 SuggestedType = ActOnTypenameType(S, SourceLocation(), 764 *SS, *II, IILoc).get(); 765 } else { 766 assert(SS && SS->isInvalid() && 767 "Invalid scope specifier has already been diagnosed"); 768 } 769 } 770 771 /// Determine whether the given result set contains either a type name 772 /// or 773 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 774 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 775 NextToken.is(tok::less); 776 777 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 778 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 779 return true; 780 781 if (CheckTemplate && isa<TemplateDecl>(*I)) 782 return true; 783 } 784 785 return false; 786 } 787 788 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 789 Scope *S, CXXScopeSpec &SS, 790 IdentifierInfo *&Name, 791 SourceLocation NameLoc) { 792 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 793 SemaRef.LookupParsedName(R, S, &SS); 794 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 795 StringRef FixItTagName; 796 switch (Tag->getTagKind()) { 797 case TTK_Class: 798 FixItTagName = "class "; 799 break; 800 801 case TTK_Enum: 802 FixItTagName = "enum "; 803 break; 804 805 case TTK_Struct: 806 FixItTagName = "struct "; 807 break; 808 809 case TTK_Interface: 810 FixItTagName = "__interface "; 811 break; 812 813 case TTK_Union: 814 FixItTagName = "union "; 815 break; 816 } 817 818 StringRef TagName = FixItTagName.drop_back(); 819 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 820 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 821 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 822 823 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 824 I != IEnd; ++I) 825 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 826 << Name << TagName; 827 828 // Replace lookup results with just the tag decl. 829 Result.clear(Sema::LookupTagName); 830 SemaRef.LookupParsedName(Result, S, &SS); 831 return true; 832 } 833 834 return false; 835 } 836 837 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 838 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 839 QualType T, SourceLocation NameLoc) { 840 ASTContext &Context = S.Context; 841 842 TypeLocBuilder Builder; 843 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 844 845 T = S.getElaboratedType(ETK_None, SS, T); 846 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 847 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 848 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 849 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 850 } 851 852 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 853 IdentifierInfo *&Name, 854 SourceLocation NameLoc, 855 const Token &NextToken, 856 CorrectionCandidateCallback *CCC) { 857 DeclarationNameInfo NameInfo(Name, NameLoc); 858 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 859 860 assert(NextToken.isNot(tok::coloncolon) && 861 "parse nested name specifiers before calling ClassifyName"); 862 if (getLangOpts().CPlusPlus && SS.isSet() && 863 isCurrentClassName(*Name, S, &SS)) { 864 // Per [class.qual]p2, this names the constructors of SS, not the 865 // injected-class-name. We don't have a classification for that. 866 // There's not much point caching this result, since the parser 867 // will reject it later. 868 return NameClassification::Unknown(); 869 } 870 871 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 872 LookupParsedName(Result, S, &SS, !CurMethod); 873 874 if (SS.isInvalid()) 875 return NameClassification::Error(); 876 877 // For unqualified lookup in a class template in MSVC mode, look into 878 // dependent base classes where the primary class template is known. 879 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 880 if (ParsedType TypeInBase = 881 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 882 return TypeInBase; 883 } 884 885 // Perform lookup for Objective-C instance variables (including automatically 886 // synthesized instance variables), if we're in an Objective-C method. 887 // FIXME: This lookup really, really needs to be folded in to the normal 888 // unqualified lookup mechanism. 889 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 890 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 891 if (Ivar.isInvalid()) 892 return NameClassification::Error(); 893 if (Ivar.isUsable()) 894 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 895 896 // We defer builtin creation until after ivar lookup inside ObjC methods. 897 if (Result.empty()) 898 LookupBuiltin(Result); 899 } 900 901 bool SecondTry = false; 902 bool IsFilteredTemplateName = false; 903 904 Corrected: 905 switch (Result.getResultKind()) { 906 case LookupResult::NotFound: 907 // If an unqualified-id is followed by a '(', then we have a function 908 // call. 909 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 910 // In C++, this is an ADL-only call. 911 // FIXME: Reference? 912 if (getLangOpts().CPlusPlus) 913 return NameClassification::UndeclaredNonType(); 914 915 // C90 6.3.2.2: 916 // If the expression that precedes the parenthesized argument list in a 917 // function call consists solely of an identifier, and if no 918 // declaration is visible for this identifier, the identifier is 919 // implicitly declared exactly as if, in the innermost block containing 920 // the function call, the declaration 921 // 922 // extern int identifier (); 923 // 924 // appeared. 925 // 926 // We also allow this in C99 as an extension. 927 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 928 return NameClassification::NonType(D); 929 } 930 931 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 932 // In C++20 onwards, this could be an ADL-only call to a function 933 // template, and we're required to assume that this is a template name. 934 // 935 // FIXME: Find a way to still do typo correction in this case. 936 TemplateName Template = 937 Context.getAssumedTemplateName(NameInfo.getName()); 938 return NameClassification::UndeclaredTemplate(Template); 939 } 940 941 // In C, we first see whether there is a tag type by the same name, in 942 // which case it's likely that the user just forgot to write "enum", 943 // "struct", or "union". 944 if (!getLangOpts().CPlusPlus && !SecondTry && 945 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 946 break; 947 } 948 949 // Perform typo correction to determine if there is another name that is 950 // close to this name. 951 if (!SecondTry && CCC) { 952 SecondTry = true; 953 if (TypoCorrection Corrected = 954 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 955 &SS, *CCC, CTK_ErrorRecovery)) { 956 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 957 unsigned QualifiedDiag = diag::err_no_member_suggest; 958 959 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 960 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 961 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 962 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 963 UnqualifiedDiag = diag::err_no_template_suggest; 964 QualifiedDiag = diag::err_no_member_template_suggest; 965 } else if (UnderlyingFirstDecl && 966 (isa<TypeDecl>(UnderlyingFirstDecl) || 967 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 968 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 969 UnqualifiedDiag = diag::err_unknown_typename_suggest; 970 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 971 } 972 973 if (SS.isEmpty()) { 974 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 975 } else {// FIXME: is this even reachable? Test it. 976 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 977 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 978 Name->getName().equals(CorrectedStr); 979 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 980 << Name << computeDeclContext(SS, false) 981 << DroppedSpecifier << SS.getRange()); 982 } 983 984 // Update the name, so that the caller has the new name. 985 Name = Corrected.getCorrectionAsIdentifierInfo(); 986 987 // Typo correction corrected to a keyword. 988 if (Corrected.isKeyword()) 989 return Name; 990 991 // Also update the LookupResult... 992 // FIXME: This should probably go away at some point 993 Result.clear(); 994 Result.setLookupName(Corrected.getCorrection()); 995 if (FirstDecl) 996 Result.addDecl(FirstDecl); 997 998 // If we found an Objective-C instance variable, let 999 // LookupInObjCMethod build the appropriate expression to 1000 // reference the ivar. 1001 // FIXME: This is a gross hack. 1002 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1003 DeclResult R = 1004 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1005 if (R.isInvalid()) 1006 return NameClassification::Error(); 1007 if (R.isUsable()) 1008 return NameClassification::NonType(Ivar); 1009 } 1010 1011 goto Corrected; 1012 } 1013 } 1014 1015 // We failed to correct; just fall through and let the parser deal with it. 1016 Result.suppressDiagnostics(); 1017 return NameClassification::Unknown(); 1018 1019 case LookupResult::NotFoundInCurrentInstantiation: { 1020 // We performed name lookup into the current instantiation, and there were 1021 // dependent bases, so we treat this result the same way as any other 1022 // dependent nested-name-specifier. 1023 1024 // C++ [temp.res]p2: 1025 // A name used in a template declaration or definition and that is 1026 // dependent on a template-parameter is assumed not to name a type 1027 // unless the applicable name lookup finds a type name or the name is 1028 // qualified by the keyword typename. 1029 // 1030 // FIXME: If the next token is '<', we might want to ask the parser to 1031 // perform some heroics to see if we actually have a 1032 // template-argument-list, which would indicate a missing 'template' 1033 // keyword here. 1034 return NameClassification::DependentNonType(); 1035 } 1036 1037 case LookupResult::Found: 1038 case LookupResult::FoundOverloaded: 1039 case LookupResult::FoundUnresolvedValue: 1040 break; 1041 1042 case LookupResult::Ambiguous: 1043 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1044 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1045 /*AllowDependent=*/false)) { 1046 // C++ [temp.local]p3: 1047 // A lookup that finds an injected-class-name (10.2) can result in an 1048 // ambiguity in certain cases (for example, if it is found in more than 1049 // one base class). If all of the injected-class-names that are found 1050 // refer to specializations of the same class template, and if the name 1051 // is followed by a template-argument-list, the reference refers to the 1052 // class template itself and not a specialization thereof, and is not 1053 // ambiguous. 1054 // 1055 // This filtering can make an ambiguous result into an unambiguous one, 1056 // so try again after filtering out template names. 1057 FilterAcceptableTemplateNames(Result); 1058 if (!Result.isAmbiguous()) { 1059 IsFilteredTemplateName = true; 1060 break; 1061 } 1062 } 1063 1064 // Diagnose the ambiguity and return an error. 1065 return NameClassification::Error(); 1066 } 1067 1068 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1069 (IsFilteredTemplateName || 1070 hasAnyAcceptableTemplateNames( 1071 Result, /*AllowFunctionTemplates=*/true, 1072 /*AllowDependent=*/false, 1073 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1074 getLangOpts().CPlusPlus20))) { 1075 // C++ [temp.names]p3: 1076 // After name lookup (3.4) finds that a name is a template-name or that 1077 // an operator-function-id or a literal- operator-id refers to a set of 1078 // overloaded functions any member of which is a function template if 1079 // this is followed by a <, the < is always taken as the delimiter of a 1080 // template-argument-list and never as the less-than operator. 1081 // C++2a [temp.names]p2: 1082 // A name is also considered to refer to a template if it is an 1083 // unqualified-id followed by a < and name lookup finds either one 1084 // or more functions or finds nothing. 1085 if (!IsFilteredTemplateName) 1086 FilterAcceptableTemplateNames(Result); 1087 1088 bool IsFunctionTemplate; 1089 bool IsVarTemplate; 1090 TemplateName Template; 1091 if (Result.end() - Result.begin() > 1) { 1092 IsFunctionTemplate = true; 1093 Template = Context.getOverloadedTemplateName(Result.begin(), 1094 Result.end()); 1095 } else if (!Result.empty()) { 1096 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1097 *Result.begin(), /*AllowFunctionTemplates=*/true, 1098 /*AllowDependent=*/false)); 1099 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1100 IsVarTemplate = isa<VarTemplateDecl>(TD); 1101 1102 if (SS.isNotEmpty()) 1103 Template = 1104 Context.getQualifiedTemplateName(SS.getScopeRep(), 1105 /*TemplateKeyword=*/false, TD); 1106 else 1107 Template = TemplateName(TD); 1108 } else { 1109 // All results were non-template functions. This is a function template 1110 // name. 1111 IsFunctionTemplate = true; 1112 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1113 } 1114 1115 if (IsFunctionTemplate) { 1116 // Function templates always go through overload resolution, at which 1117 // point we'll perform the various checks (e.g., accessibility) we need 1118 // to based on which function we selected. 1119 Result.suppressDiagnostics(); 1120 1121 return NameClassification::FunctionTemplate(Template); 1122 } 1123 1124 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1125 : NameClassification::TypeTemplate(Template); 1126 } 1127 1128 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1129 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1130 DiagnoseUseOfDecl(Type, NameLoc); 1131 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1132 QualType T = Context.getTypeDeclType(Type); 1133 if (SS.isNotEmpty()) 1134 return buildNestedType(*this, SS, T, NameLoc); 1135 return ParsedType::make(T); 1136 } 1137 1138 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1139 if (!Class) { 1140 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1141 if (ObjCCompatibleAliasDecl *Alias = 1142 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1143 Class = Alias->getClassInterface(); 1144 } 1145 1146 if (Class) { 1147 DiagnoseUseOfDecl(Class, NameLoc); 1148 1149 if (NextToken.is(tok::period)) { 1150 // Interface. <something> is parsed as a property reference expression. 1151 // Just return "unknown" as a fall-through for now. 1152 Result.suppressDiagnostics(); 1153 return NameClassification::Unknown(); 1154 } 1155 1156 QualType T = Context.getObjCInterfaceType(Class); 1157 return ParsedType::make(T); 1158 } 1159 1160 if (isa<ConceptDecl>(FirstDecl)) 1161 return NameClassification::Concept( 1162 TemplateName(cast<TemplateDecl>(FirstDecl))); 1163 1164 // We can have a type template here if we're classifying a template argument. 1165 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1166 !isa<VarTemplateDecl>(FirstDecl)) 1167 return NameClassification::TypeTemplate( 1168 TemplateName(cast<TemplateDecl>(FirstDecl))); 1169 1170 // Check for a tag type hidden by a non-type decl in a few cases where it 1171 // seems likely a type is wanted instead of the non-type that was found. 1172 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1173 if ((NextToken.is(tok::identifier) || 1174 (NextIsOp && 1175 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1176 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1177 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1178 DiagnoseUseOfDecl(Type, NameLoc); 1179 QualType T = Context.getTypeDeclType(Type); 1180 if (SS.isNotEmpty()) 1181 return buildNestedType(*this, SS, T, NameLoc); 1182 return ParsedType::make(T); 1183 } 1184 1185 // If we already know which single declaration is referenced, just annotate 1186 // that declaration directly. Defer resolving even non-overloaded class 1187 // member accesses, as we need to defer certain access checks until we know 1188 // the context. 1189 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1190 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember()) 1191 return NameClassification::NonType(Result.getRepresentativeDecl()); 1192 1193 // Otherwise, this is an overload set that we will need to resolve later. 1194 Result.suppressDiagnostics(); 1195 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( 1196 Context, Result.getNamingClass(), SS.getWithLocInContext(Context), 1197 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), 1198 Result.begin(), Result.end())); 1199 } 1200 1201 ExprResult 1202 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1203 SourceLocation NameLoc) { 1204 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1205 CXXScopeSpec SS; 1206 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1207 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1208 } 1209 1210 ExprResult 1211 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1212 IdentifierInfo *Name, 1213 SourceLocation NameLoc, 1214 bool IsAddressOfOperand) { 1215 DeclarationNameInfo NameInfo(Name, NameLoc); 1216 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1217 NameInfo, IsAddressOfOperand, 1218 /*TemplateArgs=*/nullptr); 1219 } 1220 1221 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1222 NamedDecl *Found, 1223 SourceLocation NameLoc, 1224 const Token &NextToken) { 1225 if (getCurMethodDecl() && SS.isEmpty()) 1226 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1227 return BuildIvarRefExpr(S, NameLoc, Ivar); 1228 1229 // Reconstruct the lookup result. 1230 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1231 Result.addDecl(Found); 1232 Result.resolveKind(); 1233 1234 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1235 return BuildDeclarationNameExpr(SS, Result, ADL); 1236 } 1237 1238 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { 1239 // For an implicit class member access, transform the result into a member 1240 // access expression if necessary. 1241 auto *ULE = cast<UnresolvedLookupExpr>(E); 1242 if ((*ULE->decls_begin())->isCXXClassMember()) { 1243 CXXScopeSpec SS; 1244 SS.Adopt(ULE->getQualifierLoc()); 1245 1246 // Reconstruct the lookup result. 1247 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), 1248 LookupOrdinaryName); 1249 Result.setNamingClass(ULE->getNamingClass()); 1250 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) 1251 Result.addDecl(*I, I.getAccess()); 1252 Result.resolveKind(); 1253 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1254 nullptr, S); 1255 } 1256 1257 // Otherwise, this is already in the form we needed, and no further checks 1258 // are necessary. 1259 return ULE; 1260 } 1261 1262 Sema::TemplateNameKindForDiagnostics 1263 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1264 auto *TD = Name.getAsTemplateDecl(); 1265 if (!TD) 1266 return TemplateNameKindForDiagnostics::DependentTemplate; 1267 if (isa<ClassTemplateDecl>(TD)) 1268 return TemplateNameKindForDiagnostics::ClassTemplate; 1269 if (isa<FunctionTemplateDecl>(TD)) 1270 return TemplateNameKindForDiagnostics::FunctionTemplate; 1271 if (isa<VarTemplateDecl>(TD)) 1272 return TemplateNameKindForDiagnostics::VarTemplate; 1273 if (isa<TypeAliasTemplateDecl>(TD)) 1274 return TemplateNameKindForDiagnostics::AliasTemplate; 1275 if (isa<TemplateTemplateParmDecl>(TD)) 1276 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1277 if (isa<ConceptDecl>(TD)) 1278 return TemplateNameKindForDiagnostics::Concept; 1279 return TemplateNameKindForDiagnostics::DependentTemplate; 1280 } 1281 1282 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1283 assert(DC->getLexicalParent() == CurContext && 1284 "The next DeclContext should be lexically contained in the current one."); 1285 CurContext = DC; 1286 S->setEntity(DC); 1287 } 1288 1289 void Sema::PopDeclContext() { 1290 assert(CurContext && "DeclContext imbalance!"); 1291 1292 CurContext = CurContext->getLexicalParent(); 1293 assert(CurContext && "Popped translation unit!"); 1294 } 1295 1296 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1297 Decl *D) { 1298 // Unlike PushDeclContext, the context to which we return is not necessarily 1299 // the containing DC of TD, because the new context will be some pre-existing 1300 // TagDecl definition instead of a fresh one. 1301 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1302 CurContext = cast<TagDecl>(D)->getDefinition(); 1303 assert(CurContext && "skipping definition of undefined tag"); 1304 // Start lookups from the parent of the current context; we don't want to look 1305 // into the pre-existing complete definition. 1306 S->setEntity(CurContext->getLookupParent()); 1307 return Result; 1308 } 1309 1310 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1311 CurContext = static_cast<decltype(CurContext)>(Context); 1312 } 1313 1314 /// EnterDeclaratorContext - Used when we must lookup names in the context 1315 /// of a declarator's nested name specifier. 1316 /// 1317 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1318 // C++0x [basic.lookup.unqual]p13: 1319 // A name used in the definition of a static data member of class 1320 // X (after the qualified-id of the static member) is looked up as 1321 // if the name was used in a member function of X. 1322 // C++0x [basic.lookup.unqual]p14: 1323 // If a variable member of a namespace is defined outside of the 1324 // scope of its namespace then any name used in the definition of 1325 // the variable member (after the declarator-id) is looked up as 1326 // if the definition of the variable member occurred in its 1327 // namespace. 1328 // Both of these imply that we should push a scope whose context 1329 // is the semantic context of the declaration. We can't use 1330 // PushDeclContext here because that context is not necessarily 1331 // lexically contained in the current context. Fortunately, 1332 // the containing scope should have the appropriate information. 1333 1334 assert(!S->getEntity() && "scope already has entity"); 1335 1336 #ifndef NDEBUG 1337 Scope *Ancestor = S->getParent(); 1338 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1339 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1340 #endif 1341 1342 CurContext = DC; 1343 S->setEntity(DC); 1344 1345 if (S->getParent()->isTemplateParamScope()) { 1346 // Also set the corresponding entities for all immediately-enclosing 1347 // template parameter scopes. 1348 EnterTemplatedContext(S->getParent(), DC); 1349 } 1350 } 1351 1352 void Sema::ExitDeclaratorContext(Scope *S) { 1353 assert(S->getEntity() == CurContext && "Context imbalance!"); 1354 1355 // Switch back to the lexical context. The safety of this is 1356 // enforced by an assert in EnterDeclaratorContext. 1357 Scope *Ancestor = S->getParent(); 1358 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1359 CurContext = Ancestor->getEntity(); 1360 1361 // We don't need to do anything with the scope, which is going to 1362 // disappear. 1363 } 1364 1365 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1366 assert(S->isTemplateParamScope() && 1367 "expected to be initializing a template parameter scope"); 1368 1369 // C++20 [temp.local]p7: 1370 // In the definition of a member of a class template that appears outside 1371 // of the class template definition, the name of a member of the class 1372 // template hides the name of a template-parameter of any enclosing class 1373 // templates (but not a template-parameter of the member if the member is a 1374 // class or function template). 1375 // C++20 [temp.local]p9: 1376 // In the definition of a class template or in the definition of a member 1377 // of such a template that appears outside of the template definition, for 1378 // each non-dependent base class (13.8.2.1), if the name of the base class 1379 // or the name of a member of the base class is the same as the name of a 1380 // template-parameter, the base class name or member name hides the 1381 // template-parameter name (6.4.10). 1382 // 1383 // This means that a template parameter scope should be searched immediately 1384 // after searching the DeclContext for which it is a template parameter 1385 // scope. For example, for 1386 // template<typename T> template<typename U> template<typename V> 1387 // void N::A<T>::B<U>::f(...) 1388 // we search V then B<U> (and base classes) then U then A<T> (and base 1389 // classes) then T then N then ::. 1390 unsigned ScopeDepth = getTemplateDepth(S); 1391 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1392 DeclContext *SearchDCAfterScope = DC; 1393 for (; DC; DC = DC->getLookupParent()) { 1394 if (const TemplateParameterList *TPL = 1395 cast<Decl>(DC)->getDescribedTemplateParams()) { 1396 unsigned DCDepth = TPL->getDepth() + 1; 1397 if (DCDepth > ScopeDepth) 1398 continue; 1399 if (ScopeDepth == DCDepth) 1400 SearchDCAfterScope = DC = DC->getLookupParent(); 1401 break; 1402 } 1403 } 1404 S->setLookupEntity(SearchDCAfterScope); 1405 } 1406 } 1407 1408 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1409 // We assume that the caller has already called 1410 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1411 FunctionDecl *FD = D->getAsFunction(); 1412 if (!FD) 1413 return; 1414 1415 // Same implementation as PushDeclContext, but enters the context 1416 // from the lexical parent, rather than the top-level class. 1417 assert(CurContext == FD->getLexicalParent() && 1418 "The next DeclContext should be lexically contained in the current one."); 1419 CurContext = FD; 1420 S->setEntity(CurContext); 1421 1422 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1423 ParmVarDecl *Param = FD->getParamDecl(P); 1424 // If the parameter has an identifier, then add it to the scope 1425 if (Param->getIdentifier()) { 1426 S->AddDecl(Param); 1427 IdResolver.AddDecl(Param); 1428 } 1429 } 1430 } 1431 1432 void Sema::ActOnExitFunctionContext() { 1433 // Same implementation as PopDeclContext, but returns to the lexical parent, 1434 // rather than the top-level class. 1435 assert(CurContext && "DeclContext imbalance!"); 1436 CurContext = CurContext->getLexicalParent(); 1437 assert(CurContext && "Popped translation unit!"); 1438 } 1439 1440 /// Determine whether we allow overloading of the function 1441 /// PrevDecl with another declaration. 1442 /// 1443 /// This routine determines whether overloading is possible, not 1444 /// whether some new function is actually an overload. It will return 1445 /// true in C++ (where we can always provide overloads) or, as an 1446 /// extension, in C when the previous function is already an 1447 /// overloaded function declaration or has the "overloadable" 1448 /// attribute. 1449 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1450 ASTContext &Context, 1451 const FunctionDecl *New) { 1452 if (Context.getLangOpts().CPlusPlus) 1453 return true; 1454 1455 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1456 return true; 1457 1458 return Previous.getResultKind() == LookupResult::Found && 1459 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1460 New->hasAttr<OverloadableAttr>()); 1461 } 1462 1463 /// Add this decl to the scope shadowed decl chains. 1464 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1465 // Move up the scope chain until we find the nearest enclosing 1466 // non-transparent context. The declaration will be introduced into this 1467 // scope. 1468 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1469 S = S->getParent(); 1470 1471 // Add scoped declarations into their context, so that they can be 1472 // found later. Declarations without a context won't be inserted 1473 // into any context. 1474 if (AddToContext) 1475 CurContext->addDecl(D); 1476 1477 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1478 // are function-local declarations. 1479 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) 1480 return; 1481 1482 // Template instantiations should also not be pushed into scope. 1483 if (isa<FunctionDecl>(D) && 1484 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1485 return; 1486 1487 // If this replaces anything in the current scope, 1488 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1489 IEnd = IdResolver.end(); 1490 for (; I != IEnd; ++I) { 1491 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1492 S->RemoveDecl(*I); 1493 IdResolver.RemoveDecl(*I); 1494 1495 // Should only need to replace one decl. 1496 break; 1497 } 1498 } 1499 1500 S->AddDecl(D); 1501 1502 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1503 // Implicitly-generated labels may end up getting generated in an order that 1504 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1505 // the label at the appropriate place in the identifier chain. 1506 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1507 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1508 if (IDC == CurContext) { 1509 if (!S->isDeclScope(*I)) 1510 continue; 1511 } else if (IDC->Encloses(CurContext)) 1512 break; 1513 } 1514 1515 IdResolver.InsertDeclAfter(I, D); 1516 } else { 1517 IdResolver.AddDecl(D); 1518 } 1519 } 1520 1521 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1522 bool AllowInlineNamespace) { 1523 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1524 } 1525 1526 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1527 DeclContext *TargetDC = DC->getPrimaryContext(); 1528 do { 1529 if (DeclContext *ScopeDC = S->getEntity()) 1530 if (ScopeDC->getPrimaryContext() == TargetDC) 1531 return S; 1532 } while ((S = S->getParent())); 1533 1534 return nullptr; 1535 } 1536 1537 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1538 DeclContext*, 1539 ASTContext&); 1540 1541 /// Filters out lookup results that don't fall within the given scope 1542 /// as determined by isDeclInScope. 1543 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1544 bool ConsiderLinkage, 1545 bool AllowInlineNamespace) { 1546 LookupResult::Filter F = R.makeFilter(); 1547 while (F.hasNext()) { 1548 NamedDecl *D = F.next(); 1549 1550 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1551 continue; 1552 1553 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1554 continue; 1555 1556 F.erase(); 1557 } 1558 1559 F.done(); 1560 } 1561 1562 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1563 /// have compatible owning modules. 1564 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1565 // FIXME: The Modules TS is not clear about how friend declarations are 1566 // to be treated. It's not meaningful to have different owning modules for 1567 // linkage in redeclarations of the same entity, so for now allow the 1568 // redeclaration and change the owning modules to match. 1569 if (New->getFriendObjectKind() && 1570 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1571 New->setLocalOwningModule(Old->getOwningModule()); 1572 makeMergedDefinitionVisible(New); 1573 return false; 1574 } 1575 1576 Module *NewM = New->getOwningModule(); 1577 Module *OldM = Old->getOwningModule(); 1578 1579 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1580 NewM = NewM->Parent; 1581 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1582 OldM = OldM->Parent; 1583 1584 if (NewM == OldM) 1585 return false; 1586 1587 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1588 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1589 if (NewIsModuleInterface || OldIsModuleInterface) { 1590 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1591 // if a declaration of D [...] appears in the purview of a module, all 1592 // other such declarations shall appear in the purview of the same module 1593 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1594 << New 1595 << NewIsModuleInterface 1596 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1597 << OldIsModuleInterface 1598 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1599 Diag(Old->getLocation(), diag::note_previous_declaration); 1600 New->setInvalidDecl(); 1601 return true; 1602 } 1603 1604 return false; 1605 } 1606 1607 static bool isUsingDecl(NamedDecl *D) { 1608 return isa<UsingShadowDecl>(D) || 1609 isa<UnresolvedUsingTypenameDecl>(D) || 1610 isa<UnresolvedUsingValueDecl>(D); 1611 } 1612 1613 /// Removes using shadow declarations from the lookup results. 1614 static void RemoveUsingDecls(LookupResult &R) { 1615 LookupResult::Filter F = R.makeFilter(); 1616 while (F.hasNext()) 1617 if (isUsingDecl(F.next())) 1618 F.erase(); 1619 1620 F.done(); 1621 } 1622 1623 /// Check for this common pattern: 1624 /// @code 1625 /// class S { 1626 /// S(const S&); // DO NOT IMPLEMENT 1627 /// void operator=(const S&); // DO NOT IMPLEMENT 1628 /// }; 1629 /// @endcode 1630 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1631 // FIXME: Should check for private access too but access is set after we get 1632 // the decl here. 1633 if (D->doesThisDeclarationHaveABody()) 1634 return false; 1635 1636 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1637 return CD->isCopyConstructor(); 1638 return D->isCopyAssignmentOperator(); 1639 } 1640 1641 // We need this to handle 1642 // 1643 // typedef struct { 1644 // void *foo() { return 0; } 1645 // } A; 1646 // 1647 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1648 // for example. If 'A', foo will have external linkage. If we have '*A', 1649 // foo will have no linkage. Since we can't know until we get to the end 1650 // of the typedef, this function finds out if D might have non-external linkage. 1651 // Callers should verify at the end of the TU if it D has external linkage or 1652 // not. 1653 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1654 const DeclContext *DC = D->getDeclContext(); 1655 while (!DC->isTranslationUnit()) { 1656 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1657 if (!RD->hasNameForLinkage()) 1658 return true; 1659 } 1660 DC = DC->getParent(); 1661 } 1662 1663 return !D->isExternallyVisible(); 1664 } 1665 1666 // FIXME: This needs to be refactored; some other isInMainFile users want 1667 // these semantics. 1668 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1669 if (S.TUKind != TU_Complete) 1670 return false; 1671 return S.SourceMgr.isInMainFile(Loc); 1672 } 1673 1674 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1675 assert(D); 1676 1677 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1678 return false; 1679 1680 // Ignore all entities declared within templates, and out-of-line definitions 1681 // of members of class templates. 1682 if (D->getDeclContext()->isDependentContext() || 1683 D->getLexicalDeclContext()->isDependentContext()) 1684 return false; 1685 1686 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1687 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1688 return false; 1689 // A non-out-of-line declaration of a member specialization was implicitly 1690 // instantiated; it's the out-of-line declaration that we're interested in. 1691 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1692 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1693 return false; 1694 1695 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1696 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1697 return false; 1698 } else { 1699 // 'static inline' functions are defined in headers; don't warn. 1700 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1701 return false; 1702 } 1703 1704 if (FD->doesThisDeclarationHaveABody() && 1705 Context.DeclMustBeEmitted(FD)) 1706 return false; 1707 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1708 // Constants and utility variables are defined in headers with internal 1709 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1710 // like "inline".) 1711 if (!isMainFileLoc(*this, VD->getLocation())) 1712 return false; 1713 1714 if (Context.DeclMustBeEmitted(VD)) 1715 return false; 1716 1717 if (VD->isStaticDataMember() && 1718 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1719 return false; 1720 if (VD->isStaticDataMember() && 1721 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1722 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1723 return false; 1724 1725 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1726 return false; 1727 } else { 1728 return false; 1729 } 1730 1731 // Only warn for unused decls internal to the translation unit. 1732 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1733 // for inline functions defined in the main source file, for instance. 1734 return mightHaveNonExternalLinkage(D); 1735 } 1736 1737 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1738 if (!D) 1739 return; 1740 1741 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1742 const FunctionDecl *First = FD->getFirstDecl(); 1743 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1744 return; // First should already be in the vector. 1745 } 1746 1747 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1748 const VarDecl *First = VD->getFirstDecl(); 1749 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1750 return; // First should already be in the vector. 1751 } 1752 1753 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1754 UnusedFileScopedDecls.push_back(D); 1755 } 1756 1757 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1758 if (D->isInvalidDecl()) 1759 return false; 1760 1761 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1762 // For a decomposition declaration, warn if none of the bindings are 1763 // referenced, instead of if the variable itself is referenced (which 1764 // it is, by the bindings' expressions). 1765 for (auto *BD : DD->bindings()) 1766 if (BD->isReferenced()) 1767 return false; 1768 } else if (!D->getDeclName()) { 1769 return false; 1770 } else if (D->isReferenced() || D->isUsed()) { 1771 return false; 1772 } 1773 1774 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) 1775 return false; 1776 1777 if (isa<LabelDecl>(D)) 1778 return true; 1779 1780 // Except for labels, we only care about unused decls that are local to 1781 // functions. 1782 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1783 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1784 // For dependent types, the diagnostic is deferred. 1785 WithinFunction = 1786 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1787 if (!WithinFunction) 1788 return false; 1789 1790 if (isa<TypedefNameDecl>(D)) 1791 return true; 1792 1793 // White-list anything that isn't a local variable. 1794 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1795 return false; 1796 1797 // Types of valid local variables should be complete, so this should succeed. 1798 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1799 1800 // White-list anything with an __attribute__((unused)) type. 1801 const auto *Ty = VD->getType().getTypePtr(); 1802 1803 // Only look at the outermost level of typedef. 1804 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1805 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1806 return false; 1807 } 1808 1809 // If we failed to complete the type for some reason, or if the type is 1810 // dependent, don't diagnose the variable. 1811 if (Ty->isIncompleteType() || Ty->isDependentType()) 1812 return false; 1813 1814 // Look at the element type to ensure that the warning behaviour is 1815 // consistent for both scalars and arrays. 1816 Ty = Ty->getBaseElementTypeUnsafe(); 1817 1818 if (const TagType *TT = Ty->getAs<TagType>()) { 1819 const TagDecl *Tag = TT->getDecl(); 1820 if (Tag->hasAttr<UnusedAttr>()) 1821 return false; 1822 1823 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1824 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1825 return false; 1826 1827 if (const Expr *Init = VD->getInit()) { 1828 if (const ExprWithCleanups *Cleanups = 1829 dyn_cast<ExprWithCleanups>(Init)) 1830 Init = Cleanups->getSubExpr(); 1831 const CXXConstructExpr *Construct = 1832 dyn_cast<CXXConstructExpr>(Init); 1833 if (Construct && !Construct->isElidable()) { 1834 CXXConstructorDecl *CD = Construct->getConstructor(); 1835 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1836 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1837 return false; 1838 } 1839 1840 // Suppress the warning if we don't know how this is constructed, and 1841 // it could possibly be non-trivial constructor. 1842 if (Init->isTypeDependent()) 1843 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1844 if (!Ctor->isTrivial()) 1845 return false; 1846 } 1847 } 1848 } 1849 1850 // TODO: __attribute__((unused)) templates? 1851 } 1852 1853 return true; 1854 } 1855 1856 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1857 FixItHint &Hint) { 1858 if (isa<LabelDecl>(D)) { 1859 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1860 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1861 true); 1862 if (AfterColon.isInvalid()) 1863 return; 1864 Hint = FixItHint::CreateRemoval( 1865 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1866 } 1867 } 1868 1869 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1870 if (D->getTypeForDecl()->isDependentType()) 1871 return; 1872 1873 for (auto *TmpD : D->decls()) { 1874 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1875 DiagnoseUnusedDecl(T); 1876 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1877 DiagnoseUnusedNestedTypedefs(R); 1878 } 1879 } 1880 1881 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1882 /// unless they are marked attr(unused). 1883 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1884 if (!ShouldDiagnoseUnusedDecl(D)) 1885 return; 1886 1887 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1888 // typedefs can be referenced later on, so the diagnostics are emitted 1889 // at end-of-translation-unit. 1890 UnusedLocalTypedefNameCandidates.insert(TD); 1891 return; 1892 } 1893 1894 FixItHint Hint; 1895 GenerateFixForUnusedDecl(D, Context, Hint); 1896 1897 unsigned DiagID; 1898 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1899 DiagID = diag::warn_unused_exception_param; 1900 else if (isa<LabelDecl>(D)) 1901 DiagID = diag::warn_unused_label; 1902 else 1903 DiagID = diag::warn_unused_variable; 1904 1905 Diag(D->getLocation(), DiagID) << D << Hint; 1906 } 1907 1908 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1909 // Verify that we have no forward references left. If so, there was a goto 1910 // or address of a label taken, but no definition of it. Label fwd 1911 // definitions are indicated with a null substmt which is also not a resolved 1912 // MS inline assembly label name. 1913 bool Diagnose = false; 1914 if (L->isMSAsmLabel()) 1915 Diagnose = !L->isResolvedMSAsmLabel(); 1916 else 1917 Diagnose = L->getStmt() == nullptr; 1918 if (Diagnose) 1919 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; 1920 } 1921 1922 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1923 S->mergeNRVOIntoParent(); 1924 1925 if (S->decl_empty()) return; 1926 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1927 "Scope shouldn't contain decls!"); 1928 1929 for (auto *TmpD : S->decls()) { 1930 assert(TmpD && "This decl didn't get pushed??"); 1931 1932 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1933 NamedDecl *D = cast<NamedDecl>(TmpD); 1934 1935 // Diagnose unused variables in this scope. 1936 if (!S->hasUnrecoverableErrorOccurred()) { 1937 DiagnoseUnusedDecl(D); 1938 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1939 DiagnoseUnusedNestedTypedefs(RD); 1940 } 1941 1942 if (!D->getDeclName()) continue; 1943 1944 // If this was a forward reference to a label, verify it was defined. 1945 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1946 CheckPoppedLabel(LD, *this); 1947 1948 // Remove this name from our lexical scope, and warn on it if we haven't 1949 // already. 1950 IdResolver.RemoveDecl(D); 1951 auto ShadowI = ShadowingDecls.find(D); 1952 if (ShadowI != ShadowingDecls.end()) { 1953 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1954 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1955 << D << FD << FD->getParent(); 1956 Diag(FD->getLocation(), diag::note_previous_declaration); 1957 } 1958 ShadowingDecls.erase(ShadowI); 1959 } 1960 } 1961 } 1962 1963 /// Look for an Objective-C class in the translation unit. 1964 /// 1965 /// \param Id The name of the Objective-C class we're looking for. If 1966 /// typo-correction fixes this name, the Id will be updated 1967 /// to the fixed name. 1968 /// 1969 /// \param IdLoc The location of the name in the translation unit. 1970 /// 1971 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1972 /// if there is no class with the given name. 1973 /// 1974 /// \returns The declaration of the named Objective-C class, or NULL if the 1975 /// class could not be found. 1976 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1977 SourceLocation IdLoc, 1978 bool DoTypoCorrection) { 1979 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1980 // creation from this context. 1981 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1982 1983 if (!IDecl && DoTypoCorrection) { 1984 // Perform typo correction at the given location, but only if we 1985 // find an Objective-C class name. 1986 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1987 if (TypoCorrection C = 1988 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1989 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1990 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1991 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1992 Id = IDecl->getIdentifier(); 1993 } 1994 } 1995 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1996 // This routine must always return a class definition, if any. 1997 if (Def && Def->getDefinition()) 1998 Def = Def->getDefinition(); 1999 return Def; 2000 } 2001 2002 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2003 /// from S, where a non-field would be declared. This routine copes 2004 /// with the difference between C and C++ scoping rules in structs and 2005 /// unions. For example, the following code is well-formed in C but 2006 /// ill-formed in C++: 2007 /// @code 2008 /// struct S6 { 2009 /// enum { BAR } e; 2010 /// }; 2011 /// 2012 /// void test_S6() { 2013 /// struct S6 a; 2014 /// a.e = BAR; 2015 /// } 2016 /// @endcode 2017 /// For the declaration of BAR, this routine will return a different 2018 /// scope. The scope S will be the scope of the unnamed enumeration 2019 /// within S6. In C++, this routine will return the scope associated 2020 /// with S6, because the enumeration's scope is a transparent 2021 /// context but structures can contain non-field names. In C, this 2022 /// routine will return the translation unit scope, since the 2023 /// enumeration's scope is a transparent context and structures cannot 2024 /// contain non-field names. 2025 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2026 while (((S->getFlags() & Scope::DeclScope) == 0) || 2027 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2028 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2029 S = S->getParent(); 2030 return S; 2031 } 2032 2033 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2034 ASTContext::GetBuiltinTypeError Error) { 2035 switch (Error) { 2036 case ASTContext::GE_None: 2037 return ""; 2038 case ASTContext::GE_Missing_type: 2039 return BuiltinInfo.getHeaderName(ID); 2040 case ASTContext::GE_Missing_stdio: 2041 return "stdio.h"; 2042 case ASTContext::GE_Missing_setjmp: 2043 return "setjmp.h"; 2044 case ASTContext::GE_Missing_ucontext: 2045 return "ucontext.h"; 2046 } 2047 llvm_unreachable("unhandled error kind"); 2048 } 2049 2050 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2051 unsigned ID, SourceLocation Loc) { 2052 DeclContext *Parent = Context.getTranslationUnitDecl(); 2053 2054 if (getLangOpts().CPlusPlus) { 2055 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2056 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); 2057 CLinkageDecl->setImplicit(); 2058 Parent->addDecl(CLinkageDecl); 2059 Parent = CLinkageDecl; 2060 } 2061 2062 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2063 /*TInfo=*/nullptr, SC_Extern, false, 2064 Type->isFunctionProtoType()); 2065 New->setImplicit(); 2066 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2067 2068 // Create Decl objects for each parameter, adding them to the 2069 // FunctionDecl. 2070 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2071 SmallVector<ParmVarDecl *, 16> Params; 2072 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2073 ParmVarDecl *parm = ParmVarDecl::Create( 2074 Context, New, SourceLocation(), SourceLocation(), nullptr, 2075 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2076 parm->setScopeInfo(0, i); 2077 Params.push_back(parm); 2078 } 2079 New->setParams(Params); 2080 } 2081 2082 AddKnownFunctionAttributes(New); 2083 return New; 2084 } 2085 2086 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2087 /// file scope. lazily create a decl for it. ForRedeclaration is true 2088 /// if we're creating this built-in in anticipation of redeclaring the 2089 /// built-in. 2090 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2091 Scope *S, bool ForRedeclaration, 2092 SourceLocation Loc) { 2093 LookupNecessaryTypesForBuiltin(S, ID); 2094 2095 ASTContext::GetBuiltinTypeError Error; 2096 QualType R = Context.GetBuiltinType(ID, Error); 2097 if (Error) { 2098 if (!ForRedeclaration) 2099 return nullptr; 2100 2101 // If we have a builtin without an associated type we should not emit a 2102 // warning when we were not able to find a type for it. 2103 if (Error == ASTContext::GE_Missing_type || 2104 Context.BuiltinInfo.allowTypeMismatch(ID)) 2105 return nullptr; 2106 2107 // If we could not find a type for setjmp it is because the jmp_buf type was 2108 // not defined prior to the setjmp declaration. 2109 if (Error == ASTContext::GE_Missing_setjmp) { 2110 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2111 << Context.BuiltinInfo.getName(ID); 2112 return nullptr; 2113 } 2114 2115 // Generally, we emit a warning that the declaration requires the 2116 // appropriate header. 2117 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2118 << getHeaderName(Context.BuiltinInfo, ID, Error) 2119 << Context.BuiltinInfo.getName(ID); 2120 return nullptr; 2121 } 2122 2123 if (!ForRedeclaration && 2124 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2125 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2126 Diag(Loc, diag::ext_implicit_lib_function_decl) 2127 << Context.BuiltinInfo.getName(ID) << R; 2128 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2129 Diag(Loc, diag::note_include_header_or_declare) 2130 << Header << Context.BuiltinInfo.getName(ID); 2131 } 2132 2133 if (R.isNull()) 2134 return nullptr; 2135 2136 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2137 RegisterLocallyScopedExternCDecl(New, S); 2138 2139 // TUScope is the translation-unit scope to insert this function into. 2140 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2141 // relate Scopes to DeclContexts, and probably eliminate CurContext 2142 // entirely, but we're not there yet. 2143 DeclContext *SavedContext = CurContext; 2144 CurContext = New->getDeclContext(); 2145 PushOnScopeChains(New, TUScope); 2146 CurContext = SavedContext; 2147 return New; 2148 } 2149 2150 /// Typedef declarations don't have linkage, but they still denote the same 2151 /// entity if their types are the same. 2152 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2153 /// isSameEntity. 2154 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2155 TypedefNameDecl *Decl, 2156 LookupResult &Previous) { 2157 // This is only interesting when modules are enabled. 2158 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2159 return; 2160 2161 // Empty sets are uninteresting. 2162 if (Previous.empty()) 2163 return; 2164 2165 LookupResult::Filter Filter = Previous.makeFilter(); 2166 while (Filter.hasNext()) { 2167 NamedDecl *Old = Filter.next(); 2168 2169 // Non-hidden declarations are never ignored. 2170 if (S.isVisible(Old)) 2171 continue; 2172 2173 // Declarations of the same entity are not ignored, even if they have 2174 // different linkages. 2175 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2176 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2177 Decl->getUnderlyingType())) 2178 continue; 2179 2180 // If both declarations give a tag declaration a typedef name for linkage 2181 // purposes, then they declare the same entity. 2182 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2183 Decl->getAnonDeclWithTypedefName()) 2184 continue; 2185 } 2186 2187 Filter.erase(); 2188 } 2189 2190 Filter.done(); 2191 } 2192 2193 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2194 QualType OldType; 2195 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2196 OldType = OldTypedef->getUnderlyingType(); 2197 else 2198 OldType = Context.getTypeDeclType(Old); 2199 QualType NewType = New->getUnderlyingType(); 2200 2201 if (NewType->isVariablyModifiedType()) { 2202 // Must not redefine a typedef with a variably-modified type. 2203 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2204 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2205 << Kind << NewType; 2206 if (Old->getLocation().isValid()) 2207 notePreviousDefinition(Old, New->getLocation()); 2208 New->setInvalidDecl(); 2209 return true; 2210 } 2211 2212 if (OldType != NewType && 2213 !OldType->isDependentType() && 2214 !NewType->isDependentType() && 2215 !Context.hasSameType(OldType, NewType)) { 2216 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2217 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2218 << Kind << NewType << OldType; 2219 if (Old->getLocation().isValid()) 2220 notePreviousDefinition(Old, New->getLocation()); 2221 New->setInvalidDecl(); 2222 return true; 2223 } 2224 return false; 2225 } 2226 2227 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2228 /// same name and scope as a previous declaration 'Old'. Figure out 2229 /// how to resolve this situation, merging decls or emitting 2230 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2231 /// 2232 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2233 LookupResult &OldDecls) { 2234 // If the new decl is known invalid already, don't bother doing any 2235 // merging checks. 2236 if (New->isInvalidDecl()) return; 2237 2238 // Allow multiple definitions for ObjC built-in typedefs. 2239 // FIXME: Verify the underlying types are equivalent! 2240 if (getLangOpts().ObjC) { 2241 const IdentifierInfo *TypeID = New->getIdentifier(); 2242 switch (TypeID->getLength()) { 2243 default: break; 2244 case 2: 2245 { 2246 if (!TypeID->isStr("id")) 2247 break; 2248 QualType T = New->getUnderlyingType(); 2249 if (!T->isPointerType()) 2250 break; 2251 if (!T->isVoidPointerType()) { 2252 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2253 if (!PT->isStructureType()) 2254 break; 2255 } 2256 Context.setObjCIdRedefinitionType(T); 2257 // Install the built-in type for 'id', ignoring the current definition. 2258 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2259 return; 2260 } 2261 case 5: 2262 if (!TypeID->isStr("Class")) 2263 break; 2264 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2265 // Install the built-in type for 'Class', ignoring the current definition. 2266 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2267 return; 2268 case 3: 2269 if (!TypeID->isStr("SEL")) 2270 break; 2271 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2272 // Install the built-in type for 'SEL', ignoring the current definition. 2273 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2274 return; 2275 } 2276 // Fall through - the typedef name was not a builtin type. 2277 } 2278 2279 // Verify the old decl was also a type. 2280 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2281 if (!Old) { 2282 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2283 << New->getDeclName(); 2284 2285 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2286 if (OldD->getLocation().isValid()) 2287 notePreviousDefinition(OldD, New->getLocation()); 2288 2289 return New->setInvalidDecl(); 2290 } 2291 2292 // If the old declaration is invalid, just give up here. 2293 if (Old->isInvalidDecl()) 2294 return New->setInvalidDecl(); 2295 2296 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2297 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2298 auto *NewTag = New->getAnonDeclWithTypedefName(); 2299 NamedDecl *Hidden = nullptr; 2300 if (OldTag && NewTag && 2301 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2302 !hasVisibleDefinition(OldTag, &Hidden)) { 2303 // There is a definition of this tag, but it is not visible. Use it 2304 // instead of our tag. 2305 New->setTypeForDecl(OldTD->getTypeForDecl()); 2306 if (OldTD->isModed()) 2307 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2308 OldTD->getUnderlyingType()); 2309 else 2310 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2311 2312 // Make the old tag definition visible. 2313 makeMergedDefinitionVisible(Hidden); 2314 2315 // If this was an unscoped enumeration, yank all of its enumerators 2316 // out of the scope. 2317 if (isa<EnumDecl>(NewTag)) { 2318 Scope *EnumScope = getNonFieldDeclScope(S); 2319 for (auto *D : NewTag->decls()) { 2320 auto *ED = cast<EnumConstantDecl>(D); 2321 assert(EnumScope->isDeclScope(ED)); 2322 EnumScope->RemoveDecl(ED); 2323 IdResolver.RemoveDecl(ED); 2324 ED->getLexicalDeclContext()->removeDecl(ED); 2325 } 2326 } 2327 } 2328 } 2329 2330 // If the typedef types are not identical, reject them in all languages and 2331 // with any extensions enabled. 2332 if (isIncompatibleTypedef(Old, New)) 2333 return; 2334 2335 // The types match. Link up the redeclaration chain and merge attributes if 2336 // the old declaration was a typedef. 2337 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2338 New->setPreviousDecl(Typedef); 2339 mergeDeclAttributes(New, Old); 2340 } 2341 2342 if (getLangOpts().MicrosoftExt) 2343 return; 2344 2345 if (getLangOpts().CPlusPlus) { 2346 // C++ [dcl.typedef]p2: 2347 // In a given non-class scope, a typedef specifier can be used to 2348 // redefine the name of any type declared in that scope to refer 2349 // to the type to which it already refers. 2350 if (!isa<CXXRecordDecl>(CurContext)) 2351 return; 2352 2353 // C++0x [dcl.typedef]p4: 2354 // In a given class scope, a typedef specifier can be used to redefine 2355 // any class-name declared in that scope that is not also a typedef-name 2356 // to refer to the type to which it already refers. 2357 // 2358 // This wording came in via DR424, which was a correction to the 2359 // wording in DR56, which accidentally banned code like: 2360 // 2361 // struct S { 2362 // typedef struct A { } A; 2363 // }; 2364 // 2365 // in the C++03 standard. We implement the C++0x semantics, which 2366 // allow the above but disallow 2367 // 2368 // struct S { 2369 // typedef int I; 2370 // typedef int I; 2371 // }; 2372 // 2373 // since that was the intent of DR56. 2374 if (!isa<TypedefNameDecl>(Old)) 2375 return; 2376 2377 Diag(New->getLocation(), diag::err_redefinition) 2378 << New->getDeclName(); 2379 notePreviousDefinition(Old, New->getLocation()); 2380 return New->setInvalidDecl(); 2381 } 2382 2383 // Modules always permit redefinition of typedefs, as does C11. 2384 if (getLangOpts().Modules || getLangOpts().C11) 2385 return; 2386 2387 // If we have a redefinition of a typedef in C, emit a warning. This warning 2388 // is normally mapped to an error, but can be controlled with 2389 // -Wtypedef-redefinition. If either the original or the redefinition is 2390 // in a system header, don't emit this for compatibility with GCC. 2391 if (getDiagnostics().getSuppressSystemWarnings() && 2392 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2393 (Old->isImplicit() || 2394 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2395 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2396 return; 2397 2398 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2399 << New->getDeclName(); 2400 notePreviousDefinition(Old, New->getLocation()); 2401 } 2402 2403 /// DeclhasAttr - returns true if decl Declaration already has the target 2404 /// attribute. 2405 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2406 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2407 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2408 for (const auto *i : D->attrs()) 2409 if (i->getKind() == A->getKind()) { 2410 if (Ann) { 2411 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2412 return true; 2413 continue; 2414 } 2415 // FIXME: Don't hardcode this check 2416 if (OA && isa<OwnershipAttr>(i)) 2417 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2418 return true; 2419 } 2420 2421 return false; 2422 } 2423 2424 static bool isAttributeTargetADefinition(Decl *D) { 2425 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2426 return VD->isThisDeclarationADefinition(); 2427 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2428 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2429 return true; 2430 } 2431 2432 /// Merge alignment attributes from \p Old to \p New, taking into account the 2433 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2434 /// 2435 /// \return \c true if any attributes were added to \p New. 2436 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2437 // Look for alignas attributes on Old, and pick out whichever attribute 2438 // specifies the strictest alignment requirement. 2439 AlignedAttr *OldAlignasAttr = nullptr; 2440 AlignedAttr *OldStrictestAlignAttr = nullptr; 2441 unsigned OldAlign = 0; 2442 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2443 // FIXME: We have no way of representing inherited dependent alignments 2444 // in a case like: 2445 // template<int A, int B> struct alignas(A) X; 2446 // template<int A, int B> struct alignas(B) X {}; 2447 // For now, we just ignore any alignas attributes which are not on the 2448 // definition in such a case. 2449 if (I->isAlignmentDependent()) 2450 return false; 2451 2452 if (I->isAlignas()) 2453 OldAlignasAttr = I; 2454 2455 unsigned Align = I->getAlignment(S.Context); 2456 if (Align > OldAlign) { 2457 OldAlign = Align; 2458 OldStrictestAlignAttr = I; 2459 } 2460 } 2461 2462 // Look for alignas attributes on New. 2463 AlignedAttr *NewAlignasAttr = nullptr; 2464 unsigned NewAlign = 0; 2465 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2466 if (I->isAlignmentDependent()) 2467 return false; 2468 2469 if (I->isAlignas()) 2470 NewAlignasAttr = I; 2471 2472 unsigned Align = I->getAlignment(S.Context); 2473 if (Align > NewAlign) 2474 NewAlign = Align; 2475 } 2476 2477 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2478 // Both declarations have 'alignas' attributes. We require them to match. 2479 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2480 // fall short. (If two declarations both have alignas, they must both match 2481 // every definition, and so must match each other if there is a definition.) 2482 2483 // If either declaration only contains 'alignas(0)' specifiers, then it 2484 // specifies the natural alignment for the type. 2485 if (OldAlign == 0 || NewAlign == 0) { 2486 QualType Ty; 2487 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2488 Ty = VD->getType(); 2489 else 2490 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2491 2492 if (OldAlign == 0) 2493 OldAlign = S.Context.getTypeAlign(Ty); 2494 if (NewAlign == 0) 2495 NewAlign = S.Context.getTypeAlign(Ty); 2496 } 2497 2498 if (OldAlign != NewAlign) { 2499 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2500 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2501 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2502 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2503 } 2504 } 2505 2506 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2507 // C++11 [dcl.align]p6: 2508 // if any declaration of an entity has an alignment-specifier, 2509 // every defining declaration of that entity shall specify an 2510 // equivalent alignment. 2511 // C11 6.7.5/7: 2512 // If the definition of an object does not have an alignment 2513 // specifier, any other declaration of that object shall also 2514 // have no alignment specifier. 2515 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2516 << OldAlignasAttr; 2517 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2518 << OldAlignasAttr; 2519 } 2520 2521 bool AnyAdded = false; 2522 2523 // Ensure we have an attribute representing the strictest alignment. 2524 if (OldAlign > NewAlign) { 2525 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2526 Clone->setInherited(true); 2527 New->addAttr(Clone); 2528 AnyAdded = true; 2529 } 2530 2531 // Ensure we have an alignas attribute if the old declaration had one. 2532 if (OldAlignasAttr && !NewAlignasAttr && 2533 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2534 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2535 Clone->setInherited(true); 2536 New->addAttr(Clone); 2537 AnyAdded = true; 2538 } 2539 2540 return AnyAdded; 2541 } 2542 2543 #define WANT_DECL_MERGE_LOGIC 2544 #include "clang/Sema/AttrParsedAttrImpl.inc" 2545 #undef WANT_DECL_MERGE_LOGIC 2546 2547 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2548 const InheritableAttr *Attr, 2549 Sema::AvailabilityMergeKind AMK) { 2550 // Diagnose any mutual exclusions between the attribute that we want to add 2551 // and attributes that already exist on the declaration. 2552 if (!DiagnoseMutualExclusions(S, D, Attr)) 2553 return false; 2554 2555 // This function copies an attribute Attr from a previous declaration to the 2556 // new declaration D if the new declaration doesn't itself have that attribute 2557 // yet or if that attribute allows duplicates. 2558 // If you're adding a new attribute that requires logic different from 2559 // "use explicit attribute on decl if present, else use attribute from 2560 // previous decl", for example if the attribute needs to be consistent 2561 // between redeclarations, you need to call a custom merge function here. 2562 InheritableAttr *NewAttr = nullptr; 2563 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2564 NewAttr = S.mergeAvailabilityAttr( 2565 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2566 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2567 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2568 AA->getPriority()); 2569 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2570 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2571 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2572 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2573 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2574 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2575 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2576 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2577 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2578 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2579 FA->getFirstArg()); 2580 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2581 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2582 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2583 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2584 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2585 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2586 IA->getInheritanceModel()); 2587 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2588 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2589 &S.Context.Idents.get(AA->getSpelling())); 2590 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2591 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2592 isa<CUDAGlobalAttr>(Attr))) { 2593 // CUDA target attributes are part of function signature for 2594 // overloading purposes and must not be merged. 2595 return false; 2596 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2597 NewAttr = S.mergeMinSizeAttr(D, *MA); 2598 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2599 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2600 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2601 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2602 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2603 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2604 else if (isa<AlignedAttr>(Attr)) 2605 // AlignedAttrs are handled separately, because we need to handle all 2606 // such attributes on a declaration at the same time. 2607 NewAttr = nullptr; 2608 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2609 (AMK == Sema::AMK_Override || 2610 AMK == Sema::AMK_ProtocolImplementation)) 2611 NewAttr = nullptr; 2612 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2613 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2614 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2615 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2616 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2617 NewAttr = S.mergeImportNameAttr(D, *INA); 2618 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 2619 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 2620 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 2621 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 2622 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2623 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2624 2625 if (NewAttr) { 2626 NewAttr->setInherited(true); 2627 D->addAttr(NewAttr); 2628 if (isa<MSInheritanceAttr>(NewAttr)) 2629 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2630 return true; 2631 } 2632 2633 return false; 2634 } 2635 2636 static const NamedDecl *getDefinition(const Decl *D) { 2637 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2638 return TD->getDefinition(); 2639 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2640 const VarDecl *Def = VD->getDefinition(); 2641 if (Def) 2642 return Def; 2643 return VD->getActingDefinition(); 2644 } 2645 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2646 const FunctionDecl *Def = nullptr; 2647 if (FD->isDefined(Def, true)) 2648 return Def; 2649 } 2650 return nullptr; 2651 } 2652 2653 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2654 for (const auto *Attribute : D->attrs()) 2655 if (Attribute->getKind() == Kind) 2656 return true; 2657 return false; 2658 } 2659 2660 /// checkNewAttributesAfterDef - If we already have a definition, check that 2661 /// there are no new attributes in this declaration. 2662 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2663 if (!New->hasAttrs()) 2664 return; 2665 2666 const NamedDecl *Def = getDefinition(Old); 2667 if (!Def || Def == New) 2668 return; 2669 2670 AttrVec &NewAttributes = New->getAttrs(); 2671 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2672 const Attr *NewAttribute = NewAttributes[I]; 2673 2674 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2675 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2676 Sema::SkipBodyInfo SkipBody; 2677 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2678 2679 // If we're skipping this definition, drop the "alias" attribute. 2680 if (SkipBody.ShouldSkip) { 2681 NewAttributes.erase(NewAttributes.begin() + I); 2682 --E; 2683 continue; 2684 } 2685 } else { 2686 VarDecl *VD = cast<VarDecl>(New); 2687 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2688 VarDecl::TentativeDefinition 2689 ? diag::err_alias_after_tentative 2690 : diag::err_redefinition; 2691 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2692 if (Diag == diag::err_redefinition) 2693 S.notePreviousDefinition(Def, VD->getLocation()); 2694 else 2695 S.Diag(Def->getLocation(), diag::note_previous_definition); 2696 VD->setInvalidDecl(); 2697 } 2698 ++I; 2699 continue; 2700 } 2701 2702 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2703 // Tentative definitions are only interesting for the alias check above. 2704 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2705 ++I; 2706 continue; 2707 } 2708 } 2709 2710 if (hasAttribute(Def, NewAttribute->getKind())) { 2711 ++I; 2712 continue; // regular attr merging will take care of validating this. 2713 } 2714 2715 if (isa<C11NoReturnAttr>(NewAttribute)) { 2716 // C's _Noreturn is allowed to be added to a function after it is defined. 2717 ++I; 2718 continue; 2719 } else if (isa<UuidAttr>(NewAttribute)) { 2720 // msvc will allow a subsequent definition to add an uuid to a class 2721 ++I; 2722 continue; 2723 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2724 if (AA->isAlignas()) { 2725 // C++11 [dcl.align]p6: 2726 // if any declaration of an entity has an alignment-specifier, 2727 // every defining declaration of that entity shall specify an 2728 // equivalent alignment. 2729 // C11 6.7.5/7: 2730 // If the definition of an object does not have an alignment 2731 // specifier, any other declaration of that object shall also 2732 // have no alignment specifier. 2733 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2734 << AA; 2735 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2736 << AA; 2737 NewAttributes.erase(NewAttributes.begin() + I); 2738 --E; 2739 continue; 2740 } 2741 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2742 // If there is a C definition followed by a redeclaration with this 2743 // attribute then there are two different definitions. In C++, prefer the 2744 // standard diagnostics. 2745 if (!S.getLangOpts().CPlusPlus) { 2746 S.Diag(NewAttribute->getLocation(), 2747 diag::err_loader_uninitialized_redeclaration); 2748 S.Diag(Def->getLocation(), diag::note_previous_definition); 2749 NewAttributes.erase(NewAttributes.begin() + I); 2750 --E; 2751 continue; 2752 } 2753 } else if (isa<SelectAnyAttr>(NewAttribute) && 2754 cast<VarDecl>(New)->isInline() && 2755 !cast<VarDecl>(New)->isInlineSpecified()) { 2756 // Don't warn about applying selectany to implicitly inline variables. 2757 // Older compilers and language modes would require the use of selectany 2758 // to make such variables inline, and it would have no effect if we 2759 // honored it. 2760 ++I; 2761 continue; 2762 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2763 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2764 // declarations after defintions. 2765 ++I; 2766 continue; 2767 } 2768 2769 S.Diag(NewAttribute->getLocation(), 2770 diag::warn_attribute_precede_definition); 2771 S.Diag(Def->getLocation(), diag::note_previous_definition); 2772 NewAttributes.erase(NewAttributes.begin() + I); 2773 --E; 2774 } 2775 } 2776 2777 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2778 const ConstInitAttr *CIAttr, 2779 bool AttrBeforeInit) { 2780 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2781 2782 // Figure out a good way to write this specifier on the old declaration. 2783 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2784 // enough of the attribute list spelling information to extract that without 2785 // heroics. 2786 std::string SuitableSpelling; 2787 if (S.getLangOpts().CPlusPlus20) 2788 SuitableSpelling = std::string( 2789 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2790 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2791 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2792 InsertLoc, {tok::l_square, tok::l_square, 2793 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2794 S.PP.getIdentifierInfo("require_constant_initialization"), 2795 tok::r_square, tok::r_square})); 2796 if (SuitableSpelling.empty()) 2797 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2798 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2799 S.PP.getIdentifierInfo("require_constant_initialization"), 2800 tok::r_paren, tok::r_paren})); 2801 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2802 SuitableSpelling = "constinit"; 2803 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2804 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2805 if (SuitableSpelling.empty()) 2806 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2807 SuitableSpelling += " "; 2808 2809 if (AttrBeforeInit) { 2810 // extern constinit int a; 2811 // int a = 0; // error (missing 'constinit'), accepted as extension 2812 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2813 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2814 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2815 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2816 } else { 2817 // int a = 0; 2818 // constinit extern int a; // error (missing 'constinit') 2819 S.Diag(CIAttr->getLocation(), 2820 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2821 : diag::warn_require_const_init_added_too_late) 2822 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2823 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2824 << CIAttr->isConstinit() 2825 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2826 } 2827 } 2828 2829 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2830 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2831 AvailabilityMergeKind AMK) { 2832 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2833 UsedAttr *NewAttr = OldAttr->clone(Context); 2834 NewAttr->setInherited(true); 2835 New->addAttr(NewAttr); 2836 } 2837 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { 2838 RetainAttr *NewAttr = OldAttr->clone(Context); 2839 NewAttr->setInherited(true); 2840 New->addAttr(NewAttr); 2841 } 2842 2843 if (!Old->hasAttrs() && !New->hasAttrs()) 2844 return; 2845 2846 // [dcl.constinit]p1: 2847 // If the [constinit] specifier is applied to any declaration of a 2848 // variable, it shall be applied to the initializing declaration. 2849 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2850 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2851 if (bool(OldConstInit) != bool(NewConstInit)) { 2852 const auto *OldVD = cast<VarDecl>(Old); 2853 auto *NewVD = cast<VarDecl>(New); 2854 2855 // Find the initializing declaration. Note that we might not have linked 2856 // the new declaration into the redeclaration chain yet. 2857 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2858 if (!InitDecl && 2859 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2860 InitDecl = NewVD; 2861 2862 if (InitDecl == NewVD) { 2863 // This is the initializing declaration. If it would inherit 'constinit', 2864 // that's ill-formed. (Note that we do not apply this to the attribute 2865 // form). 2866 if (OldConstInit && OldConstInit->isConstinit()) 2867 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2868 /*AttrBeforeInit=*/true); 2869 } else if (NewConstInit) { 2870 // This is the first time we've been told that this declaration should 2871 // have a constant initializer. If we already saw the initializing 2872 // declaration, this is too late. 2873 if (InitDecl && InitDecl != NewVD) { 2874 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2875 /*AttrBeforeInit=*/false); 2876 NewVD->dropAttr<ConstInitAttr>(); 2877 } 2878 } 2879 } 2880 2881 // Attributes declared post-definition are currently ignored. 2882 checkNewAttributesAfterDef(*this, New, Old); 2883 2884 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2885 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2886 if (!OldA->isEquivalent(NewA)) { 2887 // This redeclaration changes __asm__ label. 2888 Diag(New->getLocation(), diag::err_different_asm_label); 2889 Diag(OldA->getLocation(), diag::note_previous_declaration); 2890 } 2891 } else if (Old->isUsed()) { 2892 // This redeclaration adds an __asm__ label to a declaration that has 2893 // already been ODR-used. 2894 Diag(New->getLocation(), diag::err_late_asm_label_name) 2895 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2896 } 2897 } 2898 2899 // Re-declaration cannot add abi_tag's. 2900 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2901 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2902 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2903 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2904 NewTag) == OldAbiTagAttr->tags_end()) { 2905 Diag(NewAbiTagAttr->getLocation(), 2906 diag::err_new_abi_tag_on_redeclaration) 2907 << NewTag; 2908 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2909 } 2910 } 2911 } else { 2912 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2913 Diag(Old->getLocation(), diag::note_previous_declaration); 2914 } 2915 } 2916 2917 // This redeclaration adds a section attribute. 2918 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2919 if (auto *VD = dyn_cast<VarDecl>(New)) { 2920 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2921 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2922 Diag(Old->getLocation(), diag::note_previous_declaration); 2923 } 2924 } 2925 } 2926 2927 // Redeclaration adds code-seg attribute. 2928 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2929 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2930 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2931 Diag(New->getLocation(), diag::warn_mismatched_section) 2932 << 0 /*codeseg*/; 2933 Diag(Old->getLocation(), diag::note_previous_declaration); 2934 } 2935 2936 if (!Old->hasAttrs()) 2937 return; 2938 2939 bool foundAny = New->hasAttrs(); 2940 2941 // Ensure that any moving of objects within the allocated map is done before 2942 // we process them. 2943 if (!foundAny) New->setAttrs(AttrVec()); 2944 2945 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2946 // Ignore deprecated/unavailable/availability attributes if requested. 2947 AvailabilityMergeKind LocalAMK = AMK_None; 2948 if (isa<DeprecatedAttr>(I) || 2949 isa<UnavailableAttr>(I) || 2950 isa<AvailabilityAttr>(I)) { 2951 switch (AMK) { 2952 case AMK_None: 2953 continue; 2954 2955 case AMK_Redeclaration: 2956 case AMK_Override: 2957 case AMK_ProtocolImplementation: 2958 LocalAMK = AMK; 2959 break; 2960 } 2961 } 2962 2963 // Already handled. 2964 if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) 2965 continue; 2966 2967 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2968 foundAny = true; 2969 } 2970 2971 if (mergeAlignedAttrs(*this, New, Old)) 2972 foundAny = true; 2973 2974 if (!foundAny) New->dropAttrs(); 2975 } 2976 2977 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2978 /// to the new one. 2979 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2980 const ParmVarDecl *oldDecl, 2981 Sema &S) { 2982 // C++11 [dcl.attr.depend]p2: 2983 // The first declaration of a function shall specify the 2984 // carries_dependency attribute for its declarator-id if any declaration 2985 // of the function specifies the carries_dependency attribute. 2986 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2987 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2988 S.Diag(CDA->getLocation(), 2989 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2990 // Find the first declaration of the parameter. 2991 // FIXME: Should we build redeclaration chains for function parameters? 2992 const FunctionDecl *FirstFD = 2993 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2994 const ParmVarDecl *FirstVD = 2995 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2996 S.Diag(FirstVD->getLocation(), 2997 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2998 } 2999 3000 if (!oldDecl->hasAttrs()) 3001 return; 3002 3003 bool foundAny = newDecl->hasAttrs(); 3004 3005 // Ensure that any moving of objects within the allocated map is 3006 // done before we process them. 3007 if (!foundAny) newDecl->setAttrs(AttrVec()); 3008 3009 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3010 if (!DeclHasAttr(newDecl, I)) { 3011 InheritableAttr *newAttr = 3012 cast<InheritableParamAttr>(I->clone(S.Context)); 3013 newAttr->setInherited(true); 3014 newDecl->addAttr(newAttr); 3015 foundAny = true; 3016 } 3017 } 3018 3019 if (!foundAny) newDecl->dropAttrs(); 3020 } 3021 3022 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3023 const ParmVarDecl *OldParam, 3024 Sema &S) { 3025 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3026 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3027 if (*Oldnullability != *Newnullability) { 3028 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3029 << DiagNullabilityKind( 3030 *Newnullability, 3031 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3032 != 0)) 3033 << DiagNullabilityKind( 3034 *Oldnullability, 3035 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3036 != 0)); 3037 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3038 } 3039 } else { 3040 QualType NewT = NewParam->getType(); 3041 NewT = S.Context.getAttributedType( 3042 AttributedType::getNullabilityAttrKind(*Oldnullability), 3043 NewT, NewT); 3044 NewParam->setType(NewT); 3045 } 3046 } 3047 } 3048 3049 namespace { 3050 3051 /// Used in MergeFunctionDecl to keep track of function parameters in 3052 /// C. 3053 struct GNUCompatibleParamWarning { 3054 ParmVarDecl *OldParm; 3055 ParmVarDecl *NewParm; 3056 QualType PromotedType; 3057 }; 3058 3059 } // end anonymous namespace 3060 3061 // Determine whether the previous declaration was a definition, implicit 3062 // declaration, or a declaration. 3063 template <typename T> 3064 static std::pair<diag::kind, SourceLocation> 3065 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3066 diag::kind PrevDiag; 3067 SourceLocation OldLocation = Old->getLocation(); 3068 if (Old->isThisDeclarationADefinition()) 3069 PrevDiag = diag::note_previous_definition; 3070 else if (Old->isImplicit()) { 3071 PrevDiag = diag::note_previous_implicit_declaration; 3072 if (OldLocation.isInvalid()) 3073 OldLocation = New->getLocation(); 3074 } else 3075 PrevDiag = diag::note_previous_declaration; 3076 return std::make_pair(PrevDiag, OldLocation); 3077 } 3078 3079 /// canRedefineFunction - checks if a function can be redefined. Currently, 3080 /// only extern inline functions can be redefined, and even then only in 3081 /// GNU89 mode. 3082 static bool canRedefineFunction(const FunctionDecl *FD, 3083 const LangOptions& LangOpts) { 3084 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3085 !LangOpts.CPlusPlus && 3086 FD->isInlineSpecified() && 3087 FD->getStorageClass() == SC_Extern); 3088 } 3089 3090 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3091 const AttributedType *AT = T->getAs<AttributedType>(); 3092 while (AT && !AT->isCallingConv()) 3093 AT = AT->getModifiedType()->getAs<AttributedType>(); 3094 return AT; 3095 } 3096 3097 template <typename T> 3098 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3099 const DeclContext *DC = Old->getDeclContext(); 3100 if (DC->isRecord()) 3101 return false; 3102 3103 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3104 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3105 return true; 3106 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3107 return true; 3108 return false; 3109 } 3110 3111 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3112 static bool isExternC(VarTemplateDecl *) { return false; } 3113 3114 /// Check whether a redeclaration of an entity introduced by a 3115 /// using-declaration is valid, given that we know it's not an overload 3116 /// (nor a hidden tag declaration). 3117 template<typename ExpectedDecl> 3118 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3119 ExpectedDecl *New) { 3120 // C++11 [basic.scope.declarative]p4: 3121 // Given a set of declarations in a single declarative region, each of 3122 // which specifies the same unqualified name, 3123 // -- they shall all refer to the same entity, or all refer to functions 3124 // and function templates; or 3125 // -- exactly one declaration shall declare a class name or enumeration 3126 // name that is not a typedef name and the other declarations shall all 3127 // refer to the same variable or enumerator, or all refer to functions 3128 // and function templates; in this case the class name or enumeration 3129 // name is hidden (3.3.10). 3130 3131 // C++11 [namespace.udecl]p14: 3132 // If a function declaration in namespace scope or block scope has the 3133 // same name and the same parameter-type-list as a function introduced 3134 // by a using-declaration, and the declarations do not declare the same 3135 // function, the program is ill-formed. 3136 3137 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3138 if (Old && 3139 !Old->getDeclContext()->getRedeclContext()->Equals( 3140 New->getDeclContext()->getRedeclContext()) && 3141 !(isExternC(Old) && isExternC(New))) 3142 Old = nullptr; 3143 3144 if (!Old) { 3145 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3146 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3147 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3148 return true; 3149 } 3150 return false; 3151 } 3152 3153 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3154 const FunctionDecl *B) { 3155 assert(A->getNumParams() == B->getNumParams()); 3156 3157 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3158 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3159 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3160 if (AttrA == AttrB) 3161 return true; 3162 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3163 AttrA->isDynamic() == AttrB->isDynamic(); 3164 }; 3165 3166 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3167 } 3168 3169 /// If necessary, adjust the semantic declaration context for a qualified 3170 /// declaration to name the correct inline namespace within the qualifier. 3171 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3172 DeclaratorDecl *OldD) { 3173 // The only case where we need to update the DeclContext is when 3174 // redeclaration lookup for a qualified name finds a declaration 3175 // in an inline namespace within the context named by the qualifier: 3176 // 3177 // inline namespace N { int f(); } 3178 // int ::f(); // Sema DC needs adjusting from :: to N::. 3179 // 3180 // For unqualified declarations, the semantic context *can* change 3181 // along the redeclaration chain (for local extern declarations, 3182 // extern "C" declarations, and friend declarations in particular). 3183 if (!NewD->getQualifier()) 3184 return; 3185 3186 // NewD is probably already in the right context. 3187 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3188 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3189 if (NamedDC->Equals(SemaDC)) 3190 return; 3191 3192 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3193 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3194 "unexpected context for redeclaration"); 3195 3196 auto *LexDC = NewD->getLexicalDeclContext(); 3197 auto FixSemaDC = [=](NamedDecl *D) { 3198 if (!D) 3199 return; 3200 D->setDeclContext(SemaDC); 3201 D->setLexicalDeclContext(LexDC); 3202 }; 3203 3204 FixSemaDC(NewD); 3205 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3206 FixSemaDC(FD->getDescribedFunctionTemplate()); 3207 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3208 FixSemaDC(VD->getDescribedVarTemplate()); 3209 } 3210 3211 /// MergeFunctionDecl - We just parsed a function 'New' from 3212 /// declarator D which has the same name and scope as a previous 3213 /// declaration 'Old'. Figure out how to resolve this situation, 3214 /// merging decls or emitting diagnostics as appropriate. 3215 /// 3216 /// In C++, New and Old must be declarations that are not 3217 /// overloaded. Use IsOverload to determine whether New and Old are 3218 /// overloaded, and to select the Old declaration that New should be 3219 /// merged with. 3220 /// 3221 /// Returns true if there was an error, false otherwise. 3222 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3223 Scope *S, bool MergeTypeWithOld) { 3224 // Verify the old decl was also a function. 3225 FunctionDecl *Old = OldD->getAsFunction(); 3226 if (!Old) { 3227 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3228 if (New->getFriendObjectKind()) { 3229 Diag(New->getLocation(), diag::err_using_decl_friend); 3230 Diag(Shadow->getTargetDecl()->getLocation(), 3231 diag::note_using_decl_target); 3232 Diag(Shadow->getUsingDecl()->getLocation(), 3233 diag::note_using_decl) << 0; 3234 return true; 3235 } 3236 3237 // Check whether the two declarations might declare the same function. 3238 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3239 return true; 3240 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3241 } else { 3242 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3243 << New->getDeclName(); 3244 notePreviousDefinition(OldD, New->getLocation()); 3245 return true; 3246 } 3247 } 3248 3249 // If the old declaration was found in an inline namespace and the new 3250 // declaration was qualified, update the DeclContext to match. 3251 adjustDeclContextForDeclaratorDecl(New, Old); 3252 3253 // If the old declaration is invalid, just give up here. 3254 if (Old->isInvalidDecl()) 3255 return true; 3256 3257 // Disallow redeclaration of some builtins. 3258 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3259 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3260 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3261 << Old << Old->getType(); 3262 return true; 3263 } 3264 3265 diag::kind PrevDiag; 3266 SourceLocation OldLocation; 3267 std::tie(PrevDiag, OldLocation) = 3268 getNoteDiagForInvalidRedeclaration(Old, New); 3269 3270 // Don't complain about this if we're in GNU89 mode and the old function 3271 // is an extern inline function. 3272 // Don't complain about specializations. They are not supposed to have 3273 // storage classes. 3274 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3275 New->getStorageClass() == SC_Static && 3276 Old->hasExternalFormalLinkage() && 3277 !New->getTemplateSpecializationInfo() && 3278 !canRedefineFunction(Old, getLangOpts())) { 3279 if (getLangOpts().MicrosoftExt) { 3280 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3281 Diag(OldLocation, PrevDiag); 3282 } else { 3283 Diag(New->getLocation(), diag::err_static_non_static) << New; 3284 Diag(OldLocation, PrevDiag); 3285 return true; 3286 } 3287 } 3288 3289 if (New->hasAttr<InternalLinkageAttr>() && 3290 !Old->hasAttr<InternalLinkageAttr>()) { 3291 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3292 << New->getDeclName(); 3293 notePreviousDefinition(Old, New->getLocation()); 3294 New->dropAttr<InternalLinkageAttr>(); 3295 } 3296 3297 if (CheckRedeclarationModuleOwnership(New, Old)) 3298 return true; 3299 3300 if (!getLangOpts().CPlusPlus) { 3301 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3302 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3303 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3304 << New << OldOvl; 3305 3306 // Try our best to find a decl that actually has the overloadable 3307 // attribute for the note. In most cases (e.g. programs with only one 3308 // broken declaration/definition), this won't matter. 3309 // 3310 // FIXME: We could do this if we juggled some extra state in 3311 // OverloadableAttr, rather than just removing it. 3312 const Decl *DiagOld = Old; 3313 if (OldOvl) { 3314 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3315 const auto *A = D->getAttr<OverloadableAttr>(); 3316 return A && !A->isImplicit(); 3317 }); 3318 // If we've implicitly added *all* of the overloadable attrs to this 3319 // chain, emitting a "previous redecl" note is pointless. 3320 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3321 } 3322 3323 if (DiagOld) 3324 Diag(DiagOld->getLocation(), 3325 diag::note_attribute_overloadable_prev_overload) 3326 << OldOvl; 3327 3328 if (OldOvl) 3329 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3330 else 3331 New->dropAttr<OverloadableAttr>(); 3332 } 3333 } 3334 3335 // If a function is first declared with a calling convention, but is later 3336 // declared or defined without one, all following decls assume the calling 3337 // convention of the first. 3338 // 3339 // It's OK if a function is first declared without a calling convention, 3340 // but is later declared or defined with the default calling convention. 3341 // 3342 // To test if either decl has an explicit calling convention, we look for 3343 // AttributedType sugar nodes on the type as written. If they are missing or 3344 // were canonicalized away, we assume the calling convention was implicit. 3345 // 3346 // Note also that we DO NOT return at this point, because we still have 3347 // other tests to run. 3348 QualType OldQType = Context.getCanonicalType(Old->getType()); 3349 QualType NewQType = Context.getCanonicalType(New->getType()); 3350 const FunctionType *OldType = cast<FunctionType>(OldQType); 3351 const FunctionType *NewType = cast<FunctionType>(NewQType); 3352 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3353 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3354 bool RequiresAdjustment = false; 3355 3356 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3357 FunctionDecl *First = Old->getFirstDecl(); 3358 const FunctionType *FT = 3359 First->getType().getCanonicalType()->castAs<FunctionType>(); 3360 FunctionType::ExtInfo FI = FT->getExtInfo(); 3361 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3362 if (!NewCCExplicit) { 3363 // Inherit the CC from the previous declaration if it was specified 3364 // there but not here. 3365 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3366 RequiresAdjustment = true; 3367 } else if (Old->getBuiltinID()) { 3368 // Builtin attribute isn't propagated to the new one yet at this point, 3369 // so we check if the old one is a builtin. 3370 3371 // Calling Conventions on a Builtin aren't really useful and setting a 3372 // default calling convention and cdecl'ing some builtin redeclarations is 3373 // common, so warn and ignore the calling convention on the redeclaration. 3374 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3375 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3376 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3377 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3378 RequiresAdjustment = true; 3379 } else { 3380 // Calling conventions aren't compatible, so complain. 3381 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3382 Diag(New->getLocation(), diag::err_cconv_change) 3383 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3384 << !FirstCCExplicit 3385 << (!FirstCCExplicit ? "" : 3386 FunctionType::getNameForCallConv(FI.getCC())); 3387 3388 // Put the note on the first decl, since it is the one that matters. 3389 Diag(First->getLocation(), diag::note_previous_declaration); 3390 return true; 3391 } 3392 } 3393 3394 // FIXME: diagnose the other way around? 3395 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3396 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3397 RequiresAdjustment = true; 3398 } 3399 3400 // Merge regparm attribute. 3401 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3402 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3403 if (NewTypeInfo.getHasRegParm()) { 3404 Diag(New->getLocation(), diag::err_regparm_mismatch) 3405 << NewType->getRegParmType() 3406 << OldType->getRegParmType(); 3407 Diag(OldLocation, diag::note_previous_declaration); 3408 return true; 3409 } 3410 3411 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3412 RequiresAdjustment = true; 3413 } 3414 3415 // Merge ns_returns_retained attribute. 3416 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3417 if (NewTypeInfo.getProducesResult()) { 3418 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3419 << "'ns_returns_retained'"; 3420 Diag(OldLocation, diag::note_previous_declaration); 3421 return true; 3422 } 3423 3424 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3425 RequiresAdjustment = true; 3426 } 3427 3428 if (OldTypeInfo.getNoCallerSavedRegs() != 3429 NewTypeInfo.getNoCallerSavedRegs()) { 3430 if (NewTypeInfo.getNoCallerSavedRegs()) { 3431 AnyX86NoCallerSavedRegistersAttr *Attr = 3432 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3433 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3434 Diag(OldLocation, diag::note_previous_declaration); 3435 return true; 3436 } 3437 3438 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3439 RequiresAdjustment = true; 3440 } 3441 3442 if (RequiresAdjustment) { 3443 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3444 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3445 New->setType(QualType(AdjustedType, 0)); 3446 NewQType = Context.getCanonicalType(New->getType()); 3447 } 3448 3449 // If this redeclaration makes the function inline, we may need to add it to 3450 // UndefinedButUsed. 3451 if (!Old->isInlined() && New->isInlined() && 3452 !New->hasAttr<GNUInlineAttr>() && 3453 !getLangOpts().GNUInline && 3454 Old->isUsed(false) && 3455 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3456 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3457 SourceLocation())); 3458 3459 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3460 // about it. 3461 if (New->hasAttr<GNUInlineAttr>() && 3462 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3463 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3464 } 3465 3466 // If pass_object_size params don't match up perfectly, this isn't a valid 3467 // redeclaration. 3468 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3469 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3470 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3471 << New->getDeclName(); 3472 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3473 return true; 3474 } 3475 3476 if (getLangOpts().CPlusPlus) { 3477 // C++1z [over.load]p2 3478 // Certain function declarations cannot be overloaded: 3479 // -- Function declarations that differ only in the return type, 3480 // the exception specification, or both cannot be overloaded. 3481 3482 // Check the exception specifications match. This may recompute the type of 3483 // both Old and New if it resolved exception specifications, so grab the 3484 // types again after this. Because this updates the type, we do this before 3485 // any of the other checks below, which may update the "de facto" NewQType 3486 // but do not necessarily update the type of New. 3487 if (CheckEquivalentExceptionSpec(Old, New)) 3488 return true; 3489 OldQType = Context.getCanonicalType(Old->getType()); 3490 NewQType = Context.getCanonicalType(New->getType()); 3491 3492 // Go back to the type source info to compare the declared return types, 3493 // per C++1y [dcl.type.auto]p13: 3494 // Redeclarations or specializations of a function or function template 3495 // with a declared return type that uses a placeholder type shall also 3496 // use that placeholder, not a deduced type. 3497 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3498 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3499 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3500 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3501 OldDeclaredReturnType)) { 3502 QualType ResQT; 3503 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3504 OldDeclaredReturnType->isObjCObjectPointerType()) 3505 // FIXME: This does the wrong thing for a deduced return type. 3506 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3507 if (ResQT.isNull()) { 3508 if (New->isCXXClassMember() && New->isOutOfLine()) 3509 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3510 << New << New->getReturnTypeSourceRange(); 3511 else 3512 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3513 << New->getReturnTypeSourceRange(); 3514 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3515 << Old->getReturnTypeSourceRange(); 3516 return true; 3517 } 3518 else 3519 NewQType = ResQT; 3520 } 3521 3522 QualType OldReturnType = OldType->getReturnType(); 3523 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3524 if (OldReturnType != NewReturnType) { 3525 // If this function has a deduced return type and has already been 3526 // defined, copy the deduced value from the old declaration. 3527 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3528 if (OldAT && OldAT->isDeduced()) { 3529 New->setType( 3530 SubstAutoType(New->getType(), 3531 OldAT->isDependentType() ? Context.DependentTy 3532 : OldAT->getDeducedType())); 3533 NewQType = Context.getCanonicalType( 3534 SubstAutoType(NewQType, 3535 OldAT->isDependentType() ? Context.DependentTy 3536 : OldAT->getDeducedType())); 3537 } 3538 } 3539 3540 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3541 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3542 if (OldMethod && NewMethod) { 3543 // Preserve triviality. 3544 NewMethod->setTrivial(OldMethod->isTrivial()); 3545 3546 // MSVC allows explicit template specialization at class scope: 3547 // 2 CXXMethodDecls referring to the same function will be injected. 3548 // We don't want a redeclaration error. 3549 bool IsClassScopeExplicitSpecialization = 3550 OldMethod->isFunctionTemplateSpecialization() && 3551 NewMethod->isFunctionTemplateSpecialization(); 3552 bool isFriend = NewMethod->getFriendObjectKind(); 3553 3554 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3555 !IsClassScopeExplicitSpecialization) { 3556 // -- Member function declarations with the same name and the 3557 // same parameter types cannot be overloaded if any of them 3558 // is a static member function declaration. 3559 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3560 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3561 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3562 return true; 3563 } 3564 3565 // C++ [class.mem]p1: 3566 // [...] A member shall not be declared twice in the 3567 // member-specification, except that a nested class or member 3568 // class template can be declared and then later defined. 3569 if (!inTemplateInstantiation()) { 3570 unsigned NewDiag; 3571 if (isa<CXXConstructorDecl>(OldMethod)) 3572 NewDiag = diag::err_constructor_redeclared; 3573 else if (isa<CXXDestructorDecl>(NewMethod)) 3574 NewDiag = diag::err_destructor_redeclared; 3575 else if (isa<CXXConversionDecl>(NewMethod)) 3576 NewDiag = diag::err_conv_function_redeclared; 3577 else 3578 NewDiag = diag::err_member_redeclared; 3579 3580 Diag(New->getLocation(), NewDiag); 3581 } else { 3582 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3583 << New << New->getType(); 3584 } 3585 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3586 return true; 3587 3588 // Complain if this is an explicit declaration of a special 3589 // member that was initially declared implicitly. 3590 // 3591 // As an exception, it's okay to befriend such methods in order 3592 // to permit the implicit constructor/destructor/operator calls. 3593 } else if (OldMethod->isImplicit()) { 3594 if (isFriend) { 3595 NewMethod->setImplicit(); 3596 } else { 3597 Diag(NewMethod->getLocation(), 3598 diag::err_definition_of_implicitly_declared_member) 3599 << New << getSpecialMember(OldMethod); 3600 return true; 3601 } 3602 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3603 Diag(NewMethod->getLocation(), 3604 diag::err_definition_of_explicitly_defaulted_member) 3605 << getSpecialMember(OldMethod); 3606 return true; 3607 } 3608 } 3609 3610 // C++11 [dcl.attr.noreturn]p1: 3611 // The first declaration of a function shall specify the noreturn 3612 // attribute if any declaration of that function specifies the noreturn 3613 // attribute. 3614 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3615 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3616 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3617 Diag(Old->getFirstDecl()->getLocation(), 3618 diag::note_noreturn_missing_first_decl); 3619 } 3620 3621 // C++11 [dcl.attr.depend]p2: 3622 // The first declaration of a function shall specify the 3623 // carries_dependency attribute for its declarator-id if any declaration 3624 // of the function specifies the carries_dependency attribute. 3625 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3626 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3627 Diag(CDA->getLocation(), 3628 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3629 Diag(Old->getFirstDecl()->getLocation(), 3630 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3631 } 3632 3633 // (C++98 8.3.5p3): 3634 // All declarations for a function shall agree exactly in both the 3635 // return type and the parameter-type-list. 3636 // We also want to respect all the extended bits except noreturn. 3637 3638 // noreturn should now match unless the old type info didn't have it. 3639 QualType OldQTypeForComparison = OldQType; 3640 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3641 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3642 const FunctionType *OldTypeForComparison 3643 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3644 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3645 assert(OldQTypeForComparison.isCanonical()); 3646 } 3647 3648 if (haveIncompatibleLanguageLinkages(Old, New)) { 3649 // As a special case, retain the language linkage from previous 3650 // declarations of a friend function as an extension. 3651 // 3652 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3653 // and is useful because there's otherwise no way to specify language 3654 // linkage within class scope. 3655 // 3656 // Check cautiously as the friend object kind isn't yet complete. 3657 if (New->getFriendObjectKind() != Decl::FOK_None) { 3658 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3659 Diag(OldLocation, PrevDiag); 3660 } else { 3661 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3662 Diag(OldLocation, PrevDiag); 3663 return true; 3664 } 3665 } 3666 3667 // If the function types are compatible, merge the declarations. Ignore the 3668 // exception specifier because it was already checked above in 3669 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3670 // about incompatible types under -fms-compatibility. 3671 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3672 NewQType)) 3673 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3674 3675 // If the types are imprecise (due to dependent constructs in friends or 3676 // local extern declarations), it's OK if they differ. We'll check again 3677 // during instantiation. 3678 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3679 return false; 3680 3681 // Fall through for conflicting redeclarations and redefinitions. 3682 } 3683 3684 // C: Function types need to be compatible, not identical. This handles 3685 // duplicate function decls like "void f(int); void f(enum X);" properly. 3686 if (!getLangOpts().CPlusPlus && 3687 Context.typesAreCompatible(OldQType, NewQType)) { 3688 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3689 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3690 const FunctionProtoType *OldProto = nullptr; 3691 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3692 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3693 // The old declaration provided a function prototype, but the 3694 // new declaration does not. Merge in the prototype. 3695 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3696 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3697 NewQType = 3698 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3699 OldProto->getExtProtoInfo()); 3700 New->setType(NewQType); 3701 New->setHasInheritedPrototype(); 3702 3703 // Synthesize parameters with the same types. 3704 SmallVector<ParmVarDecl*, 16> Params; 3705 for (const auto &ParamType : OldProto->param_types()) { 3706 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3707 SourceLocation(), nullptr, 3708 ParamType, /*TInfo=*/nullptr, 3709 SC_None, nullptr); 3710 Param->setScopeInfo(0, Params.size()); 3711 Param->setImplicit(); 3712 Params.push_back(Param); 3713 } 3714 3715 New->setParams(Params); 3716 } 3717 3718 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3719 } 3720 3721 // Check if the function types are compatible when pointer size address 3722 // spaces are ignored. 3723 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3724 return false; 3725 3726 // GNU C permits a K&R definition to follow a prototype declaration 3727 // if the declared types of the parameters in the K&R definition 3728 // match the types in the prototype declaration, even when the 3729 // promoted types of the parameters from the K&R definition differ 3730 // from the types in the prototype. GCC then keeps the types from 3731 // the prototype. 3732 // 3733 // If a variadic prototype is followed by a non-variadic K&R definition, 3734 // the K&R definition becomes variadic. This is sort of an edge case, but 3735 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3736 // C99 6.9.1p8. 3737 if (!getLangOpts().CPlusPlus && 3738 Old->hasPrototype() && !New->hasPrototype() && 3739 New->getType()->getAs<FunctionProtoType>() && 3740 Old->getNumParams() == New->getNumParams()) { 3741 SmallVector<QualType, 16> ArgTypes; 3742 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3743 const FunctionProtoType *OldProto 3744 = Old->getType()->getAs<FunctionProtoType>(); 3745 const FunctionProtoType *NewProto 3746 = New->getType()->getAs<FunctionProtoType>(); 3747 3748 // Determine whether this is the GNU C extension. 3749 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3750 NewProto->getReturnType()); 3751 bool LooseCompatible = !MergedReturn.isNull(); 3752 for (unsigned Idx = 0, End = Old->getNumParams(); 3753 LooseCompatible && Idx != End; ++Idx) { 3754 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3755 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3756 if (Context.typesAreCompatible(OldParm->getType(), 3757 NewProto->getParamType(Idx))) { 3758 ArgTypes.push_back(NewParm->getType()); 3759 } else if (Context.typesAreCompatible(OldParm->getType(), 3760 NewParm->getType(), 3761 /*CompareUnqualified=*/true)) { 3762 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3763 NewProto->getParamType(Idx) }; 3764 Warnings.push_back(Warn); 3765 ArgTypes.push_back(NewParm->getType()); 3766 } else 3767 LooseCompatible = false; 3768 } 3769 3770 if (LooseCompatible) { 3771 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3772 Diag(Warnings[Warn].NewParm->getLocation(), 3773 diag::ext_param_promoted_not_compatible_with_prototype) 3774 << Warnings[Warn].PromotedType 3775 << Warnings[Warn].OldParm->getType(); 3776 if (Warnings[Warn].OldParm->getLocation().isValid()) 3777 Diag(Warnings[Warn].OldParm->getLocation(), 3778 diag::note_previous_declaration); 3779 } 3780 3781 if (MergeTypeWithOld) 3782 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3783 OldProto->getExtProtoInfo())); 3784 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3785 } 3786 3787 // Fall through to diagnose conflicting types. 3788 } 3789 3790 // A function that has already been declared has been redeclared or 3791 // defined with a different type; show an appropriate diagnostic. 3792 3793 // If the previous declaration was an implicitly-generated builtin 3794 // declaration, then at the very least we should use a specialized note. 3795 unsigned BuiltinID; 3796 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3797 // If it's actually a library-defined builtin function like 'malloc' 3798 // or 'printf', just warn about the incompatible redeclaration. 3799 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3800 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3801 Diag(OldLocation, diag::note_previous_builtin_declaration) 3802 << Old << Old->getType(); 3803 return false; 3804 } 3805 3806 PrevDiag = diag::note_previous_builtin_declaration; 3807 } 3808 3809 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3810 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3811 return true; 3812 } 3813 3814 /// Completes the merge of two function declarations that are 3815 /// known to be compatible. 3816 /// 3817 /// This routine handles the merging of attributes and other 3818 /// properties of function declarations from the old declaration to 3819 /// the new declaration, once we know that New is in fact a 3820 /// redeclaration of Old. 3821 /// 3822 /// \returns false 3823 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3824 Scope *S, bool MergeTypeWithOld) { 3825 // Merge the attributes 3826 mergeDeclAttributes(New, Old); 3827 3828 // Merge "pure" flag. 3829 if (Old->isPure()) 3830 New->setPure(); 3831 3832 // Merge "used" flag. 3833 if (Old->getMostRecentDecl()->isUsed(false)) 3834 New->setIsUsed(); 3835 3836 // Merge attributes from the parameters. These can mismatch with K&R 3837 // declarations. 3838 if (New->getNumParams() == Old->getNumParams()) 3839 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3840 ParmVarDecl *NewParam = New->getParamDecl(i); 3841 ParmVarDecl *OldParam = Old->getParamDecl(i); 3842 mergeParamDeclAttributes(NewParam, OldParam, *this); 3843 mergeParamDeclTypes(NewParam, OldParam, *this); 3844 } 3845 3846 if (getLangOpts().CPlusPlus) 3847 return MergeCXXFunctionDecl(New, Old, S); 3848 3849 // Merge the function types so the we get the composite types for the return 3850 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3851 // was visible. 3852 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3853 if (!Merged.isNull() && MergeTypeWithOld) 3854 New->setType(Merged); 3855 3856 return false; 3857 } 3858 3859 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3860 ObjCMethodDecl *oldMethod) { 3861 // Merge the attributes, including deprecated/unavailable 3862 AvailabilityMergeKind MergeKind = 3863 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3864 ? AMK_ProtocolImplementation 3865 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3866 : AMK_Override; 3867 3868 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3869 3870 // Merge attributes from the parameters. 3871 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3872 oe = oldMethod->param_end(); 3873 for (ObjCMethodDecl::param_iterator 3874 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3875 ni != ne && oi != oe; ++ni, ++oi) 3876 mergeParamDeclAttributes(*ni, *oi, *this); 3877 3878 CheckObjCMethodOverride(newMethod, oldMethod); 3879 } 3880 3881 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3882 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3883 3884 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3885 ? diag::err_redefinition_different_type 3886 : diag::err_redeclaration_different_type) 3887 << New->getDeclName() << New->getType() << Old->getType(); 3888 3889 diag::kind PrevDiag; 3890 SourceLocation OldLocation; 3891 std::tie(PrevDiag, OldLocation) 3892 = getNoteDiagForInvalidRedeclaration(Old, New); 3893 S.Diag(OldLocation, PrevDiag); 3894 New->setInvalidDecl(); 3895 } 3896 3897 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3898 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3899 /// emitting diagnostics as appropriate. 3900 /// 3901 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3902 /// to here in AddInitializerToDecl. We can't check them before the initializer 3903 /// is attached. 3904 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3905 bool MergeTypeWithOld) { 3906 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3907 return; 3908 3909 QualType MergedT; 3910 if (getLangOpts().CPlusPlus) { 3911 if (New->getType()->isUndeducedType()) { 3912 // We don't know what the new type is until the initializer is attached. 3913 return; 3914 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3915 // These could still be something that needs exception specs checked. 3916 return MergeVarDeclExceptionSpecs(New, Old); 3917 } 3918 // C++ [basic.link]p10: 3919 // [...] the types specified by all declarations referring to a given 3920 // object or function shall be identical, except that declarations for an 3921 // array object can specify array types that differ by the presence or 3922 // absence of a major array bound (8.3.4). 3923 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3924 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3925 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3926 3927 // We are merging a variable declaration New into Old. If it has an array 3928 // bound, and that bound differs from Old's bound, we should diagnose the 3929 // mismatch. 3930 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3931 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3932 PrevVD = PrevVD->getPreviousDecl()) { 3933 QualType PrevVDTy = PrevVD->getType(); 3934 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3935 continue; 3936 3937 if (!Context.hasSameType(New->getType(), PrevVDTy)) 3938 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3939 } 3940 } 3941 3942 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3943 if (Context.hasSameType(OldArray->getElementType(), 3944 NewArray->getElementType())) 3945 MergedT = New->getType(); 3946 } 3947 // FIXME: Check visibility. New is hidden but has a complete type. If New 3948 // has no array bound, it should not inherit one from Old, if Old is not 3949 // visible. 3950 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3951 if (Context.hasSameType(OldArray->getElementType(), 3952 NewArray->getElementType())) 3953 MergedT = Old->getType(); 3954 } 3955 } 3956 else if (New->getType()->isObjCObjectPointerType() && 3957 Old->getType()->isObjCObjectPointerType()) { 3958 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3959 Old->getType()); 3960 } 3961 } else { 3962 // C 6.2.7p2: 3963 // All declarations that refer to the same object or function shall have 3964 // compatible type. 3965 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3966 } 3967 if (MergedT.isNull()) { 3968 // It's OK if we couldn't merge types if either type is dependent, for a 3969 // block-scope variable. In other cases (static data members of class 3970 // templates, variable templates, ...), we require the types to be 3971 // equivalent. 3972 // FIXME: The C++ standard doesn't say anything about this. 3973 if ((New->getType()->isDependentType() || 3974 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3975 // If the old type was dependent, we can't merge with it, so the new type 3976 // becomes dependent for now. We'll reproduce the original type when we 3977 // instantiate the TypeSourceInfo for the variable. 3978 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3979 New->setType(Context.DependentTy); 3980 return; 3981 } 3982 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3983 } 3984 3985 // Don't actually update the type on the new declaration if the old 3986 // declaration was an extern declaration in a different scope. 3987 if (MergeTypeWithOld) 3988 New->setType(MergedT); 3989 } 3990 3991 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3992 LookupResult &Previous) { 3993 // C11 6.2.7p4: 3994 // For an identifier with internal or external linkage declared 3995 // in a scope in which a prior declaration of that identifier is 3996 // visible, if the prior declaration specifies internal or 3997 // external linkage, the type of the identifier at the later 3998 // declaration becomes the composite type. 3999 // 4000 // If the variable isn't visible, we do not merge with its type. 4001 if (Previous.isShadowed()) 4002 return false; 4003 4004 if (S.getLangOpts().CPlusPlus) { 4005 // C++11 [dcl.array]p3: 4006 // If there is a preceding declaration of the entity in the same 4007 // scope in which the bound was specified, an omitted array bound 4008 // is taken to be the same as in that earlier declaration. 4009 return NewVD->isPreviousDeclInSameBlockScope() || 4010 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4011 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4012 } else { 4013 // If the old declaration was function-local, don't merge with its 4014 // type unless we're in the same function. 4015 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4016 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4017 } 4018 } 4019 4020 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4021 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4022 /// situation, merging decls or emitting diagnostics as appropriate. 4023 /// 4024 /// Tentative definition rules (C99 6.9.2p2) are checked by 4025 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4026 /// definitions here, since the initializer hasn't been attached. 4027 /// 4028 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4029 // If the new decl is already invalid, don't do any other checking. 4030 if (New->isInvalidDecl()) 4031 return; 4032 4033 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4034 return; 4035 4036 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4037 4038 // Verify the old decl was also a variable or variable template. 4039 VarDecl *Old = nullptr; 4040 VarTemplateDecl *OldTemplate = nullptr; 4041 if (Previous.isSingleResult()) { 4042 if (NewTemplate) { 4043 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4044 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4045 4046 if (auto *Shadow = 4047 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4048 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4049 return New->setInvalidDecl(); 4050 } else { 4051 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4052 4053 if (auto *Shadow = 4054 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4055 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4056 return New->setInvalidDecl(); 4057 } 4058 } 4059 if (!Old) { 4060 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4061 << New->getDeclName(); 4062 notePreviousDefinition(Previous.getRepresentativeDecl(), 4063 New->getLocation()); 4064 return New->setInvalidDecl(); 4065 } 4066 4067 // If the old declaration was found in an inline namespace and the new 4068 // declaration was qualified, update the DeclContext to match. 4069 adjustDeclContextForDeclaratorDecl(New, Old); 4070 4071 // Ensure the template parameters are compatible. 4072 if (NewTemplate && 4073 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4074 OldTemplate->getTemplateParameters(), 4075 /*Complain=*/true, TPL_TemplateMatch)) 4076 return New->setInvalidDecl(); 4077 4078 // C++ [class.mem]p1: 4079 // A member shall not be declared twice in the member-specification [...] 4080 // 4081 // Here, we need only consider static data members. 4082 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4083 Diag(New->getLocation(), diag::err_duplicate_member) 4084 << New->getIdentifier(); 4085 Diag(Old->getLocation(), diag::note_previous_declaration); 4086 New->setInvalidDecl(); 4087 } 4088 4089 mergeDeclAttributes(New, Old); 4090 // Warn if an already-declared variable is made a weak_import in a subsequent 4091 // declaration 4092 if (New->hasAttr<WeakImportAttr>() && 4093 Old->getStorageClass() == SC_None && 4094 !Old->hasAttr<WeakImportAttr>()) { 4095 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4096 notePreviousDefinition(Old, New->getLocation()); 4097 // Remove weak_import attribute on new declaration. 4098 New->dropAttr<WeakImportAttr>(); 4099 } 4100 4101 if (New->hasAttr<InternalLinkageAttr>() && 4102 !Old->hasAttr<InternalLinkageAttr>()) { 4103 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4104 << New->getDeclName(); 4105 notePreviousDefinition(Old, New->getLocation()); 4106 New->dropAttr<InternalLinkageAttr>(); 4107 } 4108 4109 // Merge the types. 4110 VarDecl *MostRecent = Old->getMostRecentDecl(); 4111 if (MostRecent != Old) { 4112 MergeVarDeclTypes(New, MostRecent, 4113 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4114 if (New->isInvalidDecl()) 4115 return; 4116 } 4117 4118 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4119 if (New->isInvalidDecl()) 4120 return; 4121 4122 diag::kind PrevDiag; 4123 SourceLocation OldLocation; 4124 std::tie(PrevDiag, OldLocation) = 4125 getNoteDiagForInvalidRedeclaration(Old, New); 4126 4127 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4128 if (New->getStorageClass() == SC_Static && 4129 !New->isStaticDataMember() && 4130 Old->hasExternalFormalLinkage()) { 4131 if (getLangOpts().MicrosoftExt) { 4132 Diag(New->getLocation(), diag::ext_static_non_static) 4133 << New->getDeclName(); 4134 Diag(OldLocation, PrevDiag); 4135 } else { 4136 Diag(New->getLocation(), diag::err_static_non_static) 4137 << New->getDeclName(); 4138 Diag(OldLocation, PrevDiag); 4139 return New->setInvalidDecl(); 4140 } 4141 } 4142 // C99 6.2.2p4: 4143 // For an identifier declared with the storage-class specifier 4144 // extern in a scope in which a prior declaration of that 4145 // identifier is visible,23) if the prior declaration specifies 4146 // internal or external linkage, the linkage of the identifier at 4147 // the later declaration is the same as the linkage specified at 4148 // the prior declaration. If no prior declaration is visible, or 4149 // if the prior declaration specifies no linkage, then the 4150 // identifier has external linkage. 4151 if (New->hasExternalStorage() && Old->hasLinkage()) 4152 /* Okay */; 4153 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4154 !New->isStaticDataMember() && 4155 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4156 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4157 Diag(OldLocation, PrevDiag); 4158 return New->setInvalidDecl(); 4159 } 4160 4161 // Check if extern is followed by non-extern and vice-versa. 4162 if (New->hasExternalStorage() && 4163 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4164 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4165 Diag(OldLocation, PrevDiag); 4166 return New->setInvalidDecl(); 4167 } 4168 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4169 !New->hasExternalStorage()) { 4170 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4171 Diag(OldLocation, PrevDiag); 4172 return New->setInvalidDecl(); 4173 } 4174 4175 if (CheckRedeclarationModuleOwnership(New, Old)) 4176 return; 4177 4178 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4179 4180 // FIXME: The test for external storage here seems wrong? We still 4181 // need to check for mismatches. 4182 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4183 // Don't complain about out-of-line definitions of static members. 4184 !(Old->getLexicalDeclContext()->isRecord() && 4185 !New->getLexicalDeclContext()->isRecord())) { 4186 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4187 Diag(OldLocation, PrevDiag); 4188 return New->setInvalidDecl(); 4189 } 4190 4191 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4192 if (VarDecl *Def = Old->getDefinition()) { 4193 // C++1z [dcl.fcn.spec]p4: 4194 // If the definition of a variable appears in a translation unit before 4195 // its first declaration as inline, the program is ill-formed. 4196 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4197 Diag(Def->getLocation(), diag::note_previous_definition); 4198 } 4199 } 4200 4201 // If this redeclaration makes the variable inline, we may need to add it to 4202 // UndefinedButUsed. 4203 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4204 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4205 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4206 SourceLocation())); 4207 4208 if (New->getTLSKind() != Old->getTLSKind()) { 4209 if (!Old->getTLSKind()) { 4210 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4211 Diag(OldLocation, PrevDiag); 4212 } else if (!New->getTLSKind()) { 4213 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4214 Diag(OldLocation, PrevDiag); 4215 } else { 4216 // Do not allow redeclaration to change the variable between requiring 4217 // static and dynamic initialization. 4218 // FIXME: GCC allows this, but uses the TLS keyword on the first 4219 // declaration to determine the kind. Do we need to be compatible here? 4220 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4221 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4222 Diag(OldLocation, PrevDiag); 4223 } 4224 } 4225 4226 // C++ doesn't have tentative definitions, so go right ahead and check here. 4227 if (getLangOpts().CPlusPlus && 4228 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4229 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4230 Old->getCanonicalDecl()->isConstexpr()) { 4231 // This definition won't be a definition any more once it's been merged. 4232 Diag(New->getLocation(), 4233 diag::warn_deprecated_redundant_constexpr_static_def); 4234 } else if (VarDecl *Def = Old->getDefinition()) { 4235 if (checkVarDeclRedefinition(Def, New)) 4236 return; 4237 } 4238 } 4239 4240 if (haveIncompatibleLanguageLinkages(Old, New)) { 4241 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4242 Diag(OldLocation, PrevDiag); 4243 New->setInvalidDecl(); 4244 return; 4245 } 4246 4247 // Merge "used" flag. 4248 if (Old->getMostRecentDecl()->isUsed(false)) 4249 New->setIsUsed(); 4250 4251 // Keep a chain of previous declarations. 4252 New->setPreviousDecl(Old); 4253 if (NewTemplate) 4254 NewTemplate->setPreviousDecl(OldTemplate); 4255 4256 // Inherit access appropriately. 4257 New->setAccess(Old->getAccess()); 4258 if (NewTemplate) 4259 NewTemplate->setAccess(New->getAccess()); 4260 4261 if (Old->isInline()) 4262 New->setImplicitlyInline(); 4263 } 4264 4265 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4266 SourceManager &SrcMgr = getSourceManager(); 4267 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4268 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4269 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4270 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4271 auto &HSI = PP.getHeaderSearchInfo(); 4272 StringRef HdrFilename = 4273 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4274 4275 auto noteFromModuleOrInclude = [&](Module *Mod, 4276 SourceLocation IncLoc) -> bool { 4277 // Redefinition errors with modules are common with non modular mapped 4278 // headers, example: a non-modular header H in module A that also gets 4279 // included directly in a TU. Pointing twice to the same header/definition 4280 // is confusing, try to get better diagnostics when modules is on. 4281 if (IncLoc.isValid()) { 4282 if (Mod) { 4283 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4284 << HdrFilename.str() << Mod->getFullModuleName(); 4285 if (!Mod->DefinitionLoc.isInvalid()) 4286 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4287 << Mod->getFullModuleName(); 4288 } else { 4289 Diag(IncLoc, diag::note_redefinition_include_same_file) 4290 << HdrFilename.str(); 4291 } 4292 return true; 4293 } 4294 4295 return false; 4296 }; 4297 4298 // Is it the same file and same offset? Provide more information on why 4299 // this leads to a redefinition error. 4300 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4301 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4302 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4303 bool EmittedDiag = 4304 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4305 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4306 4307 // If the header has no guards, emit a note suggesting one. 4308 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4309 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4310 4311 if (EmittedDiag) 4312 return; 4313 } 4314 4315 // Redefinition coming from different files or couldn't do better above. 4316 if (Old->getLocation().isValid()) 4317 Diag(Old->getLocation(), diag::note_previous_definition); 4318 } 4319 4320 /// We've just determined that \p Old and \p New both appear to be definitions 4321 /// of the same variable. Either diagnose or fix the problem. 4322 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4323 if (!hasVisibleDefinition(Old) && 4324 (New->getFormalLinkage() == InternalLinkage || 4325 New->isInline() || 4326 New->getDescribedVarTemplate() || 4327 New->getNumTemplateParameterLists() || 4328 New->getDeclContext()->isDependentContext())) { 4329 // The previous definition is hidden, and multiple definitions are 4330 // permitted (in separate TUs). Demote this to a declaration. 4331 New->demoteThisDefinitionToDeclaration(); 4332 4333 // Make the canonical definition visible. 4334 if (auto *OldTD = Old->getDescribedVarTemplate()) 4335 makeMergedDefinitionVisible(OldTD); 4336 makeMergedDefinitionVisible(Old); 4337 return false; 4338 } else { 4339 Diag(New->getLocation(), diag::err_redefinition) << New; 4340 notePreviousDefinition(Old, New->getLocation()); 4341 New->setInvalidDecl(); 4342 return true; 4343 } 4344 } 4345 4346 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4347 /// no declarator (e.g. "struct foo;") is parsed. 4348 Decl * 4349 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4350 RecordDecl *&AnonRecord) { 4351 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4352 AnonRecord); 4353 } 4354 4355 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4356 // disambiguate entities defined in different scopes. 4357 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4358 // compatibility. 4359 // We will pick our mangling number depending on which version of MSVC is being 4360 // targeted. 4361 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4362 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4363 ? S->getMSCurManglingNumber() 4364 : S->getMSLastManglingNumber(); 4365 } 4366 4367 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4368 if (!Context.getLangOpts().CPlusPlus) 4369 return; 4370 4371 if (isa<CXXRecordDecl>(Tag->getParent())) { 4372 // If this tag is the direct child of a class, number it if 4373 // it is anonymous. 4374 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4375 return; 4376 MangleNumberingContext &MCtx = 4377 Context.getManglingNumberContext(Tag->getParent()); 4378 Context.setManglingNumber( 4379 Tag, MCtx.getManglingNumber( 4380 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4381 return; 4382 } 4383 4384 // If this tag isn't a direct child of a class, number it if it is local. 4385 MangleNumberingContext *MCtx; 4386 Decl *ManglingContextDecl; 4387 std::tie(MCtx, ManglingContextDecl) = 4388 getCurrentMangleNumberContext(Tag->getDeclContext()); 4389 if (MCtx) { 4390 Context.setManglingNumber( 4391 Tag, MCtx->getManglingNumber( 4392 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4393 } 4394 } 4395 4396 namespace { 4397 struct NonCLikeKind { 4398 enum { 4399 None, 4400 BaseClass, 4401 DefaultMemberInit, 4402 Lambda, 4403 Friend, 4404 OtherMember, 4405 Invalid, 4406 } Kind = None; 4407 SourceRange Range; 4408 4409 explicit operator bool() { return Kind != None; } 4410 }; 4411 } 4412 4413 /// Determine whether a class is C-like, according to the rules of C++ 4414 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4415 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4416 if (RD->isInvalidDecl()) 4417 return {NonCLikeKind::Invalid, {}}; 4418 4419 // C++ [dcl.typedef]p9: [P1766R1] 4420 // An unnamed class with a typedef name for linkage purposes shall not 4421 // 4422 // -- have any base classes 4423 if (RD->getNumBases()) 4424 return {NonCLikeKind::BaseClass, 4425 SourceRange(RD->bases_begin()->getBeginLoc(), 4426 RD->bases_end()[-1].getEndLoc())}; 4427 bool Invalid = false; 4428 for (Decl *D : RD->decls()) { 4429 // Don't complain about things we already diagnosed. 4430 if (D->isInvalidDecl()) { 4431 Invalid = true; 4432 continue; 4433 } 4434 4435 // -- have any [...] default member initializers 4436 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4437 if (FD->hasInClassInitializer()) { 4438 auto *Init = FD->getInClassInitializer(); 4439 return {NonCLikeKind::DefaultMemberInit, 4440 Init ? Init->getSourceRange() : D->getSourceRange()}; 4441 } 4442 continue; 4443 } 4444 4445 // FIXME: We don't allow friend declarations. This violates the wording of 4446 // P1766, but not the intent. 4447 if (isa<FriendDecl>(D)) 4448 return {NonCLikeKind::Friend, D->getSourceRange()}; 4449 4450 // -- declare any members other than non-static data members, member 4451 // enumerations, or member classes, 4452 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4453 isa<EnumDecl>(D)) 4454 continue; 4455 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4456 if (!MemberRD) { 4457 if (D->isImplicit()) 4458 continue; 4459 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4460 } 4461 4462 // -- contain a lambda-expression, 4463 if (MemberRD->isLambda()) 4464 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4465 4466 // and all member classes shall also satisfy these requirements 4467 // (recursively). 4468 if (MemberRD->isThisDeclarationADefinition()) { 4469 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4470 return Kind; 4471 } 4472 } 4473 4474 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4475 } 4476 4477 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4478 TypedefNameDecl *NewTD) { 4479 if (TagFromDeclSpec->isInvalidDecl()) 4480 return; 4481 4482 // Do nothing if the tag already has a name for linkage purposes. 4483 if (TagFromDeclSpec->hasNameForLinkage()) 4484 return; 4485 4486 // A well-formed anonymous tag must always be a TUK_Definition. 4487 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4488 4489 // The type must match the tag exactly; no qualifiers allowed. 4490 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4491 Context.getTagDeclType(TagFromDeclSpec))) { 4492 if (getLangOpts().CPlusPlus) 4493 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4494 return; 4495 } 4496 4497 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4498 // An unnamed class with a typedef name for linkage purposes shall [be 4499 // C-like]. 4500 // 4501 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4502 // shouldn't happen, but there are constructs that the language rule doesn't 4503 // disallow for which we can't reasonably avoid computing linkage early. 4504 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4505 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4506 : NonCLikeKind(); 4507 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4508 if (NonCLike || ChangesLinkage) { 4509 if (NonCLike.Kind == NonCLikeKind::Invalid) 4510 return; 4511 4512 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4513 if (ChangesLinkage) { 4514 // If the linkage changes, we can't accept this as an extension. 4515 if (NonCLike.Kind == NonCLikeKind::None) 4516 DiagID = diag::err_typedef_changes_linkage; 4517 else 4518 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4519 } 4520 4521 SourceLocation FixitLoc = 4522 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4523 llvm::SmallString<40> TextToInsert; 4524 TextToInsert += ' '; 4525 TextToInsert += NewTD->getIdentifier()->getName(); 4526 4527 Diag(FixitLoc, DiagID) 4528 << isa<TypeAliasDecl>(NewTD) 4529 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4530 if (NonCLike.Kind != NonCLikeKind::None) { 4531 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4532 << NonCLike.Kind - 1 << NonCLike.Range; 4533 } 4534 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4535 << NewTD << isa<TypeAliasDecl>(NewTD); 4536 4537 if (ChangesLinkage) 4538 return; 4539 } 4540 4541 // Otherwise, set this as the anon-decl typedef for the tag. 4542 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4543 } 4544 4545 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4546 switch (T) { 4547 case DeclSpec::TST_class: 4548 return 0; 4549 case DeclSpec::TST_struct: 4550 return 1; 4551 case DeclSpec::TST_interface: 4552 return 2; 4553 case DeclSpec::TST_union: 4554 return 3; 4555 case DeclSpec::TST_enum: 4556 return 4; 4557 default: 4558 llvm_unreachable("unexpected type specifier"); 4559 } 4560 } 4561 4562 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4563 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4564 /// parameters to cope with template friend declarations. 4565 Decl * 4566 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4567 MultiTemplateParamsArg TemplateParams, 4568 bool IsExplicitInstantiation, 4569 RecordDecl *&AnonRecord) { 4570 Decl *TagD = nullptr; 4571 TagDecl *Tag = nullptr; 4572 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4573 DS.getTypeSpecType() == DeclSpec::TST_struct || 4574 DS.getTypeSpecType() == DeclSpec::TST_interface || 4575 DS.getTypeSpecType() == DeclSpec::TST_union || 4576 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4577 TagD = DS.getRepAsDecl(); 4578 4579 if (!TagD) // We probably had an error 4580 return nullptr; 4581 4582 // Note that the above type specs guarantee that the 4583 // type rep is a Decl, whereas in many of the others 4584 // it's a Type. 4585 if (isa<TagDecl>(TagD)) 4586 Tag = cast<TagDecl>(TagD); 4587 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4588 Tag = CTD->getTemplatedDecl(); 4589 } 4590 4591 if (Tag) { 4592 handleTagNumbering(Tag, S); 4593 Tag->setFreeStanding(); 4594 if (Tag->isInvalidDecl()) 4595 return Tag; 4596 } 4597 4598 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4599 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4600 // or incomplete types shall not be restrict-qualified." 4601 if (TypeQuals & DeclSpec::TQ_restrict) 4602 Diag(DS.getRestrictSpecLoc(), 4603 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4604 << DS.getSourceRange(); 4605 } 4606 4607 if (DS.isInlineSpecified()) 4608 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4609 << getLangOpts().CPlusPlus17; 4610 4611 if (DS.hasConstexprSpecifier()) { 4612 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4613 // and definitions of functions and variables. 4614 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4615 // the declaration of a function or function template 4616 if (Tag) 4617 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4618 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4619 << static_cast<int>(DS.getConstexprSpecifier()); 4620 else 4621 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4622 << static_cast<int>(DS.getConstexprSpecifier()); 4623 // Don't emit warnings after this error. 4624 return TagD; 4625 } 4626 4627 DiagnoseFunctionSpecifiers(DS); 4628 4629 if (DS.isFriendSpecified()) { 4630 // If we're dealing with a decl but not a TagDecl, assume that 4631 // whatever routines created it handled the friendship aspect. 4632 if (TagD && !Tag) 4633 return nullptr; 4634 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4635 } 4636 4637 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4638 bool IsExplicitSpecialization = 4639 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4640 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4641 !IsExplicitInstantiation && !IsExplicitSpecialization && 4642 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4643 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4644 // nested-name-specifier unless it is an explicit instantiation 4645 // or an explicit specialization. 4646 // 4647 // FIXME: We allow class template partial specializations here too, per the 4648 // obvious intent of DR1819. 4649 // 4650 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4651 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4652 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4653 return nullptr; 4654 } 4655 4656 // Track whether this decl-specifier declares anything. 4657 bool DeclaresAnything = true; 4658 4659 // Handle anonymous struct definitions. 4660 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4661 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4662 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4663 if (getLangOpts().CPlusPlus || 4664 Record->getDeclContext()->isRecord()) { 4665 // If CurContext is a DeclContext that can contain statements, 4666 // RecursiveASTVisitor won't visit the decls that 4667 // BuildAnonymousStructOrUnion() will put into CurContext. 4668 // Also store them here so that they can be part of the 4669 // DeclStmt that gets created in this case. 4670 // FIXME: Also return the IndirectFieldDecls created by 4671 // BuildAnonymousStructOr union, for the same reason? 4672 if (CurContext->isFunctionOrMethod()) 4673 AnonRecord = Record; 4674 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4675 Context.getPrintingPolicy()); 4676 } 4677 4678 DeclaresAnything = false; 4679 } 4680 } 4681 4682 // C11 6.7.2.1p2: 4683 // A struct-declaration that does not declare an anonymous structure or 4684 // anonymous union shall contain a struct-declarator-list. 4685 // 4686 // This rule also existed in C89 and C99; the grammar for struct-declaration 4687 // did not permit a struct-declaration without a struct-declarator-list. 4688 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4689 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4690 // Check for Microsoft C extension: anonymous struct/union member. 4691 // Handle 2 kinds of anonymous struct/union: 4692 // struct STRUCT; 4693 // union UNION; 4694 // and 4695 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4696 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4697 if ((Tag && Tag->getDeclName()) || 4698 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4699 RecordDecl *Record = nullptr; 4700 if (Tag) 4701 Record = dyn_cast<RecordDecl>(Tag); 4702 else if (const RecordType *RT = 4703 DS.getRepAsType().get()->getAsStructureType()) 4704 Record = RT->getDecl(); 4705 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4706 Record = UT->getDecl(); 4707 4708 if (Record && getLangOpts().MicrosoftExt) { 4709 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4710 << Record->isUnion() << DS.getSourceRange(); 4711 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4712 } 4713 4714 DeclaresAnything = false; 4715 } 4716 } 4717 4718 // Skip all the checks below if we have a type error. 4719 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4720 (TagD && TagD->isInvalidDecl())) 4721 return TagD; 4722 4723 if (getLangOpts().CPlusPlus && 4724 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4725 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4726 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4727 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4728 DeclaresAnything = false; 4729 4730 if (!DS.isMissingDeclaratorOk()) { 4731 // Customize diagnostic for a typedef missing a name. 4732 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4733 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4734 << DS.getSourceRange(); 4735 else 4736 DeclaresAnything = false; 4737 } 4738 4739 if (DS.isModulePrivateSpecified() && 4740 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4741 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4742 << Tag->getTagKind() 4743 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4744 4745 ActOnDocumentableDecl(TagD); 4746 4747 // C 6.7/2: 4748 // A declaration [...] shall declare at least a declarator [...], a tag, 4749 // or the members of an enumeration. 4750 // C++ [dcl.dcl]p3: 4751 // [If there are no declarators], and except for the declaration of an 4752 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4753 // names into the program, or shall redeclare a name introduced by a 4754 // previous declaration. 4755 if (!DeclaresAnything) { 4756 // In C, we allow this as a (popular) extension / bug. Don't bother 4757 // producing further diagnostics for redundant qualifiers after this. 4758 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 4759 ? diag::err_no_declarators 4760 : diag::ext_no_declarators) 4761 << DS.getSourceRange(); 4762 return TagD; 4763 } 4764 4765 // C++ [dcl.stc]p1: 4766 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4767 // init-declarator-list of the declaration shall not be empty. 4768 // C++ [dcl.fct.spec]p1: 4769 // If a cv-qualifier appears in a decl-specifier-seq, the 4770 // init-declarator-list of the declaration shall not be empty. 4771 // 4772 // Spurious qualifiers here appear to be valid in C. 4773 unsigned DiagID = diag::warn_standalone_specifier; 4774 if (getLangOpts().CPlusPlus) 4775 DiagID = diag::ext_standalone_specifier; 4776 4777 // Note that a linkage-specification sets a storage class, but 4778 // 'extern "C" struct foo;' is actually valid and not theoretically 4779 // useless. 4780 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4781 if (SCS == DeclSpec::SCS_mutable) 4782 // Since mutable is not a viable storage class specifier in C, there is 4783 // no reason to treat it as an extension. Instead, diagnose as an error. 4784 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4785 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4786 Diag(DS.getStorageClassSpecLoc(), DiagID) 4787 << DeclSpec::getSpecifierName(SCS); 4788 } 4789 4790 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4791 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4792 << DeclSpec::getSpecifierName(TSCS); 4793 if (DS.getTypeQualifiers()) { 4794 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4795 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4796 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4797 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4798 // Restrict is covered above. 4799 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4800 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4801 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4802 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4803 } 4804 4805 // Warn about ignored type attributes, for example: 4806 // __attribute__((aligned)) struct A; 4807 // Attributes should be placed after tag to apply to type declaration. 4808 if (!DS.getAttributes().empty()) { 4809 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4810 if (TypeSpecType == DeclSpec::TST_class || 4811 TypeSpecType == DeclSpec::TST_struct || 4812 TypeSpecType == DeclSpec::TST_interface || 4813 TypeSpecType == DeclSpec::TST_union || 4814 TypeSpecType == DeclSpec::TST_enum) { 4815 for (const ParsedAttr &AL : DS.getAttributes()) 4816 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4817 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4818 } 4819 } 4820 4821 return TagD; 4822 } 4823 4824 /// We are trying to inject an anonymous member into the given scope; 4825 /// check if there's an existing declaration that can't be overloaded. 4826 /// 4827 /// \return true if this is a forbidden redeclaration 4828 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4829 Scope *S, 4830 DeclContext *Owner, 4831 DeclarationName Name, 4832 SourceLocation NameLoc, 4833 bool IsUnion) { 4834 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4835 Sema::ForVisibleRedeclaration); 4836 if (!SemaRef.LookupName(R, S)) return false; 4837 4838 // Pick a representative declaration. 4839 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4840 assert(PrevDecl && "Expected a non-null Decl"); 4841 4842 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4843 return false; 4844 4845 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4846 << IsUnion << Name; 4847 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4848 4849 return true; 4850 } 4851 4852 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4853 /// anonymous struct or union AnonRecord into the owning context Owner 4854 /// and scope S. This routine will be invoked just after we realize 4855 /// that an unnamed union or struct is actually an anonymous union or 4856 /// struct, e.g., 4857 /// 4858 /// @code 4859 /// union { 4860 /// int i; 4861 /// float f; 4862 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4863 /// // f into the surrounding scope.x 4864 /// @endcode 4865 /// 4866 /// This routine is recursive, injecting the names of nested anonymous 4867 /// structs/unions into the owning context and scope as well. 4868 static bool 4869 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4870 RecordDecl *AnonRecord, AccessSpecifier AS, 4871 SmallVectorImpl<NamedDecl *> &Chaining) { 4872 bool Invalid = false; 4873 4874 // Look every FieldDecl and IndirectFieldDecl with a name. 4875 for (auto *D : AnonRecord->decls()) { 4876 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4877 cast<NamedDecl>(D)->getDeclName()) { 4878 ValueDecl *VD = cast<ValueDecl>(D); 4879 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4880 VD->getLocation(), 4881 AnonRecord->isUnion())) { 4882 // C++ [class.union]p2: 4883 // The names of the members of an anonymous union shall be 4884 // distinct from the names of any other entity in the 4885 // scope in which the anonymous union is declared. 4886 Invalid = true; 4887 } else { 4888 // C++ [class.union]p2: 4889 // For the purpose of name lookup, after the anonymous union 4890 // definition, the members of the anonymous union are 4891 // considered to have been defined in the scope in which the 4892 // anonymous union is declared. 4893 unsigned OldChainingSize = Chaining.size(); 4894 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4895 Chaining.append(IF->chain_begin(), IF->chain_end()); 4896 else 4897 Chaining.push_back(VD); 4898 4899 assert(Chaining.size() >= 2); 4900 NamedDecl **NamedChain = 4901 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4902 for (unsigned i = 0; i < Chaining.size(); i++) 4903 NamedChain[i] = Chaining[i]; 4904 4905 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4906 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4907 VD->getType(), {NamedChain, Chaining.size()}); 4908 4909 for (const auto *Attr : VD->attrs()) 4910 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4911 4912 IndirectField->setAccess(AS); 4913 IndirectField->setImplicit(); 4914 SemaRef.PushOnScopeChains(IndirectField, S); 4915 4916 // That includes picking up the appropriate access specifier. 4917 if (AS != AS_none) IndirectField->setAccess(AS); 4918 4919 Chaining.resize(OldChainingSize); 4920 } 4921 } 4922 } 4923 4924 return Invalid; 4925 } 4926 4927 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4928 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4929 /// illegal input values are mapped to SC_None. 4930 static StorageClass 4931 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4932 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4933 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4934 "Parser allowed 'typedef' as storage class VarDecl."); 4935 switch (StorageClassSpec) { 4936 case DeclSpec::SCS_unspecified: return SC_None; 4937 case DeclSpec::SCS_extern: 4938 if (DS.isExternInLinkageSpec()) 4939 return SC_None; 4940 return SC_Extern; 4941 case DeclSpec::SCS_static: return SC_Static; 4942 case DeclSpec::SCS_auto: return SC_Auto; 4943 case DeclSpec::SCS_register: return SC_Register; 4944 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4945 // Illegal SCSs map to None: error reporting is up to the caller. 4946 case DeclSpec::SCS_mutable: // Fall through. 4947 case DeclSpec::SCS_typedef: return SC_None; 4948 } 4949 llvm_unreachable("unknown storage class specifier"); 4950 } 4951 4952 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4953 assert(Record->hasInClassInitializer()); 4954 4955 for (const auto *I : Record->decls()) { 4956 const auto *FD = dyn_cast<FieldDecl>(I); 4957 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4958 FD = IFD->getAnonField(); 4959 if (FD && FD->hasInClassInitializer()) 4960 return FD->getLocation(); 4961 } 4962 4963 llvm_unreachable("couldn't find in-class initializer"); 4964 } 4965 4966 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4967 SourceLocation DefaultInitLoc) { 4968 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4969 return; 4970 4971 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4972 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4973 } 4974 4975 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4976 CXXRecordDecl *AnonUnion) { 4977 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4978 return; 4979 4980 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4981 } 4982 4983 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4984 /// anonymous structure or union. Anonymous unions are a C++ feature 4985 /// (C++ [class.union]) and a C11 feature; anonymous structures 4986 /// are a C11 feature and GNU C++ extension. 4987 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4988 AccessSpecifier AS, 4989 RecordDecl *Record, 4990 const PrintingPolicy &Policy) { 4991 DeclContext *Owner = Record->getDeclContext(); 4992 4993 // Diagnose whether this anonymous struct/union is an extension. 4994 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4995 Diag(Record->getLocation(), diag::ext_anonymous_union); 4996 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4997 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4998 else if (!Record->isUnion() && !getLangOpts().C11) 4999 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 5000 5001 // C and C++ require different kinds of checks for anonymous 5002 // structs/unions. 5003 bool Invalid = false; 5004 if (getLangOpts().CPlusPlus) { 5005 const char *PrevSpec = nullptr; 5006 if (Record->isUnion()) { 5007 // C++ [class.union]p6: 5008 // C++17 [class.union.anon]p2: 5009 // Anonymous unions declared in a named namespace or in the 5010 // global namespace shall be declared static. 5011 unsigned DiagID; 5012 DeclContext *OwnerScope = Owner->getRedeclContext(); 5013 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5014 (OwnerScope->isTranslationUnit() || 5015 (OwnerScope->isNamespace() && 5016 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5017 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5018 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5019 5020 // Recover by adding 'static'. 5021 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5022 PrevSpec, DiagID, Policy); 5023 } 5024 // C++ [class.union]p6: 5025 // A storage class is not allowed in a declaration of an 5026 // anonymous union in a class scope. 5027 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5028 isa<RecordDecl>(Owner)) { 5029 Diag(DS.getStorageClassSpecLoc(), 5030 diag::err_anonymous_union_with_storage_spec) 5031 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5032 5033 // Recover by removing the storage specifier. 5034 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5035 SourceLocation(), 5036 PrevSpec, DiagID, Context.getPrintingPolicy()); 5037 } 5038 } 5039 5040 // Ignore const/volatile/restrict qualifiers. 5041 if (DS.getTypeQualifiers()) { 5042 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5043 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5044 << Record->isUnion() << "const" 5045 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5046 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5047 Diag(DS.getVolatileSpecLoc(), 5048 diag::ext_anonymous_struct_union_qualified) 5049 << Record->isUnion() << "volatile" 5050 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5051 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5052 Diag(DS.getRestrictSpecLoc(), 5053 diag::ext_anonymous_struct_union_qualified) 5054 << Record->isUnion() << "restrict" 5055 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5056 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5057 Diag(DS.getAtomicSpecLoc(), 5058 diag::ext_anonymous_struct_union_qualified) 5059 << Record->isUnion() << "_Atomic" 5060 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5061 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5062 Diag(DS.getUnalignedSpecLoc(), 5063 diag::ext_anonymous_struct_union_qualified) 5064 << Record->isUnion() << "__unaligned" 5065 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5066 5067 DS.ClearTypeQualifiers(); 5068 } 5069 5070 // C++ [class.union]p2: 5071 // The member-specification of an anonymous union shall only 5072 // define non-static data members. [Note: nested types and 5073 // functions cannot be declared within an anonymous union. ] 5074 for (auto *Mem : Record->decls()) { 5075 // Ignore invalid declarations; we already diagnosed them. 5076 if (Mem->isInvalidDecl()) 5077 continue; 5078 5079 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5080 // C++ [class.union]p3: 5081 // An anonymous union shall not have private or protected 5082 // members (clause 11). 5083 assert(FD->getAccess() != AS_none); 5084 if (FD->getAccess() != AS_public) { 5085 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5086 << Record->isUnion() << (FD->getAccess() == AS_protected); 5087 Invalid = true; 5088 } 5089 5090 // C++ [class.union]p1 5091 // An object of a class with a non-trivial constructor, a non-trivial 5092 // copy constructor, a non-trivial destructor, or a non-trivial copy 5093 // assignment operator cannot be a member of a union, nor can an 5094 // array of such objects. 5095 if (CheckNontrivialField(FD)) 5096 Invalid = true; 5097 } else if (Mem->isImplicit()) { 5098 // Any implicit members are fine. 5099 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5100 // This is a type that showed up in an 5101 // elaborated-type-specifier inside the anonymous struct or 5102 // union, but which actually declares a type outside of the 5103 // anonymous struct or union. It's okay. 5104 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5105 if (!MemRecord->isAnonymousStructOrUnion() && 5106 MemRecord->getDeclName()) { 5107 // Visual C++ allows type definition in anonymous struct or union. 5108 if (getLangOpts().MicrosoftExt) 5109 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5110 << Record->isUnion(); 5111 else { 5112 // This is a nested type declaration. 5113 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5114 << Record->isUnion(); 5115 Invalid = true; 5116 } 5117 } else { 5118 // This is an anonymous type definition within another anonymous type. 5119 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5120 // not part of standard C++. 5121 Diag(MemRecord->getLocation(), 5122 diag::ext_anonymous_record_with_anonymous_type) 5123 << Record->isUnion(); 5124 } 5125 } else if (isa<AccessSpecDecl>(Mem)) { 5126 // Any access specifier is fine. 5127 } else if (isa<StaticAssertDecl>(Mem)) { 5128 // In C++1z, static_assert declarations are also fine. 5129 } else { 5130 // We have something that isn't a non-static data 5131 // member. Complain about it. 5132 unsigned DK = diag::err_anonymous_record_bad_member; 5133 if (isa<TypeDecl>(Mem)) 5134 DK = diag::err_anonymous_record_with_type; 5135 else if (isa<FunctionDecl>(Mem)) 5136 DK = diag::err_anonymous_record_with_function; 5137 else if (isa<VarDecl>(Mem)) 5138 DK = diag::err_anonymous_record_with_static; 5139 5140 // Visual C++ allows type definition in anonymous struct or union. 5141 if (getLangOpts().MicrosoftExt && 5142 DK == diag::err_anonymous_record_with_type) 5143 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5144 << Record->isUnion(); 5145 else { 5146 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5147 Invalid = true; 5148 } 5149 } 5150 } 5151 5152 // C++11 [class.union]p8 (DR1460): 5153 // At most one variant member of a union may have a 5154 // brace-or-equal-initializer. 5155 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5156 Owner->isRecord()) 5157 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5158 cast<CXXRecordDecl>(Record)); 5159 } 5160 5161 if (!Record->isUnion() && !Owner->isRecord()) { 5162 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5163 << getLangOpts().CPlusPlus; 5164 Invalid = true; 5165 } 5166 5167 // C++ [dcl.dcl]p3: 5168 // [If there are no declarators], and except for the declaration of an 5169 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5170 // names into the program 5171 // C++ [class.mem]p2: 5172 // each such member-declaration shall either declare at least one member 5173 // name of the class or declare at least one unnamed bit-field 5174 // 5175 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5176 if (getLangOpts().CPlusPlus && Record->field_empty()) 5177 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5178 5179 // Mock up a declarator. 5180 Declarator Dc(DS, DeclaratorContext::Member); 5181 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5182 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5183 5184 // Create a declaration for this anonymous struct/union. 5185 NamedDecl *Anon = nullptr; 5186 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5187 Anon = FieldDecl::Create( 5188 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5189 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5190 /*BitWidth=*/nullptr, /*Mutable=*/false, 5191 /*InitStyle=*/ICIS_NoInit); 5192 Anon->setAccess(AS); 5193 ProcessDeclAttributes(S, Anon, Dc); 5194 5195 if (getLangOpts().CPlusPlus) 5196 FieldCollector->Add(cast<FieldDecl>(Anon)); 5197 } else { 5198 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5199 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5200 if (SCSpec == DeclSpec::SCS_mutable) { 5201 // mutable can only appear on non-static class members, so it's always 5202 // an error here 5203 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5204 Invalid = true; 5205 SC = SC_None; 5206 } 5207 5208 assert(DS.getAttributes().empty() && "No attribute expected"); 5209 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5210 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5211 Context.getTypeDeclType(Record), TInfo, SC); 5212 5213 // Default-initialize the implicit variable. This initialization will be 5214 // trivial in almost all cases, except if a union member has an in-class 5215 // initializer: 5216 // union { int n = 0; }; 5217 if (!Invalid) 5218 ActOnUninitializedDecl(Anon); 5219 } 5220 Anon->setImplicit(); 5221 5222 // Mark this as an anonymous struct/union type. 5223 Record->setAnonymousStructOrUnion(true); 5224 5225 // Add the anonymous struct/union object to the current 5226 // context. We'll be referencing this object when we refer to one of 5227 // its members. 5228 Owner->addDecl(Anon); 5229 5230 // Inject the members of the anonymous struct/union into the owning 5231 // context and into the identifier resolver chain for name lookup 5232 // purposes. 5233 SmallVector<NamedDecl*, 2> Chain; 5234 Chain.push_back(Anon); 5235 5236 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5237 Invalid = true; 5238 5239 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5240 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5241 MangleNumberingContext *MCtx; 5242 Decl *ManglingContextDecl; 5243 std::tie(MCtx, ManglingContextDecl) = 5244 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5245 if (MCtx) { 5246 Context.setManglingNumber( 5247 NewVD, MCtx->getManglingNumber( 5248 NewVD, getMSManglingNumber(getLangOpts(), S))); 5249 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5250 } 5251 } 5252 } 5253 5254 if (Invalid) 5255 Anon->setInvalidDecl(); 5256 5257 return Anon; 5258 } 5259 5260 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5261 /// Microsoft C anonymous structure. 5262 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5263 /// Example: 5264 /// 5265 /// struct A { int a; }; 5266 /// struct B { struct A; int b; }; 5267 /// 5268 /// void foo() { 5269 /// B var; 5270 /// var.a = 3; 5271 /// } 5272 /// 5273 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5274 RecordDecl *Record) { 5275 assert(Record && "expected a record!"); 5276 5277 // Mock up a declarator. 5278 Declarator Dc(DS, DeclaratorContext::TypeName); 5279 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5280 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5281 5282 auto *ParentDecl = cast<RecordDecl>(CurContext); 5283 QualType RecTy = Context.getTypeDeclType(Record); 5284 5285 // Create a declaration for this anonymous struct. 5286 NamedDecl *Anon = 5287 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5288 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5289 /*BitWidth=*/nullptr, /*Mutable=*/false, 5290 /*InitStyle=*/ICIS_NoInit); 5291 Anon->setImplicit(); 5292 5293 // Add the anonymous struct object to the current context. 5294 CurContext->addDecl(Anon); 5295 5296 // Inject the members of the anonymous struct into the current 5297 // context and into the identifier resolver chain for name lookup 5298 // purposes. 5299 SmallVector<NamedDecl*, 2> Chain; 5300 Chain.push_back(Anon); 5301 5302 RecordDecl *RecordDef = Record->getDefinition(); 5303 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5304 diag::err_field_incomplete_or_sizeless) || 5305 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5306 AS_none, Chain)) { 5307 Anon->setInvalidDecl(); 5308 ParentDecl->setInvalidDecl(); 5309 } 5310 5311 return Anon; 5312 } 5313 5314 /// GetNameForDeclarator - Determine the full declaration name for the 5315 /// given Declarator. 5316 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5317 return GetNameFromUnqualifiedId(D.getName()); 5318 } 5319 5320 /// Retrieves the declaration name from a parsed unqualified-id. 5321 DeclarationNameInfo 5322 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5323 DeclarationNameInfo NameInfo; 5324 NameInfo.setLoc(Name.StartLocation); 5325 5326 switch (Name.getKind()) { 5327 5328 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5329 case UnqualifiedIdKind::IK_Identifier: 5330 NameInfo.setName(Name.Identifier); 5331 return NameInfo; 5332 5333 case UnqualifiedIdKind::IK_DeductionGuideName: { 5334 // C++ [temp.deduct.guide]p3: 5335 // The simple-template-id shall name a class template specialization. 5336 // The template-name shall be the same identifier as the template-name 5337 // of the simple-template-id. 5338 // These together intend to imply that the template-name shall name a 5339 // class template. 5340 // FIXME: template<typename T> struct X {}; 5341 // template<typename T> using Y = X<T>; 5342 // Y(int) -> Y<int>; 5343 // satisfies these rules but does not name a class template. 5344 TemplateName TN = Name.TemplateName.get().get(); 5345 auto *Template = TN.getAsTemplateDecl(); 5346 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5347 Diag(Name.StartLocation, 5348 diag::err_deduction_guide_name_not_class_template) 5349 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5350 if (Template) 5351 Diag(Template->getLocation(), diag::note_template_decl_here); 5352 return DeclarationNameInfo(); 5353 } 5354 5355 NameInfo.setName( 5356 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5357 return NameInfo; 5358 } 5359 5360 case UnqualifiedIdKind::IK_OperatorFunctionId: 5361 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5362 Name.OperatorFunctionId.Operator)); 5363 NameInfo.setCXXOperatorNameRange(SourceRange( 5364 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5365 return NameInfo; 5366 5367 case UnqualifiedIdKind::IK_LiteralOperatorId: 5368 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5369 Name.Identifier)); 5370 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5371 return NameInfo; 5372 5373 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5374 TypeSourceInfo *TInfo; 5375 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5376 if (Ty.isNull()) 5377 return DeclarationNameInfo(); 5378 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5379 Context.getCanonicalType(Ty))); 5380 NameInfo.setNamedTypeInfo(TInfo); 5381 return NameInfo; 5382 } 5383 5384 case UnqualifiedIdKind::IK_ConstructorName: { 5385 TypeSourceInfo *TInfo; 5386 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5387 if (Ty.isNull()) 5388 return DeclarationNameInfo(); 5389 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5390 Context.getCanonicalType(Ty))); 5391 NameInfo.setNamedTypeInfo(TInfo); 5392 return NameInfo; 5393 } 5394 5395 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5396 // In well-formed code, we can only have a constructor 5397 // template-id that refers to the current context, so go there 5398 // to find the actual type being constructed. 5399 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5400 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5401 return DeclarationNameInfo(); 5402 5403 // Determine the type of the class being constructed. 5404 QualType CurClassType = Context.getTypeDeclType(CurClass); 5405 5406 // FIXME: Check two things: that the template-id names the same type as 5407 // CurClassType, and that the template-id does not occur when the name 5408 // was qualified. 5409 5410 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5411 Context.getCanonicalType(CurClassType))); 5412 // FIXME: should we retrieve TypeSourceInfo? 5413 NameInfo.setNamedTypeInfo(nullptr); 5414 return NameInfo; 5415 } 5416 5417 case UnqualifiedIdKind::IK_DestructorName: { 5418 TypeSourceInfo *TInfo; 5419 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5420 if (Ty.isNull()) 5421 return DeclarationNameInfo(); 5422 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5423 Context.getCanonicalType(Ty))); 5424 NameInfo.setNamedTypeInfo(TInfo); 5425 return NameInfo; 5426 } 5427 5428 case UnqualifiedIdKind::IK_TemplateId: { 5429 TemplateName TName = Name.TemplateId->Template.get(); 5430 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5431 return Context.getNameForTemplate(TName, TNameLoc); 5432 } 5433 5434 } // switch (Name.getKind()) 5435 5436 llvm_unreachable("Unknown name kind"); 5437 } 5438 5439 static QualType getCoreType(QualType Ty) { 5440 do { 5441 if (Ty->isPointerType() || Ty->isReferenceType()) 5442 Ty = Ty->getPointeeType(); 5443 else if (Ty->isArrayType()) 5444 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5445 else 5446 return Ty.withoutLocalFastQualifiers(); 5447 } while (true); 5448 } 5449 5450 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5451 /// and Definition have "nearly" matching parameters. This heuristic is 5452 /// used to improve diagnostics in the case where an out-of-line function 5453 /// definition doesn't match any declaration within the class or namespace. 5454 /// Also sets Params to the list of indices to the parameters that differ 5455 /// between the declaration and the definition. If hasSimilarParameters 5456 /// returns true and Params is empty, then all of the parameters match. 5457 static bool hasSimilarParameters(ASTContext &Context, 5458 FunctionDecl *Declaration, 5459 FunctionDecl *Definition, 5460 SmallVectorImpl<unsigned> &Params) { 5461 Params.clear(); 5462 if (Declaration->param_size() != Definition->param_size()) 5463 return false; 5464 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5465 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5466 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5467 5468 // The parameter types are identical 5469 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5470 continue; 5471 5472 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5473 QualType DefParamBaseTy = getCoreType(DefParamTy); 5474 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5475 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5476 5477 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5478 (DeclTyName && DeclTyName == DefTyName)) 5479 Params.push_back(Idx); 5480 else // The two parameters aren't even close 5481 return false; 5482 } 5483 5484 return true; 5485 } 5486 5487 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5488 /// declarator needs to be rebuilt in the current instantiation. 5489 /// Any bits of declarator which appear before the name are valid for 5490 /// consideration here. That's specifically the type in the decl spec 5491 /// and the base type in any member-pointer chunks. 5492 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5493 DeclarationName Name) { 5494 // The types we specifically need to rebuild are: 5495 // - typenames, typeofs, and decltypes 5496 // - types which will become injected class names 5497 // Of course, we also need to rebuild any type referencing such a 5498 // type. It's safest to just say "dependent", but we call out a 5499 // few cases here. 5500 5501 DeclSpec &DS = D.getMutableDeclSpec(); 5502 switch (DS.getTypeSpecType()) { 5503 case DeclSpec::TST_typename: 5504 case DeclSpec::TST_typeofType: 5505 case DeclSpec::TST_underlyingType: 5506 case DeclSpec::TST_atomic: { 5507 // Grab the type from the parser. 5508 TypeSourceInfo *TSI = nullptr; 5509 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5510 if (T.isNull() || !T->isInstantiationDependentType()) break; 5511 5512 // Make sure there's a type source info. This isn't really much 5513 // of a waste; most dependent types should have type source info 5514 // attached already. 5515 if (!TSI) 5516 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5517 5518 // Rebuild the type in the current instantiation. 5519 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5520 if (!TSI) return true; 5521 5522 // Store the new type back in the decl spec. 5523 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5524 DS.UpdateTypeRep(LocType); 5525 break; 5526 } 5527 5528 case DeclSpec::TST_decltype: 5529 case DeclSpec::TST_typeofExpr: { 5530 Expr *E = DS.getRepAsExpr(); 5531 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5532 if (Result.isInvalid()) return true; 5533 DS.UpdateExprRep(Result.get()); 5534 break; 5535 } 5536 5537 default: 5538 // Nothing to do for these decl specs. 5539 break; 5540 } 5541 5542 // It doesn't matter what order we do this in. 5543 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5544 DeclaratorChunk &Chunk = D.getTypeObject(I); 5545 5546 // The only type information in the declarator which can come 5547 // before the declaration name is the base type of a member 5548 // pointer. 5549 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5550 continue; 5551 5552 // Rebuild the scope specifier in-place. 5553 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5554 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5555 return true; 5556 } 5557 5558 return false; 5559 } 5560 5561 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5562 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 5563 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5564 5565 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5566 Dcl && Dcl->getDeclContext()->isFileContext()) 5567 Dcl->setTopLevelDeclInObjCContainer(); 5568 5569 if (getLangOpts().OpenCL) 5570 setCurrentOpenCLExtensionForDecl(Dcl); 5571 5572 return Dcl; 5573 } 5574 5575 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5576 /// If T is the name of a class, then each of the following shall have a 5577 /// name different from T: 5578 /// - every static data member of class T; 5579 /// - every member function of class T 5580 /// - every member of class T that is itself a type; 5581 /// \returns true if the declaration name violates these rules. 5582 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5583 DeclarationNameInfo NameInfo) { 5584 DeclarationName Name = NameInfo.getName(); 5585 5586 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5587 while (Record && Record->isAnonymousStructOrUnion()) 5588 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5589 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5590 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5591 return true; 5592 } 5593 5594 return false; 5595 } 5596 5597 /// Diagnose a declaration whose declarator-id has the given 5598 /// nested-name-specifier. 5599 /// 5600 /// \param SS The nested-name-specifier of the declarator-id. 5601 /// 5602 /// \param DC The declaration context to which the nested-name-specifier 5603 /// resolves. 5604 /// 5605 /// \param Name The name of the entity being declared. 5606 /// 5607 /// \param Loc The location of the name of the entity being declared. 5608 /// 5609 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5610 /// we're declaring an explicit / partial specialization / instantiation. 5611 /// 5612 /// \returns true if we cannot safely recover from this error, false otherwise. 5613 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5614 DeclarationName Name, 5615 SourceLocation Loc, bool IsTemplateId) { 5616 DeclContext *Cur = CurContext; 5617 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5618 Cur = Cur->getParent(); 5619 5620 // If the user provided a superfluous scope specifier that refers back to the 5621 // class in which the entity is already declared, diagnose and ignore it. 5622 // 5623 // class X { 5624 // void X::f(); 5625 // }; 5626 // 5627 // Note, it was once ill-formed to give redundant qualification in all 5628 // contexts, but that rule was removed by DR482. 5629 if (Cur->Equals(DC)) { 5630 if (Cur->isRecord()) { 5631 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5632 : diag::err_member_extra_qualification) 5633 << Name << FixItHint::CreateRemoval(SS.getRange()); 5634 SS.clear(); 5635 } else { 5636 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5637 } 5638 return false; 5639 } 5640 5641 // Check whether the qualifying scope encloses the scope of the original 5642 // declaration. For a template-id, we perform the checks in 5643 // CheckTemplateSpecializationScope. 5644 if (!Cur->Encloses(DC) && !IsTemplateId) { 5645 if (Cur->isRecord()) 5646 Diag(Loc, diag::err_member_qualification) 5647 << Name << SS.getRange(); 5648 else if (isa<TranslationUnitDecl>(DC)) 5649 Diag(Loc, diag::err_invalid_declarator_global_scope) 5650 << Name << SS.getRange(); 5651 else if (isa<FunctionDecl>(Cur)) 5652 Diag(Loc, diag::err_invalid_declarator_in_function) 5653 << Name << SS.getRange(); 5654 else if (isa<BlockDecl>(Cur)) 5655 Diag(Loc, diag::err_invalid_declarator_in_block) 5656 << Name << SS.getRange(); 5657 else 5658 Diag(Loc, diag::err_invalid_declarator_scope) 5659 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5660 5661 return true; 5662 } 5663 5664 if (Cur->isRecord()) { 5665 // Cannot qualify members within a class. 5666 Diag(Loc, diag::err_member_qualification) 5667 << Name << SS.getRange(); 5668 SS.clear(); 5669 5670 // C++ constructors and destructors with incorrect scopes can break 5671 // our AST invariants by having the wrong underlying types. If 5672 // that's the case, then drop this declaration entirely. 5673 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5674 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5675 !Context.hasSameType(Name.getCXXNameType(), 5676 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5677 return true; 5678 5679 return false; 5680 } 5681 5682 // C++11 [dcl.meaning]p1: 5683 // [...] "The nested-name-specifier of the qualified declarator-id shall 5684 // not begin with a decltype-specifer" 5685 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5686 while (SpecLoc.getPrefix()) 5687 SpecLoc = SpecLoc.getPrefix(); 5688 if (dyn_cast_or_null<DecltypeType>( 5689 SpecLoc.getNestedNameSpecifier()->getAsType())) 5690 Diag(Loc, diag::err_decltype_in_declarator) 5691 << SpecLoc.getTypeLoc().getSourceRange(); 5692 5693 return false; 5694 } 5695 5696 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5697 MultiTemplateParamsArg TemplateParamLists) { 5698 // TODO: consider using NameInfo for diagnostic. 5699 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5700 DeclarationName Name = NameInfo.getName(); 5701 5702 // All of these full declarators require an identifier. If it doesn't have 5703 // one, the ParsedFreeStandingDeclSpec action should be used. 5704 if (D.isDecompositionDeclarator()) { 5705 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5706 } else if (!Name) { 5707 if (!D.isInvalidType()) // Reject this if we think it is valid. 5708 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5709 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5710 return nullptr; 5711 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5712 return nullptr; 5713 5714 // The scope passed in may not be a decl scope. Zip up the scope tree until 5715 // we find one that is. 5716 while ((S->getFlags() & Scope::DeclScope) == 0 || 5717 (S->getFlags() & Scope::TemplateParamScope) != 0) 5718 S = S->getParent(); 5719 5720 DeclContext *DC = CurContext; 5721 if (D.getCXXScopeSpec().isInvalid()) 5722 D.setInvalidType(); 5723 else if (D.getCXXScopeSpec().isSet()) { 5724 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5725 UPPC_DeclarationQualifier)) 5726 return nullptr; 5727 5728 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5729 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5730 if (!DC || isa<EnumDecl>(DC)) { 5731 // If we could not compute the declaration context, it's because the 5732 // declaration context is dependent but does not refer to a class, 5733 // class template, or class template partial specialization. Complain 5734 // and return early, to avoid the coming semantic disaster. 5735 Diag(D.getIdentifierLoc(), 5736 diag::err_template_qualified_declarator_no_match) 5737 << D.getCXXScopeSpec().getScopeRep() 5738 << D.getCXXScopeSpec().getRange(); 5739 return nullptr; 5740 } 5741 bool IsDependentContext = DC->isDependentContext(); 5742 5743 if (!IsDependentContext && 5744 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5745 return nullptr; 5746 5747 // If a class is incomplete, do not parse entities inside it. 5748 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5749 Diag(D.getIdentifierLoc(), 5750 diag::err_member_def_undefined_record) 5751 << Name << DC << D.getCXXScopeSpec().getRange(); 5752 return nullptr; 5753 } 5754 if (!D.getDeclSpec().isFriendSpecified()) { 5755 if (diagnoseQualifiedDeclaration( 5756 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5757 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5758 if (DC->isRecord()) 5759 return nullptr; 5760 5761 D.setInvalidType(); 5762 } 5763 } 5764 5765 // Check whether we need to rebuild the type of the given 5766 // declaration in the current instantiation. 5767 if (EnteringContext && IsDependentContext && 5768 TemplateParamLists.size() != 0) { 5769 ContextRAII SavedContext(*this, DC); 5770 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5771 D.setInvalidType(); 5772 } 5773 } 5774 5775 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5776 QualType R = TInfo->getType(); 5777 5778 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5779 UPPC_DeclarationType)) 5780 D.setInvalidType(); 5781 5782 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5783 forRedeclarationInCurContext()); 5784 5785 // See if this is a redefinition of a variable in the same scope. 5786 if (!D.getCXXScopeSpec().isSet()) { 5787 bool IsLinkageLookup = false; 5788 bool CreateBuiltins = false; 5789 5790 // If the declaration we're planning to build will be a function 5791 // or object with linkage, then look for another declaration with 5792 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5793 // 5794 // If the declaration we're planning to build will be declared with 5795 // external linkage in the translation unit, create any builtin with 5796 // the same name. 5797 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5798 /* Do nothing*/; 5799 else if (CurContext->isFunctionOrMethod() && 5800 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5801 R->isFunctionType())) { 5802 IsLinkageLookup = true; 5803 CreateBuiltins = 5804 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5805 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5806 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5807 CreateBuiltins = true; 5808 5809 if (IsLinkageLookup) { 5810 Previous.clear(LookupRedeclarationWithLinkage); 5811 Previous.setRedeclarationKind(ForExternalRedeclaration); 5812 } 5813 5814 LookupName(Previous, S, CreateBuiltins); 5815 } else { // Something like "int foo::x;" 5816 LookupQualifiedName(Previous, DC); 5817 5818 // C++ [dcl.meaning]p1: 5819 // When the declarator-id is qualified, the declaration shall refer to a 5820 // previously declared member of the class or namespace to which the 5821 // qualifier refers (or, in the case of a namespace, of an element of the 5822 // inline namespace set of that namespace (7.3.1)) or to a specialization 5823 // thereof; [...] 5824 // 5825 // Note that we already checked the context above, and that we do not have 5826 // enough information to make sure that Previous contains the declaration 5827 // we want to match. For example, given: 5828 // 5829 // class X { 5830 // void f(); 5831 // void f(float); 5832 // }; 5833 // 5834 // void X::f(int) { } // ill-formed 5835 // 5836 // In this case, Previous will point to the overload set 5837 // containing the two f's declared in X, but neither of them 5838 // matches. 5839 5840 // C++ [dcl.meaning]p1: 5841 // [...] the member shall not merely have been introduced by a 5842 // using-declaration in the scope of the class or namespace nominated by 5843 // the nested-name-specifier of the declarator-id. 5844 RemoveUsingDecls(Previous); 5845 } 5846 5847 if (Previous.isSingleResult() && 5848 Previous.getFoundDecl()->isTemplateParameter()) { 5849 // Maybe we will complain about the shadowed template parameter. 5850 if (!D.isInvalidType()) 5851 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5852 Previous.getFoundDecl()); 5853 5854 // Just pretend that we didn't see the previous declaration. 5855 Previous.clear(); 5856 } 5857 5858 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5859 // Forget that the previous declaration is the injected-class-name. 5860 Previous.clear(); 5861 5862 // In C++, the previous declaration we find might be a tag type 5863 // (class or enum). In this case, the new declaration will hide the 5864 // tag type. Note that this applies to functions, function templates, and 5865 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5866 if (Previous.isSingleTagDecl() && 5867 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5868 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5869 Previous.clear(); 5870 5871 // Check that there are no default arguments other than in the parameters 5872 // of a function declaration (C++ only). 5873 if (getLangOpts().CPlusPlus) 5874 CheckExtraCXXDefaultArguments(D); 5875 5876 NamedDecl *New; 5877 5878 bool AddToScope = true; 5879 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5880 if (TemplateParamLists.size()) { 5881 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5882 return nullptr; 5883 } 5884 5885 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5886 } else if (R->isFunctionType()) { 5887 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5888 TemplateParamLists, 5889 AddToScope); 5890 } else { 5891 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5892 AddToScope); 5893 } 5894 5895 if (!New) 5896 return nullptr; 5897 5898 // If this has an identifier and is not a function template specialization, 5899 // add it to the scope stack. 5900 if (New->getDeclName() && AddToScope) 5901 PushOnScopeChains(New, S); 5902 5903 if (isInOpenMPDeclareTargetContext()) 5904 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5905 5906 return New; 5907 } 5908 5909 /// Helper method to turn variable array types into constant array 5910 /// types in certain situations which would otherwise be errors (for 5911 /// GCC compatibility). 5912 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5913 ASTContext &Context, 5914 bool &SizeIsNegative, 5915 llvm::APSInt &Oversized) { 5916 // This method tries to turn a variable array into a constant 5917 // array even when the size isn't an ICE. This is necessary 5918 // for compatibility with code that depends on gcc's buggy 5919 // constant expression folding, like struct {char x[(int)(char*)2];} 5920 SizeIsNegative = false; 5921 Oversized = 0; 5922 5923 if (T->isDependentType()) 5924 return QualType(); 5925 5926 QualifierCollector Qs; 5927 const Type *Ty = Qs.strip(T); 5928 5929 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5930 QualType Pointee = PTy->getPointeeType(); 5931 QualType FixedType = 5932 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5933 Oversized); 5934 if (FixedType.isNull()) return FixedType; 5935 FixedType = Context.getPointerType(FixedType); 5936 return Qs.apply(Context, FixedType); 5937 } 5938 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5939 QualType Inner = PTy->getInnerType(); 5940 QualType FixedType = 5941 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5942 Oversized); 5943 if (FixedType.isNull()) return FixedType; 5944 FixedType = Context.getParenType(FixedType); 5945 return Qs.apply(Context, FixedType); 5946 } 5947 5948 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5949 if (!VLATy) 5950 return QualType(); 5951 5952 QualType ElemTy = VLATy->getElementType(); 5953 if (ElemTy->isVariablyModifiedType()) { 5954 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 5955 SizeIsNegative, Oversized); 5956 if (ElemTy.isNull()) 5957 return QualType(); 5958 } 5959 5960 Expr::EvalResult Result; 5961 if (!VLATy->getSizeExpr() || 5962 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5963 return QualType(); 5964 5965 llvm::APSInt Res = Result.Val.getInt(); 5966 5967 // Check whether the array size is negative. 5968 if (Res.isSigned() && Res.isNegative()) { 5969 SizeIsNegative = true; 5970 return QualType(); 5971 } 5972 5973 // Check whether the array is too large to be addressed. 5974 unsigned ActiveSizeBits = 5975 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 5976 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 5977 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 5978 : Res.getActiveBits(); 5979 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5980 Oversized = Res; 5981 return QualType(); 5982 } 5983 5984 QualType FoldedArrayType = Context.getConstantArrayType( 5985 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 5986 return Qs.apply(Context, FoldedArrayType); 5987 } 5988 5989 static void 5990 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5991 SrcTL = SrcTL.getUnqualifiedLoc(); 5992 DstTL = DstTL.getUnqualifiedLoc(); 5993 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5994 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5995 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5996 DstPTL.getPointeeLoc()); 5997 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5998 return; 5999 } 6000 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 6001 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 6002 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 6003 DstPTL.getInnerLoc()); 6004 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 6005 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 6006 return; 6007 } 6008 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6009 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6010 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6011 TypeLoc DstElemTL = DstATL.getElementLoc(); 6012 if (VariableArrayTypeLoc SrcElemATL = 6013 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6014 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6015 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6016 } else { 6017 DstElemTL.initializeFullCopy(SrcElemTL); 6018 } 6019 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6020 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6021 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6022 } 6023 6024 /// Helper method to turn variable array types into constant array 6025 /// types in certain situations which would otherwise be errors (for 6026 /// GCC compatibility). 6027 static TypeSourceInfo* 6028 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6029 ASTContext &Context, 6030 bool &SizeIsNegative, 6031 llvm::APSInt &Oversized) { 6032 QualType FixedTy 6033 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6034 SizeIsNegative, Oversized); 6035 if (FixedTy.isNull()) 6036 return nullptr; 6037 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6038 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6039 FixedTInfo->getTypeLoc()); 6040 return FixedTInfo; 6041 } 6042 6043 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6044 /// true if we were successful. 6045 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, 6046 QualType &T, SourceLocation Loc, 6047 unsigned FailedFoldDiagID) { 6048 bool SizeIsNegative; 6049 llvm::APSInt Oversized; 6050 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6051 TInfo, Context, SizeIsNegative, Oversized); 6052 if (FixedTInfo) { 6053 Diag(Loc, diag::ext_vla_folded_to_constant); 6054 TInfo = FixedTInfo; 6055 T = FixedTInfo->getType(); 6056 return true; 6057 } 6058 6059 if (SizeIsNegative) 6060 Diag(Loc, diag::err_typecheck_negative_array_size); 6061 else if (Oversized.getBoolValue()) 6062 Diag(Loc, diag::err_array_too_large) << Oversized.toString(10); 6063 else if (FailedFoldDiagID) 6064 Diag(Loc, FailedFoldDiagID); 6065 return false; 6066 } 6067 6068 /// Register the given locally-scoped extern "C" declaration so 6069 /// that it can be found later for redeclarations. We include any extern "C" 6070 /// declaration that is not visible in the translation unit here, not just 6071 /// function-scope declarations. 6072 void 6073 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6074 if (!getLangOpts().CPlusPlus && 6075 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6076 // Don't need to track declarations in the TU in C. 6077 return; 6078 6079 // Note that we have a locally-scoped external with this name. 6080 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6081 } 6082 6083 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6084 // FIXME: We can have multiple results via __attribute__((overloadable)). 6085 auto Result = Context.getExternCContextDecl()->lookup(Name); 6086 return Result.empty() ? nullptr : *Result.begin(); 6087 } 6088 6089 /// Diagnose function specifiers on a declaration of an identifier that 6090 /// does not identify a function. 6091 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6092 // FIXME: We should probably indicate the identifier in question to avoid 6093 // confusion for constructs like "virtual int a(), b;" 6094 if (DS.isVirtualSpecified()) 6095 Diag(DS.getVirtualSpecLoc(), 6096 diag::err_virtual_non_function); 6097 6098 if (DS.hasExplicitSpecifier()) 6099 Diag(DS.getExplicitSpecLoc(), 6100 diag::err_explicit_non_function); 6101 6102 if (DS.isNoreturnSpecified()) 6103 Diag(DS.getNoreturnSpecLoc(), 6104 diag::err_noreturn_non_function); 6105 } 6106 6107 NamedDecl* 6108 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6109 TypeSourceInfo *TInfo, LookupResult &Previous) { 6110 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6111 if (D.getCXXScopeSpec().isSet()) { 6112 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6113 << D.getCXXScopeSpec().getRange(); 6114 D.setInvalidType(); 6115 // Pretend we didn't see the scope specifier. 6116 DC = CurContext; 6117 Previous.clear(); 6118 } 6119 6120 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6121 6122 if (D.getDeclSpec().isInlineSpecified()) 6123 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6124 << getLangOpts().CPlusPlus17; 6125 if (D.getDeclSpec().hasConstexprSpecifier()) 6126 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6127 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6128 6129 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6130 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6131 Diag(D.getName().StartLocation, 6132 diag::err_deduction_guide_invalid_specifier) 6133 << "typedef"; 6134 else 6135 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6136 << D.getName().getSourceRange(); 6137 return nullptr; 6138 } 6139 6140 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6141 if (!NewTD) return nullptr; 6142 6143 // Handle attributes prior to checking for duplicates in MergeVarDecl 6144 ProcessDeclAttributes(S, NewTD, D); 6145 6146 CheckTypedefForVariablyModifiedType(S, NewTD); 6147 6148 bool Redeclaration = D.isRedeclaration(); 6149 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6150 D.setRedeclaration(Redeclaration); 6151 return ND; 6152 } 6153 6154 void 6155 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6156 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6157 // then it shall have block scope. 6158 // Note that variably modified types must be fixed before merging the decl so 6159 // that redeclarations will match. 6160 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6161 QualType T = TInfo->getType(); 6162 if (T->isVariablyModifiedType()) { 6163 setFunctionHasBranchProtectedScope(); 6164 6165 if (S->getFnParent() == nullptr) { 6166 bool SizeIsNegative; 6167 llvm::APSInt Oversized; 6168 TypeSourceInfo *FixedTInfo = 6169 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6170 SizeIsNegative, 6171 Oversized); 6172 if (FixedTInfo) { 6173 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6174 NewTD->setTypeSourceInfo(FixedTInfo); 6175 } else { 6176 if (SizeIsNegative) 6177 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6178 else if (T->isVariableArrayType()) 6179 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6180 else if (Oversized.getBoolValue()) 6181 Diag(NewTD->getLocation(), diag::err_array_too_large) 6182 << Oversized.toString(10); 6183 else 6184 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6185 NewTD->setInvalidDecl(); 6186 } 6187 } 6188 } 6189 } 6190 6191 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6192 /// declares a typedef-name, either using the 'typedef' type specifier or via 6193 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6194 NamedDecl* 6195 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6196 LookupResult &Previous, bool &Redeclaration) { 6197 6198 // Find the shadowed declaration before filtering for scope. 6199 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6200 6201 // Merge the decl with the existing one if appropriate. If the decl is 6202 // in an outer scope, it isn't the same thing. 6203 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6204 /*AllowInlineNamespace*/false); 6205 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6206 if (!Previous.empty()) { 6207 Redeclaration = true; 6208 MergeTypedefNameDecl(S, NewTD, Previous); 6209 } else { 6210 inferGslPointerAttribute(NewTD); 6211 } 6212 6213 if (ShadowedDecl && !Redeclaration) 6214 CheckShadow(NewTD, ShadowedDecl, Previous); 6215 6216 // If this is the C FILE type, notify the AST context. 6217 if (IdentifierInfo *II = NewTD->getIdentifier()) 6218 if (!NewTD->isInvalidDecl() && 6219 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6220 if (II->isStr("FILE")) 6221 Context.setFILEDecl(NewTD); 6222 else if (II->isStr("jmp_buf")) 6223 Context.setjmp_bufDecl(NewTD); 6224 else if (II->isStr("sigjmp_buf")) 6225 Context.setsigjmp_bufDecl(NewTD); 6226 else if (II->isStr("ucontext_t")) 6227 Context.setucontext_tDecl(NewTD); 6228 } 6229 6230 return NewTD; 6231 } 6232 6233 /// Determines whether the given declaration is an out-of-scope 6234 /// previous declaration. 6235 /// 6236 /// This routine should be invoked when name lookup has found a 6237 /// previous declaration (PrevDecl) that is not in the scope where a 6238 /// new declaration by the same name is being introduced. If the new 6239 /// declaration occurs in a local scope, previous declarations with 6240 /// linkage may still be considered previous declarations (C99 6241 /// 6.2.2p4-5, C++ [basic.link]p6). 6242 /// 6243 /// \param PrevDecl the previous declaration found by name 6244 /// lookup 6245 /// 6246 /// \param DC the context in which the new declaration is being 6247 /// declared. 6248 /// 6249 /// \returns true if PrevDecl is an out-of-scope previous declaration 6250 /// for a new delcaration with the same name. 6251 static bool 6252 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6253 ASTContext &Context) { 6254 if (!PrevDecl) 6255 return false; 6256 6257 if (!PrevDecl->hasLinkage()) 6258 return false; 6259 6260 if (Context.getLangOpts().CPlusPlus) { 6261 // C++ [basic.link]p6: 6262 // If there is a visible declaration of an entity with linkage 6263 // having the same name and type, ignoring entities declared 6264 // outside the innermost enclosing namespace scope, the block 6265 // scope declaration declares that same entity and receives the 6266 // linkage of the previous declaration. 6267 DeclContext *OuterContext = DC->getRedeclContext(); 6268 if (!OuterContext->isFunctionOrMethod()) 6269 // This rule only applies to block-scope declarations. 6270 return false; 6271 6272 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6273 if (PrevOuterContext->isRecord()) 6274 // We found a member function: ignore it. 6275 return false; 6276 6277 // Find the innermost enclosing namespace for the new and 6278 // previous declarations. 6279 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6280 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6281 6282 // The previous declaration is in a different namespace, so it 6283 // isn't the same function. 6284 if (!OuterContext->Equals(PrevOuterContext)) 6285 return false; 6286 } 6287 6288 return true; 6289 } 6290 6291 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6292 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6293 if (!SS.isSet()) return; 6294 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6295 } 6296 6297 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6298 QualType type = decl->getType(); 6299 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6300 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6301 // Various kinds of declaration aren't allowed to be __autoreleasing. 6302 unsigned kind = -1U; 6303 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6304 if (var->hasAttr<BlocksAttr>()) 6305 kind = 0; // __block 6306 else if (!var->hasLocalStorage()) 6307 kind = 1; // global 6308 } else if (isa<ObjCIvarDecl>(decl)) { 6309 kind = 3; // ivar 6310 } else if (isa<FieldDecl>(decl)) { 6311 kind = 2; // field 6312 } 6313 6314 if (kind != -1U) { 6315 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6316 << kind; 6317 } 6318 } else if (lifetime == Qualifiers::OCL_None) { 6319 // Try to infer lifetime. 6320 if (!type->isObjCLifetimeType()) 6321 return false; 6322 6323 lifetime = type->getObjCARCImplicitLifetime(); 6324 type = Context.getLifetimeQualifiedType(type, lifetime); 6325 decl->setType(type); 6326 } 6327 6328 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6329 // Thread-local variables cannot have lifetime. 6330 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6331 var->getTLSKind()) { 6332 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6333 << var->getType(); 6334 return true; 6335 } 6336 } 6337 6338 return false; 6339 } 6340 6341 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6342 if (Decl->getType().hasAddressSpace()) 6343 return; 6344 if (Decl->getType()->isDependentType()) 6345 return; 6346 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6347 QualType Type = Var->getType(); 6348 if (Type->isSamplerT() || Type->isVoidType()) 6349 return; 6350 LangAS ImplAS = LangAS::opencl_private; 6351 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6352 Var->hasGlobalStorage()) 6353 ImplAS = LangAS::opencl_global; 6354 // If the original type from a decayed type is an array type and that array 6355 // type has no address space yet, deduce it now. 6356 if (auto DT = dyn_cast<DecayedType>(Type)) { 6357 auto OrigTy = DT->getOriginalType(); 6358 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6359 // Add the address space to the original array type and then propagate 6360 // that to the element type through `getAsArrayType`. 6361 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6362 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6363 // Re-generate the decayed type. 6364 Type = Context.getDecayedType(OrigTy); 6365 } 6366 } 6367 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6368 // Apply any qualifiers (including address space) from the array type to 6369 // the element type. This implements C99 6.7.3p8: "If the specification of 6370 // an array type includes any type qualifiers, the element type is so 6371 // qualified, not the array type." 6372 if (Type->isArrayType()) 6373 Type = QualType(Context.getAsArrayType(Type), 0); 6374 Decl->setType(Type); 6375 } 6376 } 6377 6378 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6379 // Ensure that an auto decl is deduced otherwise the checks below might cache 6380 // the wrong linkage. 6381 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6382 6383 // 'weak' only applies to declarations with external linkage. 6384 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6385 if (!ND.isExternallyVisible()) { 6386 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6387 ND.dropAttr<WeakAttr>(); 6388 } 6389 } 6390 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6391 if (ND.isExternallyVisible()) { 6392 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6393 ND.dropAttr<WeakRefAttr>(); 6394 ND.dropAttr<AliasAttr>(); 6395 } 6396 } 6397 6398 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6399 if (VD->hasInit()) { 6400 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6401 assert(VD->isThisDeclarationADefinition() && 6402 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6403 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6404 VD->dropAttr<AliasAttr>(); 6405 } 6406 } 6407 } 6408 6409 // 'selectany' only applies to externally visible variable declarations. 6410 // It does not apply to functions. 6411 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6412 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6413 S.Diag(Attr->getLocation(), 6414 diag::err_attribute_selectany_non_extern_data); 6415 ND.dropAttr<SelectAnyAttr>(); 6416 } 6417 } 6418 6419 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6420 auto *VD = dyn_cast<VarDecl>(&ND); 6421 bool IsAnonymousNS = false; 6422 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6423 if (VD) { 6424 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6425 while (NS && !IsAnonymousNS) { 6426 IsAnonymousNS = NS->isAnonymousNamespace(); 6427 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6428 } 6429 } 6430 // dll attributes require external linkage. Static locals may have external 6431 // linkage but still cannot be explicitly imported or exported. 6432 // In Microsoft mode, a variable defined in anonymous namespace must have 6433 // external linkage in order to be exported. 6434 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6435 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6436 (!AnonNSInMicrosoftMode && 6437 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6438 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6439 << &ND << Attr; 6440 ND.setInvalidDecl(); 6441 } 6442 } 6443 6444 // Check the attributes on the function type, if any. 6445 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6446 // Don't declare this variable in the second operand of the for-statement; 6447 // GCC miscompiles that by ending its lifetime before evaluating the 6448 // third operand. See gcc.gnu.org/PR86769. 6449 AttributedTypeLoc ATL; 6450 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6451 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6452 TL = ATL.getModifiedLoc()) { 6453 // The [[lifetimebound]] attribute can be applied to the implicit object 6454 // parameter of a non-static member function (other than a ctor or dtor) 6455 // by applying it to the function type. 6456 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6457 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6458 if (!MD || MD->isStatic()) { 6459 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6460 << !MD << A->getRange(); 6461 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6462 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6463 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6464 } 6465 } 6466 } 6467 } 6468 } 6469 6470 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6471 NamedDecl *NewDecl, 6472 bool IsSpecialization, 6473 bool IsDefinition) { 6474 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6475 return; 6476 6477 bool IsTemplate = false; 6478 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6479 OldDecl = OldTD->getTemplatedDecl(); 6480 IsTemplate = true; 6481 if (!IsSpecialization) 6482 IsDefinition = false; 6483 } 6484 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6485 NewDecl = NewTD->getTemplatedDecl(); 6486 IsTemplate = true; 6487 } 6488 6489 if (!OldDecl || !NewDecl) 6490 return; 6491 6492 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6493 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6494 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6495 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6496 6497 // dllimport and dllexport are inheritable attributes so we have to exclude 6498 // inherited attribute instances. 6499 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6500 (NewExportAttr && !NewExportAttr->isInherited()); 6501 6502 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6503 // the only exception being explicit specializations. 6504 // Implicitly generated declarations are also excluded for now because there 6505 // is no other way to switch these to use dllimport or dllexport. 6506 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6507 6508 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6509 // Allow with a warning for free functions and global variables. 6510 bool JustWarn = false; 6511 if (!OldDecl->isCXXClassMember()) { 6512 auto *VD = dyn_cast<VarDecl>(OldDecl); 6513 if (VD && !VD->getDescribedVarTemplate()) 6514 JustWarn = true; 6515 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6516 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6517 JustWarn = true; 6518 } 6519 6520 // We cannot change a declaration that's been used because IR has already 6521 // been emitted. Dllimported functions will still work though (modulo 6522 // address equality) as they can use the thunk. 6523 if (OldDecl->isUsed()) 6524 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6525 JustWarn = false; 6526 6527 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6528 : diag::err_attribute_dll_redeclaration; 6529 S.Diag(NewDecl->getLocation(), DiagID) 6530 << NewDecl 6531 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6532 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6533 if (!JustWarn) { 6534 NewDecl->setInvalidDecl(); 6535 return; 6536 } 6537 } 6538 6539 // A redeclaration is not allowed to drop a dllimport attribute, the only 6540 // exceptions being inline function definitions (except for function 6541 // templates), local extern declarations, qualified friend declarations or 6542 // special MSVC extension: in the last case, the declaration is treated as if 6543 // it were marked dllexport. 6544 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6545 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 6546 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6547 // Ignore static data because out-of-line definitions are diagnosed 6548 // separately. 6549 IsStaticDataMember = VD->isStaticDataMember(); 6550 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6551 VarDecl::DeclarationOnly; 6552 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6553 IsInline = FD->isInlined(); 6554 IsQualifiedFriend = FD->getQualifier() && 6555 FD->getFriendObjectKind() == Decl::FOK_Declared; 6556 } 6557 6558 if (OldImportAttr && !HasNewAttr && 6559 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 6560 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6561 if (IsMicrosoftABI && IsDefinition) { 6562 S.Diag(NewDecl->getLocation(), 6563 diag::warn_redeclaration_without_import_attribute) 6564 << NewDecl; 6565 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6566 NewDecl->dropAttr<DLLImportAttr>(); 6567 NewDecl->addAttr( 6568 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6569 } else { 6570 S.Diag(NewDecl->getLocation(), 6571 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6572 << NewDecl << OldImportAttr; 6573 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6574 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6575 OldDecl->dropAttr<DLLImportAttr>(); 6576 NewDecl->dropAttr<DLLImportAttr>(); 6577 } 6578 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 6579 // In MinGW, seeing a function declared inline drops the dllimport 6580 // attribute. 6581 OldDecl->dropAttr<DLLImportAttr>(); 6582 NewDecl->dropAttr<DLLImportAttr>(); 6583 S.Diag(NewDecl->getLocation(), 6584 diag::warn_dllimport_dropped_from_inline_function) 6585 << NewDecl << OldImportAttr; 6586 } 6587 6588 // A specialization of a class template member function is processed here 6589 // since it's a redeclaration. If the parent class is dllexport, the 6590 // specialization inherits that attribute. This doesn't happen automatically 6591 // since the parent class isn't instantiated until later. 6592 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6593 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6594 !NewImportAttr && !NewExportAttr) { 6595 if (const DLLExportAttr *ParentExportAttr = 6596 MD->getParent()->getAttr<DLLExportAttr>()) { 6597 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6598 NewAttr->setInherited(true); 6599 NewDecl->addAttr(NewAttr); 6600 } 6601 } 6602 } 6603 } 6604 6605 /// Given that we are within the definition of the given function, 6606 /// will that definition behave like C99's 'inline', where the 6607 /// definition is discarded except for optimization purposes? 6608 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6609 // Try to avoid calling GetGVALinkageForFunction. 6610 6611 // All cases of this require the 'inline' keyword. 6612 if (!FD->isInlined()) return false; 6613 6614 // This is only possible in C++ with the gnu_inline attribute. 6615 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6616 return false; 6617 6618 // Okay, go ahead and call the relatively-more-expensive function. 6619 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6620 } 6621 6622 /// Determine whether a variable is extern "C" prior to attaching 6623 /// an initializer. We can't just call isExternC() here, because that 6624 /// will also compute and cache whether the declaration is externally 6625 /// visible, which might change when we attach the initializer. 6626 /// 6627 /// This can only be used if the declaration is known to not be a 6628 /// redeclaration of an internal linkage declaration. 6629 /// 6630 /// For instance: 6631 /// 6632 /// auto x = []{}; 6633 /// 6634 /// Attaching the initializer here makes this declaration not externally 6635 /// visible, because its type has internal linkage. 6636 /// 6637 /// FIXME: This is a hack. 6638 template<typename T> 6639 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6640 if (S.getLangOpts().CPlusPlus) { 6641 // In C++, the overloadable attribute negates the effects of extern "C". 6642 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6643 return false; 6644 6645 // So do CUDA's host/device attributes. 6646 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6647 D->template hasAttr<CUDAHostAttr>())) 6648 return false; 6649 } 6650 return D->isExternC(); 6651 } 6652 6653 static bool shouldConsiderLinkage(const VarDecl *VD) { 6654 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6655 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6656 isa<OMPDeclareMapperDecl>(DC)) 6657 return VD->hasExternalStorage(); 6658 if (DC->isFileContext()) 6659 return true; 6660 if (DC->isRecord()) 6661 return false; 6662 if (isa<RequiresExprBodyDecl>(DC)) 6663 return false; 6664 llvm_unreachable("Unexpected context"); 6665 } 6666 6667 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6668 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6669 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6670 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6671 return true; 6672 if (DC->isRecord()) 6673 return false; 6674 llvm_unreachable("Unexpected context"); 6675 } 6676 6677 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6678 ParsedAttr::Kind Kind) { 6679 // Check decl attributes on the DeclSpec. 6680 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6681 return true; 6682 6683 // Walk the declarator structure, checking decl attributes that were in a type 6684 // position to the decl itself. 6685 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6686 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6687 return true; 6688 } 6689 6690 // Finally, check attributes on the decl itself. 6691 return PD.getAttributes().hasAttribute(Kind); 6692 } 6693 6694 /// Adjust the \c DeclContext for a function or variable that might be a 6695 /// function-local external declaration. 6696 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6697 if (!DC->isFunctionOrMethod()) 6698 return false; 6699 6700 // If this is a local extern function or variable declared within a function 6701 // template, don't add it into the enclosing namespace scope until it is 6702 // instantiated; it might have a dependent type right now. 6703 if (DC->isDependentContext()) 6704 return true; 6705 6706 // C++11 [basic.link]p7: 6707 // When a block scope declaration of an entity with linkage is not found to 6708 // refer to some other declaration, then that entity is a member of the 6709 // innermost enclosing namespace. 6710 // 6711 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6712 // semantically-enclosing namespace, not a lexically-enclosing one. 6713 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6714 DC = DC->getParent(); 6715 return true; 6716 } 6717 6718 /// Returns true if given declaration has external C language linkage. 6719 static bool isDeclExternC(const Decl *D) { 6720 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6721 return FD->isExternC(); 6722 if (const auto *VD = dyn_cast<VarDecl>(D)) 6723 return VD->isExternC(); 6724 6725 llvm_unreachable("Unknown type of decl!"); 6726 } 6727 6728 /// Returns true if there hasn't been any invalid type diagnosed. 6729 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { 6730 DeclContext *DC = NewVD->getDeclContext(); 6731 QualType R = NewVD->getType(); 6732 6733 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6734 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6735 // argument. 6736 if (R->isImageType() || R->isPipeType()) { 6737 Se.Diag(NewVD->getLocation(), 6738 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6739 << R; 6740 NewVD->setInvalidDecl(); 6741 return false; 6742 } 6743 6744 // OpenCL v1.2 s6.9.r: 6745 // The event type cannot be used to declare a program scope variable. 6746 // OpenCL v2.0 s6.9.q: 6747 // The clk_event_t and reserve_id_t types cannot be declared in program 6748 // scope. 6749 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { 6750 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6751 Se.Diag(NewVD->getLocation(), 6752 diag::err_invalid_type_for_program_scope_var) 6753 << R; 6754 NewVD->setInvalidDecl(); 6755 return false; 6756 } 6757 } 6758 6759 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6760 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 6761 Se.getLangOpts())) { 6762 QualType NR = R.getCanonicalType(); 6763 while (NR->isPointerType() || NR->isMemberFunctionPointerType() || 6764 NR->isReferenceType()) { 6765 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || 6766 NR->isFunctionReferenceType()) { 6767 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer) 6768 << NR->isReferenceType(); 6769 NewVD->setInvalidDecl(); 6770 return false; 6771 } 6772 NR = NR->getPointeeType(); 6773 } 6774 } 6775 6776 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 6777 Se.getLangOpts())) { 6778 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6779 // half array type (unless the cl_khr_fp16 extension is enabled). 6780 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6781 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R; 6782 NewVD->setInvalidDecl(); 6783 return false; 6784 } 6785 } 6786 6787 // OpenCL v1.2 s6.9.r: 6788 // The event type cannot be used with the __local, __constant and __global 6789 // address space qualifiers. 6790 if (R->isEventT()) { 6791 if (R.getAddressSpace() != LangAS::opencl_private) { 6792 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual); 6793 NewVD->setInvalidDecl(); 6794 return false; 6795 } 6796 } 6797 6798 if (R->isSamplerT()) { 6799 // OpenCL v1.2 s6.9.b p4: 6800 // The sampler type cannot be used with the __local and __global address 6801 // space qualifiers. 6802 if (R.getAddressSpace() == LangAS::opencl_local || 6803 R.getAddressSpace() == LangAS::opencl_global) { 6804 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace); 6805 NewVD->setInvalidDecl(); 6806 } 6807 6808 // OpenCL v1.2 s6.12.14.1: 6809 // A global sampler must be declared with either the constant address 6810 // space qualifier or with the const qualifier. 6811 if (DC->isTranslationUnit() && 6812 !(R.getAddressSpace() == LangAS::opencl_constant || 6813 R.isConstQualified())) { 6814 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler); 6815 NewVD->setInvalidDecl(); 6816 } 6817 if (NewVD->isInvalidDecl()) 6818 return false; 6819 } 6820 6821 return true; 6822 } 6823 6824 template <typename AttrTy> 6825 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { 6826 const TypedefNameDecl *TND = TT->getDecl(); 6827 if (const auto *Attribute = TND->getAttr<AttrTy>()) { 6828 AttrTy *Clone = Attribute->clone(S.Context); 6829 Clone->setInherited(true); 6830 D->addAttr(Clone); 6831 } 6832 } 6833 6834 NamedDecl *Sema::ActOnVariableDeclarator( 6835 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6836 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6837 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6838 QualType R = TInfo->getType(); 6839 DeclarationName Name = GetNameForDeclarator(D).getName(); 6840 6841 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6842 6843 if (D.isDecompositionDeclarator()) { 6844 // Take the name of the first declarator as our name for diagnostic 6845 // purposes. 6846 auto &Decomp = D.getDecompositionDeclarator(); 6847 if (!Decomp.bindings().empty()) { 6848 II = Decomp.bindings()[0].Name; 6849 Name = II; 6850 } 6851 } else if (!II) { 6852 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6853 return nullptr; 6854 } 6855 6856 6857 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6858 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6859 6860 // dllimport globals without explicit storage class are treated as extern. We 6861 // have to change the storage class this early to get the right DeclContext. 6862 if (SC == SC_None && !DC->isRecord() && 6863 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6864 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6865 SC = SC_Extern; 6866 6867 DeclContext *OriginalDC = DC; 6868 bool IsLocalExternDecl = SC == SC_Extern && 6869 adjustContextForLocalExternDecl(DC); 6870 6871 if (SCSpec == DeclSpec::SCS_mutable) { 6872 // mutable can only appear on non-static class members, so it's always 6873 // an error here 6874 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6875 D.setInvalidType(); 6876 SC = SC_None; 6877 } 6878 6879 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6880 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6881 D.getDeclSpec().getStorageClassSpecLoc())) { 6882 // In C++11, the 'register' storage class specifier is deprecated. 6883 // Suppress the warning in system macros, it's used in macros in some 6884 // popular C system headers, such as in glibc's htonl() macro. 6885 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6886 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6887 : diag::warn_deprecated_register) 6888 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6889 } 6890 6891 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6892 6893 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6894 // C99 6.9p2: The storage-class specifiers auto and register shall not 6895 // appear in the declaration specifiers in an external declaration. 6896 // Global Register+Asm is a GNU extension we support. 6897 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6898 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6899 D.setInvalidType(); 6900 } 6901 } 6902 6903 // If this variable has a VLA type and an initializer, try to 6904 // fold to a constant-sized type. This is otherwise invalid. 6905 if (D.hasInitializer() && R->isVariableArrayType()) 6906 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(), 6907 /*DiagID=*/0); 6908 6909 bool IsMemberSpecialization = false; 6910 bool IsVariableTemplateSpecialization = false; 6911 bool IsPartialSpecialization = false; 6912 bool IsVariableTemplate = false; 6913 VarDecl *NewVD = nullptr; 6914 VarTemplateDecl *NewTemplate = nullptr; 6915 TemplateParameterList *TemplateParams = nullptr; 6916 if (!getLangOpts().CPlusPlus) { 6917 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6918 II, R, TInfo, SC); 6919 6920 if (R->getContainedDeducedType()) 6921 ParsingInitForAutoVars.insert(NewVD); 6922 6923 if (D.isInvalidType()) 6924 NewVD->setInvalidDecl(); 6925 6926 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6927 NewVD->hasLocalStorage()) 6928 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6929 NTCUC_AutoVar, NTCUK_Destruct); 6930 } else { 6931 bool Invalid = false; 6932 6933 if (DC->isRecord() && !CurContext->isRecord()) { 6934 // This is an out-of-line definition of a static data member. 6935 switch (SC) { 6936 case SC_None: 6937 break; 6938 case SC_Static: 6939 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6940 diag::err_static_out_of_line) 6941 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6942 break; 6943 case SC_Auto: 6944 case SC_Register: 6945 case SC_Extern: 6946 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6947 // to names of variables declared in a block or to function parameters. 6948 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6949 // of class members 6950 6951 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6952 diag::err_storage_class_for_static_member) 6953 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6954 break; 6955 case SC_PrivateExtern: 6956 llvm_unreachable("C storage class in c++!"); 6957 } 6958 } 6959 6960 if (SC == SC_Static && CurContext->isRecord()) { 6961 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6962 // Walk up the enclosing DeclContexts to check for any that are 6963 // incompatible with static data members. 6964 const DeclContext *FunctionOrMethod = nullptr; 6965 const CXXRecordDecl *AnonStruct = nullptr; 6966 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 6967 if (Ctxt->isFunctionOrMethod()) { 6968 FunctionOrMethod = Ctxt; 6969 break; 6970 } 6971 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 6972 if (ParentDecl && !ParentDecl->getDeclName()) { 6973 AnonStruct = ParentDecl; 6974 break; 6975 } 6976 } 6977 if (FunctionOrMethod) { 6978 // C++ [class.static.data]p5: A local class shall not have static data 6979 // members. 6980 Diag(D.getIdentifierLoc(), 6981 diag::err_static_data_member_not_allowed_in_local_class) 6982 << Name << RD->getDeclName() << RD->getTagKind(); 6983 } else if (AnonStruct) { 6984 // C++ [class.static.data]p4: Unnamed classes and classes contained 6985 // directly or indirectly within unnamed classes shall not contain 6986 // static data members. 6987 Diag(D.getIdentifierLoc(), 6988 diag::err_static_data_member_not_allowed_in_anon_struct) 6989 << Name << AnonStruct->getTagKind(); 6990 Invalid = true; 6991 } else if (RD->isUnion()) { 6992 // C++98 [class.union]p1: If a union contains a static data member, 6993 // the program is ill-formed. C++11 drops this restriction. 6994 Diag(D.getIdentifierLoc(), 6995 getLangOpts().CPlusPlus11 6996 ? diag::warn_cxx98_compat_static_data_member_in_union 6997 : diag::ext_static_data_member_in_union) << Name; 6998 } 6999 } 7000 } 7001 7002 // Match up the template parameter lists with the scope specifier, then 7003 // determine whether we have a template or a template specialization. 7004 bool InvalidScope = false; 7005 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7006 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7007 D.getCXXScopeSpec(), 7008 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7009 ? D.getName().TemplateId 7010 : nullptr, 7011 TemplateParamLists, 7012 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7013 Invalid |= InvalidScope; 7014 7015 if (TemplateParams) { 7016 if (!TemplateParams->size() && 7017 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7018 // There is an extraneous 'template<>' for this variable. Complain 7019 // about it, but allow the declaration of the variable. 7020 Diag(TemplateParams->getTemplateLoc(), 7021 diag::err_template_variable_noparams) 7022 << II 7023 << SourceRange(TemplateParams->getTemplateLoc(), 7024 TemplateParams->getRAngleLoc()); 7025 TemplateParams = nullptr; 7026 } else { 7027 // Check that we can declare a template here. 7028 if (CheckTemplateDeclScope(S, TemplateParams)) 7029 return nullptr; 7030 7031 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7032 // This is an explicit specialization or a partial specialization. 7033 IsVariableTemplateSpecialization = true; 7034 IsPartialSpecialization = TemplateParams->size() > 0; 7035 } else { // if (TemplateParams->size() > 0) 7036 // This is a template declaration. 7037 IsVariableTemplate = true; 7038 7039 // Only C++1y supports variable templates (N3651). 7040 Diag(D.getIdentifierLoc(), 7041 getLangOpts().CPlusPlus14 7042 ? diag::warn_cxx11_compat_variable_template 7043 : diag::ext_variable_template); 7044 } 7045 } 7046 } else { 7047 // Check that we can declare a member specialization here. 7048 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7049 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7050 return nullptr; 7051 assert((Invalid || 7052 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7053 "should have a 'template<>' for this decl"); 7054 } 7055 7056 if (IsVariableTemplateSpecialization) { 7057 SourceLocation TemplateKWLoc = 7058 TemplateParamLists.size() > 0 7059 ? TemplateParamLists[0]->getTemplateLoc() 7060 : SourceLocation(); 7061 DeclResult Res = ActOnVarTemplateSpecialization( 7062 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7063 IsPartialSpecialization); 7064 if (Res.isInvalid()) 7065 return nullptr; 7066 NewVD = cast<VarDecl>(Res.get()); 7067 AddToScope = false; 7068 } else if (D.isDecompositionDeclarator()) { 7069 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7070 D.getIdentifierLoc(), R, TInfo, SC, 7071 Bindings); 7072 } else 7073 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7074 D.getIdentifierLoc(), II, R, TInfo, SC); 7075 7076 // If this is supposed to be a variable template, create it as such. 7077 if (IsVariableTemplate) { 7078 NewTemplate = 7079 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7080 TemplateParams, NewVD); 7081 NewVD->setDescribedVarTemplate(NewTemplate); 7082 } 7083 7084 // If this decl has an auto type in need of deduction, make a note of the 7085 // Decl so we can diagnose uses of it in its own initializer. 7086 if (R->getContainedDeducedType()) 7087 ParsingInitForAutoVars.insert(NewVD); 7088 7089 if (D.isInvalidType() || Invalid) { 7090 NewVD->setInvalidDecl(); 7091 if (NewTemplate) 7092 NewTemplate->setInvalidDecl(); 7093 } 7094 7095 SetNestedNameSpecifier(*this, NewVD, D); 7096 7097 // If we have any template parameter lists that don't directly belong to 7098 // the variable (matching the scope specifier), store them. 7099 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7100 if (TemplateParamLists.size() > VDTemplateParamLists) 7101 NewVD->setTemplateParameterListsInfo( 7102 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7103 } 7104 7105 if (D.getDeclSpec().isInlineSpecified()) { 7106 if (!getLangOpts().CPlusPlus) { 7107 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7108 << 0; 7109 } else if (CurContext->isFunctionOrMethod()) { 7110 // 'inline' is not allowed on block scope variable declaration. 7111 Diag(D.getDeclSpec().getInlineSpecLoc(), 7112 diag::err_inline_declaration_block_scope) << Name 7113 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7114 } else { 7115 Diag(D.getDeclSpec().getInlineSpecLoc(), 7116 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7117 : diag::ext_inline_variable); 7118 NewVD->setInlineSpecified(); 7119 } 7120 } 7121 7122 // Set the lexical context. If the declarator has a C++ scope specifier, the 7123 // lexical context will be different from the semantic context. 7124 NewVD->setLexicalDeclContext(CurContext); 7125 if (NewTemplate) 7126 NewTemplate->setLexicalDeclContext(CurContext); 7127 7128 if (IsLocalExternDecl) { 7129 if (D.isDecompositionDeclarator()) 7130 for (auto *B : Bindings) 7131 B->setLocalExternDecl(); 7132 else 7133 NewVD->setLocalExternDecl(); 7134 } 7135 7136 bool EmitTLSUnsupportedError = false; 7137 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7138 // C++11 [dcl.stc]p4: 7139 // When thread_local is applied to a variable of block scope the 7140 // storage-class-specifier static is implied if it does not appear 7141 // explicitly. 7142 // Core issue: 'static' is not implied if the variable is declared 7143 // 'extern'. 7144 if (NewVD->hasLocalStorage() && 7145 (SCSpec != DeclSpec::SCS_unspecified || 7146 TSCS != DeclSpec::TSCS_thread_local || 7147 !DC->isFunctionOrMethod())) 7148 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7149 diag::err_thread_non_global) 7150 << DeclSpec::getSpecifierName(TSCS); 7151 else if (!Context.getTargetInfo().isTLSSupported()) { 7152 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7153 getLangOpts().SYCLIsDevice) { 7154 // Postpone error emission until we've collected attributes required to 7155 // figure out whether it's a host or device variable and whether the 7156 // error should be ignored. 7157 EmitTLSUnsupportedError = true; 7158 // We still need to mark the variable as TLS so it shows up in AST with 7159 // proper storage class for other tools to use even if we're not going 7160 // to emit any code for it. 7161 NewVD->setTSCSpec(TSCS); 7162 } else 7163 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7164 diag::err_thread_unsupported); 7165 } else 7166 NewVD->setTSCSpec(TSCS); 7167 } 7168 7169 switch (D.getDeclSpec().getConstexprSpecifier()) { 7170 case ConstexprSpecKind::Unspecified: 7171 break; 7172 7173 case ConstexprSpecKind::Consteval: 7174 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7175 diag::err_constexpr_wrong_decl_kind) 7176 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7177 LLVM_FALLTHROUGH; 7178 7179 case ConstexprSpecKind::Constexpr: 7180 NewVD->setConstexpr(true); 7181 MaybeAddCUDAConstantAttr(NewVD); 7182 // C++1z [dcl.spec.constexpr]p1: 7183 // A static data member declared with the constexpr specifier is 7184 // implicitly an inline variable. 7185 if (NewVD->isStaticDataMember() && 7186 (getLangOpts().CPlusPlus17 || 7187 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7188 NewVD->setImplicitlyInline(); 7189 break; 7190 7191 case ConstexprSpecKind::Constinit: 7192 if (!NewVD->hasGlobalStorage()) 7193 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7194 diag::err_constinit_local_variable); 7195 else 7196 NewVD->addAttr(ConstInitAttr::Create( 7197 Context, D.getDeclSpec().getConstexprSpecLoc(), 7198 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7199 break; 7200 } 7201 7202 // C99 6.7.4p3 7203 // An inline definition of a function with external linkage shall 7204 // not contain a definition of a modifiable object with static or 7205 // thread storage duration... 7206 // We only apply this when the function is required to be defined 7207 // elsewhere, i.e. when the function is not 'extern inline'. Note 7208 // that a local variable with thread storage duration still has to 7209 // be marked 'static'. Also note that it's possible to get these 7210 // semantics in C++ using __attribute__((gnu_inline)). 7211 if (SC == SC_Static && S->getFnParent() != nullptr && 7212 !NewVD->getType().isConstQualified()) { 7213 FunctionDecl *CurFD = getCurFunctionDecl(); 7214 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7215 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7216 diag::warn_static_local_in_extern_inline); 7217 MaybeSuggestAddingStaticToDecl(CurFD); 7218 } 7219 } 7220 7221 if (D.getDeclSpec().isModulePrivateSpecified()) { 7222 if (IsVariableTemplateSpecialization) 7223 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7224 << (IsPartialSpecialization ? 1 : 0) 7225 << FixItHint::CreateRemoval( 7226 D.getDeclSpec().getModulePrivateSpecLoc()); 7227 else if (IsMemberSpecialization) 7228 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7229 << 2 7230 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7231 else if (NewVD->hasLocalStorage()) 7232 Diag(NewVD->getLocation(), diag::err_module_private_local) 7233 << 0 << NewVD 7234 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7235 << FixItHint::CreateRemoval( 7236 D.getDeclSpec().getModulePrivateSpecLoc()); 7237 else { 7238 NewVD->setModulePrivate(); 7239 if (NewTemplate) 7240 NewTemplate->setModulePrivate(); 7241 for (auto *B : Bindings) 7242 B->setModulePrivate(); 7243 } 7244 } 7245 7246 if (getLangOpts().OpenCL) { 7247 deduceOpenCLAddressSpace(NewVD); 7248 7249 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 7250 if (TSC != TSCS_unspecified) { 7251 bool IsCXX = getLangOpts().OpenCLCPlusPlus; 7252 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7253 diag::err_opencl_unknown_type_specifier) 7254 << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString() 7255 << DeclSpec::getSpecifierName(TSC) << 1; 7256 NewVD->setInvalidDecl(); 7257 } 7258 } 7259 7260 // Handle attributes prior to checking for duplicates in MergeVarDecl 7261 ProcessDeclAttributes(S, NewVD, D); 7262 7263 // FIXME: This is probably the wrong location to be doing this and we should 7264 // probably be doing this for more attributes (especially for function 7265 // pointer attributes such as format, warn_unused_result, etc.). Ideally 7266 // the code to copy attributes would be generated by TableGen. 7267 if (R->isFunctionPointerType()) 7268 if (const auto *TT = R->getAs<TypedefType>()) 7269 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT); 7270 7271 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7272 getLangOpts().SYCLIsDevice) { 7273 if (EmitTLSUnsupportedError && 7274 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7275 (getLangOpts().OpenMPIsDevice && 7276 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7277 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7278 diag::err_thread_unsupported); 7279 7280 if (EmitTLSUnsupportedError && 7281 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7282 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7283 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7284 // storage [duration]." 7285 if (SC == SC_None && S->getFnParent() != nullptr && 7286 (NewVD->hasAttr<CUDASharedAttr>() || 7287 NewVD->hasAttr<CUDAConstantAttr>())) { 7288 NewVD->setStorageClass(SC_Static); 7289 } 7290 } 7291 7292 // Ensure that dllimport globals without explicit storage class are treated as 7293 // extern. The storage class is set above using parsed attributes. Now we can 7294 // check the VarDecl itself. 7295 assert(!NewVD->hasAttr<DLLImportAttr>() || 7296 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7297 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7298 7299 // In auto-retain/release, infer strong retension for variables of 7300 // retainable type. 7301 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7302 NewVD->setInvalidDecl(); 7303 7304 // Handle GNU asm-label extension (encoded as an attribute). 7305 if (Expr *E = (Expr*)D.getAsmLabel()) { 7306 // The parser guarantees this is a string. 7307 StringLiteral *SE = cast<StringLiteral>(E); 7308 StringRef Label = SE->getString(); 7309 if (S->getFnParent() != nullptr) { 7310 switch (SC) { 7311 case SC_None: 7312 case SC_Auto: 7313 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7314 break; 7315 case SC_Register: 7316 // Local Named register 7317 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7318 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7319 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7320 break; 7321 case SC_Static: 7322 case SC_Extern: 7323 case SC_PrivateExtern: 7324 break; 7325 } 7326 } else if (SC == SC_Register) { 7327 // Global Named register 7328 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7329 const auto &TI = Context.getTargetInfo(); 7330 bool HasSizeMismatch; 7331 7332 if (!TI.isValidGCCRegisterName(Label)) 7333 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7334 else if (!TI.validateGlobalRegisterVariable(Label, 7335 Context.getTypeSize(R), 7336 HasSizeMismatch)) 7337 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7338 else if (HasSizeMismatch) 7339 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7340 } 7341 7342 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7343 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7344 NewVD->setInvalidDecl(true); 7345 } 7346 } 7347 7348 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7349 /*IsLiteralLabel=*/true, 7350 SE->getStrTokenLoc(0))); 7351 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7352 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7353 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7354 if (I != ExtnameUndeclaredIdentifiers.end()) { 7355 if (isDeclExternC(NewVD)) { 7356 NewVD->addAttr(I->second); 7357 ExtnameUndeclaredIdentifiers.erase(I); 7358 } else 7359 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7360 << /*Variable*/1 << NewVD; 7361 } 7362 } 7363 7364 // Find the shadowed declaration before filtering for scope. 7365 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7366 ? getShadowedDeclaration(NewVD, Previous) 7367 : nullptr; 7368 7369 // Don't consider existing declarations that are in a different 7370 // scope and are out-of-semantic-context declarations (if the new 7371 // declaration has linkage). 7372 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7373 D.getCXXScopeSpec().isNotEmpty() || 7374 IsMemberSpecialization || 7375 IsVariableTemplateSpecialization); 7376 7377 // Check whether the previous declaration is in the same block scope. This 7378 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7379 if (getLangOpts().CPlusPlus && 7380 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7381 NewVD->setPreviousDeclInSameBlockScope( 7382 Previous.isSingleResult() && !Previous.isShadowed() && 7383 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7384 7385 if (!getLangOpts().CPlusPlus) { 7386 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7387 } else { 7388 // If this is an explicit specialization of a static data member, check it. 7389 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7390 CheckMemberSpecialization(NewVD, Previous)) 7391 NewVD->setInvalidDecl(); 7392 7393 // Merge the decl with the existing one if appropriate. 7394 if (!Previous.empty()) { 7395 if (Previous.isSingleResult() && 7396 isa<FieldDecl>(Previous.getFoundDecl()) && 7397 D.getCXXScopeSpec().isSet()) { 7398 // The user tried to define a non-static data member 7399 // out-of-line (C++ [dcl.meaning]p1). 7400 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7401 << D.getCXXScopeSpec().getRange(); 7402 Previous.clear(); 7403 NewVD->setInvalidDecl(); 7404 } 7405 } else if (D.getCXXScopeSpec().isSet()) { 7406 // No previous declaration in the qualifying scope. 7407 Diag(D.getIdentifierLoc(), diag::err_no_member) 7408 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7409 << D.getCXXScopeSpec().getRange(); 7410 NewVD->setInvalidDecl(); 7411 } 7412 7413 if (!IsVariableTemplateSpecialization) 7414 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7415 7416 if (NewTemplate) { 7417 VarTemplateDecl *PrevVarTemplate = 7418 NewVD->getPreviousDecl() 7419 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7420 : nullptr; 7421 7422 // Check the template parameter list of this declaration, possibly 7423 // merging in the template parameter list from the previous variable 7424 // template declaration. 7425 if (CheckTemplateParameterList( 7426 TemplateParams, 7427 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7428 : nullptr, 7429 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7430 DC->isDependentContext()) 7431 ? TPC_ClassTemplateMember 7432 : TPC_VarTemplate)) 7433 NewVD->setInvalidDecl(); 7434 7435 // If we are providing an explicit specialization of a static variable 7436 // template, make a note of that. 7437 if (PrevVarTemplate && 7438 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7439 PrevVarTemplate->setMemberSpecialization(); 7440 } 7441 } 7442 7443 // Diagnose shadowed variables iff this isn't a redeclaration. 7444 if (ShadowedDecl && !D.isRedeclaration()) 7445 CheckShadow(NewVD, ShadowedDecl, Previous); 7446 7447 ProcessPragmaWeak(S, NewVD); 7448 7449 // If this is the first declaration of an extern C variable, update 7450 // the map of such variables. 7451 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7452 isIncompleteDeclExternC(*this, NewVD)) 7453 RegisterLocallyScopedExternCDecl(NewVD, S); 7454 7455 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7456 MangleNumberingContext *MCtx; 7457 Decl *ManglingContextDecl; 7458 std::tie(MCtx, ManglingContextDecl) = 7459 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7460 if (MCtx) { 7461 Context.setManglingNumber( 7462 NewVD, MCtx->getManglingNumber( 7463 NewVD, getMSManglingNumber(getLangOpts(), S))); 7464 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7465 } 7466 } 7467 7468 // Special handling of variable named 'main'. 7469 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7470 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7471 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7472 7473 // C++ [basic.start.main]p3 7474 // A program that declares a variable main at global scope is ill-formed. 7475 if (getLangOpts().CPlusPlus) 7476 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7477 7478 // In C, and external-linkage variable named main results in undefined 7479 // behavior. 7480 else if (NewVD->hasExternalFormalLinkage()) 7481 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7482 } 7483 7484 if (D.isRedeclaration() && !Previous.empty()) { 7485 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7486 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7487 D.isFunctionDefinition()); 7488 } 7489 7490 if (NewTemplate) { 7491 if (NewVD->isInvalidDecl()) 7492 NewTemplate->setInvalidDecl(); 7493 ActOnDocumentableDecl(NewTemplate); 7494 return NewTemplate; 7495 } 7496 7497 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7498 CompleteMemberSpecialization(NewVD, Previous); 7499 7500 return NewVD; 7501 } 7502 7503 /// Enum describing the %select options in diag::warn_decl_shadow. 7504 enum ShadowedDeclKind { 7505 SDK_Local, 7506 SDK_Global, 7507 SDK_StaticMember, 7508 SDK_Field, 7509 SDK_Typedef, 7510 SDK_Using, 7511 SDK_StructuredBinding 7512 }; 7513 7514 /// Determine what kind of declaration we're shadowing. 7515 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7516 const DeclContext *OldDC) { 7517 if (isa<TypeAliasDecl>(ShadowedDecl)) 7518 return SDK_Using; 7519 else if (isa<TypedefDecl>(ShadowedDecl)) 7520 return SDK_Typedef; 7521 else if (isa<BindingDecl>(ShadowedDecl)) 7522 return SDK_StructuredBinding; 7523 else if (isa<RecordDecl>(OldDC)) 7524 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7525 7526 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7527 } 7528 7529 /// Return the location of the capture if the given lambda captures the given 7530 /// variable \p VD, or an invalid source location otherwise. 7531 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7532 const VarDecl *VD) { 7533 for (const Capture &Capture : LSI->Captures) { 7534 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7535 return Capture.getLocation(); 7536 } 7537 return SourceLocation(); 7538 } 7539 7540 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7541 const LookupResult &R) { 7542 // Only diagnose if we're shadowing an unambiguous field or variable. 7543 if (R.getResultKind() != LookupResult::Found) 7544 return false; 7545 7546 // Return false if warning is ignored. 7547 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7548 } 7549 7550 /// Return the declaration shadowed by the given variable \p D, or null 7551 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7552 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7553 const LookupResult &R) { 7554 if (!shouldWarnIfShadowedDecl(Diags, R)) 7555 return nullptr; 7556 7557 // Don't diagnose declarations at file scope. 7558 if (D->hasGlobalStorage()) 7559 return nullptr; 7560 7561 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7562 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7563 : nullptr; 7564 } 7565 7566 /// Return the declaration shadowed by the given typedef \p D, or null 7567 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7568 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7569 const LookupResult &R) { 7570 // Don't warn if typedef declaration is part of a class 7571 if (D->getDeclContext()->isRecord()) 7572 return nullptr; 7573 7574 if (!shouldWarnIfShadowedDecl(Diags, R)) 7575 return nullptr; 7576 7577 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7578 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7579 } 7580 7581 /// Return the declaration shadowed by the given variable \p D, or null 7582 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7583 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, 7584 const LookupResult &R) { 7585 if (!shouldWarnIfShadowedDecl(Diags, R)) 7586 return nullptr; 7587 7588 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7589 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7590 : nullptr; 7591 } 7592 7593 /// Diagnose variable or built-in function shadowing. Implements 7594 /// -Wshadow. 7595 /// 7596 /// This method is called whenever a VarDecl is added to a "useful" 7597 /// scope. 7598 /// 7599 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7600 /// \param R the lookup of the name 7601 /// 7602 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7603 const LookupResult &R) { 7604 DeclContext *NewDC = D->getDeclContext(); 7605 7606 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7607 // Fields are not shadowed by variables in C++ static methods. 7608 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7609 if (MD->isStatic()) 7610 return; 7611 7612 // Fields shadowed by constructor parameters are a special case. Usually 7613 // the constructor initializes the field with the parameter. 7614 if (isa<CXXConstructorDecl>(NewDC)) 7615 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7616 // Remember that this was shadowed so we can either warn about its 7617 // modification or its existence depending on warning settings. 7618 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7619 return; 7620 } 7621 } 7622 7623 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7624 if (shadowedVar->isExternC()) { 7625 // For shadowing external vars, make sure that we point to the global 7626 // declaration, not a locally scoped extern declaration. 7627 for (auto I : shadowedVar->redecls()) 7628 if (I->isFileVarDecl()) { 7629 ShadowedDecl = I; 7630 break; 7631 } 7632 } 7633 7634 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7635 7636 unsigned WarningDiag = diag::warn_decl_shadow; 7637 SourceLocation CaptureLoc; 7638 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7639 isa<CXXMethodDecl>(NewDC)) { 7640 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7641 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7642 if (RD->getLambdaCaptureDefault() == LCD_None) { 7643 // Try to avoid warnings for lambdas with an explicit capture list. 7644 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7645 // Warn only when the lambda captures the shadowed decl explicitly. 7646 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7647 if (CaptureLoc.isInvalid()) 7648 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7649 } else { 7650 // Remember that this was shadowed so we can avoid the warning if the 7651 // shadowed decl isn't captured and the warning settings allow it. 7652 cast<LambdaScopeInfo>(getCurFunction()) 7653 ->ShadowingDecls.push_back( 7654 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7655 return; 7656 } 7657 } 7658 7659 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7660 // A variable can't shadow a local variable in an enclosing scope, if 7661 // they are separated by a non-capturing declaration context. 7662 for (DeclContext *ParentDC = NewDC; 7663 ParentDC && !ParentDC->Equals(OldDC); 7664 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7665 // Only block literals, captured statements, and lambda expressions 7666 // can capture; other scopes don't. 7667 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7668 !isLambdaCallOperator(ParentDC)) { 7669 return; 7670 } 7671 } 7672 } 7673 } 7674 } 7675 7676 // Only warn about certain kinds of shadowing for class members. 7677 if (NewDC && NewDC->isRecord()) { 7678 // In particular, don't warn about shadowing non-class members. 7679 if (!OldDC->isRecord()) 7680 return; 7681 7682 // TODO: should we warn about static data members shadowing 7683 // static data members from base classes? 7684 7685 // TODO: don't diagnose for inaccessible shadowed members. 7686 // This is hard to do perfectly because we might friend the 7687 // shadowing context, but that's just a false negative. 7688 } 7689 7690 7691 DeclarationName Name = R.getLookupName(); 7692 7693 // Emit warning and note. 7694 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7695 return; 7696 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7697 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7698 if (!CaptureLoc.isInvalid()) 7699 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7700 << Name << /*explicitly*/ 1; 7701 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7702 } 7703 7704 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7705 /// when these variables are captured by the lambda. 7706 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7707 for (const auto &Shadow : LSI->ShadowingDecls) { 7708 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7709 // Try to avoid the warning when the shadowed decl isn't captured. 7710 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7711 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7712 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7713 ? diag::warn_decl_shadow_uncaptured_local 7714 : diag::warn_decl_shadow) 7715 << Shadow.VD->getDeclName() 7716 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7717 if (!CaptureLoc.isInvalid()) 7718 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7719 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7720 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7721 } 7722 } 7723 7724 /// Check -Wshadow without the advantage of a previous lookup. 7725 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7726 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7727 return; 7728 7729 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7730 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7731 LookupName(R, S); 7732 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7733 CheckShadow(D, ShadowedDecl, R); 7734 } 7735 7736 /// Check if 'E', which is an expression that is about to be modified, refers 7737 /// to a constructor parameter that shadows a field. 7738 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7739 // Quickly ignore expressions that can't be shadowing ctor parameters. 7740 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7741 return; 7742 E = E->IgnoreParenImpCasts(); 7743 auto *DRE = dyn_cast<DeclRefExpr>(E); 7744 if (!DRE) 7745 return; 7746 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7747 auto I = ShadowingDecls.find(D); 7748 if (I == ShadowingDecls.end()) 7749 return; 7750 const NamedDecl *ShadowedDecl = I->second; 7751 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7752 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7753 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7754 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7755 7756 // Avoid issuing multiple warnings about the same decl. 7757 ShadowingDecls.erase(I); 7758 } 7759 7760 /// Check for conflict between this global or extern "C" declaration and 7761 /// previous global or extern "C" declarations. This is only used in C++. 7762 template<typename T> 7763 static bool checkGlobalOrExternCConflict( 7764 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7765 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7766 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7767 7768 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7769 // The common case: this global doesn't conflict with any extern "C" 7770 // declaration. 7771 return false; 7772 } 7773 7774 if (Prev) { 7775 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7776 // Both the old and new declarations have C language linkage. This is a 7777 // redeclaration. 7778 Previous.clear(); 7779 Previous.addDecl(Prev); 7780 return true; 7781 } 7782 7783 // This is a global, non-extern "C" declaration, and there is a previous 7784 // non-global extern "C" declaration. Diagnose if this is a variable 7785 // declaration. 7786 if (!isa<VarDecl>(ND)) 7787 return false; 7788 } else { 7789 // The declaration is extern "C". Check for any declaration in the 7790 // translation unit which might conflict. 7791 if (IsGlobal) { 7792 // We have already performed the lookup into the translation unit. 7793 IsGlobal = false; 7794 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7795 I != E; ++I) { 7796 if (isa<VarDecl>(*I)) { 7797 Prev = *I; 7798 break; 7799 } 7800 } 7801 } else { 7802 DeclContext::lookup_result R = 7803 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7804 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7805 I != E; ++I) { 7806 if (isa<VarDecl>(*I)) { 7807 Prev = *I; 7808 break; 7809 } 7810 // FIXME: If we have any other entity with this name in global scope, 7811 // the declaration is ill-formed, but that is a defect: it breaks the 7812 // 'stat' hack, for instance. Only variables can have mangled name 7813 // clashes with extern "C" declarations, so only they deserve a 7814 // diagnostic. 7815 } 7816 } 7817 7818 if (!Prev) 7819 return false; 7820 } 7821 7822 // Use the first declaration's location to ensure we point at something which 7823 // is lexically inside an extern "C" linkage-spec. 7824 assert(Prev && "should have found a previous declaration to diagnose"); 7825 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7826 Prev = FD->getFirstDecl(); 7827 else 7828 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7829 7830 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7831 << IsGlobal << ND; 7832 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7833 << IsGlobal; 7834 return false; 7835 } 7836 7837 /// Apply special rules for handling extern "C" declarations. Returns \c true 7838 /// if we have found that this is a redeclaration of some prior entity. 7839 /// 7840 /// Per C++ [dcl.link]p6: 7841 /// Two declarations [for a function or variable] with C language linkage 7842 /// with the same name that appear in different scopes refer to the same 7843 /// [entity]. An entity with C language linkage shall not be declared with 7844 /// the same name as an entity in global scope. 7845 template<typename T> 7846 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7847 LookupResult &Previous) { 7848 if (!S.getLangOpts().CPlusPlus) { 7849 // In C, when declaring a global variable, look for a corresponding 'extern' 7850 // variable declared in function scope. We don't need this in C++, because 7851 // we find local extern decls in the surrounding file-scope DeclContext. 7852 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7853 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7854 Previous.clear(); 7855 Previous.addDecl(Prev); 7856 return true; 7857 } 7858 } 7859 return false; 7860 } 7861 7862 // A declaration in the translation unit can conflict with an extern "C" 7863 // declaration. 7864 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7865 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7866 7867 // An extern "C" declaration can conflict with a declaration in the 7868 // translation unit or can be a redeclaration of an extern "C" declaration 7869 // in another scope. 7870 if (isIncompleteDeclExternC(S,ND)) 7871 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7872 7873 // Neither global nor extern "C": nothing to do. 7874 return false; 7875 } 7876 7877 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7878 // If the decl is already known invalid, don't check it. 7879 if (NewVD->isInvalidDecl()) 7880 return; 7881 7882 QualType T = NewVD->getType(); 7883 7884 // Defer checking an 'auto' type until its initializer is attached. 7885 if (T->isUndeducedType()) 7886 return; 7887 7888 if (NewVD->hasAttrs()) 7889 CheckAlignasUnderalignment(NewVD); 7890 7891 if (T->isObjCObjectType()) { 7892 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7893 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7894 T = Context.getObjCObjectPointerType(T); 7895 NewVD->setType(T); 7896 } 7897 7898 // Emit an error if an address space was applied to decl with local storage. 7899 // This includes arrays of objects with address space qualifiers, but not 7900 // automatic variables that point to other address spaces. 7901 // ISO/IEC TR 18037 S5.1.2 7902 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7903 T.getAddressSpace() != LangAS::Default) { 7904 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7905 NewVD->setInvalidDecl(); 7906 return; 7907 } 7908 7909 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7910 // scope. 7911 if (getLangOpts().OpenCLVersion == 120 && 7912 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", 7913 getLangOpts()) && 7914 NewVD->isStaticLocal()) { 7915 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7916 NewVD->setInvalidDecl(); 7917 return; 7918 } 7919 7920 if (getLangOpts().OpenCL) { 7921 if (!diagnoseOpenCLTypes(*this, NewVD)) 7922 return; 7923 7924 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7925 if (NewVD->hasAttr<BlocksAttr>()) { 7926 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7927 return; 7928 } 7929 7930 if (T->isBlockPointerType()) { 7931 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7932 // can't use 'extern' storage class. 7933 if (!T.isConstQualified()) { 7934 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7935 << 0 /*const*/; 7936 NewVD->setInvalidDecl(); 7937 return; 7938 } 7939 if (NewVD->hasExternalStorage()) { 7940 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7941 NewVD->setInvalidDecl(); 7942 return; 7943 } 7944 } 7945 7946 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7947 // __constant address space. 7948 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7949 // variables inside a function can also be declared in the global 7950 // address space. 7951 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7952 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7953 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7954 NewVD->hasExternalStorage()) { 7955 if (!T->isSamplerT() && 7956 !T->isDependentType() && 7957 !(T.getAddressSpace() == LangAS::opencl_constant || 7958 (T.getAddressSpace() == LangAS::opencl_global && 7959 (getLangOpts().OpenCLVersion == 200 || 7960 getLangOpts().OpenCLCPlusPlus)))) { 7961 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7962 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7963 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7964 << Scope << "global or constant"; 7965 else 7966 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7967 << Scope << "constant"; 7968 NewVD->setInvalidDecl(); 7969 return; 7970 } 7971 } else { 7972 if (T.getAddressSpace() == LangAS::opencl_global) { 7973 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7974 << 1 /*is any function*/ << "global"; 7975 NewVD->setInvalidDecl(); 7976 return; 7977 } 7978 if (T.getAddressSpace() == LangAS::opencl_constant || 7979 T.getAddressSpace() == LangAS::opencl_local) { 7980 FunctionDecl *FD = getCurFunctionDecl(); 7981 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7982 // in functions. 7983 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7984 if (T.getAddressSpace() == LangAS::opencl_constant) 7985 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7986 << 0 /*non-kernel only*/ << "constant"; 7987 else 7988 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7989 << 0 /*non-kernel only*/ << "local"; 7990 NewVD->setInvalidDecl(); 7991 return; 7992 } 7993 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7994 // in the outermost scope of a kernel function. 7995 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7996 if (!getCurScope()->isFunctionScope()) { 7997 if (T.getAddressSpace() == LangAS::opencl_constant) 7998 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7999 << "constant"; 8000 else 8001 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8002 << "local"; 8003 NewVD->setInvalidDecl(); 8004 return; 8005 } 8006 } 8007 } else if (T.getAddressSpace() != LangAS::opencl_private && 8008 // If we are parsing a template we didn't deduce an addr 8009 // space yet. 8010 T.getAddressSpace() != LangAS::Default) { 8011 // Do not allow other address spaces on automatic variable. 8012 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 8013 NewVD->setInvalidDecl(); 8014 return; 8015 } 8016 } 8017 } 8018 8019 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 8020 && !NewVD->hasAttr<BlocksAttr>()) { 8021 if (getLangOpts().getGC() != LangOptions::NonGC) 8022 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 8023 else { 8024 assert(!getLangOpts().ObjCAutoRefCount); 8025 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 8026 } 8027 } 8028 8029 bool isVM = T->isVariablyModifiedType(); 8030 if (isVM || NewVD->hasAttr<CleanupAttr>() || 8031 NewVD->hasAttr<BlocksAttr>()) 8032 setFunctionHasBranchProtectedScope(); 8033 8034 if ((isVM && NewVD->hasLinkage()) || 8035 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8036 bool SizeIsNegative; 8037 llvm::APSInt Oversized; 8038 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8039 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8040 QualType FixedT; 8041 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8042 FixedT = FixedTInfo->getType(); 8043 else if (FixedTInfo) { 8044 // Type and type-as-written are canonically different. We need to fix up 8045 // both types separately. 8046 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8047 Oversized); 8048 } 8049 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8050 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8051 // FIXME: This won't give the correct result for 8052 // int a[10][n]; 8053 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8054 8055 if (NewVD->isFileVarDecl()) 8056 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8057 << SizeRange; 8058 else if (NewVD->isStaticLocal()) 8059 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8060 << SizeRange; 8061 else 8062 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8063 << SizeRange; 8064 NewVD->setInvalidDecl(); 8065 return; 8066 } 8067 8068 if (!FixedTInfo) { 8069 if (NewVD->isFileVarDecl()) 8070 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8071 else 8072 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8073 NewVD->setInvalidDecl(); 8074 return; 8075 } 8076 8077 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8078 NewVD->setType(FixedT); 8079 NewVD->setTypeSourceInfo(FixedTInfo); 8080 } 8081 8082 if (T->isVoidType()) { 8083 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8084 // of objects and functions. 8085 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8086 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8087 << T; 8088 NewVD->setInvalidDecl(); 8089 return; 8090 } 8091 } 8092 8093 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8094 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8095 NewVD->setInvalidDecl(); 8096 return; 8097 } 8098 8099 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8100 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8101 NewVD->setInvalidDecl(); 8102 return; 8103 } 8104 8105 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8106 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8107 NewVD->setInvalidDecl(); 8108 return; 8109 } 8110 8111 if (NewVD->isConstexpr() && !T->isDependentType() && 8112 RequireLiteralType(NewVD->getLocation(), T, 8113 diag::err_constexpr_var_non_literal)) { 8114 NewVD->setInvalidDecl(); 8115 return; 8116 } 8117 8118 // PPC MMA non-pointer types are not allowed as non-local variable types. 8119 if (Context.getTargetInfo().getTriple().isPPC64() && 8120 !NewVD->isLocalVarDecl() && 8121 CheckPPCMMAType(T, NewVD->getLocation())) { 8122 NewVD->setInvalidDecl(); 8123 return; 8124 } 8125 } 8126 8127 /// Perform semantic checking on a newly-created variable 8128 /// declaration. 8129 /// 8130 /// This routine performs all of the type-checking required for a 8131 /// variable declaration once it has been built. It is used both to 8132 /// check variables after they have been parsed and their declarators 8133 /// have been translated into a declaration, and to check variables 8134 /// that have been instantiated from a template. 8135 /// 8136 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8137 /// 8138 /// Returns true if the variable declaration is a redeclaration. 8139 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8140 CheckVariableDeclarationType(NewVD); 8141 8142 // If the decl is already known invalid, don't check it. 8143 if (NewVD->isInvalidDecl()) 8144 return false; 8145 8146 // If we did not find anything by this name, look for a non-visible 8147 // extern "C" declaration with the same name. 8148 if (Previous.empty() && 8149 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8150 Previous.setShadowed(); 8151 8152 if (!Previous.empty()) { 8153 MergeVarDecl(NewVD, Previous); 8154 return true; 8155 } 8156 return false; 8157 } 8158 8159 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8160 /// and if so, check that it's a valid override and remember it. 8161 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8162 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8163 8164 // Look for methods in base classes that this method might override. 8165 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8166 /*DetectVirtual=*/false); 8167 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8168 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8169 DeclarationName Name = MD->getDeclName(); 8170 8171 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8172 // We really want to find the base class destructor here. 8173 QualType T = Context.getTypeDeclType(BaseRecord); 8174 CanQualType CT = Context.getCanonicalType(T); 8175 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8176 } 8177 8178 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8179 CXXMethodDecl *BaseMD = 8180 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8181 if (!BaseMD || !BaseMD->isVirtual() || 8182 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8183 /*ConsiderCudaAttrs=*/true, 8184 // C++2a [class.virtual]p2 does not consider requires 8185 // clauses when overriding. 8186 /*ConsiderRequiresClauses=*/false)) 8187 continue; 8188 8189 if (Overridden.insert(BaseMD).second) { 8190 MD->addOverriddenMethod(BaseMD); 8191 CheckOverridingFunctionReturnType(MD, BaseMD); 8192 CheckOverridingFunctionAttributes(MD, BaseMD); 8193 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8194 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8195 } 8196 8197 // A method can only override one function from each base class. We 8198 // don't track indirectly overridden methods from bases of bases. 8199 return true; 8200 } 8201 8202 return false; 8203 }; 8204 8205 DC->lookupInBases(VisitBase, Paths); 8206 return !Overridden.empty(); 8207 } 8208 8209 namespace { 8210 // Struct for holding all of the extra arguments needed by 8211 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8212 struct ActOnFDArgs { 8213 Scope *S; 8214 Declarator &D; 8215 MultiTemplateParamsArg TemplateParamLists; 8216 bool AddToScope; 8217 }; 8218 } // end anonymous namespace 8219 8220 namespace { 8221 8222 // Callback to only accept typo corrections that have a non-zero edit distance. 8223 // Also only accept corrections that have the same parent decl. 8224 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8225 public: 8226 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8227 CXXRecordDecl *Parent) 8228 : Context(Context), OriginalFD(TypoFD), 8229 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8230 8231 bool ValidateCandidate(const TypoCorrection &candidate) override { 8232 if (candidate.getEditDistance() == 0) 8233 return false; 8234 8235 SmallVector<unsigned, 1> MismatchedParams; 8236 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8237 CDeclEnd = candidate.end(); 8238 CDecl != CDeclEnd; ++CDecl) { 8239 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8240 8241 if (FD && !FD->hasBody() && 8242 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8243 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8244 CXXRecordDecl *Parent = MD->getParent(); 8245 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8246 return true; 8247 } else if (!ExpectedParent) { 8248 return true; 8249 } 8250 } 8251 } 8252 8253 return false; 8254 } 8255 8256 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8257 return std::make_unique<DifferentNameValidatorCCC>(*this); 8258 } 8259 8260 private: 8261 ASTContext &Context; 8262 FunctionDecl *OriginalFD; 8263 CXXRecordDecl *ExpectedParent; 8264 }; 8265 8266 } // end anonymous namespace 8267 8268 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8269 TypoCorrectedFunctionDefinitions.insert(F); 8270 } 8271 8272 /// Generate diagnostics for an invalid function redeclaration. 8273 /// 8274 /// This routine handles generating the diagnostic messages for an invalid 8275 /// function redeclaration, including finding possible similar declarations 8276 /// or performing typo correction if there are no previous declarations with 8277 /// the same name. 8278 /// 8279 /// Returns a NamedDecl iff typo correction was performed and substituting in 8280 /// the new declaration name does not cause new errors. 8281 static NamedDecl *DiagnoseInvalidRedeclaration( 8282 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8283 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8284 DeclarationName Name = NewFD->getDeclName(); 8285 DeclContext *NewDC = NewFD->getDeclContext(); 8286 SmallVector<unsigned, 1> MismatchedParams; 8287 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8288 TypoCorrection Correction; 8289 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8290 unsigned DiagMsg = 8291 IsLocalFriend ? diag::err_no_matching_local_friend : 8292 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8293 diag::err_member_decl_does_not_match; 8294 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8295 IsLocalFriend ? Sema::LookupLocalFriendName 8296 : Sema::LookupOrdinaryName, 8297 Sema::ForVisibleRedeclaration); 8298 8299 NewFD->setInvalidDecl(); 8300 if (IsLocalFriend) 8301 SemaRef.LookupName(Prev, S); 8302 else 8303 SemaRef.LookupQualifiedName(Prev, NewDC); 8304 assert(!Prev.isAmbiguous() && 8305 "Cannot have an ambiguity in previous-declaration lookup"); 8306 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8307 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8308 MD ? MD->getParent() : nullptr); 8309 if (!Prev.empty()) { 8310 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8311 Func != FuncEnd; ++Func) { 8312 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8313 if (FD && 8314 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8315 // Add 1 to the index so that 0 can mean the mismatch didn't 8316 // involve a parameter 8317 unsigned ParamNum = 8318 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8319 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8320 } 8321 } 8322 // If the qualified name lookup yielded nothing, try typo correction 8323 } else if ((Correction = SemaRef.CorrectTypo( 8324 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8325 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8326 IsLocalFriend ? nullptr : NewDC))) { 8327 // Set up everything for the call to ActOnFunctionDeclarator 8328 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8329 ExtraArgs.D.getIdentifierLoc()); 8330 Previous.clear(); 8331 Previous.setLookupName(Correction.getCorrection()); 8332 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8333 CDeclEnd = Correction.end(); 8334 CDecl != CDeclEnd; ++CDecl) { 8335 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8336 if (FD && !FD->hasBody() && 8337 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8338 Previous.addDecl(FD); 8339 } 8340 } 8341 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8342 8343 NamedDecl *Result; 8344 // Retry building the function declaration with the new previous 8345 // declarations, and with errors suppressed. 8346 { 8347 // Trap errors. 8348 Sema::SFINAETrap Trap(SemaRef); 8349 8350 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8351 // pieces need to verify the typo-corrected C++ declaration and hopefully 8352 // eliminate the need for the parameter pack ExtraArgs. 8353 Result = SemaRef.ActOnFunctionDeclarator( 8354 ExtraArgs.S, ExtraArgs.D, 8355 Correction.getCorrectionDecl()->getDeclContext(), 8356 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8357 ExtraArgs.AddToScope); 8358 8359 if (Trap.hasErrorOccurred()) 8360 Result = nullptr; 8361 } 8362 8363 if (Result) { 8364 // Determine which correction we picked. 8365 Decl *Canonical = Result->getCanonicalDecl(); 8366 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8367 I != E; ++I) 8368 if ((*I)->getCanonicalDecl() == Canonical) 8369 Correction.setCorrectionDecl(*I); 8370 8371 // Let Sema know about the correction. 8372 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8373 SemaRef.diagnoseTypo( 8374 Correction, 8375 SemaRef.PDiag(IsLocalFriend 8376 ? diag::err_no_matching_local_friend_suggest 8377 : diag::err_member_decl_does_not_match_suggest) 8378 << Name << NewDC << IsDefinition); 8379 return Result; 8380 } 8381 8382 // Pretend the typo correction never occurred 8383 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8384 ExtraArgs.D.getIdentifierLoc()); 8385 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8386 Previous.clear(); 8387 Previous.setLookupName(Name); 8388 } 8389 8390 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8391 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8392 8393 bool NewFDisConst = false; 8394 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8395 NewFDisConst = NewMD->isConst(); 8396 8397 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8398 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8399 NearMatch != NearMatchEnd; ++NearMatch) { 8400 FunctionDecl *FD = NearMatch->first; 8401 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8402 bool FDisConst = MD && MD->isConst(); 8403 bool IsMember = MD || !IsLocalFriend; 8404 8405 // FIXME: These notes are poorly worded for the local friend case. 8406 if (unsigned Idx = NearMatch->second) { 8407 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8408 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8409 if (Loc.isInvalid()) Loc = FD->getLocation(); 8410 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8411 : diag::note_local_decl_close_param_match) 8412 << Idx << FDParam->getType() 8413 << NewFD->getParamDecl(Idx - 1)->getType(); 8414 } else if (FDisConst != NewFDisConst) { 8415 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8416 << NewFDisConst << FD->getSourceRange().getEnd(); 8417 } else 8418 SemaRef.Diag(FD->getLocation(), 8419 IsMember ? diag::note_member_def_close_match 8420 : diag::note_local_decl_close_match); 8421 } 8422 return nullptr; 8423 } 8424 8425 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8426 switch (D.getDeclSpec().getStorageClassSpec()) { 8427 default: llvm_unreachable("Unknown storage class!"); 8428 case DeclSpec::SCS_auto: 8429 case DeclSpec::SCS_register: 8430 case DeclSpec::SCS_mutable: 8431 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8432 diag::err_typecheck_sclass_func); 8433 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8434 D.setInvalidType(); 8435 break; 8436 case DeclSpec::SCS_unspecified: break; 8437 case DeclSpec::SCS_extern: 8438 if (D.getDeclSpec().isExternInLinkageSpec()) 8439 return SC_None; 8440 return SC_Extern; 8441 case DeclSpec::SCS_static: { 8442 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8443 // C99 6.7.1p5: 8444 // The declaration of an identifier for a function that has 8445 // block scope shall have no explicit storage-class specifier 8446 // other than extern 8447 // See also (C++ [dcl.stc]p4). 8448 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8449 diag::err_static_block_func); 8450 break; 8451 } else 8452 return SC_Static; 8453 } 8454 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8455 } 8456 8457 // No explicit storage class has already been returned 8458 return SC_None; 8459 } 8460 8461 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8462 DeclContext *DC, QualType &R, 8463 TypeSourceInfo *TInfo, 8464 StorageClass SC, 8465 bool &IsVirtualOkay) { 8466 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8467 DeclarationName Name = NameInfo.getName(); 8468 8469 FunctionDecl *NewFD = nullptr; 8470 bool isInline = D.getDeclSpec().isInlineSpecified(); 8471 8472 if (!SemaRef.getLangOpts().CPlusPlus) { 8473 // Determine whether the function was written with a 8474 // prototype. This true when: 8475 // - there is a prototype in the declarator, or 8476 // - the type R of the function is some kind of typedef or other non- 8477 // attributed reference to a type name (which eventually refers to a 8478 // function type). 8479 bool HasPrototype = 8480 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8481 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8482 8483 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8484 R, TInfo, SC, isInline, HasPrototype, 8485 ConstexprSpecKind::Unspecified, 8486 /*TrailingRequiresClause=*/nullptr); 8487 if (D.isInvalidType()) 8488 NewFD->setInvalidDecl(); 8489 8490 return NewFD; 8491 } 8492 8493 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8494 8495 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8496 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8497 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8498 diag::err_constexpr_wrong_decl_kind) 8499 << static_cast<int>(ConstexprKind); 8500 ConstexprKind = ConstexprSpecKind::Unspecified; 8501 D.getMutableDeclSpec().ClearConstexprSpec(); 8502 } 8503 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8504 8505 // Check that the return type is not an abstract class type. 8506 // For record types, this is done by the AbstractClassUsageDiagnoser once 8507 // the class has been completely parsed. 8508 if (!DC->isRecord() && 8509 SemaRef.RequireNonAbstractType( 8510 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8511 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8512 D.setInvalidType(); 8513 8514 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8515 // This is a C++ constructor declaration. 8516 assert(DC->isRecord() && 8517 "Constructors can only be declared in a member context"); 8518 8519 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8520 return CXXConstructorDecl::Create( 8521 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8522 TInfo, ExplicitSpecifier, isInline, 8523 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8524 TrailingRequiresClause); 8525 8526 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8527 // This is a C++ destructor declaration. 8528 if (DC->isRecord()) { 8529 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8530 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8531 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8532 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8533 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8534 TrailingRequiresClause); 8535 8536 // If the destructor needs an implicit exception specification, set it 8537 // now. FIXME: It'd be nice to be able to create the right type to start 8538 // with, but the type needs to reference the destructor declaration. 8539 if (SemaRef.getLangOpts().CPlusPlus11) 8540 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8541 8542 IsVirtualOkay = true; 8543 return NewDD; 8544 8545 } else { 8546 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8547 D.setInvalidType(); 8548 8549 // Create a FunctionDecl to satisfy the function definition parsing 8550 // code path. 8551 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8552 D.getIdentifierLoc(), Name, R, TInfo, SC, 8553 isInline, 8554 /*hasPrototype=*/true, ConstexprKind, 8555 TrailingRequiresClause); 8556 } 8557 8558 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8559 if (!DC->isRecord()) { 8560 SemaRef.Diag(D.getIdentifierLoc(), 8561 diag::err_conv_function_not_member); 8562 return nullptr; 8563 } 8564 8565 SemaRef.CheckConversionDeclarator(D, R, SC); 8566 if (D.isInvalidType()) 8567 return nullptr; 8568 8569 IsVirtualOkay = true; 8570 return CXXConversionDecl::Create( 8571 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8572 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8573 TrailingRequiresClause); 8574 8575 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8576 if (TrailingRequiresClause) 8577 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8578 diag::err_trailing_requires_clause_on_deduction_guide) 8579 << TrailingRequiresClause->getSourceRange(); 8580 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8581 8582 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8583 ExplicitSpecifier, NameInfo, R, TInfo, 8584 D.getEndLoc()); 8585 } else if (DC->isRecord()) { 8586 // If the name of the function is the same as the name of the record, 8587 // then this must be an invalid constructor that has a return type. 8588 // (The parser checks for a return type and makes the declarator a 8589 // constructor if it has no return type). 8590 if (Name.getAsIdentifierInfo() && 8591 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8592 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8593 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8594 << SourceRange(D.getIdentifierLoc()); 8595 return nullptr; 8596 } 8597 8598 // This is a C++ method declaration. 8599 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8600 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8601 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8602 TrailingRequiresClause); 8603 IsVirtualOkay = !Ret->isStatic(); 8604 return Ret; 8605 } else { 8606 bool isFriend = 8607 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8608 if (!isFriend && SemaRef.CurContext->isRecord()) 8609 return nullptr; 8610 8611 // Determine whether the function was written with a 8612 // prototype. This true when: 8613 // - we're in C++ (where every function has a prototype), 8614 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8615 R, TInfo, SC, isInline, true /*HasPrototype*/, 8616 ConstexprKind, TrailingRequiresClause); 8617 } 8618 } 8619 8620 enum OpenCLParamType { 8621 ValidKernelParam, 8622 PtrPtrKernelParam, 8623 PtrKernelParam, 8624 InvalidAddrSpacePtrKernelParam, 8625 InvalidKernelParam, 8626 RecordKernelParam 8627 }; 8628 8629 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8630 // Size dependent types are just typedefs to normal integer types 8631 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8632 // integers other than by their names. 8633 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8634 8635 // Remove typedefs one by one until we reach a typedef 8636 // for a size dependent type. 8637 QualType DesugaredTy = Ty; 8638 do { 8639 ArrayRef<StringRef> Names(SizeTypeNames); 8640 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8641 if (Names.end() != Match) 8642 return true; 8643 8644 Ty = DesugaredTy; 8645 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8646 } while (DesugaredTy != Ty); 8647 8648 return false; 8649 } 8650 8651 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8652 if (PT->isPointerType() || PT->isReferenceType()) { 8653 QualType PointeeType = PT->getPointeeType(); 8654 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8655 PointeeType.getAddressSpace() == LangAS::opencl_private || 8656 PointeeType.getAddressSpace() == LangAS::Default) 8657 return InvalidAddrSpacePtrKernelParam; 8658 8659 if (PointeeType->isPointerType()) { 8660 // This is a pointer to pointer parameter. 8661 // Recursively check inner type. 8662 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 8663 if (ParamKind == InvalidAddrSpacePtrKernelParam || 8664 ParamKind == InvalidKernelParam) 8665 return ParamKind; 8666 8667 return PtrPtrKernelParam; 8668 } 8669 8670 // C++ for OpenCL v1.0 s2.4: 8671 // Moreover the types used in parameters of the kernel functions must be: 8672 // Standard layout types for pointer parameters. The same applies to 8673 // reference if an implementation supports them in kernel parameters. 8674 if (S.getLangOpts().OpenCLCPlusPlus && !PointeeType->isAtomicType() && 8675 !PointeeType->isVoidType() && !PointeeType->isStandardLayoutType()) 8676 return InvalidKernelParam; 8677 8678 return PtrKernelParam; 8679 } 8680 8681 // OpenCL v1.2 s6.9.k: 8682 // Arguments to kernel functions in a program cannot be declared with the 8683 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8684 // uintptr_t or a struct and/or union that contain fields declared to be one 8685 // of these built-in scalar types. 8686 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8687 return InvalidKernelParam; 8688 8689 if (PT->isImageType()) 8690 return PtrKernelParam; 8691 8692 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8693 return InvalidKernelParam; 8694 8695 // OpenCL extension spec v1.2 s9.5: 8696 // This extension adds support for half scalar and vector types as built-in 8697 // types that can be used for arithmetic operations, conversions etc. 8698 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 8699 PT->isHalfType()) 8700 return InvalidKernelParam; 8701 8702 // Look into an array argument to check if it has a forbidden type. 8703 if (PT->isArrayType()) { 8704 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8705 // Call ourself to check an underlying type of an array. Since the 8706 // getPointeeOrArrayElementType returns an innermost type which is not an 8707 // array, this recursive call only happens once. 8708 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8709 } 8710 8711 // C++ for OpenCL v1.0 s2.4: 8712 // Moreover the types used in parameters of the kernel functions must be: 8713 // Trivial and standard-layout types C++17 [basic.types] (plain old data 8714 // types) for parameters passed by value; 8715 if (S.getLangOpts().OpenCLCPlusPlus && !PT->isOpenCLSpecificType() && 8716 !PT.isPODType(S.Context)) 8717 return InvalidKernelParam; 8718 8719 if (PT->isRecordType()) 8720 return RecordKernelParam; 8721 8722 return ValidKernelParam; 8723 } 8724 8725 static void checkIsValidOpenCLKernelParameter( 8726 Sema &S, 8727 Declarator &D, 8728 ParmVarDecl *Param, 8729 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8730 QualType PT = Param->getType(); 8731 8732 // Cache the valid types we encounter to avoid rechecking structs that are 8733 // used again 8734 if (ValidTypes.count(PT.getTypePtr())) 8735 return; 8736 8737 switch (getOpenCLKernelParameterType(S, PT)) { 8738 case PtrPtrKernelParam: 8739 // OpenCL v3.0 s6.11.a: 8740 // A kernel function argument cannot be declared as a pointer to a pointer 8741 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 8742 if (S.getLangOpts().OpenCLVersion < 120 && 8743 !S.getLangOpts().OpenCLCPlusPlus) { 8744 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8745 D.setInvalidType(); 8746 return; 8747 } 8748 8749 ValidTypes.insert(PT.getTypePtr()); 8750 return; 8751 8752 case InvalidAddrSpacePtrKernelParam: 8753 // OpenCL v1.0 s6.5: 8754 // __kernel function arguments declared to be a pointer of a type can point 8755 // to one of the following address spaces only : __global, __local or 8756 // __constant. 8757 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8758 D.setInvalidType(); 8759 return; 8760 8761 // OpenCL v1.2 s6.9.k: 8762 // Arguments to kernel functions in a program cannot be declared with the 8763 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8764 // uintptr_t or a struct and/or union that contain fields declared to be 8765 // one of these built-in scalar types. 8766 8767 case InvalidKernelParam: 8768 // OpenCL v1.2 s6.8 n: 8769 // A kernel function argument cannot be declared 8770 // of event_t type. 8771 // Do not diagnose half type since it is diagnosed as invalid argument 8772 // type for any function elsewhere. 8773 if (!PT->isHalfType()) { 8774 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8775 8776 // Explain what typedefs are involved. 8777 const TypedefType *Typedef = nullptr; 8778 while ((Typedef = PT->getAs<TypedefType>())) { 8779 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8780 // SourceLocation may be invalid for a built-in type. 8781 if (Loc.isValid()) 8782 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8783 PT = Typedef->desugar(); 8784 } 8785 } 8786 8787 D.setInvalidType(); 8788 return; 8789 8790 case PtrKernelParam: 8791 case ValidKernelParam: 8792 ValidTypes.insert(PT.getTypePtr()); 8793 return; 8794 8795 case RecordKernelParam: 8796 break; 8797 } 8798 8799 // Track nested structs we will inspect 8800 SmallVector<const Decl *, 4> VisitStack; 8801 8802 // Track where we are in the nested structs. Items will migrate from 8803 // VisitStack to HistoryStack as we do the DFS for bad field. 8804 SmallVector<const FieldDecl *, 4> HistoryStack; 8805 HistoryStack.push_back(nullptr); 8806 8807 // At this point we already handled everything except of a RecordType or 8808 // an ArrayType of a RecordType. 8809 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8810 const RecordType *RecTy = 8811 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8812 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8813 8814 VisitStack.push_back(RecTy->getDecl()); 8815 assert(VisitStack.back() && "First decl null?"); 8816 8817 do { 8818 const Decl *Next = VisitStack.pop_back_val(); 8819 if (!Next) { 8820 assert(!HistoryStack.empty()); 8821 // Found a marker, we have gone up a level 8822 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8823 ValidTypes.insert(Hist->getType().getTypePtr()); 8824 8825 continue; 8826 } 8827 8828 // Adds everything except the original parameter declaration (which is not a 8829 // field itself) to the history stack. 8830 const RecordDecl *RD; 8831 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8832 HistoryStack.push_back(Field); 8833 8834 QualType FieldTy = Field->getType(); 8835 // Other field types (known to be valid or invalid) are handled while we 8836 // walk around RecordDecl::fields(). 8837 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8838 "Unexpected type."); 8839 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8840 8841 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8842 } else { 8843 RD = cast<RecordDecl>(Next); 8844 } 8845 8846 // Add a null marker so we know when we've gone back up a level 8847 VisitStack.push_back(nullptr); 8848 8849 for (const auto *FD : RD->fields()) { 8850 QualType QT = FD->getType(); 8851 8852 if (ValidTypes.count(QT.getTypePtr())) 8853 continue; 8854 8855 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8856 if (ParamType == ValidKernelParam) 8857 continue; 8858 8859 if (ParamType == RecordKernelParam) { 8860 VisitStack.push_back(FD); 8861 continue; 8862 } 8863 8864 // OpenCL v1.2 s6.9.p: 8865 // Arguments to kernel functions that are declared to be a struct or union 8866 // do not allow OpenCL objects to be passed as elements of the struct or 8867 // union. 8868 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8869 ParamType == InvalidAddrSpacePtrKernelParam) { 8870 S.Diag(Param->getLocation(), 8871 diag::err_record_with_pointers_kernel_param) 8872 << PT->isUnionType() 8873 << PT; 8874 } else { 8875 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8876 } 8877 8878 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8879 << OrigRecDecl->getDeclName(); 8880 8881 // We have an error, now let's go back up through history and show where 8882 // the offending field came from 8883 for (ArrayRef<const FieldDecl *>::const_iterator 8884 I = HistoryStack.begin() + 1, 8885 E = HistoryStack.end(); 8886 I != E; ++I) { 8887 const FieldDecl *OuterField = *I; 8888 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8889 << OuterField->getType(); 8890 } 8891 8892 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8893 << QT->isPointerType() 8894 << QT; 8895 D.setInvalidType(); 8896 return; 8897 } 8898 } while (!VisitStack.empty()); 8899 } 8900 8901 /// Find the DeclContext in which a tag is implicitly declared if we see an 8902 /// elaborated type specifier in the specified context, and lookup finds 8903 /// nothing. 8904 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8905 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8906 DC = DC->getParent(); 8907 return DC; 8908 } 8909 8910 /// Find the Scope in which a tag is implicitly declared if we see an 8911 /// elaborated type specifier in the specified context, and lookup finds 8912 /// nothing. 8913 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8914 while (S->isClassScope() || 8915 (LangOpts.CPlusPlus && 8916 S->isFunctionPrototypeScope()) || 8917 ((S->getFlags() & Scope::DeclScope) == 0) || 8918 (S->getEntity() && S->getEntity()->isTransparentContext())) 8919 S = S->getParent(); 8920 return S; 8921 } 8922 8923 NamedDecl* 8924 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8925 TypeSourceInfo *TInfo, LookupResult &Previous, 8926 MultiTemplateParamsArg TemplateParamListsRef, 8927 bool &AddToScope) { 8928 QualType R = TInfo->getType(); 8929 8930 assert(R->isFunctionType()); 8931 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 8932 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 8933 8934 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8935 for (TemplateParameterList *TPL : TemplateParamListsRef) 8936 TemplateParamLists.push_back(TPL); 8937 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8938 if (!TemplateParamLists.empty() && 8939 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8940 TemplateParamLists.back() = Invented; 8941 else 8942 TemplateParamLists.push_back(Invented); 8943 } 8944 8945 // TODO: consider using NameInfo for diagnostic. 8946 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8947 DeclarationName Name = NameInfo.getName(); 8948 StorageClass SC = getFunctionStorageClass(*this, D); 8949 8950 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8951 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8952 diag::err_invalid_thread) 8953 << DeclSpec::getSpecifierName(TSCS); 8954 8955 if (D.isFirstDeclarationOfMember()) 8956 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8957 D.getIdentifierLoc()); 8958 8959 bool isFriend = false; 8960 FunctionTemplateDecl *FunctionTemplate = nullptr; 8961 bool isMemberSpecialization = false; 8962 bool isFunctionTemplateSpecialization = false; 8963 8964 bool isDependentClassScopeExplicitSpecialization = false; 8965 bool HasExplicitTemplateArgs = false; 8966 TemplateArgumentListInfo TemplateArgs; 8967 8968 bool isVirtualOkay = false; 8969 8970 DeclContext *OriginalDC = DC; 8971 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8972 8973 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8974 isVirtualOkay); 8975 if (!NewFD) return nullptr; 8976 8977 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8978 NewFD->setTopLevelDeclInObjCContainer(); 8979 8980 // Set the lexical context. If this is a function-scope declaration, or has a 8981 // C++ scope specifier, or is the object of a friend declaration, the lexical 8982 // context will be different from the semantic context. 8983 NewFD->setLexicalDeclContext(CurContext); 8984 8985 if (IsLocalExternDecl) 8986 NewFD->setLocalExternDecl(); 8987 8988 if (getLangOpts().CPlusPlus) { 8989 bool isInline = D.getDeclSpec().isInlineSpecified(); 8990 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8991 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8992 isFriend = D.getDeclSpec().isFriendSpecified(); 8993 if (isFriend && !isInline && D.isFunctionDefinition()) { 8994 // C++ [class.friend]p5 8995 // A function can be defined in a friend declaration of a 8996 // class . . . . Such a function is implicitly inline. 8997 NewFD->setImplicitlyInline(); 8998 } 8999 9000 // If this is a method defined in an __interface, and is not a constructor 9001 // or an overloaded operator, then set the pure flag (isVirtual will already 9002 // return true). 9003 if (const CXXRecordDecl *Parent = 9004 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 9005 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 9006 NewFD->setPure(true); 9007 9008 // C++ [class.union]p2 9009 // A union can have member functions, but not virtual functions. 9010 if (isVirtual && Parent->isUnion()) 9011 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 9012 } 9013 9014 SetNestedNameSpecifier(*this, NewFD, D); 9015 isMemberSpecialization = false; 9016 isFunctionTemplateSpecialization = false; 9017 if (D.isInvalidType()) 9018 NewFD->setInvalidDecl(); 9019 9020 // Match up the template parameter lists with the scope specifier, then 9021 // determine whether we have a template or a template specialization. 9022 bool Invalid = false; 9023 TemplateParameterList *TemplateParams = 9024 MatchTemplateParametersToScopeSpecifier( 9025 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 9026 D.getCXXScopeSpec(), 9027 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 9028 ? D.getName().TemplateId 9029 : nullptr, 9030 TemplateParamLists, isFriend, isMemberSpecialization, 9031 Invalid); 9032 if (TemplateParams) { 9033 // Check that we can declare a template here. 9034 if (CheckTemplateDeclScope(S, TemplateParams)) 9035 NewFD->setInvalidDecl(); 9036 9037 if (TemplateParams->size() > 0) { 9038 // This is a function template 9039 9040 // A destructor cannot be a template. 9041 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9042 Diag(NewFD->getLocation(), diag::err_destructor_template); 9043 NewFD->setInvalidDecl(); 9044 } 9045 9046 // If we're adding a template to a dependent context, we may need to 9047 // rebuilding some of the types used within the template parameter list, 9048 // now that we know what the current instantiation is. 9049 if (DC->isDependentContext()) { 9050 ContextRAII SavedContext(*this, DC); 9051 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9052 Invalid = true; 9053 } 9054 9055 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9056 NewFD->getLocation(), 9057 Name, TemplateParams, 9058 NewFD); 9059 FunctionTemplate->setLexicalDeclContext(CurContext); 9060 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9061 9062 // For source fidelity, store the other template param lists. 9063 if (TemplateParamLists.size() > 1) { 9064 NewFD->setTemplateParameterListsInfo(Context, 9065 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9066 .drop_back(1)); 9067 } 9068 } else { 9069 // This is a function template specialization. 9070 isFunctionTemplateSpecialization = true; 9071 // For source fidelity, store all the template param lists. 9072 if (TemplateParamLists.size() > 0) 9073 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9074 9075 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9076 if (isFriend) { 9077 // We want to remove the "template<>", found here. 9078 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9079 9080 // If we remove the template<> and the name is not a 9081 // template-id, we're actually silently creating a problem: 9082 // the friend declaration will refer to an untemplated decl, 9083 // and clearly the user wants a template specialization. So 9084 // we need to insert '<>' after the name. 9085 SourceLocation InsertLoc; 9086 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9087 InsertLoc = D.getName().getSourceRange().getEnd(); 9088 InsertLoc = getLocForEndOfToken(InsertLoc); 9089 } 9090 9091 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9092 << Name << RemoveRange 9093 << FixItHint::CreateRemoval(RemoveRange) 9094 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9095 } 9096 } 9097 } else { 9098 // Check that we can declare a template here. 9099 if (!TemplateParamLists.empty() && isMemberSpecialization && 9100 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9101 NewFD->setInvalidDecl(); 9102 9103 // All template param lists were matched against the scope specifier: 9104 // this is NOT (an explicit specialization of) a template. 9105 if (TemplateParamLists.size() > 0) 9106 // For source fidelity, store all the template param lists. 9107 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9108 } 9109 9110 if (Invalid) { 9111 NewFD->setInvalidDecl(); 9112 if (FunctionTemplate) 9113 FunctionTemplate->setInvalidDecl(); 9114 } 9115 9116 // C++ [dcl.fct.spec]p5: 9117 // The virtual specifier shall only be used in declarations of 9118 // nonstatic class member functions that appear within a 9119 // member-specification of a class declaration; see 10.3. 9120 // 9121 if (isVirtual && !NewFD->isInvalidDecl()) { 9122 if (!isVirtualOkay) { 9123 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9124 diag::err_virtual_non_function); 9125 } else if (!CurContext->isRecord()) { 9126 // 'virtual' was specified outside of the class. 9127 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9128 diag::err_virtual_out_of_class) 9129 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9130 } else if (NewFD->getDescribedFunctionTemplate()) { 9131 // C++ [temp.mem]p3: 9132 // A member function template shall not be virtual. 9133 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9134 diag::err_virtual_member_function_template) 9135 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9136 } else { 9137 // Okay: Add virtual to the method. 9138 NewFD->setVirtualAsWritten(true); 9139 } 9140 9141 if (getLangOpts().CPlusPlus14 && 9142 NewFD->getReturnType()->isUndeducedType()) 9143 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9144 } 9145 9146 if (getLangOpts().CPlusPlus14 && 9147 (NewFD->isDependentContext() || 9148 (isFriend && CurContext->isDependentContext())) && 9149 NewFD->getReturnType()->isUndeducedType()) { 9150 // If the function template is referenced directly (for instance, as a 9151 // member of the current instantiation), pretend it has a dependent type. 9152 // This is not really justified by the standard, but is the only sane 9153 // thing to do. 9154 // FIXME: For a friend function, we have not marked the function as being 9155 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9156 const FunctionProtoType *FPT = 9157 NewFD->getType()->castAs<FunctionProtoType>(); 9158 QualType Result = 9159 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9160 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9161 FPT->getExtProtoInfo())); 9162 } 9163 9164 // C++ [dcl.fct.spec]p3: 9165 // The inline specifier shall not appear on a block scope function 9166 // declaration. 9167 if (isInline && !NewFD->isInvalidDecl()) { 9168 if (CurContext->isFunctionOrMethod()) { 9169 // 'inline' is not allowed on block scope function declaration. 9170 Diag(D.getDeclSpec().getInlineSpecLoc(), 9171 diag::err_inline_declaration_block_scope) << Name 9172 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9173 } 9174 } 9175 9176 // C++ [dcl.fct.spec]p6: 9177 // The explicit specifier shall be used only in the declaration of a 9178 // constructor or conversion function within its class definition; 9179 // see 12.3.1 and 12.3.2. 9180 if (hasExplicit && !NewFD->isInvalidDecl() && 9181 !isa<CXXDeductionGuideDecl>(NewFD)) { 9182 if (!CurContext->isRecord()) { 9183 // 'explicit' was specified outside of the class. 9184 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9185 diag::err_explicit_out_of_class) 9186 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9187 } else if (!isa<CXXConstructorDecl>(NewFD) && 9188 !isa<CXXConversionDecl>(NewFD)) { 9189 // 'explicit' was specified on a function that wasn't a constructor 9190 // or conversion function. 9191 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9192 diag::err_explicit_non_ctor_or_conv_function) 9193 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9194 } 9195 } 9196 9197 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9198 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9199 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9200 // are implicitly inline. 9201 NewFD->setImplicitlyInline(); 9202 9203 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9204 // be either constructors or to return a literal type. Therefore, 9205 // destructors cannot be declared constexpr. 9206 if (isa<CXXDestructorDecl>(NewFD) && 9207 (!getLangOpts().CPlusPlus20 || 9208 ConstexprKind == ConstexprSpecKind::Consteval)) { 9209 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9210 << static_cast<int>(ConstexprKind); 9211 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9212 ? ConstexprSpecKind::Unspecified 9213 : ConstexprSpecKind::Constexpr); 9214 } 9215 // C++20 [dcl.constexpr]p2: An allocation function, or a 9216 // deallocation function shall not be declared with the consteval 9217 // specifier. 9218 if (ConstexprKind == ConstexprSpecKind::Consteval && 9219 (NewFD->getOverloadedOperator() == OO_New || 9220 NewFD->getOverloadedOperator() == OO_Array_New || 9221 NewFD->getOverloadedOperator() == OO_Delete || 9222 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9223 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9224 diag::err_invalid_consteval_decl_kind) 9225 << NewFD; 9226 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9227 } 9228 } 9229 9230 // If __module_private__ was specified, mark the function accordingly. 9231 if (D.getDeclSpec().isModulePrivateSpecified()) { 9232 if (isFunctionTemplateSpecialization) { 9233 SourceLocation ModulePrivateLoc 9234 = D.getDeclSpec().getModulePrivateSpecLoc(); 9235 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9236 << 0 9237 << FixItHint::CreateRemoval(ModulePrivateLoc); 9238 } else { 9239 NewFD->setModulePrivate(); 9240 if (FunctionTemplate) 9241 FunctionTemplate->setModulePrivate(); 9242 } 9243 } 9244 9245 if (isFriend) { 9246 if (FunctionTemplate) { 9247 FunctionTemplate->setObjectOfFriendDecl(); 9248 FunctionTemplate->setAccess(AS_public); 9249 } 9250 NewFD->setObjectOfFriendDecl(); 9251 NewFD->setAccess(AS_public); 9252 } 9253 9254 // If a function is defined as defaulted or deleted, mark it as such now. 9255 // We'll do the relevant checks on defaulted / deleted functions later. 9256 switch (D.getFunctionDefinitionKind()) { 9257 case FunctionDefinitionKind::Declaration: 9258 case FunctionDefinitionKind::Definition: 9259 break; 9260 9261 case FunctionDefinitionKind::Defaulted: 9262 NewFD->setDefaulted(); 9263 break; 9264 9265 case FunctionDefinitionKind::Deleted: 9266 NewFD->setDeletedAsWritten(); 9267 break; 9268 } 9269 9270 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9271 D.isFunctionDefinition()) { 9272 // C++ [class.mfct]p2: 9273 // A member function may be defined (8.4) in its class definition, in 9274 // which case it is an inline member function (7.1.2) 9275 NewFD->setImplicitlyInline(); 9276 } 9277 9278 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9279 !CurContext->isRecord()) { 9280 // C++ [class.static]p1: 9281 // A data or function member of a class may be declared static 9282 // in a class definition, in which case it is a static member of 9283 // the class. 9284 9285 // Complain about the 'static' specifier if it's on an out-of-line 9286 // member function definition. 9287 9288 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9289 // member function template declaration and class member template 9290 // declaration (MSVC versions before 2015), warn about this. 9291 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9292 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9293 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9294 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9295 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9296 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9297 } 9298 9299 // C++11 [except.spec]p15: 9300 // A deallocation function with no exception-specification is treated 9301 // as if it were specified with noexcept(true). 9302 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9303 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9304 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9305 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9306 NewFD->setType(Context.getFunctionType( 9307 FPT->getReturnType(), FPT->getParamTypes(), 9308 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9309 } 9310 9311 // Filter out previous declarations that don't match the scope. 9312 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9313 D.getCXXScopeSpec().isNotEmpty() || 9314 isMemberSpecialization || 9315 isFunctionTemplateSpecialization); 9316 9317 // Handle GNU asm-label extension (encoded as an attribute). 9318 if (Expr *E = (Expr*) D.getAsmLabel()) { 9319 // The parser guarantees this is a string. 9320 StringLiteral *SE = cast<StringLiteral>(E); 9321 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9322 /*IsLiteralLabel=*/true, 9323 SE->getStrTokenLoc(0))); 9324 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9325 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9326 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9327 if (I != ExtnameUndeclaredIdentifiers.end()) { 9328 if (isDeclExternC(NewFD)) { 9329 NewFD->addAttr(I->second); 9330 ExtnameUndeclaredIdentifiers.erase(I); 9331 } else 9332 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9333 << /*Variable*/0 << NewFD; 9334 } 9335 } 9336 9337 // Copy the parameter declarations from the declarator D to the function 9338 // declaration NewFD, if they are available. First scavenge them into Params. 9339 SmallVector<ParmVarDecl*, 16> Params; 9340 unsigned FTIIdx; 9341 if (D.isFunctionDeclarator(FTIIdx)) { 9342 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9343 9344 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9345 // function that takes no arguments, not a function that takes a 9346 // single void argument. 9347 // We let through "const void" here because Sema::GetTypeForDeclarator 9348 // already checks for that case. 9349 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9350 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9351 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9352 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9353 Param->setDeclContext(NewFD); 9354 Params.push_back(Param); 9355 9356 if (Param->isInvalidDecl()) 9357 NewFD->setInvalidDecl(); 9358 } 9359 } 9360 9361 if (!getLangOpts().CPlusPlus) { 9362 // In C, find all the tag declarations from the prototype and move them 9363 // into the function DeclContext. Remove them from the surrounding tag 9364 // injection context of the function, which is typically but not always 9365 // the TU. 9366 DeclContext *PrototypeTagContext = 9367 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9368 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9369 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9370 9371 // We don't want to reparent enumerators. Look at their parent enum 9372 // instead. 9373 if (!TD) { 9374 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9375 TD = cast<EnumDecl>(ECD->getDeclContext()); 9376 } 9377 if (!TD) 9378 continue; 9379 DeclContext *TagDC = TD->getLexicalDeclContext(); 9380 if (!TagDC->containsDecl(TD)) 9381 continue; 9382 TagDC->removeDecl(TD); 9383 TD->setDeclContext(NewFD); 9384 NewFD->addDecl(TD); 9385 9386 // Preserve the lexical DeclContext if it is not the surrounding tag 9387 // injection context of the FD. In this example, the semantic context of 9388 // E will be f and the lexical context will be S, while both the 9389 // semantic and lexical contexts of S will be f: 9390 // void f(struct S { enum E { a } f; } s); 9391 if (TagDC != PrototypeTagContext) 9392 TD->setLexicalDeclContext(TagDC); 9393 } 9394 } 9395 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9396 // When we're declaring a function with a typedef, typeof, etc as in the 9397 // following example, we'll need to synthesize (unnamed) 9398 // parameters for use in the declaration. 9399 // 9400 // @code 9401 // typedef void fn(int); 9402 // fn f; 9403 // @endcode 9404 9405 // Synthesize a parameter for each argument type. 9406 for (const auto &AI : FT->param_types()) { 9407 ParmVarDecl *Param = 9408 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9409 Param->setScopeInfo(0, Params.size()); 9410 Params.push_back(Param); 9411 } 9412 } else { 9413 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9414 "Should not need args for typedef of non-prototype fn"); 9415 } 9416 9417 // Finally, we know we have the right number of parameters, install them. 9418 NewFD->setParams(Params); 9419 9420 if (D.getDeclSpec().isNoreturnSpecified()) 9421 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9422 D.getDeclSpec().getNoreturnSpecLoc(), 9423 AttributeCommonInfo::AS_Keyword)); 9424 9425 // Functions returning a variably modified type violate C99 6.7.5.2p2 9426 // because all functions have linkage. 9427 if (!NewFD->isInvalidDecl() && 9428 NewFD->getReturnType()->isVariablyModifiedType()) { 9429 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9430 NewFD->setInvalidDecl(); 9431 } 9432 9433 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9434 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9435 !NewFD->hasAttr<SectionAttr>()) 9436 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9437 Context, PragmaClangTextSection.SectionName, 9438 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9439 9440 // Apply an implicit SectionAttr if #pragma code_seg is active. 9441 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9442 !NewFD->hasAttr<SectionAttr>()) { 9443 NewFD->addAttr(SectionAttr::CreateImplicit( 9444 Context, CodeSegStack.CurrentValue->getString(), 9445 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9446 SectionAttr::Declspec_allocate)); 9447 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9448 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9449 ASTContext::PSF_Read, 9450 NewFD)) 9451 NewFD->dropAttr<SectionAttr>(); 9452 } 9453 9454 // Apply an implicit CodeSegAttr from class declspec or 9455 // apply an implicit SectionAttr from #pragma code_seg if active. 9456 if (!NewFD->hasAttr<CodeSegAttr>()) { 9457 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9458 D.isFunctionDefinition())) { 9459 NewFD->addAttr(SAttr); 9460 } 9461 } 9462 9463 // Handle attributes. 9464 ProcessDeclAttributes(S, NewFD, D); 9465 9466 if (getLangOpts().OpenCL) { 9467 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9468 // type declaration will generate a compilation error. 9469 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9470 if (AddressSpace != LangAS::Default) { 9471 Diag(NewFD->getLocation(), 9472 diag::err_opencl_return_value_with_address_space); 9473 NewFD->setInvalidDecl(); 9474 } 9475 } 9476 9477 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) 9478 checkDeviceDecl(NewFD, D.getBeginLoc()); 9479 9480 if (!getLangOpts().CPlusPlus) { 9481 // Perform semantic checking on the function declaration. 9482 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9483 CheckMain(NewFD, D.getDeclSpec()); 9484 9485 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9486 CheckMSVCRTEntryPoint(NewFD); 9487 9488 if (!NewFD->isInvalidDecl()) 9489 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9490 isMemberSpecialization)); 9491 else if (!Previous.empty()) 9492 // Recover gracefully from an invalid redeclaration. 9493 D.setRedeclaration(true); 9494 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9495 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9496 "previous declaration set still overloaded"); 9497 9498 // Diagnose no-prototype function declarations with calling conventions that 9499 // don't support variadic calls. Only do this in C and do it after merging 9500 // possibly prototyped redeclarations. 9501 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9502 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9503 CallingConv CC = FT->getExtInfo().getCC(); 9504 if (!supportsVariadicCall(CC)) { 9505 // Windows system headers sometimes accidentally use stdcall without 9506 // (void) parameters, so we relax this to a warning. 9507 int DiagID = 9508 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9509 Diag(NewFD->getLocation(), DiagID) 9510 << FunctionType::getNameForCallConv(CC); 9511 } 9512 } 9513 9514 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9515 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9516 checkNonTrivialCUnion(NewFD->getReturnType(), 9517 NewFD->getReturnTypeSourceRange().getBegin(), 9518 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9519 } else { 9520 // C++11 [replacement.functions]p3: 9521 // The program's definitions shall not be specified as inline. 9522 // 9523 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9524 // 9525 // Suppress the diagnostic if the function is __attribute__((used)), since 9526 // that forces an external definition to be emitted. 9527 if (D.getDeclSpec().isInlineSpecified() && 9528 NewFD->isReplaceableGlobalAllocationFunction() && 9529 !NewFD->hasAttr<UsedAttr>()) 9530 Diag(D.getDeclSpec().getInlineSpecLoc(), 9531 diag::ext_operator_new_delete_declared_inline) 9532 << NewFD->getDeclName(); 9533 9534 // If the declarator is a template-id, translate the parser's template 9535 // argument list into our AST format. 9536 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9537 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9538 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9539 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9540 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9541 TemplateId->NumArgs); 9542 translateTemplateArguments(TemplateArgsPtr, 9543 TemplateArgs); 9544 9545 HasExplicitTemplateArgs = true; 9546 9547 if (NewFD->isInvalidDecl()) { 9548 HasExplicitTemplateArgs = false; 9549 } else if (FunctionTemplate) { 9550 // Function template with explicit template arguments. 9551 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9552 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9553 9554 HasExplicitTemplateArgs = false; 9555 } else { 9556 assert((isFunctionTemplateSpecialization || 9557 D.getDeclSpec().isFriendSpecified()) && 9558 "should have a 'template<>' for this decl"); 9559 // "friend void foo<>(int);" is an implicit specialization decl. 9560 isFunctionTemplateSpecialization = true; 9561 } 9562 } else if (isFriend && isFunctionTemplateSpecialization) { 9563 // This combination is only possible in a recovery case; the user 9564 // wrote something like: 9565 // template <> friend void foo(int); 9566 // which we're recovering from as if the user had written: 9567 // friend void foo<>(int); 9568 // Go ahead and fake up a template id. 9569 HasExplicitTemplateArgs = true; 9570 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9571 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9572 } 9573 9574 // We do not add HD attributes to specializations here because 9575 // they may have different constexpr-ness compared to their 9576 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9577 // may end up with different effective targets. Instead, a 9578 // specialization inherits its target attributes from its template 9579 // in the CheckFunctionTemplateSpecialization() call below. 9580 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9581 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9582 9583 // If it's a friend (and only if it's a friend), it's possible 9584 // that either the specialized function type or the specialized 9585 // template is dependent, and therefore matching will fail. In 9586 // this case, don't check the specialization yet. 9587 if (isFunctionTemplateSpecialization && isFriend && 9588 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9589 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 9590 TemplateArgs.arguments()))) { 9591 assert(HasExplicitTemplateArgs && 9592 "friend function specialization without template args"); 9593 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9594 Previous)) 9595 NewFD->setInvalidDecl(); 9596 } else if (isFunctionTemplateSpecialization) { 9597 if (CurContext->isDependentContext() && CurContext->isRecord() 9598 && !isFriend) { 9599 isDependentClassScopeExplicitSpecialization = true; 9600 } else if (!NewFD->isInvalidDecl() && 9601 CheckFunctionTemplateSpecialization( 9602 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9603 Previous)) 9604 NewFD->setInvalidDecl(); 9605 9606 // C++ [dcl.stc]p1: 9607 // A storage-class-specifier shall not be specified in an explicit 9608 // specialization (14.7.3) 9609 FunctionTemplateSpecializationInfo *Info = 9610 NewFD->getTemplateSpecializationInfo(); 9611 if (Info && SC != SC_None) { 9612 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9613 Diag(NewFD->getLocation(), 9614 diag::err_explicit_specialization_inconsistent_storage_class) 9615 << SC 9616 << FixItHint::CreateRemoval( 9617 D.getDeclSpec().getStorageClassSpecLoc()); 9618 9619 else 9620 Diag(NewFD->getLocation(), 9621 diag::ext_explicit_specialization_storage_class) 9622 << FixItHint::CreateRemoval( 9623 D.getDeclSpec().getStorageClassSpecLoc()); 9624 } 9625 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9626 if (CheckMemberSpecialization(NewFD, Previous)) 9627 NewFD->setInvalidDecl(); 9628 } 9629 9630 // Perform semantic checking on the function declaration. 9631 if (!isDependentClassScopeExplicitSpecialization) { 9632 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9633 CheckMain(NewFD, D.getDeclSpec()); 9634 9635 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9636 CheckMSVCRTEntryPoint(NewFD); 9637 9638 if (!NewFD->isInvalidDecl()) 9639 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9640 isMemberSpecialization)); 9641 else if (!Previous.empty()) 9642 // Recover gracefully from an invalid redeclaration. 9643 D.setRedeclaration(true); 9644 } 9645 9646 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9647 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9648 "previous declaration set still overloaded"); 9649 9650 NamedDecl *PrincipalDecl = (FunctionTemplate 9651 ? cast<NamedDecl>(FunctionTemplate) 9652 : NewFD); 9653 9654 if (isFriend && NewFD->getPreviousDecl()) { 9655 AccessSpecifier Access = AS_public; 9656 if (!NewFD->isInvalidDecl()) 9657 Access = NewFD->getPreviousDecl()->getAccess(); 9658 9659 NewFD->setAccess(Access); 9660 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9661 } 9662 9663 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9664 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9665 PrincipalDecl->setNonMemberOperator(); 9666 9667 // If we have a function template, check the template parameter 9668 // list. This will check and merge default template arguments. 9669 if (FunctionTemplate) { 9670 FunctionTemplateDecl *PrevTemplate = 9671 FunctionTemplate->getPreviousDecl(); 9672 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9673 PrevTemplate ? PrevTemplate->getTemplateParameters() 9674 : nullptr, 9675 D.getDeclSpec().isFriendSpecified() 9676 ? (D.isFunctionDefinition() 9677 ? TPC_FriendFunctionTemplateDefinition 9678 : TPC_FriendFunctionTemplate) 9679 : (D.getCXXScopeSpec().isSet() && 9680 DC && DC->isRecord() && 9681 DC->isDependentContext()) 9682 ? TPC_ClassTemplateMember 9683 : TPC_FunctionTemplate); 9684 } 9685 9686 if (NewFD->isInvalidDecl()) { 9687 // Ignore all the rest of this. 9688 } else if (!D.isRedeclaration()) { 9689 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9690 AddToScope }; 9691 // Fake up an access specifier if it's supposed to be a class member. 9692 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9693 NewFD->setAccess(AS_public); 9694 9695 // Qualified decls generally require a previous declaration. 9696 if (D.getCXXScopeSpec().isSet()) { 9697 // ...with the major exception of templated-scope or 9698 // dependent-scope friend declarations. 9699 9700 // TODO: we currently also suppress this check in dependent 9701 // contexts because (1) the parameter depth will be off when 9702 // matching friend templates and (2) we might actually be 9703 // selecting a friend based on a dependent factor. But there 9704 // are situations where these conditions don't apply and we 9705 // can actually do this check immediately. 9706 // 9707 // Unless the scope is dependent, it's always an error if qualified 9708 // redeclaration lookup found nothing at all. Diagnose that now; 9709 // nothing will diagnose that error later. 9710 if (isFriend && 9711 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9712 (!Previous.empty() && CurContext->isDependentContext()))) { 9713 // ignore these 9714 } else if (NewFD->isCPUDispatchMultiVersion() || 9715 NewFD->isCPUSpecificMultiVersion()) { 9716 // ignore this, we allow the redeclaration behavior here to create new 9717 // versions of the function. 9718 } else { 9719 // The user tried to provide an out-of-line definition for a 9720 // function that is a member of a class or namespace, but there 9721 // was no such member function declared (C++ [class.mfct]p2, 9722 // C++ [namespace.memdef]p2). For example: 9723 // 9724 // class X { 9725 // void f() const; 9726 // }; 9727 // 9728 // void X::f() { } // ill-formed 9729 // 9730 // Complain about this problem, and attempt to suggest close 9731 // matches (e.g., those that differ only in cv-qualifiers and 9732 // whether the parameter types are references). 9733 9734 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9735 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9736 AddToScope = ExtraArgs.AddToScope; 9737 return Result; 9738 } 9739 } 9740 9741 // Unqualified local friend declarations are required to resolve 9742 // to something. 9743 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9744 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9745 *this, Previous, NewFD, ExtraArgs, true, S)) { 9746 AddToScope = ExtraArgs.AddToScope; 9747 return Result; 9748 } 9749 } 9750 } else if (!D.isFunctionDefinition() && 9751 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9752 !isFriend && !isFunctionTemplateSpecialization && 9753 !isMemberSpecialization) { 9754 // An out-of-line member function declaration must also be a 9755 // definition (C++ [class.mfct]p2). 9756 // Note that this is not the case for explicit specializations of 9757 // function templates or member functions of class templates, per 9758 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9759 // extension for compatibility with old SWIG code which likes to 9760 // generate them. 9761 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9762 << D.getCXXScopeSpec().getRange(); 9763 } 9764 } 9765 9766 // If this is the first declaration of a library builtin function, add 9767 // attributes as appropriate. 9768 if (!D.isRedeclaration() && 9769 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 9770 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 9771 if (unsigned BuiltinID = II->getBuiltinID()) { 9772 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 9773 // Validate the type matches unless this builtin is specified as 9774 // matching regardless of its declared type. 9775 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 9776 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9777 } else { 9778 ASTContext::GetBuiltinTypeError Error; 9779 LookupNecessaryTypesForBuiltin(S, BuiltinID); 9780 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 9781 9782 if (!Error && !BuiltinType.isNull() && 9783 Context.hasSameFunctionTypeIgnoringExceptionSpec( 9784 NewFD->getType(), BuiltinType)) 9785 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9786 } 9787 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 9788 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9789 // FIXME: We should consider this a builtin only in the std namespace. 9790 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9791 } 9792 } 9793 } 9794 } 9795 9796 ProcessPragmaWeak(S, NewFD); 9797 checkAttributesAfterMerging(*this, *NewFD); 9798 9799 AddKnownFunctionAttributes(NewFD); 9800 9801 if (NewFD->hasAttr<OverloadableAttr>() && 9802 !NewFD->getType()->getAs<FunctionProtoType>()) { 9803 Diag(NewFD->getLocation(), 9804 diag::err_attribute_overloadable_no_prototype) 9805 << NewFD; 9806 9807 // Turn this into a variadic function with no parameters. 9808 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9809 FunctionProtoType::ExtProtoInfo EPI( 9810 Context.getDefaultCallingConvention(true, false)); 9811 EPI.Variadic = true; 9812 EPI.ExtInfo = FT->getExtInfo(); 9813 9814 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9815 NewFD->setType(R); 9816 } 9817 9818 // If there's a #pragma GCC visibility in scope, and this isn't a class 9819 // member, set the visibility of this function. 9820 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9821 AddPushedVisibilityAttribute(NewFD); 9822 9823 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9824 // marking the function. 9825 AddCFAuditedAttribute(NewFD); 9826 9827 // If this is a function definition, check if we have to apply optnone due to 9828 // a pragma. 9829 if(D.isFunctionDefinition()) 9830 AddRangeBasedOptnone(NewFD); 9831 9832 // If this is the first declaration of an extern C variable, update 9833 // the map of such variables. 9834 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9835 isIncompleteDeclExternC(*this, NewFD)) 9836 RegisterLocallyScopedExternCDecl(NewFD, S); 9837 9838 // Set this FunctionDecl's range up to the right paren. 9839 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9840 9841 if (D.isRedeclaration() && !Previous.empty()) { 9842 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9843 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9844 isMemberSpecialization || 9845 isFunctionTemplateSpecialization, 9846 D.isFunctionDefinition()); 9847 } 9848 9849 if (getLangOpts().CUDA) { 9850 IdentifierInfo *II = NewFD->getIdentifier(); 9851 if (II && II->isStr(getCudaConfigureFuncName()) && 9852 !NewFD->isInvalidDecl() && 9853 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9854 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) 9855 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9856 << getCudaConfigureFuncName(); 9857 Context.setcudaConfigureCallDecl(NewFD); 9858 } 9859 9860 // Variadic functions, other than a *declaration* of printf, are not allowed 9861 // in device-side CUDA code, unless someone passed 9862 // -fcuda-allow-variadic-functions. 9863 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9864 (NewFD->hasAttr<CUDADeviceAttr>() || 9865 NewFD->hasAttr<CUDAGlobalAttr>()) && 9866 !(II && II->isStr("printf") && NewFD->isExternC() && 9867 !D.isFunctionDefinition())) { 9868 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9869 } 9870 } 9871 9872 MarkUnusedFileScopedDecl(NewFD); 9873 9874 9875 9876 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9877 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9878 if ((getLangOpts().OpenCLVersion >= 120) 9879 && (SC == SC_Static)) { 9880 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9881 D.setInvalidType(); 9882 } 9883 9884 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9885 if (!NewFD->getReturnType()->isVoidType()) { 9886 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9887 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9888 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9889 : FixItHint()); 9890 D.setInvalidType(); 9891 } 9892 9893 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9894 for (auto Param : NewFD->parameters()) 9895 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9896 9897 if (getLangOpts().OpenCLCPlusPlus) { 9898 if (DC->isRecord()) { 9899 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9900 D.setInvalidType(); 9901 } 9902 if (FunctionTemplate) { 9903 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9904 D.setInvalidType(); 9905 } 9906 } 9907 } 9908 9909 if (getLangOpts().CPlusPlus) { 9910 if (FunctionTemplate) { 9911 if (NewFD->isInvalidDecl()) 9912 FunctionTemplate->setInvalidDecl(); 9913 return FunctionTemplate; 9914 } 9915 9916 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9917 CompleteMemberSpecialization(NewFD, Previous); 9918 } 9919 9920 for (const ParmVarDecl *Param : NewFD->parameters()) { 9921 QualType PT = Param->getType(); 9922 9923 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9924 // types. 9925 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9926 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9927 QualType ElemTy = PipeTy->getElementType(); 9928 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9929 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9930 D.setInvalidType(); 9931 } 9932 } 9933 } 9934 } 9935 9936 // Here we have an function template explicit specialization at class scope. 9937 // The actual specialization will be postponed to template instatiation 9938 // time via the ClassScopeFunctionSpecializationDecl node. 9939 if (isDependentClassScopeExplicitSpecialization) { 9940 ClassScopeFunctionSpecializationDecl *NewSpec = 9941 ClassScopeFunctionSpecializationDecl::Create( 9942 Context, CurContext, NewFD->getLocation(), 9943 cast<CXXMethodDecl>(NewFD), 9944 HasExplicitTemplateArgs, TemplateArgs); 9945 CurContext->addDecl(NewSpec); 9946 AddToScope = false; 9947 } 9948 9949 // Diagnose availability attributes. Availability cannot be used on functions 9950 // that are run during load/unload. 9951 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9952 if (NewFD->hasAttr<ConstructorAttr>()) { 9953 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9954 << 1; 9955 NewFD->dropAttr<AvailabilityAttr>(); 9956 } 9957 if (NewFD->hasAttr<DestructorAttr>()) { 9958 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9959 << 2; 9960 NewFD->dropAttr<AvailabilityAttr>(); 9961 } 9962 } 9963 9964 // Diagnose no_builtin attribute on function declaration that are not a 9965 // definition. 9966 // FIXME: We should really be doing this in 9967 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9968 // the FunctionDecl and at this point of the code 9969 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9970 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9971 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9972 switch (D.getFunctionDefinitionKind()) { 9973 case FunctionDefinitionKind::Defaulted: 9974 case FunctionDefinitionKind::Deleted: 9975 Diag(NBA->getLocation(), 9976 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9977 << NBA->getSpelling(); 9978 break; 9979 case FunctionDefinitionKind::Declaration: 9980 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9981 << NBA->getSpelling(); 9982 break; 9983 case FunctionDefinitionKind::Definition: 9984 break; 9985 } 9986 9987 return NewFD; 9988 } 9989 9990 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9991 /// when __declspec(code_seg) "is applied to a class, all member functions of 9992 /// the class and nested classes -- this includes compiler-generated special 9993 /// member functions -- are put in the specified segment." 9994 /// The actual behavior is a little more complicated. The Microsoft compiler 9995 /// won't check outer classes if there is an active value from #pragma code_seg. 9996 /// The CodeSeg is always applied from the direct parent but only from outer 9997 /// classes when the #pragma code_seg stack is empty. See: 9998 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9999 /// available since MS has removed the page. 10000 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 10001 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 10002 if (!Method) 10003 return nullptr; 10004 const CXXRecordDecl *Parent = Method->getParent(); 10005 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10006 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10007 NewAttr->setImplicit(true); 10008 return NewAttr; 10009 } 10010 10011 // The Microsoft compiler won't check outer classes for the CodeSeg 10012 // when the #pragma code_seg stack is active. 10013 if (S.CodeSegStack.CurrentValue) 10014 return nullptr; 10015 10016 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 10017 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10018 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10019 NewAttr->setImplicit(true); 10020 return NewAttr; 10021 } 10022 } 10023 return nullptr; 10024 } 10025 10026 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 10027 /// containing class. Otherwise it will return implicit SectionAttr if the 10028 /// function is a definition and there is an active value on CodeSegStack 10029 /// (from the current #pragma code-seg value). 10030 /// 10031 /// \param FD Function being declared. 10032 /// \param IsDefinition Whether it is a definition or just a declarartion. 10033 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 10034 /// nullptr if no attribute should be added. 10035 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 10036 bool IsDefinition) { 10037 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 10038 return A; 10039 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 10040 CodeSegStack.CurrentValue) 10041 return SectionAttr::CreateImplicit( 10042 getASTContext(), CodeSegStack.CurrentValue->getString(), 10043 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 10044 SectionAttr::Declspec_allocate); 10045 return nullptr; 10046 } 10047 10048 /// Determines if we can perform a correct type check for \p D as a 10049 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 10050 /// best-effort check. 10051 /// 10052 /// \param NewD The new declaration. 10053 /// \param OldD The old declaration. 10054 /// \param NewT The portion of the type of the new declaration to check. 10055 /// \param OldT The portion of the type of the old declaration to check. 10056 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 10057 QualType NewT, QualType OldT) { 10058 if (!NewD->getLexicalDeclContext()->isDependentContext()) 10059 return true; 10060 10061 // For dependently-typed local extern declarations and friends, we can't 10062 // perform a correct type check in general until instantiation: 10063 // 10064 // int f(); 10065 // template<typename T> void g() { T f(); } 10066 // 10067 // (valid if g() is only instantiated with T = int). 10068 if (NewT->isDependentType() && 10069 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10070 return false; 10071 10072 // Similarly, if the previous declaration was a dependent local extern 10073 // declaration, we don't really know its type yet. 10074 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10075 return false; 10076 10077 return true; 10078 } 10079 10080 /// Checks if the new declaration declared in dependent context must be 10081 /// put in the same redeclaration chain as the specified declaration. 10082 /// 10083 /// \param D Declaration that is checked. 10084 /// \param PrevDecl Previous declaration found with proper lookup method for the 10085 /// same declaration name. 10086 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10087 /// belongs to. 10088 /// 10089 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10090 if (!D->getLexicalDeclContext()->isDependentContext()) 10091 return true; 10092 10093 // Don't chain dependent friend function definitions until instantiation, to 10094 // permit cases like 10095 // 10096 // void func(); 10097 // template<typename T> class C1 { friend void func() {} }; 10098 // template<typename T> class C2 { friend void func() {} }; 10099 // 10100 // ... which is valid if only one of C1 and C2 is ever instantiated. 10101 // 10102 // FIXME: This need only apply to function definitions. For now, we proxy 10103 // this by checking for a file-scope function. We do not want this to apply 10104 // to friend declarations nominating member functions, because that gets in 10105 // the way of access checks. 10106 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10107 return false; 10108 10109 auto *VD = dyn_cast<ValueDecl>(D); 10110 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10111 return !VD || !PrevVD || 10112 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10113 PrevVD->getType()); 10114 } 10115 10116 /// Check the target attribute of the function for MultiVersion 10117 /// validity. 10118 /// 10119 /// Returns true if there was an error, false otherwise. 10120 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10121 const auto *TA = FD->getAttr<TargetAttr>(); 10122 assert(TA && "MultiVersion Candidate requires a target attribute"); 10123 ParsedTargetAttr ParseInfo = TA->parse(); 10124 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10125 enum ErrType { Feature = 0, Architecture = 1 }; 10126 10127 if (!ParseInfo.Architecture.empty() && 10128 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10129 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10130 << Architecture << ParseInfo.Architecture; 10131 return true; 10132 } 10133 10134 for (const auto &Feat : ParseInfo.Features) { 10135 auto BareFeat = StringRef{Feat}.substr(1); 10136 if (Feat[0] == '-') { 10137 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10138 << Feature << ("no-" + BareFeat).str(); 10139 return true; 10140 } 10141 10142 if (!TargetInfo.validateCpuSupports(BareFeat) || 10143 !TargetInfo.isValidFeatureName(BareFeat)) { 10144 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10145 << Feature << BareFeat; 10146 return true; 10147 } 10148 } 10149 return false; 10150 } 10151 10152 // Provide a white-list of attributes that are allowed to be combined with 10153 // multiversion functions. 10154 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10155 MultiVersionKind MVType) { 10156 // Note: this list/diagnosis must match the list in 10157 // checkMultiversionAttributesAllSame. 10158 switch (Kind) { 10159 default: 10160 return false; 10161 case attr::Used: 10162 return MVType == MultiVersionKind::Target; 10163 case attr::NonNull: 10164 case attr::NoThrow: 10165 return true; 10166 } 10167 } 10168 10169 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10170 const FunctionDecl *FD, 10171 const FunctionDecl *CausedFD, 10172 MultiVersionKind MVType) { 10173 bool IsCPUSpecificCPUDispatchMVType = 10174 MVType == MultiVersionKind::CPUDispatch || 10175 MVType == MultiVersionKind::CPUSpecific; 10176 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType]( 10177 Sema &S, const Attr *A) { 10178 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10179 << IsCPUSpecificCPUDispatchMVType << A; 10180 if (CausedFD) 10181 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10182 return true; 10183 }; 10184 10185 for (const Attr *A : FD->attrs()) { 10186 switch (A->getKind()) { 10187 case attr::CPUDispatch: 10188 case attr::CPUSpecific: 10189 if (MVType != MultiVersionKind::CPUDispatch && 10190 MVType != MultiVersionKind::CPUSpecific) 10191 return Diagnose(S, A); 10192 break; 10193 case attr::Target: 10194 if (MVType != MultiVersionKind::Target) 10195 return Diagnose(S, A); 10196 break; 10197 default: 10198 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10199 return Diagnose(S, A); 10200 break; 10201 } 10202 } 10203 return false; 10204 } 10205 10206 bool Sema::areMultiversionVariantFunctionsCompatible( 10207 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10208 const PartialDiagnostic &NoProtoDiagID, 10209 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10210 const PartialDiagnosticAt &NoSupportDiagIDAt, 10211 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10212 bool ConstexprSupported, bool CLinkageMayDiffer) { 10213 enum DoesntSupport { 10214 FuncTemplates = 0, 10215 VirtFuncs = 1, 10216 DeducedReturn = 2, 10217 Constructors = 3, 10218 Destructors = 4, 10219 DeletedFuncs = 5, 10220 DefaultedFuncs = 6, 10221 ConstexprFuncs = 7, 10222 ConstevalFuncs = 8, 10223 }; 10224 enum Different { 10225 CallingConv = 0, 10226 ReturnType = 1, 10227 ConstexprSpec = 2, 10228 InlineSpec = 3, 10229 StorageClass = 4, 10230 Linkage = 5, 10231 }; 10232 10233 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10234 !OldFD->getType()->getAs<FunctionProtoType>()) { 10235 Diag(OldFD->getLocation(), NoProtoDiagID); 10236 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10237 return true; 10238 } 10239 10240 if (NoProtoDiagID.getDiagID() != 0 && 10241 !NewFD->getType()->getAs<FunctionProtoType>()) 10242 return Diag(NewFD->getLocation(), NoProtoDiagID); 10243 10244 if (!TemplatesSupported && 10245 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10246 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10247 << FuncTemplates; 10248 10249 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10250 if (NewCXXFD->isVirtual()) 10251 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10252 << VirtFuncs; 10253 10254 if (isa<CXXConstructorDecl>(NewCXXFD)) 10255 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10256 << Constructors; 10257 10258 if (isa<CXXDestructorDecl>(NewCXXFD)) 10259 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10260 << Destructors; 10261 } 10262 10263 if (NewFD->isDeleted()) 10264 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10265 << DeletedFuncs; 10266 10267 if (NewFD->isDefaulted()) 10268 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10269 << DefaultedFuncs; 10270 10271 if (!ConstexprSupported && NewFD->isConstexpr()) 10272 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10273 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10274 10275 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10276 const auto *NewType = cast<FunctionType>(NewQType); 10277 QualType NewReturnType = NewType->getReturnType(); 10278 10279 if (NewReturnType->isUndeducedType()) 10280 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10281 << DeducedReturn; 10282 10283 // Ensure the return type is identical. 10284 if (OldFD) { 10285 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10286 const auto *OldType = cast<FunctionType>(OldQType); 10287 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10288 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10289 10290 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10291 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10292 10293 QualType OldReturnType = OldType->getReturnType(); 10294 10295 if (OldReturnType != NewReturnType) 10296 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10297 10298 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10299 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10300 10301 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10302 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10303 10304 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10305 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10306 10307 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10308 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10309 10310 if (CheckEquivalentExceptionSpec( 10311 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10312 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10313 return true; 10314 } 10315 return false; 10316 } 10317 10318 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10319 const FunctionDecl *NewFD, 10320 bool CausesMV, 10321 MultiVersionKind MVType) { 10322 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10323 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10324 if (OldFD) 10325 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10326 return true; 10327 } 10328 10329 bool IsCPUSpecificCPUDispatchMVType = 10330 MVType == MultiVersionKind::CPUDispatch || 10331 MVType == MultiVersionKind::CPUSpecific; 10332 10333 if (CausesMV && OldFD && 10334 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType)) 10335 return true; 10336 10337 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType)) 10338 return true; 10339 10340 // Only allow transition to MultiVersion if it hasn't been used. 10341 if (OldFD && CausesMV && OldFD->isUsed(false)) 10342 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10343 10344 return S.areMultiversionVariantFunctionsCompatible( 10345 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10346 PartialDiagnosticAt(NewFD->getLocation(), 10347 S.PDiag(diag::note_multiversioning_caused_here)), 10348 PartialDiagnosticAt(NewFD->getLocation(), 10349 S.PDiag(diag::err_multiversion_doesnt_support) 10350 << IsCPUSpecificCPUDispatchMVType), 10351 PartialDiagnosticAt(NewFD->getLocation(), 10352 S.PDiag(diag::err_multiversion_diff)), 10353 /*TemplatesSupported=*/false, 10354 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10355 /*CLinkageMayDiffer=*/false); 10356 } 10357 10358 /// Check the validity of a multiversion function declaration that is the 10359 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10360 /// 10361 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10362 /// 10363 /// Returns true if there was an error, false otherwise. 10364 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10365 MultiVersionKind MVType, 10366 const TargetAttr *TA) { 10367 assert(MVType != MultiVersionKind::None && 10368 "Function lacks multiversion attribute"); 10369 10370 // Target only causes MV if it is default, otherwise this is a normal 10371 // function. 10372 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10373 return false; 10374 10375 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10376 FD->setInvalidDecl(); 10377 return true; 10378 } 10379 10380 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10381 FD->setInvalidDecl(); 10382 return true; 10383 } 10384 10385 FD->setIsMultiVersion(); 10386 return false; 10387 } 10388 10389 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10390 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10391 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10392 return true; 10393 } 10394 10395 return false; 10396 } 10397 10398 static bool CheckTargetCausesMultiVersioning( 10399 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10400 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10401 LookupResult &Previous) { 10402 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10403 ParsedTargetAttr NewParsed = NewTA->parse(); 10404 // Sort order doesn't matter, it just needs to be consistent. 10405 llvm::sort(NewParsed.Features); 10406 10407 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10408 // to change, this is a simple redeclaration. 10409 if (!NewTA->isDefaultVersion() && 10410 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10411 return false; 10412 10413 // Otherwise, this decl causes MultiVersioning. 10414 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10415 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10416 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10417 NewFD->setInvalidDecl(); 10418 return true; 10419 } 10420 10421 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10422 MultiVersionKind::Target)) { 10423 NewFD->setInvalidDecl(); 10424 return true; 10425 } 10426 10427 if (CheckMultiVersionValue(S, NewFD)) { 10428 NewFD->setInvalidDecl(); 10429 return true; 10430 } 10431 10432 // If this is 'default', permit the forward declaration. 10433 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10434 Redeclaration = true; 10435 OldDecl = OldFD; 10436 OldFD->setIsMultiVersion(); 10437 NewFD->setIsMultiVersion(); 10438 return false; 10439 } 10440 10441 if (CheckMultiVersionValue(S, OldFD)) { 10442 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10443 NewFD->setInvalidDecl(); 10444 return true; 10445 } 10446 10447 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10448 10449 if (OldParsed == NewParsed) { 10450 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10451 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10452 NewFD->setInvalidDecl(); 10453 return true; 10454 } 10455 10456 for (const auto *FD : OldFD->redecls()) { 10457 const auto *CurTA = FD->getAttr<TargetAttr>(); 10458 // We allow forward declarations before ANY multiversioning attributes, but 10459 // nothing after the fact. 10460 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10461 (!CurTA || CurTA->isInherited())) { 10462 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10463 << 0; 10464 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10465 NewFD->setInvalidDecl(); 10466 return true; 10467 } 10468 } 10469 10470 OldFD->setIsMultiVersion(); 10471 NewFD->setIsMultiVersion(); 10472 Redeclaration = false; 10473 MergeTypeWithPrevious = false; 10474 OldDecl = nullptr; 10475 Previous.clear(); 10476 return false; 10477 } 10478 10479 /// Check the validity of a new function declaration being added to an existing 10480 /// multiversioned declaration collection. 10481 static bool CheckMultiVersionAdditionalDecl( 10482 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10483 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10484 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10485 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10486 LookupResult &Previous) { 10487 10488 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10489 // Disallow mixing of multiversioning types. 10490 if ((OldMVType == MultiVersionKind::Target && 10491 NewMVType != MultiVersionKind::Target) || 10492 (NewMVType == MultiVersionKind::Target && 10493 OldMVType != MultiVersionKind::Target)) { 10494 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10495 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10496 NewFD->setInvalidDecl(); 10497 return true; 10498 } 10499 10500 ParsedTargetAttr NewParsed; 10501 if (NewTA) { 10502 NewParsed = NewTA->parse(); 10503 llvm::sort(NewParsed.Features); 10504 } 10505 10506 bool UseMemberUsingDeclRules = 10507 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10508 10509 // Next, check ALL non-overloads to see if this is a redeclaration of a 10510 // previous member of the MultiVersion set. 10511 for (NamedDecl *ND : Previous) { 10512 FunctionDecl *CurFD = ND->getAsFunction(); 10513 if (!CurFD) 10514 continue; 10515 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10516 continue; 10517 10518 if (NewMVType == MultiVersionKind::Target) { 10519 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10520 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10521 NewFD->setIsMultiVersion(); 10522 Redeclaration = true; 10523 OldDecl = ND; 10524 return false; 10525 } 10526 10527 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10528 if (CurParsed == NewParsed) { 10529 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10530 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10531 NewFD->setInvalidDecl(); 10532 return true; 10533 } 10534 } else { 10535 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10536 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10537 // Handle CPUDispatch/CPUSpecific versions. 10538 // Only 1 CPUDispatch function is allowed, this will make it go through 10539 // the redeclaration errors. 10540 if (NewMVType == MultiVersionKind::CPUDispatch && 10541 CurFD->hasAttr<CPUDispatchAttr>()) { 10542 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10543 std::equal( 10544 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10545 NewCPUDisp->cpus_begin(), 10546 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10547 return Cur->getName() == New->getName(); 10548 })) { 10549 NewFD->setIsMultiVersion(); 10550 Redeclaration = true; 10551 OldDecl = ND; 10552 return false; 10553 } 10554 10555 // If the declarations don't match, this is an error condition. 10556 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10557 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10558 NewFD->setInvalidDecl(); 10559 return true; 10560 } 10561 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10562 10563 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10564 std::equal( 10565 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10566 NewCPUSpec->cpus_begin(), 10567 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10568 return Cur->getName() == New->getName(); 10569 })) { 10570 NewFD->setIsMultiVersion(); 10571 Redeclaration = true; 10572 OldDecl = ND; 10573 return false; 10574 } 10575 10576 // Only 1 version of CPUSpecific is allowed for each CPU. 10577 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10578 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10579 if (CurII == NewII) { 10580 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10581 << NewII; 10582 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10583 NewFD->setInvalidDecl(); 10584 return true; 10585 } 10586 } 10587 } 10588 } 10589 // If the two decls aren't the same MVType, there is no possible error 10590 // condition. 10591 } 10592 } 10593 10594 // Else, this is simply a non-redecl case. Checking the 'value' is only 10595 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10596 // handled in the attribute adding step. 10597 if (NewMVType == MultiVersionKind::Target && 10598 CheckMultiVersionValue(S, NewFD)) { 10599 NewFD->setInvalidDecl(); 10600 return true; 10601 } 10602 10603 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10604 !OldFD->isMultiVersion(), NewMVType)) { 10605 NewFD->setInvalidDecl(); 10606 return true; 10607 } 10608 10609 // Permit forward declarations in the case where these two are compatible. 10610 if (!OldFD->isMultiVersion()) { 10611 OldFD->setIsMultiVersion(); 10612 NewFD->setIsMultiVersion(); 10613 Redeclaration = true; 10614 OldDecl = OldFD; 10615 return false; 10616 } 10617 10618 NewFD->setIsMultiVersion(); 10619 Redeclaration = false; 10620 MergeTypeWithPrevious = false; 10621 OldDecl = nullptr; 10622 Previous.clear(); 10623 return false; 10624 } 10625 10626 10627 /// Check the validity of a mulitversion function declaration. 10628 /// Also sets the multiversion'ness' of the function itself. 10629 /// 10630 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10631 /// 10632 /// Returns true if there was an error, false otherwise. 10633 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10634 bool &Redeclaration, NamedDecl *&OldDecl, 10635 bool &MergeTypeWithPrevious, 10636 LookupResult &Previous) { 10637 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10638 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10639 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10640 10641 // Mixing Multiversioning types is prohibited. 10642 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10643 (NewCPUDisp && NewCPUSpec)) { 10644 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10645 NewFD->setInvalidDecl(); 10646 return true; 10647 } 10648 10649 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10650 10651 // Main isn't allowed to become a multiversion function, however it IS 10652 // permitted to have 'main' be marked with the 'target' optimization hint. 10653 if (NewFD->isMain()) { 10654 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10655 MVType == MultiVersionKind::CPUDispatch || 10656 MVType == MultiVersionKind::CPUSpecific) { 10657 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10658 NewFD->setInvalidDecl(); 10659 return true; 10660 } 10661 return false; 10662 } 10663 10664 if (!OldDecl || !OldDecl->getAsFunction() || 10665 OldDecl->getDeclContext()->getRedeclContext() != 10666 NewFD->getDeclContext()->getRedeclContext()) { 10667 // If there's no previous declaration, AND this isn't attempting to cause 10668 // multiversioning, this isn't an error condition. 10669 if (MVType == MultiVersionKind::None) 10670 return false; 10671 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10672 } 10673 10674 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10675 10676 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10677 return false; 10678 10679 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10680 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10681 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10682 NewFD->setInvalidDecl(); 10683 return true; 10684 } 10685 10686 // Handle the target potentially causes multiversioning case. 10687 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10688 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10689 Redeclaration, OldDecl, 10690 MergeTypeWithPrevious, Previous); 10691 10692 // At this point, we have a multiversion function decl (in OldFD) AND an 10693 // appropriate attribute in the current function decl. Resolve that these are 10694 // still compatible with previous declarations. 10695 return CheckMultiVersionAdditionalDecl( 10696 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10697 OldDecl, MergeTypeWithPrevious, Previous); 10698 } 10699 10700 /// Perform semantic checking of a new function declaration. 10701 /// 10702 /// Performs semantic analysis of the new function declaration 10703 /// NewFD. This routine performs all semantic checking that does not 10704 /// require the actual declarator involved in the declaration, and is 10705 /// used both for the declaration of functions as they are parsed 10706 /// (called via ActOnDeclarator) and for the declaration of functions 10707 /// that have been instantiated via C++ template instantiation (called 10708 /// via InstantiateDecl). 10709 /// 10710 /// \param IsMemberSpecialization whether this new function declaration is 10711 /// a member specialization (that replaces any definition provided by the 10712 /// previous declaration). 10713 /// 10714 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10715 /// 10716 /// \returns true if the function declaration is a redeclaration. 10717 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10718 LookupResult &Previous, 10719 bool IsMemberSpecialization) { 10720 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10721 "Variably modified return types are not handled here"); 10722 10723 // Determine whether the type of this function should be merged with 10724 // a previous visible declaration. This never happens for functions in C++, 10725 // and always happens in C if the previous declaration was visible. 10726 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10727 !Previous.isShadowed(); 10728 10729 bool Redeclaration = false; 10730 NamedDecl *OldDecl = nullptr; 10731 bool MayNeedOverloadableChecks = false; 10732 10733 // Merge or overload the declaration with an existing declaration of 10734 // the same name, if appropriate. 10735 if (!Previous.empty()) { 10736 // Determine whether NewFD is an overload of PrevDecl or 10737 // a declaration that requires merging. If it's an overload, 10738 // there's no more work to do here; we'll just add the new 10739 // function to the scope. 10740 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10741 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10742 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10743 Redeclaration = true; 10744 OldDecl = Candidate; 10745 } 10746 } else { 10747 MayNeedOverloadableChecks = true; 10748 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10749 /*NewIsUsingDecl*/ false)) { 10750 case Ovl_Match: 10751 Redeclaration = true; 10752 break; 10753 10754 case Ovl_NonFunction: 10755 Redeclaration = true; 10756 break; 10757 10758 case Ovl_Overload: 10759 Redeclaration = false; 10760 break; 10761 } 10762 } 10763 } 10764 10765 // Check for a previous extern "C" declaration with this name. 10766 if (!Redeclaration && 10767 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10768 if (!Previous.empty()) { 10769 // This is an extern "C" declaration with the same name as a previous 10770 // declaration, and thus redeclares that entity... 10771 Redeclaration = true; 10772 OldDecl = Previous.getFoundDecl(); 10773 MergeTypeWithPrevious = false; 10774 10775 // ... except in the presence of __attribute__((overloadable)). 10776 if (OldDecl->hasAttr<OverloadableAttr>() || 10777 NewFD->hasAttr<OverloadableAttr>()) { 10778 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10779 MayNeedOverloadableChecks = true; 10780 Redeclaration = false; 10781 OldDecl = nullptr; 10782 } 10783 } 10784 } 10785 } 10786 10787 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10788 MergeTypeWithPrevious, Previous)) 10789 return Redeclaration; 10790 10791 // PPC MMA non-pointer types are not allowed as function return types. 10792 if (Context.getTargetInfo().getTriple().isPPC64() && 10793 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 10794 NewFD->setInvalidDecl(); 10795 } 10796 10797 // C++11 [dcl.constexpr]p8: 10798 // A constexpr specifier for a non-static member function that is not 10799 // a constructor declares that member function to be const. 10800 // 10801 // This needs to be delayed until we know whether this is an out-of-line 10802 // definition of a static member function. 10803 // 10804 // This rule is not present in C++1y, so we produce a backwards 10805 // compatibility warning whenever it happens in C++11. 10806 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10807 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10808 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10809 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10810 CXXMethodDecl *OldMD = nullptr; 10811 if (OldDecl) 10812 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10813 if (!OldMD || !OldMD->isStatic()) { 10814 const FunctionProtoType *FPT = 10815 MD->getType()->castAs<FunctionProtoType>(); 10816 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10817 EPI.TypeQuals.addConst(); 10818 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10819 FPT->getParamTypes(), EPI)); 10820 10821 // Warn that we did this, if we're not performing template instantiation. 10822 // In that case, we'll have warned already when the template was defined. 10823 if (!inTemplateInstantiation()) { 10824 SourceLocation AddConstLoc; 10825 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10826 .IgnoreParens().getAs<FunctionTypeLoc>()) 10827 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10828 10829 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10830 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10831 } 10832 } 10833 } 10834 10835 if (Redeclaration) { 10836 // NewFD and OldDecl represent declarations that need to be 10837 // merged. 10838 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10839 NewFD->setInvalidDecl(); 10840 return Redeclaration; 10841 } 10842 10843 Previous.clear(); 10844 Previous.addDecl(OldDecl); 10845 10846 if (FunctionTemplateDecl *OldTemplateDecl = 10847 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10848 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10849 FunctionTemplateDecl *NewTemplateDecl 10850 = NewFD->getDescribedFunctionTemplate(); 10851 assert(NewTemplateDecl && "Template/non-template mismatch"); 10852 10853 // The call to MergeFunctionDecl above may have created some state in 10854 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10855 // can add it as a redeclaration. 10856 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10857 10858 NewFD->setPreviousDeclaration(OldFD); 10859 if (NewFD->isCXXClassMember()) { 10860 NewFD->setAccess(OldTemplateDecl->getAccess()); 10861 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10862 } 10863 10864 // If this is an explicit specialization of a member that is a function 10865 // template, mark it as a member specialization. 10866 if (IsMemberSpecialization && 10867 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10868 NewTemplateDecl->setMemberSpecialization(); 10869 assert(OldTemplateDecl->isMemberSpecialization()); 10870 // Explicit specializations of a member template do not inherit deleted 10871 // status from the parent member template that they are specializing. 10872 if (OldFD->isDeleted()) { 10873 // FIXME: This assert will not hold in the presence of modules. 10874 assert(OldFD->getCanonicalDecl() == OldFD); 10875 // FIXME: We need an update record for this AST mutation. 10876 OldFD->setDeletedAsWritten(false); 10877 } 10878 } 10879 10880 } else { 10881 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10882 auto *OldFD = cast<FunctionDecl>(OldDecl); 10883 // This needs to happen first so that 'inline' propagates. 10884 NewFD->setPreviousDeclaration(OldFD); 10885 if (NewFD->isCXXClassMember()) 10886 NewFD->setAccess(OldFD->getAccess()); 10887 } 10888 } 10889 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10890 !NewFD->getAttr<OverloadableAttr>()) { 10891 assert((Previous.empty() || 10892 llvm::any_of(Previous, 10893 [](const NamedDecl *ND) { 10894 return ND->hasAttr<OverloadableAttr>(); 10895 })) && 10896 "Non-redecls shouldn't happen without overloadable present"); 10897 10898 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10899 const auto *FD = dyn_cast<FunctionDecl>(ND); 10900 return FD && !FD->hasAttr<OverloadableAttr>(); 10901 }); 10902 10903 if (OtherUnmarkedIter != Previous.end()) { 10904 Diag(NewFD->getLocation(), 10905 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10906 Diag((*OtherUnmarkedIter)->getLocation(), 10907 diag::note_attribute_overloadable_prev_overload) 10908 << false; 10909 10910 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10911 } 10912 } 10913 10914 if (LangOpts.OpenMP) 10915 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 10916 10917 // Semantic checking for this function declaration (in isolation). 10918 10919 if (getLangOpts().CPlusPlus) { 10920 // C++-specific checks. 10921 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10922 CheckConstructor(Constructor); 10923 } else if (CXXDestructorDecl *Destructor = 10924 dyn_cast<CXXDestructorDecl>(NewFD)) { 10925 CXXRecordDecl *Record = Destructor->getParent(); 10926 QualType ClassType = Context.getTypeDeclType(Record); 10927 10928 // FIXME: Shouldn't we be able to perform this check even when the class 10929 // type is dependent? Both gcc and edg can handle that. 10930 if (!ClassType->isDependentType()) { 10931 DeclarationName Name 10932 = Context.DeclarationNames.getCXXDestructorName( 10933 Context.getCanonicalType(ClassType)); 10934 if (NewFD->getDeclName() != Name) { 10935 Diag(NewFD->getLocation(), diag::err_destructor_name); 10936 NewFD->setInvalidDecl(); 10937 return Redeclaration; 10938 } 10939 } 10940 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10941 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10942 CheckDeductionGuideTemplate(TD); 10943 10944 // A deduction guide is not on the list of entities that can be 10945 // explicitly specialized. 10946 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10947 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10948 << /*explicit specialization*/ 1; 10949 } 10950 10951 // Find any virtual functions that this function overrides. 10952 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10953 if (!Method->isFunctionTemplateSpecialization() && 10954 !Method->getDescribedFunctionTemplate() && 10955 Method->isCanonicalDecl()) { 10956 AddOverriddenMethods(Method->getParent(), Method); 10957 } 10958 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10959 // C++2a [class.virtual]p6 10960 // A virtual method shall not have a requires-clause. 10961 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10962 diag::err_constrained_virtual_method); 10963 10964 if (Method->isStatic()) 10965 checkThisInStaticMemberFunctionType(Method); 10966 } 10967 10968 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 10969 ActOnConversionDeclarator(Conversion); 10970 10971 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10972 if (NewFD->isOverloadedOperator() && 10973 CheckOverloadedOperatorDeclaration(NewFD)) { 10974 NewFD->setInvalidDecl(); 10975 return Redeclaration; 10976 } 10977 10978 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10979 if (NewFD->getLiteralIdentifier() && 10980 CheckLiteralOperatorDeclaration(NewFD)) { 10981 NewFD->setInvalidDecl(); 10982 return Redeclaration; 10983 } 10984 10985 // In C++, check default arguments now that we have merged decls. Unless 10986 // the lexical context is the class, because in this case this is done 10987 // during delayed parsing anyway. 10988 if (!CurContext->isRecord()) 10989 CheckCXXDefaultArguments(NewFD); 10990 10991 // If this function is declared as being extern "C", then check to see if 10992 // the function returns a UDT (class, struct, or union type) that is not C 10993 // compatible, and if it does, warn the user. 10994 // But, issue any diagnostic on the first declaration only. 10995 if (Previous.empty() && NewFD->isExternC()) { 10996 QualType R = NewFD->getReturnType(); 10997 if (R->isIncompleteType() && !R->isVoidType()) 10998 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10999 << NewFD << R; 11000 else if (!R.isPODType(Context) && !R->isVoidType() && 11001 !R->isObjCObjectPointerType()) 11002 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 11003 } 11004 11005 // C++1z [dcl.fct]p6: 11006 // [...] whether the function has a non-throwing exception-specification 11007 // [is] part of the function type 11008 // 11009 // This results in an ABI break between C++14 and C++17 for functions whose 11010 // declared type includes an exception-specification in a parameter or 11011 // return type. (Exception specifications on the function itself are OK in 11012 // most cases, and exception specifications are not permitted in most other 11013 // contexts where they could make it into a mangling.) 11014 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 11015 auto HasNoexcept = [&](QualType T) -> bool { 11016 // Strip off declarator chunks that could be between us and a function 11017 // type. We don't need to look far, exception specifications are very 11018 // restricted prior to C++17. 11019 if (auto *RT = T->getAs<ReferenceType>()) 11020 T = RT->getPointeeType(); 11021 else if (T->isAnyPointerType()) 11022 T = T->getPointeeType(); 11023 else if (auto *MPT = T->getAs<MemberPointerType>()) 11024 T = MPT->getPointeeType(); 11025 if (auto *FPT = T->getAs<FunctionProtoType>()) 11026 if (FPT->isNothrow()) 11027 return true; 11028 return false; 11029 }; 11030 11031 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 11032 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 11033 for (QualType T : FPT->param_types()) 11034 AnyNoexcept |= HasNoexcept(T); 11035 if (AnyNoexcept) 11036 Diag(NewFD->getLocation(), 11037 diag::warn_cxx17_compat_exception_spec_in_signature) 11038 << NewFD; 11039 } 11040 11041 if (!Redeclaration && LangOpts.CUDA) 11042 checkCUDATargetOverload(NewFD, Previous); 11043 } 11044 return Redeclaration; 11045 } 11046 11047 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11048 // C++11 [basic.start.main]p3: 11049 // A program that [...] declares main to be inline, static or 11050 // constexpr is ill-formed. 11051 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11052 // appear in a declaration of main. 11053 // static main is not an error under C99, but we should warn about it. 11054 // We accept _Noreturn main as an extension. 11055 if (FD->getStorageClass() == SC_Static) 11056 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11057 ? diag::err_static_main : diag::warn_static_main) 11058 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11059 if (FD->isInlineSpecified()) 11060 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11061 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11062 if (DS.isNoreturnSpecified()) { 11063 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11064 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11065 Diag(NoreturnLoc, diag::ext_noreturn_main); 11066 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11067 << FixItHint::CreateRemoval(NoreturnRange); 11068 } 11069 if (FD->isConstexpr()) { 11070 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11071 << FD->isConsteval() 11072 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11073 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11074 } 11075 11076 if (getLangOpts().OpenCL) { 11077 Diag(FD->getLocation(), diag::err_opencl_no_main) 11078 << FD->hasAttr<OpenCLKernelAttr>(); 11079 FD->setInvalidDecl(); 11080 return; 11081 } 11082 11083 QualType T = FD->getType(); 11084 assert(T->isFunctionType() && "function decl is not of function type"); 11085 const FunctionType* FT = T->castAs<FunctionType>(); 11086 11087 // Set default calling convention for main() 11088 if (FT->getCallConv() != CC_C) { 11089 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11090 FD->setType(QualType(FT, 0)); 11091 T = Context.getCanonicalType(FD->getType()); 11092 } 11093 11094 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11095 // In C with GNU extensions we allow main() to have non-integer return 11096 // type, but we should warn about the extension, and we disable the 11097 // implicit-return-zero rule. 11098 11099 // GCC in C mode accepts qualified 'int'. 11100 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11101 FD->setHasImplicitReturnZero(true); 11102 else { 11103 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11104 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11105 if (RTRange.isValid()) 11106 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11107 << FixItHint::CreateReplacement(RTRange, "int"); 11108 } 11109 } else { 11110 // In C and C++, main magically returns 0 if you fall off the end; 11111 // set the flag which tells us that. 11112 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11113 11114 // All the standards say that main() should return 'int'. 11115 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11116 FD->setHasImplicitReturnZero(true); 11117 else { 11118 // Otherwise, this is just a flat-out error. 11119 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11120 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11121 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11122 : FixItHint()); 11123 FD->setInvalidDecl(true); 11124 } 11125 } 11126 11127 // Treat protoless main() as nullary. 11128 if (isa<FunctionNoProtoType>(FT)) return; 11129 11130 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11131 unsigned nparams = FTP->getNumParams(); 11132 assert(FD->getNumParams() == nparams); 11133 11134 bool HasExtraParameters = (nparams > 3); 11135 11136 if (FTP->isVariadic()) { 11137 Diag(FD->getLocation(), diag::ext_variadic_main); 11138 // FIXME: if we had information about the location of the ellipsis, we 11139 // could add a FixIt hint to remove it as a parameter. 11140 } 11141 11142 // Darwin passes an undocumented fourth argument of type char**. If 11143 // other platforms start sprouting these, the logic below will start 11144 // getting shifty. 11145 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11146 HasExtraParameters = false; 11147 11148 if (HasExtraParameters) { 11149 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11150 FD->setInvalidDecl(true); 11151 nparams = 3; 11152 } 11153 11154 // FIXME: a lot of the following diagnostics would be improved 11155 // if we had some location information about types. 11156 11157 QualType CharPP = 11158 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11159 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11160 11161 for (unsigned i = 0; i < nparams; ++i) { 11162 QualType AT = FTP->getParamType(i); 11163 11164 bool mismatch = true; 11165 11166 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11167 mismatch = false; 11168 else if (Expected[i] == CharPP) { 11169 // As an extension, the following forms are okay: 11170 // char const ** 11171 // char const * const * 11172 // char * const * 11173 11174 QualifierCollector qs; 11175 const PointerType* PT; 11176 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11177 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11178 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11179 Context.CharTy)) { 11180 qs.removeConst(); 11181 mismatch = !qs.empty(); 11182 } 11183 } 11184 11185 if (mismatch) { 11186 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11187 // TODO: suggest replacing given type with expected type 11188 FD->setInvalidDecl(true); 11189 } 11190 } 11191 11192 if (nparams == 1 && !FD->isInvalidDecl()) { 11193 Diag(FD->getLocation(), diag::warn_main_one_arg); 11194 } 11195 11196 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11197 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11198 FD->setInvalidDecl(); 11199 } 11200 } 11201 11202 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 11203 11204 // Default calling convention for main and wmain is __cdecl 11205 if (FD->getName() == "main" || FD->getName() == "wmain") 11206 return false; 11207 11208 // Default calling convention for MinGW is __cdecl 11209 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 11210 if (T.isWindowsGNUEnvironment()) 11211 return false; 11212 11213 // Default calling convention for WinMain, wWinMain and DllMain 11214 // is __stdcall on 32 bit Windows 11215 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 11216 return true; 11217 11218 return false; 11219 } 11220 11221 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11222 QualType T = FD->getType(); 11223 assert(T->isFunctionType() && "function decl is not of function type"); 11224 const FunctionType *FT = T->castAs<FunctionType>(); 11225 11226 // Set an implicit return of 'zero' if the function can return some integral, 11227 // enumeration, pointer or nullptr type. 11228 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11229 FT->getReturnType()->isAnyPointerType() || 11230 FT->getReturnType()->isNullPtrType()) 11231 // DllMain is exempt because a return value of zero means it failed. 11232 if (FD->getName() != "DllMain") 11233 FD->setHasImplicitReturnZero(true); 11234 11235 // Explicity specified calling conventions are applied to MSVC entry points 11236 if (!hasExplicitCallingConv(T)) { 11237 if (isDefaultStdCall(FD, *this)) { 11238 if (FT->getCallConv() != CC_X86StdCall) { 11239 FT = Context.adjustFunctionType( 11240 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 11241 FD->setType(QualType(FT, 0)); 11242 } 11243 } else if (FT->getCallConv() != CC_C) { 11244 FT = Context.adjustFunctionType(FT, 11245 FT->getExtInfo().withCallingConv(CC_C)); 11246 FD->setType(QualType(FT, 0)); 11247 } 11248 } 11249 11250 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11251 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11252 FD->setInvalidDecl(); 11253 } 11254 } 11255 11256 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11257 // FIXME: Need strict checking. In C89, we need to check for 11258 // any assignment, increment, decrement, function-calls, or 11259 // commas outside of a sizeof. In C99, it's the same list, 11260 // except that the aforementioned are allowed in unevaluated 11261 // expressions. Everything else falls under the 11262 // "may accept other forms of constant expressions" exception. 11263 // 11264 // Regular C++ code will not end up here (exceptions: language extensions, 11265 // OpenCL C++ etc), so the constant expression rules there don't matter. 11266 if (Init->isValueDependent()) { 11267 assert(Init->containsErrors() && 11268 "Dependent code should only occur in error-recovery path."); 11269 return true; 11270 } 11271 const Expr *Culprit; 11272 if (Init->isConstantInitializer(Context, false, &Culprit)) 11273 return false; 11274 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11275 << Culprit->getSourceRange(); 11276 return true; 11277 } 11278 11279 namespace { 11280 // Visits an initialization expression to see if OrigDecl is evaluated in 11281 // its own initialization and throws a warning if it does. 11282 class SelfReferenceChecker 11283 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11284 Sema &S; 11285 Decl *OrigDecl; 11286 bool isRecordType; 11287 bool isPODType; 11288 bool isReferenceType; 11289 11290 bool isInitList; 11291 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11292 11293 public: 11294 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11295 11296 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11297 S(S), OrigDecl(OrigDecl) { 11298 isPODType = false; 11299 isRecordType = false; 11300 isReferenceType = false; 11301 isInitList = false; 11302 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11303 isPODType = VD->getType().isPODType(S.Context); 11304 isRecordType = VD->getType()->isRecordType(); 11305 isReferenceType = VD->getType()->isReferenceType(); 11306 } 11307 } 11308 11309 // For most expressions, just call the visitor. For initializer lists, 11310 // track the index of the field being initialized since fields are 11311 // initialized in order allowing use of previously initialized fields. 11312 void CheckExpr(Expr *E) { 11313 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11314 if (!InitList) { 11315 Visit(E); 11316 return; 11317 } 11318 11319 // Track and increment the index here. 11320 isInitList = true; 11321 InitFieldIndex.push_back(0); 11322 for (auto Child : InitList->children()) { 11323 CheckExpr(cast<Expr>(Child)); 11324 ++InitFieldIndex.back(); 11325 } 11326 InitFieldIndex.pop_back(); 11327 } 11328 11329 // Returns true if MemberExpr is checked and no further checking is needed. 11330 // Returns false if additional checking is required. 11331 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11332 llvm::SmallVector<FieldDecl*, 4> Fields; 11333 Expr *Base = E; 11334 bool ReferenceField = false; 11335 11336 // Get the field members used. 11337 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11338 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11339 if (!FD) 11340 return false; 11341 Fields.push_back(FD); 11342 if (FD->getType()->isReferenceType()) 11343 ReferenceField = true; 11344 Base = ME->getBase()->IgnoreParenImpCasts(); 11345 } 11346 11347 // Keep checking only if the base Decl is the same. 11348 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11349 if (!DRE || DRE->getDecl() != OrigDecl) 11350 return false; 11351 11352 // A reference field can be bound to an unininitialized field. 11353 if (CheckReference && !ReferenceField) 11354 return true; 11355 11356 // Convert FieldDecls to their index number. 11357 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11358 for (const FieldDecl *I : llvm::reverse(Fields)) 11359 UsedFieldIndex.push_back(I->getFieldIndex()); 11360 11361 // See if a warning is needed by checking the first difference in index 11362 // numbers. If field being used has index less than the field being 11363 // initialized, then the use is safe. 11364 for (auto UsedIter = UsedFieldIndex.begin(), 11365 UsedEnd = UsedFieldIndex.end(), 11366 OrigIter = InitFieldIndex.begin(), 11367 OrigEnd = InitFieldIndex.end(); 11368 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11369 if (*UsedIter < *OrigIter) 11370 return true; 11371 if (*UsedIter > *OrigIter) 11372 break; 11373 } 11374 11375 // TODO: Add a different warning which will print the field names. 11376 HandleDeclRefExpr(DRE); 11377 return true; 11378 } 11379 11380 // For most expressions, the cast is directly above the DeclRefExpr. 11381 // For conditional operators, the cast can be outside the conditional 11382 // operator if both expressions are DeclRefExpr's. 11383 void HandleValue(Expr *E) { 11384 E = E->IgnoreParens(); 11385 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11386 HandleDeclRefExpr(DRE); 11387 return; 11388 } 11389 11390 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11391 Visit(CO->getCond()); 11392 HandleValue(CO->getTrueExpr()); 11393 HandleValue(CO->getFalseExpr()); 11394 return; 11395 } 11396 11397 if (BinaryConditionalOperator *BCO = 11398 dyn_cast<BinaryConditionalOperator>(E)) { 11399 Visit(BCO->getCond()); 11400 HandleValue(BCO->getFalseExpr()); 11401 return; 11402 } 11403 11404 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11405 HandleValue(OVE->getSourceExpr()); 11406 return; 11407 } 11408 11409 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11410 if (BO->getOpcode() == BO_Comma) { 11411 Visit(BO->getLHS()); 11412 HandleValue(BO->getRHS()); 11413 return; 11414 } 11415 } 11416 11417 if (isa<MemberExpr>(E)) { 11418 if (isInitList) { 11419 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11420 false /*CheckReference*/)) 11421 return; 11422 } 11423 11424 Expr *Base = E->IgnoreParenImpCasts(); 11425 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11426 // Check for static member variables and don't warn on them. 11427 if (!isa<FieldDecl>(ME->getMemberDecl())) 11428 return; 11429 Base = ME->getBase()->IgnoreParenImpCasts(); 11430 } 11431 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11432 HandleDeclRefExpr(DRE); 11433 return; 11434 } 11435 11436 Visit(E); 11437 } 11438 11439 // Reference types not handled in HandleValue are handled here since all 11440 // uses of references are bad, not just r-value uses. 11441 void VisitDeclRefExpr(DeclRefExpr *E) { 11442 if (isReferenceType) 11443 HandleDeclRefExpr(E); 11444 } 11445 11446 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11447 if (E->getCastKind() == CK_LValueToRValue) { 11448 HandleValue(E->getSubExpr()); 11449 return; 11450 } 11451 11452 Inherited::VisitImplicitCastExpr(E); 11453 } 11454 11455 void VisitMemberExpr(MemberExpr *E) { 11456 if (isInitList) { 11457 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11458 return; 11459 } 11460 11461 // Don't warn on arrays since they can be treated as pointers. 11462 if (E->getType()->canDecayToPointerType()) return; 11463 11464 // Warn when a non-static method call is followed by non-static member 11465 // field accesses, which is followed by a DeclRefExpr. 11466 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11467 bool Warn = (MD && !MD->isStatic()); 11468 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11469 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11470 if (!isa<FieldDecl>(ME->getMemberDecl())) 11471 Warn = false; 11472 Base = ME->getBase()->IgnoreParenImpCasts(); 11473 } 11474 11475 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11476 if (Warn) 11477 HandleDeclRefExpr(DRE); 11478 return; 11479 } 11480 11481 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11482 // Visit that expression. 11483 Visit(Base); 11484 } 11485 11486 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11487 Expr *Callee = E->getCallee(); 11488 11489 if (isa<UnresolvedLookupExpr>(Callee)) 11490 return Inherited::VisitCXXOperatorCallExpr(E); 11491 11492 Visit(Callee); 11493 for (auto Arg: E->arguments()) 11494 HandleValue(Arg->IgnoreParenImpCasts()); 11495 } 11496 11497 void VisitUnaryOperator(UnaryOperator *E) { 11498 // For POD record types, addresses of its own members are well-defined. 11499 if (E->getOpcode() == UO_AddrOf && isRecordType && 11500 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11501 if (!isPODType) 11502 HandleValue(E->getSubExpr()); 11503 return; 11504 } 11505 11506 if (E->isIncrementDecrementOp()) { 11507 HandleValue(E->getSubExpr()); 11508 return; 11509 } 11510 11511 Inherited::VisitUnaryOperator(E); 11512 } 11513 11514 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11515 11516 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11517 if (E->getConstructor()->isCopyConstructor()) { 11518 Expr *ArgExpr = E->getArg(0); 11519 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11520 if (ILE->getNumInits() == 1) 11521 ArgExpr = ILE->getInit(0); 11522 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11523 if (ICE->getCastKind() == CK_NoOp) 11524 ArgExpr = ICE->getSubExpr(); 11525 HandleValue(ArgExpr); 11526 return; 11527 } 11528 Inherited::VisitCXXConstructExpr(E); 11529 } 11530 11531 void VisitCallExpr(CallExpr *E) { 11532 // Treat std::move as a use. 11533 if (E->isCallToStdMove()) { 11534 HandleValue(E->getArg(0)); 11535 return; 11536 } 11537 11538 Inherited::VisitCallExpr(E); 11539 } 11540 11541 void VisitBinaryOperator(BinaryOperator *E) { 11542 if (E->isCompoundAssignmentOp()) { 11543 HandleValue(E->getLHS()); 11544 Visit(E->getRHS()); 11545 return; 11546 } 11547 11548 Inherited::VisitBinaryOperator(E); 11549 } 11550 11551 // A custom visitor for BinaryConditionalOperator is needed because the 11552 // regular visitor would check the condition and true expression separately 11553 // but both point to the same place giving duplicate diagnostics. 11554 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11555 Visit(E->getCond()); 11556 Visit(E->getFalseExpr()); 11557 } 11558 11559 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11560 Decl* ReferenceDecl = DRE->getDecl(); 11561 if (OrigDecl != ReferenceDecl) return; 11562 unsigned diag; 11563 if (isReferenceType) { 11564 diag = diag::warn_uninit_self_reference_in_reference_init; 11565 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11566 diag = diag::warn_static_self_reference_in_init; 11567 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11568 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11569 DRE->getDecl()->getType()->isRecordType()) { 11570 diag = diag::warn_uninit_self_reference_in_init; 11571 } else { 11572 // Local variables will be handled by the CFG analysis. 11573 return; 11574 } 11575 11576 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11577 S.PDiag(diag) 11578 << DRE->getDecl() << OrigDecl->getLocation() 11579 << DRE->getSourceRange()); 11580 } 11581 }; 11582 11583 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11584 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11585 bool DirectInit) { 11586 // Parameters arguments are occassionially constructed with itself, 11587 // for instance, in recursive functions. Skip them. 11588 if (isa<ParmVarDecl>(OrigDecl)) 11589 return; 11590 11591 E = E->IgnoreParens(); 11592 11593 // Skip checking T a = a where T is not a record or reference type. 11594 // Doing so is a way to silence uninitialized warnings. 11595 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11596 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11597 if (ICE->getCastKind() == CK_LValueToRValue) 11598 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11599 if (DRE->getDecl() == OrigDecl) 11600 return; 11601 11602 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11603 } 11604 } // end anonymous namespace 11605 11606 namespace { 11607 // Simple wrapper to add the name of a variable or (if no variable is 11608 // available) a DeclarationName into a diagnostic. 11609 struct VarDeclOrName { 11610 VarDecl *VDecl; 11611 DeclarationName Name; 11612 11613 friend const Sema::SemaDiagnosticBuilder & 11614 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11615 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11616 } 11617 }; 11618 } // end anonymous namespace 11619 11620 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11621 DeclarationName Name, QualType Type, 11622 TypeSourceInfo *TSI, 11623 SourceRange Range, bool DirectInit, 11624 Expr *Init) { 11625 bool IsInitCapture = !VDecl; 11626 assert((!VDecl || !VDecl->isInitCapture()) && 11627 "init captures are expected to be deduced prior to initialization"); 11628 11629 VarDeclOrName VN{VDecl, Name}; 11630 11631 DeducedType *Deduced = Type->getContainedDeducedType(); 11632 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11633 11634 // C++11 [dcl.spec.auto]p3 11635 if (!Init) { 11636 assert(VDecl && "no init for init capture deduction?"); 11637 11638 // Except for class argument deduction, and then for an initializing 11639 // declaration only, i.e. no static at class scope or extern. 11640 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11641 VDecl->hasExternalStorage() || 11642 VDecl->isStaticDataMember()) { 11643 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11644 << VDecl->getDeclName() << Type; 11645 return QualType(); 11646 } 11647 } 11648 11649 ArrayRef<Expr*> DeduceInits; 11650 if (Init) 11651 DeduceInits = Init; 11652 11653 if (DirectInit) { 11654 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11655 DeduceInits = PL->exprs(); 11656 } 11657 11658 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11659 assert(VDecl && "non-auto type for init capture deduction?"); 11660 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11661 InitializationKind Kind = InitializationKind::CreateForInit( 11662 VDecl->getLocation(), DirectInit, Init); 11663 // FIXME: Initialization should not be taking a mutable list of inits. 11664 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11665 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11666 InitsCopy); 11667 } 11668 11669 if (DirectInit) { 11670 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11671 DeduceInits = IL->inits(); 11672 } 11673 11674 // Deduction only works if we have exactly one source expression. 11675 if (DeduceInits.empty()) { 11676 // It isn't possible to write this directly, but it is possible to 11677 // end up in this situation with "auto x(some_pack...);" 11678 Diag(Init->getBeginLoc(), IsInitCapture 11679 ? diag::err_init_capture_no_expression 11680 : diag::err_auto_var_init_no_expression) 11681 << VN << Type << Range; 11682 return QualType(); 11683 } 11684 11685 if (DeduceInits.size() > 1) { 11686 Diag(DeduceInits[1]->getBeginLoc(), 11687 IsInitCapture ? diag::err_init_capture_multiple_expressions 11688 : diag::err_auto_var_init_multiple_expressions) 11689 << VN << Type << Range; 11690 return QualType(); 11691 } 11692 11693 Expr *DeduceInit = DeduceInits[0]; 11694 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11695 Diag(Init->getBeginLoc(), IsInitCapture 11696 ? diag::err_init_capture_paren_braces 11697 : diag::err_auto_var_init_paren_braces) 11698 << isa<InitListExpr>(Init) << VN << Type << Range; 11699 return QualType(); 11700 } 11701 11702 // Expressions default to 'id' when we're in a debugger. 11703 bool DefaultedAnyToId = false; 11704 if (getLangOpts().DebuggerCastResultToId && 11705 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11706 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11707 if (Result.isInvalid()) { 11708 return QualType(); 11709 } 11710 Init = Result.get(); 11711 DefaultedAnyToId = true; 11712 } 11713 11714 // C++ [dcl.decomp]p1: 11715 // If the assignment-expression [...] has array type A and no ref-qualifier 11716 // is present, e has type cv A 11717 if (VDecl && isa<DecompositionDecl>(VDecl) && 11718 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11719 DeduceInit->getType()->isConstantArrayType()) 11720 return Context.getQualifiedType(DeduceInit->getType(), 11721 Type.getQualifiers()); 11722 11723 QualType DeducedType; 11724 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11725 if (!IsInitCapture) 11726 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11727 else if (isa<InitListExpr>(Init)) 11728 Diag(Range.getBegin(), 11729 diag::err_init_capture_deduction_failure_from_init_list) 11730 << VN 11731 << (DeduceInit->getType().isNull() ? TSI->getType() 11732 : DeduceInit->getType()) 11733 << DeduceInit->getSourceRange(); 11734 else 11735 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11736 << VN << TSI->getType() 11737 << (DeduceInit->getType().isNull() ? TSI->getType() 11738 : DeduceInit->getType()) 11739 << DeduceInit->getSourceRange(); 11740 } 11741 11742 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11743 // 'id' instead of a specific object type prevents most of our usual 11744 // checks. 11745 // We only want to warn outside of template instantiations, though: 11746 // inside a template, the 'id' could have come from a parameter. 11747 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11748 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11749 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11750 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11751 } 11752 11753 return DeducedType; 11754 } 11755 11756 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11757 Expr *Init) { 11758 assert(!Init || !Init->containsErrors()); 11759 QualType DeducedType = deduceVarTypeFromInitializer( 11760 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11761 VDecl->getSourceRange(), DirectInit, Init); 11762 if (DeducedType.isNull()) { 11763 VDecl->setInvalidDecl(); 11764 return true; 11765 } 11766 11767 VDecl->setType(DeducedType); 11768 assert(VDecl->isLinkageValid()); 11769 11770 // In ARC, infer lifetime. 11771 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11772 VDecl->setInvalidDecl(); 11773 11774 if (getLangOpts().OpenCL) 11775 deduceOpenCLAddressSpace(VDecl); 11776 11777 // If this is a redeclaration, check that the type we just deduced matches 11778 // the previously declared type. 11779 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11780 // We never need to merge the type, because we cannot form an incomplete 11781 // array of auto, nor deduce such a type. 11782 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11783 } 11784 11785 // Check the deduced type is valid for a variable declaration. 11786 CheckVariableDeclarationType(VDecl); 11787 return VDecl->isInvalidDecl(); 11788 } 11789 11790 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11791 SourceLocation Loc) { 11792 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11793 Init = EWC->getSubExpr(); 11794 11795 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11796 Init = CE->getSubExpr(); 11797 11798 QualType InitType = Init->getType(); 11799 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11800 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11801 "shouldn't be called if type doesn't have a non-trivial C struct"); 11802 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11803 for (auto I : ILE->inits()) { 11804 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11805 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11806 continue; 11807 SourceLocation SL = I->getExprLoc(); 11808 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11809 } 11810 return; 11811 } 11812 11813 if (isa<ImplicitValueInitExpr>(Init)) { 11814 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11815 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11816 NTCUK_Init); 11817 } else { 11818 // Assume all other explicit initializers involving copying some existing 11819 // object. 11820 // TODO: ignore any explicit initializers where we can guarantee 11821 // copy-elision. 11822 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11823 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11824 } 11825 } 11826 11827 namespace { 11828 11829 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11830 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11831 // in the source code or implicitly by the compiler if it is in a union 11832 // defined in a system header and has non-trivial ObjC ownership 11833 // qualifications. We don't want those fields to participate in determining 11834 // whether the containing union is non-trivial. 11835 return FD->hasAttr<UnavailableAttr>(); 11836 } 11837 11838 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11839 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11840 void> { 11841 using Super = 11842 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11843 void>; 11844 11845 DiagNonTrivalCUnionDefaultInitializeVisitor( 11846 QualType OrigTy, SourceLocation OrigLoc, 11847 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11848 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11849 11850 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11851 const FieldDecl *FD, bool InNonTrivialUnion) { 11852 if (const auto *AT = S.Context.getAsArrayType(QT)) 11853 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11854 InNonTrivialUnion); 11855 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11856 } 11857 11858 void visitARCStrong(QualType QT, const FieldDecl *FD, 11859 bool InNonTrivialUnion) { 11860 if (InNonTrivialUnion) 11861 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11862 << 1 << 0 << QT << FD->getName(); 11863 } 11864 11865 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11866 if (InNonTrivialUnion) 11867 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11868 << 1 << 0 << QT << FD->getName(); 11869 } 11870 11871 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11872 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11873 if (RD->isUnion()) { 11874 if (OrigLoc.isValid()) { 11875 bool IsUnion = false; 11876 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11877 IsUnion = OrigRD->isUnion(); 11878 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11879 << 0 << OrigTy << IsUnion << UseContext; 11880 // Reset OrigLoc so that this diagnostic is emitted only once. 11881 OrigLoc = SourceLocation(); 11882 } 11883 InNonTrivialUnion = true; 11884 } 11885 11886 if (InNonTrivialUnion) 11887 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11888 << 0 << 0 << QT.getUnqualifiedType() << ""; 11889 11890 for (const FieldDecl *FD : RD->fields()) 11891 if (!shouldIgnoreForRecordTriviality(FD)) 11892 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11893 } 11894 11895 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11896 11897 // The non-trivial C union type or the struct/union type that contains a 11898 // non-trivial C union. 11899 QualType OrigTy; 11900 SourceLocation OrigLoc; 11901 Sema::NonTrivialCUnionContext UseContext; 11902 Sema &S; 11903 }; 11904 11905 struct DiagNonTrivalCUnionDestructedTypeVisitor 11906 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11907 using Super = 11908 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11909 11910 DiagNonTrivalCUnionDestructedTypeVisitor( 11911 QualType OrigTy, SourceLocation OrigLoc, 11912 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11913 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11914 11915 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11916 const FieldDecl *FD, bool InNonTrivialUnion) { 11917 if (const auto *AT = S.Context.getAsArrayType(QT)) 11918 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11919 InNonTrivialUnion); 11920 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11921 } 11922 11923 void visitARCStrong(QualType QT, const FieldDecl *FD, 11924 bool InNonTrivialUnion) { 11925 if (InNonTrivialUnion) 11926 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11927 << 1 << 1 << QT << FD->getName(); 11928 } 11929 11930 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11931 if (InNonTrivialUnion) 11932 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11933 << 1 << 1 << QT << FD->getName(); 11934 } 11935 11936 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11937 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11938 if (RD->isUnion()) { 11939 if (OrigLoc.isValid()) { 11940 bool IsUnion = false; 11941 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11942 IsUnion = OrigRD->isUnion(); 11943 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11944 << 1 << OrigTy << IsUnion << UseContext; 11945 // Reset OrigLoc so that this diagnostic is emitted only once. 11946 OrigLoc = SourceLocation(); 11947 } 11948 InNonTrivialUnion = true; 11949 } 11950 11951 if (InNonTrivialUnion) 11952 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11953 << 0 << 1 << QT.getUnqualifiedType() << ""; 11954 11955 for (const FieldDecl *FD : RD->fields()) 11956 if (!shouldIgnoreForRecordTriviality(FD)) 11957 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11958 } 11959 11960 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11961 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11962 bool InNonTrivialUnion) {} 11963 11964 // The non-trivial C union type or the struct/union type that contains a 11965 // non-trivial C union. 11966 QualType OrigTy; 11967 SourceLocation OrigLoc; 11968 Sema::NonTrivialCUnionContext UseContext; 11969 Sema &S; 11970 }; 11971 11972 struct DiagNonTrivalCUnionCopyVisitor 11973 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11974 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11975 11976 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11977 Sema::NonTrivialCUnionContext UseContext, 11978 Sema &S) 11979 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11980 11981 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11982 const FieldDecl *FD, bool InNonTrivialUnion) { 11983 if (const auto *AT = S.Context.getAsArrayType(QT)) 11984 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11985 InNonTrivialUnion); 11986 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11987 } 11988 11989 void visitARCStrong(QualType QT, const FieldDecl *FD, 11990 bool InNonTrivialUnion) { 11991 if (InNonTrivialUnion) 11992 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11993 << 1 << 2 << QT << FD->getName(); 11994 } 11995 11996 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11997 if (InNonTrivialUnion) 11998 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11999 << 1 << 2 << QT << FD->getName(); 12000 } 12001 12002 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12003 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12004 if (RD->isUnion()) { 12005 if (OrigLoc.isValid()) { 12006 bool IsUnion = false; 12007 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12008 IsUnion = OrigRD->isUnion(); 12009 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12010 << 2 << OrigTy << IsUnion << UseContext; 12011 // Reset OrigLoc so that this diagnostic is emitted only once. 12012 OrigLoc = SourceLocation(); 12013 } 12014 InNonTrivialUnion = true; 12015 } 12016 12017 if (InNonTrivialUnion) 12018 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12019 << 0 << 2 << QT.getUnqualifiedType() << ""; 12020 12021 for (const FieldDecl *FD : RD->fields()) 12022 if (!shouldIgnoreForRecordTriviality(FD)) 12023 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12024 } 12025 12026 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 12027 const FieldDecl *FD, bool InNonTrivialUnion) {} 12028 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12029 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 12030 bool InNonTrivialUnion) {} 12031 12032 // The non-trivial C union type or the struct/union type that contains a 12033 // non-trivial C union. 12034 QualType OrigTy; 12035 SourceLocation OrigLoc; 12036 Sema::NonTrivialCUnionContext UseContext; 12037 Sema &S; 12038 }; 12039 12040 } // namespace 12041 12042 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 12043 NonTrivialCUnionContext UseContext, 12044 unsigned NonTrivialKind) { 12045 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12046 QT.hasNonTrivialToPrimitiveDestructCUnion() || 12047 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 12048 "shouldn't be called if type doesn't have a non-trivial C union"); 12049 12050 if ((NonTrivialKind & NTCUK_Init) && 12051 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12052 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 12053 .visit(QT, nullptr, false); 12054 if ((NonTrivialKind & NTCUK_Destruct) && 12055 QT.hasNonTrivialToPrimitiveDestructCUnion()) 12056 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 12057 .visit(QT, nullptr, false); 12058 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 12059 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 12060 .visit(QT, nullptr, false); 12061 } 12062 12063 /// AddInitializerToDecl - Adds the initializer Init to the 12064 /// declaration dcl. If DirectInit is true, this is C++ direct 12065 /// initialization rather than copy initialization. 12066 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 12067 // If there is no declaration, there was an error parsing it. Just ignore 12068 // the initializer. 12069 if (!RealDecl || RealDecl->isInvalidDecl()) { 12070 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 12071 return; 12072 } 12073 12074 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 12075 // Pure-specifiers are handled in ActOnPureSpecifier. 12076 Diag(Method->getLocation(), diag::err_member_function_initialization) 12077 << Method->getDeclName() << Init->getSourceRange(); 12078 Method->setInvalidDecl(); 12079 return; 12080 } 12081 12082 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12083 if (!VDecl) { 12084 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 12085 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12086 RealDecl->setInvalidDecl(); 12087 return; 12088 } 12089 12090 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12091 if (VDecl->getType()->isUndeducedType()) { 12092 // Attempt typo correction early so that the type of the init expression can 12093 // be deduced based on the chosen correction if the original init contains a 12094 // TypoExpr. 12095 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12096 if (!Res.isUsable()) { 12097 // There are unresolved typos in Init, just drop them. 12098 // FIXME: improve the recovery strategy to preserve the Init. 12099 RealDecl->setInvalidDecl(); 12100 return; 12101 } 12102 if (Res.get()->containsErrors()) { 12103 // Invalidate the decl as we don't know the type for recovery-expr yet. 12104 RealDecl->setInvalidDecl(); 12105 VDecl->setInit(Res.get()); 12106 return; 12107 } 12108 Init = Res.get(); 12109 12110 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12111 return; 12112 } 12113 12114 // dllimport cannot be used on variable definitions. 12115 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12116 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12117 VDecl->setInvalidDecl(); 12118 return; 12119 } 12120 12121 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12122 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12123 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12124 VDecl->setInvalidDecl(); 12125 return; 12126 } 12127 12128 if (!VDecl->getType()->isDependentType()) { 12129 // A definition must end up with a complete type, which means it must be 12130 // complete with the restriction that an array type might be completed by 12131 // the initializer; note that later code assumes this restriction. 12132 QualType BaseDeclType = VDecl->getType(); 12133 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12134 BaseDeclType = Array->getElementType(); 12135 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12136 diag::err_typecheck_decl_incomplete_type)) { 12137 RealDecl->setInvalidDecl(); 12138 return; 12139 } 12140 12141 // The variable can not have an abstract class type. 12142 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12143 diag::err_abstract_type_in_decl, 12144 AbstractVariableType)) 12145 VDecl->setInvalidDecl(); 12146 } 12147 12148 // If adding the initializer will turn this declaration into a definition, 12149 // and we already have a definition for this variable, diagnose or otherwise 12150 // handle the situation. 12151 VarDecl *Def; 12152 if ((Def = VDecl->getDefinition()) && Def != VDecl && 12153 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12154 !VDecl->isThisDeclarationADemotedDefinition() && 12155 checkVarDeclRedefinition(Def, VDecl)) 12156 return; 12157 12158 if (getLangOpts().CPlusPlus) { 12159 // C++ [class.static.data]p4 12160 // If a static data member is of const integral or const 12161 // enumeration type, its declaration in the class definition can 12162 // specify a constant-initializer which shall be an integral 12163 // constant expression (5.19). In that case, the member can appear 12164 // in integral constant expressions. The member shall still be 12165 // defined in a namespace scope if it is used in the program and the 12166 // namespace scope definition shall not contain an initializer. 12167 // 12168 // We already performed a redefinition check above, but for static 12169 // data members we also need to check whether there was an in-class 12170 // declaration with an initializer. 12171 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12172 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12173 << VDecl->getDeclName(); 12174 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12175 diag::note_previous_initializer) 12176 << 0; 12177 return; 12178 } 12179 12180 if (VDecl->hasLocalStorage()) 12181 setFunctionHasBranchProtectedScope(); 12182 12183 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12184 VDecl->setInvalidDecl(); 12185 return; 12186 } 12187 } 12188 12189 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12190 // a kernel function cannot be initialized." 12191 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12192 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12193 VDecl->setInvalidDecl(); 12194 return; 12195 } 12196 12197 // The LoaderUninitialized attribute acts as a definition (of undef). 12198 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12199 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12200 VDecl->setInvalidDecl(); 12201 return; 12202 } 12203 12204 // Get the decls type and save a reference for later, since 12205 // CheckInitializerTypes may change it. 12206 QualType DclT = VDecl->getType(), SavT = DclT; 12207 12208 // Expressions default to 'id' when we're in a debugger 12209 // and we are assigning it to a variable of Objective-C pointer type. 12210 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12211 Init->getType() == Context.UnknownAnyTy) { 12212 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12213 if (Result.isInvalid()) { 12214 VDecl->setInvalidDecl(); 12215 return; 12216 } 12217 Init = Result.get(); 12218 } 12219 12220 // Perform the initialization. 12221 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12222 if (!VDecl->isInvalidDecl()) { 12223 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12224 InitializationKind Kind = InitializationKind::CreateForInit( 12225 VDecl->getLocation(), DirectInit, Init); 12226 12227 MultiExprArg Args = Init; 12228 if (CXXDirectInit) 12229 Args = MultiExprArg(CXXDirectInit->getExprs(), 12230 CXXDirectInit->getNumExprs()); 12231 12232 // Try to correct any TypoExprs in the initialization arguments. 12233 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12234 ExprResult Res = CorrectDelayedTyposInExpr( 12235 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12236 [this, Entity, Kind](Expr *E) { 12237 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12238 return Init.Failed() ? ExprError() : E; 12239 }); 12240 if (Res.isInvalid()) { 12241 VDecl->setInvalidDecl(); 12242 } else if (Res.get() != Args[Idx]) { 12243 Args[Idx] = Res.get(); 12244 } 12245 } 12246 if (VDecl->isInvalidDecl()) 12247 return; 12248 12249 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12250 /*TopLevelOfInitList=*/false, 12251 /*TreatUnavailableAsInvalid=*/false); 12252 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12253 if (Result.isInvalid()) { 12254 // If the provied initializer fails to initialize the var decl, 12255 // we attach a recovery expr for better recovery. 12256 auto RecoveryExpr = 12257 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12258 if (RecoveryExpr.get()) 12259 VDecl->setInit(RecoveryExpr.get()); 12260 return; 12261 } 12262 12263 Init = Result.getAs<Expr>(); 12264 } 12265 12266 // Check for self-references within variable initializers. 12267 // Variables declared within a function/method body (except for references) 12268 // are handled by a dataflow analysis. 12269 // This is undefined behavior in C++, but valid in C. 12270 if (getLangOpts().CPlusPlus) { 12271 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12272 VDecl->getType()->isReferenceType()) { 12273 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12274 } 12275 } 12276 12277 // If the type changed, it means we had an incomplete type that was 12278 // completed by the initializer. For example: 12279 // int ary[] = { 1, 3, 5 }; 12280 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12281 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12282 VDecl->setType(DclT); 12283 12284 if (!VDecl->isInvalidDecl()) { 12285 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12286 12287 if (VDecl->hasAttr<BlocksAttr>()) 12288 checkRetainCycles(VDecl, Init); 12289 12290 // It is safe to assign a weak reference into a strong variable. 12291 // Although this code can still have problems: 12292 // id x = self.weakProp; 12293 // id y = self.weakProp; 12294 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12295 // paths through the function. This should be revisited if 12296 // -Wrepeated-use-of-weak is made flow-sensitive. 12297 if (FunctionScopeInfo *FSI = getCurFunction()) 12298 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12299 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12300 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12301 Init->getBeginLoc())) 12302 FSI->markSafeWeakUse(Init); 12303 } 12304 12305 // The initialization is usually a full-expression. 12306 // 12307 // FIXME: If this is a braced initialization of an aggregate, it is not 12308 // an expression, and each individual field initializer is a separate 12309 // full-expression. For instance, in: 12310 // 12311 // struct Temp { ~Temp(); }; 12312 // struct S { S(Temp); }; 12313 // struct T { S a, b; } t = { Temp(), Temp() } 12314 // 12315 // we should destroy the first Temp before constructing the second. 12316 ExprResult Result = 12317 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12318 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12319 if (Result.isInvalid()) { 12320 VDecl->setInvalidDecl(); 12321 return; 12322 } 12323 Init = Result.get(); 12324 12325 // Attach the initializer to the decl. 12326 VDecl->setInit(Init); 12327 12328 if (VDecl->isLocalVarDecl()) { 12329 // Don't check the initializer if the declaration is malformed. 12330 if (VDecl->isInvalidDecl()) { 12331 // do nothing 12332 12333 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12334 // This is true even in C++ for OpenCL. 12335 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12336 CheckForConstantInitializer(Init, DclT); 12337 12338 // Otherwise, C++ does not restrict the initializer. 12339 } else if (getLangOpts().CPlusPlus) { 12340 // do nothing 12341 12342 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12343 // static storage duration shall be constant expressions or string literals. 12344 } else if (VDecl->getStorageClass() == SC_Static) { 12345 CheckForConstantInitializer(Init, DclT); 12346 12347 // C89 is stricter than C99 for aggregate initializers. 12348 // C89 6.5.7p3: All the expressions [...] in an initializer list 12349 // for an object that has aggregate or union type shall be 12350 // constant expressions. 12351 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12352 isa<InitListExpr>(Init)) { 12353 const Expr *Culprit; 12354 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12355 Diag(Culprit->getExprLoc(), 12356 diag::ext_aggregate_init_not_constant) 12357 << Culprit->getSourceRange(); 12358 } 12359 } 12360 12361 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12362 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12363 if (VDecl->hasLocalStorage()) 12364 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12365 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12366 VDecl->getLexicalDeclContext()->isRecord()) { 12367 // This is an in-class initialization for a static data member, e.g., 12368 // 12369 // struct S { 12370 // static const int value = 17; 12371 // }; 12372 12373 // C++ [class.mem]p4: 12374 // A member-declarator can contain a constant-initializer only 12375 // if it declares a static member (9.4) of const integral or 12376 // const enumeration type, see 9.4.2. 12377 // 12378 // C++11 [class.static.data]p3: 12379 // If a non-volatile non-inline const static data member is of integral 12380 // or enumeration type, its declaration in the class definition can 12381 // specify a brace-or-equal-initializer in which every initializer-clause 12382 // that is an assignment-expression is a constant expression. A static 12383 // data member of literal type can be declared in the class definition 12384 // with the constexpr specifier; if so, its declaration shall specify a 12385 // brace-or-equal-initializer in which every initializer-clause that is 12386 // an assignment-expression is a constant expression. 12387 12388 // Do nothing on dependent types. 12389 if (DclT->isDependentType()) { 12390 12391 // Allow any 'static constexpr' members, whether or not they are of literal 12392 // type. We separately check that every constexpr variable is of literal 12393 // type. 12394 } else if (VDecl->isConstexpr()) { 12395 12396 // Require constness. 12397 } else if (!DclT.isConstQualified()) { 12398 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12399 << Init->getSourceRange(); 12400 VDecl->setInvalidDecl(); 12401 12402 // We allow integer constant expressions in all cases. 12403 } else if (DclT->isIntegralOrEnumerationType()) { 12404 // Check whether the expression is a constant expression. 12405 SourceLocation Loc; 12406 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12407 // In C++11, a non-constexpr const static data member with an 12408 // in-class initializer cannot be volatile. 12409 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12410 else if (Init->isValueDependent()) 12411 ; // Nothing to check. 12412 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12413 ; // Ok, it's an ICE! 12414 else if (Init->getType()->isScopedEnumeralType() && 12415 Init->isCXX11ConstantExpr(Context)) 12416 ; // Ok, it is a scoped-enum constant expression. 12417 else if (Init->isEvaluatable(Context)) { 12418 // If we can constant fold the initializer through heroics, accept it, 12419 // but report this as a use of an extension for -pedantic. 12420 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12421 << Init->getSourceRange(); 12422 } else { 12423 // Otherwise, this is some crazy unknown case. Report the issue at the 12424 // location provided by the isIntegerConstantExpr failed check. 12425 Diag(Loc, diag::err_in_class_initializer_non_constant) 12426 << Init->getSourceRange(); 12427 VDecl->setInvalidDecl(); 12428 } 12429 12430 // We allow foldable floating-point constants as an extension. 12431 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12432 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12433 // it anyway and provide a fixit to add the 'constexpr'. 12434 if (getLangOpts().CPlusPlus11) { 12435 Diag(VDecl->getLocation(), 12436 diag::ext_in_class_initializer_float_type_cxx11) 12437 << DclT << Init->getSourceRange(); 12438 Diag(VDecl->getBeginLoc(), 12439 diag::note_in_class_initializer_float_type_cxx11) 12440 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12441 } else { 12442 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12443 << DclT << Init->getSourceRange(); 12444 12445 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12446 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12447 << Init->getSourceRange(); 12448 VDecl->setInvalidDecl(); 12449 } 12450 } 12451 12452 // Suggest adding 'constexpr' in C++11 for literal types. 12453 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12454 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12455 << DclT << Init->getSourceRange() 12456 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12457 VDecl->setConstexpr(true); 12458 12459 } else { 12460 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12461 << DclT << Init->getSourceRange(); 12462 VDecl->setInvalidDecl(); 12463 } 12464 } else if (VDecl->isFileVarDecl()) { 12465 // In C, extern is typically used to avoid tentative definitions when 12466 // declaring variables in headers, but adding an intializer makes it a 12467 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12468 // In C++, extern is often used to give implictly static const variables 12469 // external linkage, so don't warn in that case. If selectany is present, 12470 // this might be header code intended for C and C++ inclusion, so apply the 12471 // C++ rules. 12472 if (VDecl->getStorageClass() == SC_Extern && 12473 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12474 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12475 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12476 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12477 Diag(VDecl->getLocation(), diag::warn_extern_init); 12478 12479 // In Microsoft C++ mode, a const variable defined in namespace scope has 12480 // external linkage by default if the variable is declared with 12481 // __declspec(dllexport). 12482 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12483 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12484 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12485 VDecl->setStorageClass(SC_Extern); 12486 12487 // C99 6.7.8p4. All file scoped initializers need to be constant. 12488 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12489 CheckForConstantInitializer(Init, DclT); 12490 } 12491 12492 QualType InitType = Init->getType(); 12493 if (!InitType.isNull() && 12494 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12495 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12496 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12497 12498 // We will represent direct-initialization similarly to copy-initialization: 12499 // int x(1); -as-> int x = 1; 12500 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12501 // 12502 // Clients that want to distinguish between the two forms, can check for 12503 // direct initializer using VarDecl::getInitStyle(). 12504 // A major benefit is that clients that don't particularly care about which 12505 // exactly form was it (like the CodeGen) can handle both cases without 12506 // special case code. 12507 12508 // C++ 8.5p11: 12509 // The form of initialization (using parentheses or '=') is generally 12510 // insignificant, but does matter when the entity being initialized has a 12511 // class type. 12512 if (CXXDirectInit) { 12513 assert(DirectInit && "Call-style initializer must be direct init."); 12514 VDecl->setInitStyle(VarDecl::CallInit); 12515 } else if (DirectInit) { 12516 // This must be list-initialization. No other way is direct-initialization. 12517 VDecl->setInitStyle(VarDecl::ListInit); 12518 } 12519 12520 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12521 DeclsToCheckForDeferredDiags.push_back(VDecl); 12522 CheckCompleteVariableDeclaration(VDecl); 12523 } 12524 12525 /// ActOnInitializerError - Given that there was an error parsing an 12526 /// initializer for the given declaration, try to return to some form 12527 /// of sanity. 12528 void Sema::ActOnInitializerError(Decl *D) { 12529 // Our main concern here is re-establishing invariants like "a 12530 // variable's type is either dependent or complete". 12531 if (!D || D->isInvalidDecl()) return; 12532 12533 VarDecl *VD = dyn_cast<VarDecl>(D); 12534 if (!VD) return; 12535 12536 // Bindings are not usable if we can't make sense of the initializer. 12537 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12538 for (auto *BD : DD->bindings()) 12539 BD->setInvalidDecl(); 12540 12541 // Auto types are meaningless if we can't make sense of the initializer. 12542 if (VD->getType()->isUndeducedType()) { 12543 D->setInvalidDecl(); 12544 return; 12545 } 12546 12547 QualType Ty = VD->getType(); 12548 if (Ty->isDependentType()) return; 12549 12550 // Require a complete type. 12551 if (RequireCompleteType(VD->getLocation(), 12552 Context.getBaseElementType(Ty), 12553 diag::err_typecheck_decl_incomplete_type)) { 12554 VD->setInvalidDecl(); 12555 return; 12556 } 12557 12558 // Require a non-abstract type. 12559 if (RequireNonAbstractType(VD->getLocation(), Ty, 12560 diag::err_abstract_type_in_decl, 12561 AbstractVariableType)) { 12562 VD->setInvalidDecl(); 12563 return; 12564 } 12565 12566 // Don't bother complaining about constructors or destructors, 12567 // though. 12568 } 12569 12570 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12571 // If there is no declaration, there was an error parsing it. Just ignore it. 12572 if (!RealDecl) 12573 return; 12574 12575 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12576 QualType Type = Var->getType(); 12577 12578 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12579 if (isa<DecompositionDecl>(RealDecl)) { 12580 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12581 Var->setInvalidDecl(); 12582 return; 12583 } 12584 12585 if (Type->isUndeducedType() && 12586 DeduceVariableDeclarationType(Var, false, nullptr)) 12587 return; 12588 12589 // C++11 [class.static.data]p3: A static data member can be declared with 12590 // the constexpr specifier; if so, its declaration shall specify 12591 // a brace-or-equal-initializer. 12592 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12593 // the definition of a variable [...] or the declaration of a static data 12594 // member. 12595 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12596 !Var->isThisDeclarationADemotedDefinition()) { 12597 if (Var->isStaticDataMember()) { 12598 // C++1z removes the relevant rule; the in-class declaration is always 12599 // a definition there. 12600 if (!getLangOpts().CPlusPlus17 && 12601 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12602 Diag(Var->getLocation(), 12603 diag::err_constexpr_static_mem_var_requires_init) 12604 << Var; 12605 Var->setInvalidDecl(); 12606 return; 12607 } 12608 } else { 12609 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12610 Var->setInvalidDecl(); 12611 return; 12612 } 12613 } 12614 12615 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12616 // be initialized. 12617 if (!Var->isInvalidDecl() && 12618 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12619 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12620 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12621 Var->setInvalidDecl(); 12622 return; 12623 } 12624 12625 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12626 if (Var->getStorageClass() == SC_Extern) { 12627 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12628 << Var; 12629 Var->setInvalidDecl(); 12630 return; 12631 } 12632 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12633 diag::err_typecheck_decl_incomplete_type)) { 12634 Var->setInvalidDecl(); 12635 return; 12636 } 12637 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12638 if (!RD->hasTrivialDefaultConstructor()) { 12639 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12640 Var->setInvalidDecl(); 12641 return; 12642 } 12643 } 12644 // The declaration is unitialized, no need for further checks. 12645 return; 12646 } 12647 12648 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12649 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12650 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12651 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12652 NTCUC_DefaultInitializedObject, NTCUK_Init); 12653 12654 12655 switch (DefKind) { 12656 case VarDecl::Definition: 12657 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12658 break; 12659 12660 // We have an out-of-line definition of a static data member 12661 // that has an in-class initializer, so we type-check this like 12662 // a declaration. 12663 // 12664 LLVM_FALLTHROUGH; 12665 12666 case VarDecl::DeclarationOnly: 12667 // It's only a declaration. 12668 12669 // Block scope. C99 6.7p7: If an identifier for an object is 12670 // declared with no linkage (C99 6.2.2p6), the type for the 12671 // object shall be complete. 12672 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12673 !Var->hasLinkage() && !Var->isInvalidDecl() && 12674 RequireCompleteType(Var->getLocation(), Type, 12675 diag::err_typecheck_decl_incomplete_type)) 12676 Var->setInvalidDecl(); 12677 12678 // Make sure that the type is not abstract. 12679 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12680 RequireNonAbstractType(Var->getLocation(), Type, 12681 diag::err_abstract_type_in_decl, 12682 AbstractVariableType)) 12683 Var->setInvalidDecl(); 12684 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12685 Var->getStorageClass() == SC_PrivateExtern) { 12686 Diag(Var->getLocation(), diag::warn_private_extern); 12687 Diag(Var->getLocation(), diag::note_private_extern); 12688 } 12689 12690 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 12691 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12692 ExternalDeclarations.push_back(Var); 12693 12694 return; 12695 12696 case VarDecl::TentativeDefinition: 12697 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12698 // object that has file scope without an initializer, and without a 12699 // storage-class specifier or with the storage-class specifier "static", 12700 // constitutes a tentative definition. Note: A tentative definition with 12701 // external linkage is valid (C99 6.2.2p5). 12702 if (!Var->isInvalidDecl()) { 12703 if (const IncompleteArrayType *ArrayT 12704 = Context.getAsIncompleteArrayType(Type)) { 12705 if (RequireCompleteSizedType( 12706 Var->getLocation(), ArrayT->getElementType(), 12707 diag::err_array_incomplete_or_sizeless_type)) 12708 Var->setInvalidDecl(); 12709 } else if (Var->getStorageClass() == SC_Static) { 12710 // C99 6.9.2p3: If the declaration of an identifier for an object is 12711 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12712 // declared type shall not be an incomplete type. 12713 // NOTE: code such as the following 12714 // static struct s; 12715 // struct s { int a; }; 12716 // is accepted by gcc. Hence here we issue a warning instead of 12717 // an error and we do not invalidate the static declaration. 12718 // NOTE: to avoid multiple warnings, only check the first declaration. 12719 if (Var->isFirstDecl()) 12720 RequireCompleteType(Var->getLocation(), Type, 12721 diag::ext_typecheck_decl_incomplete_type); 12722 } 12723 } 12724 12725 // Record the tentative definition; we're done. 12726 if (!Var->isInvalidDecl()) 12727 TentativeDefinitions.push_back(Var); 12728 return; 12729 } 12730 12731 // Provide a specific diagnostic for uninitialized variable 12732 // definitions with incomplete array type. 12733 if (Type->isIncompleteArrayType()) { 12734 Diag(Var->getLocation(), 12735 diag::err_typecheck_incomplete_array_needs_initializer); 12736 Var->setInvalidDecl(); 12737 return; 12738 } 12739 12740 // Provide a specific diagnostic for uninitialized variable 12741 // definitions with reference type. 12742 if (Type->isReferenceType()) { 12743 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12744 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 12745 Var->setInvalidDecl(); 12746 return; 12747 } 12748 12749 // Do not attempt to type-check the default initializer for a 12750 // variable with dependent type. 12751 if (Type->isDependentType()) 12752 return; 12753 12754 if (Var->isInvalidDecl()) 12755 return; 12756 12757 if (!Var->hasAttr<AliasAttr>()) { 12758 if (RequireCompleteType(Var->getLocation(), 12759 Context.getBaseElementType(Type), 12760 diag::err_typecheck_decl_incomplete_type)) { 12761 Var->setInvalidDecl(); 12762 return; 12763 } 12764 } else { 12765 return; 12766 } 12767 12768 // The variable can not have an abstract class type. 12769 if (RequireNonAbstractType(Var->getLocation(), Type, 12770 diag::err_abstract_type_in_decl, 12771 AbstractVariableType)) { 12772 Var->setInvalidDecl(); 12773 return; 12774 } 12775 12776 // Check for jumps past the implicit initializer. C++0x 12777 // clarifies that this applies to a "variable with automatic 12778 // storage duration", not a "local variable". 12779 // C++11 [stmt.dcl]p3 12780 // A program that jumps from a point where a variable with automatic 12781 // storage duration is not in scope to a point where it is in scope is 12782 // ill-formed unless the variable has scalar type, class type with a 12783 // trivial default constructor and a trivial destructor, a cv-qualified 12784 // version of one of these types, or an array of one of the preceding 12785 // types and is declared without an initializer. 12786 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12787 if (const RecordType *Record 12788 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12789 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12790 // Mark the function (if we're in one) for further checking even if the 12791 // looser rules of C++11 do not require such checks, so that we can 12792 // diagnose incompatibilities with C++98. 12793 if (!CXXRecord->isPOD()) 12794 setFunctionHasBranchProtectedScope(); 12795 } 12796 } 12797 // In OpenCL, we can't initialize objects in the __local address space, 12798 // even implicitly, so don't synthesize an implicit initializer. 12799 if (getLangOpts().OpenCL && 12800 Var->getType().getAddressSpace() == LangAS::opencl_local) 12801 return; 12802 // C++03 [dcl.init]p9: 12803 // If no initializer is specified for an object, and the 12804 // object is of (possibly cv-qualified) non-POD class type (or 12805 // array thereof), the object shall be default-initialized; if 12806 // the object is of const-qualified type, the underlying class 12807 // type shall have a user-declared default 12808 // constructor. Otherwise, if no initializer is specified for 12809 // a non- static object, the object and its subobjects, if 12810 // any, have an indeterminate initial value); if the object 12811 // or any of its subobjects are of const-qualified type, the 12812 // program is ill-formed. 12813 // C++0x [dcl.init]p11: 12814 // If no initializer is specified for an object, the object is 12815 // default-initialized; [...]. 12816 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12817 InitializationKind Kind 12818 = InitializationKind::CreateDefault(Var->getLocation()); 12819 12820 InitializationSequence InitSeq(*this, Entity, Kind, None); 12821 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12822 12823 if (Init.get()) { 12824 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12825 // This is important for template substitution. 12826 Var->setInitStyle(VarDecl::CallInit); 12827 } else if (Init.isInvalid()) { 12828 // If default-init fails, attach a recovery-expr initializer to track 12829 // that initialization was attempted and failed. 12830 auto RecoveryExpr = 12831 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12832 if (RecoveryExpr.get()) 12833 Var->setInit(RecoveryExpr.get()); 12834 } 12835 12836 CheckCompleteVariableDeclaration(Var); 12837 } 12838 } 12839 12840 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12841 // If there is no declaration, there was an error parsing it. Ignore it. 12842 if (!D) 12843 return; 12844 12845 VarDecl *VD = dyn_cast<VarDecl>(D); 12846 if (!VD) { 12847 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12848 D->setInvalidDecl(); 12849 return; 12850 } 12851 12852 VD->setCXXForRangeDecl(true); 12853 12854 // for-range-declaration cannot be given a storage class specifier. 12855 int Error = -1; 12856 switch (VD->getStorageClass()) { 12857 case SC_None: 12858 break; 12859 case SC_Extern: 12860 Error = 0; 12861 break; 12862 case SC_Static: 12863 Error = 1; 12864 break; 12865 case SC_PrivateExtern: 12866 Error = 2; 12867 break; 12868 case SC_Auto: 12869 Error = 3; 12870 break; 12871 case SC_Register: 12872 Error = 4; 12873 break; 12874 } 12875 12876 // for-range-declaration cannot be given a storage class specifier con't. 12877 switch (VD->getTSCSpec()) { 12878 case TSCS_thread_local: 12879 Error = 6; 12880 break; 12881 case TSCS___thread: 12882 case TSCS__Thread_local: 12883 case TSCS_unspecified: 12884 break; 12885 } 12886 12887 if (Error != -1) { 12888 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12889 << VD << Error; 12890 D->setInvalidDecl(); 12891 } 12892 } 12893 12894 StmtResult 12895 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12896 IdentifierInfo *Ident, 12897 ParsedAttributes &Attrs, 12898 SourceLocation AttrEnd) { 12899 // C++1y [stmt.iter]p1: 12900 // A range-based for statement of the form 12901 // for ( for-range-identifier : for-range-initializer ) statement 12902 // is equivalent to 12903 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12904 DeclSpec DS(Attrs.getPool().getFactory()); 12905 12906 const char *PrevSpec; 12907 unsigned DiagID; 12908 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12909 getPrintingPolicy()); 12910 12911 Declarator D(DS, DeclaratorContext::ForInit); 12912 D.SetIdentifier(Ident, IdentLoc); 12913 D.takeAttributes(Attrs, AttrEnd); 12914 12915 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12916 IdentLoc); 12917 Decl *Var = ActOnDeclarator(S, D); 12918 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12919 FinalizeDeclaration(Var); 12920 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12921 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12922 } 12923 12924 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12925 if (var->isInvalidDecl()) return; 12926 12927 if (getLangOpts().OpenCL) { 12928 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12929 // initialiser 12930 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12931 !var->hasInit()) { 12932 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12933 << 1 /*Init*/; 12934 var->setInvalidDecl(); 12935 return; 12936 } 12937 } 12938 12939 // In Objective-C, don't allow jumps past the implicit initialization of a 12940 // local retaining variable. 12941 if (getLangOpts().ObjC && 12942 var->hasLocalStorage()) { 12943 switch (var->getType().getObjCLifetime()) { 12944 case Qualifiers::OCL_None: 12945 case Qualifiers::OCL_ExplicitNone: 12946 case Qualifiers::OCL_Autoreleasing: 12947 break; 12948 12949 case Qualifiers::OCL_Weak: 12950 case Qualifiers::OCL_Strong: 12951 setFunctionHasBranchProtectedScope(); 12952 break; 12953 } 12954 } 12955 12956 if (var->hasLocalStorage() && 12957 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12958 setFunctionHasBranchProtectedScope(); 12959 12960 // Warn about externally-visible variables being defined without a 12961 // prior declaration. We only want to do this for global 12962 // declarations, but we also specifically need to avoid doing it for 12963 // class members because the linkage of an anonymous class can 12964 // change if it's later given a typedef name. 12965 if (var->isThisDeclarationADefinition() && 12966 var->getDeclContext()->getRedeclContext()->isFileContext() && 12967 var->isExternallyVisible() && var->hasLinkage() && 12968 !var->isInline() && !var->getDescribedVarTemplate() && 12969 !isa<VarTemplatePartialSpecializationDecl>(var) && 12970 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12971 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12972 var->getLocation())) { 12973 // Find a previous declaration that's not a definition. 12974 VarDecl *prev = var->getPreviousDecl(); 12975 while (prev && prev->isThisDeclarationADefinition()) 12976 prev = prev->getPreviousDecl(); 12977 12978 if (!prev) { 12979 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12980 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12981 << /* variable */ 0; 12982 } 12983 } 12984 12985 // Cache the result of checking for constant initialization. 12986 Optional<bool> CacheHasConstInit; 12987 const Expr *CacheCulprit = nullptr; 12988 auto checkConstInit = [&]() mutable { 12989 if (!CacheHasConstInit) 12990 CacheHasConstInit = var->getInit()->isConstantInitializer( 12991 Context, var->getType()->isReferenceType(), &CacheCulprit); 12992 return *CacheHasConstInit; 12993 }; 12994 12995 if (var->getTLSKind() == VarDecl::TLS_Static) { 12996 if (var->getType().isDestructedType()) { 12997 // GNU C++98 edits for __thread, [basic.start.term]p3: 12998 // The type of an object with thread storage duration shall not 12999 // have a non-trivial destructor. 13000 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 13001 if (getLangOpts().CPlusPlus11) 13002 Diag(var->getLocation(), diag::note_use_thread_local); 13003 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 13004 if (!checkConstInit()) { 13005 // GNU C++98 edits for __thread, [basic.start.init]p4: 13006 // An object of thread storage duration shall not require dynamic 13007 // initialization. 13008 // FIXME: Need strict checking here. 13009 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 13010 << CacheCulprit->getSourceRange(); 13011 if (getLangOpts().CPlusPlus11) 13012 Diag(var->getLocation(), diag::note_use_thread_local); 13013 } 13014 } 13015 } 13016 13017 // Apply section attributes and pragmas to global variables. 13018 bool GlobalStorage = var->hasGlobalStorage(); 13019 if (GlobalStorage && var->isThisDeclarationADefinition() && 13020 !inTemplateInstantiation()) { 13021 PragmaStack<StringLiteral *> *Stack = nullptr; 13022 int SectionFlags = ASTContext::PSF_Read; 13023 if (var->getType().isConstQualified()) 13024 Stack = &ConstSegStack; 13025 else if (!var->getInit()) { 13026 Stack = &BSSSegStack; 13027 SectionFlags |= ASTContext::PSF_Write; 13028 } else { 13029 Stack = &DataSegStack; 13030 SectionFlags |= ASTContext::PSF_Write; 13031 } 13032 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 13033 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 13034 SectionFlags |= ASTContext::PSF_Implicit; 13035 UnifySection(SA->getName(), SectionFlags, var); 13036 } else if (Stack->CurrentValue) { 13037 SectionFlags |= ASTContext::PSF_Implicit; 13038 auto SectionName = Stack->CurrentValue->getString(); 13039 var->addAttr(SectionAttr::CreateImplicit( 13040 Context, SectionName, Stack->CurrentPragmaLocation, 13041 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 13042 if (UnifySection(SectionName, SectionFlags, var)) 13043 var->dropAttr<SectionAttr>(); 13044 } 13045 13046 // Apply the init_seg attribute if this has an initializer. If the 13047 // initializer turns out to not be dynamic, we'll end up ignoring this 13048 // attribute. 13049 if (CurInitSeg && var->getInit()) 13050 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 13051 CurInitSegLoc, 13052 AttributeCommonInfo::AS_Pragma)); 13053 } 13054 13055 if (!var->getType()->isStructureType() && var->hasInit() && 13056 isa<InitListExpr>(var->getInit())) { 13057 const auto *ILE = cast<InitListExpr>(var->getInit()); 13058 unsigned NumInits = ILE->getNumInits(); 13059 if (NumInits > 2) 13060 for (unsigned I = 0; I < NumInits; ++I) { 13061 const auto *Init = ILE->getInit(I); 13062 if (!Init) 13063 break; 13064 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13065 if (!SL) 13066 break; 13067 13068 unsigned NumConcat = SL->getNumConcatenated(); 13069 // Diagnose missing comma in string array initialization. 13070 // Do not warn when all the elements in the initializer are concatenated 13071 // together. Do not warn for macros too. 13072 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 13073 bool OnlyOneMissingComma = true; 13074 for (unsigned J = I + 1; J < NumInits; ++J) { 13075 const auto *Init = ILE->getInit(J); 13076 if (!Init) 13077 break; 13078 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13079 if (!SLJ || SLJ->getNumConcatenated() > 1) { 13080 OnlyOneMissingComma = false; 13081 break; 13082 } 13083 } 13084 13085 if (OnlyOneMissingComma) { 13086 SmallVector<FixItHint, 1> Hints; 13087 for (unsigned i = 0; i < NumConcat - 1; ++i) 13088 Hints.push_back(FixItHint::CreateInsertion( 13089 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13090 13091 Diag(SL->getStrTokenLoc(1), 13092 diag::warn_concatenated_literal_array_init) 13093 << Hints; 13094 Diag(SL->getBeginLoc(), 13095 diag::note_concatenated_string_literal_silence); 13096 } 13097 // In any case, stop now. 13098 break; 13099 } 13100 } 13101 } 13102 13103 // All the following checks are C++ only. 13104 if (!getLangOpts().CPlusPlus) { 13105 // If this variable must be emitted, add it as an initializer for the 13106 // current module. 13107 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13108 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13109 return; 13110 } 13111 13112 QualType type = var->getType(); 13113 13114 if (var->hasAttr<BlocksAttr>()) 13115 getCurFunction()->addByrefBlockVar(var); 13116 13117 Expr *Init = var->getInit(); 13118 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13119 QualType baseType = Context.getBaseElementType(type); 13120 13121 // Check whether the initializer is sufficiently constant. 13122 if (!type->isDependentType() && Init && !Init->isValueDependent() && 13123 (GlobalStorage || var->isConstexpr() || 13124 var->mightBeUsableInConstantExpressions(Context))) { 13125 // If this variable might have a constant initializer or might be usable in 13126 // constant expressions, check whether or not it actually is now. We can't 13127 // do this lazily, because the result might depend on things that change 13128 // later, such as which constexpr functions happen to be defined. 13129 SmallVector<PartialDiagnosticAt, 8> Notes; 13130 bool HasConstInit; 13131 if (!getLangOpts().CPlusPlus11) { 13132 // Prior to C++11, in contexts where a constant initializer is required, 13133 // the set of valid constant initializers is described by syntactic rules 13134 // in [expr.const]p2-6. 13135 // FIXME: Stricter checking for these rules would be useful for constinit / 13136 // -Wglobal-constructors. 13137 HasConstInit = checkConstInit(); 13138 13139 // Compute and cache the constant value, and remember that we have a 13140 // constant initializer. 13141 if (HasConstInit) { 13142 (void)var->checkForConstantInitialization(Notes); 13143 Notes.clear(); 13144 } else if (CacheCulprit) { 13145 Notes.emplace_back(CacheCulprit->getExprLoc(), 13146 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13147 Notes.back().second << CacheCulprit->getSourceRange(); 13148 } 13149 } else { 13150 // Evaluate the initializer to see if it's a constant initializer. 13151 HasConstInit = var->checkForConstantInitialization(Notes); 13152 } 13153 13154 if (HasConstInit) { 13155 // FIXME: Consider replacing the initializer with a ConstantExpr. 13156 } else if (var->isConstexpr()) { 13157 SourceLocation DiagLoc = var->getLocation(); 13158 // If the note doesn't add any useful information other than a source 13159 // location, fold it into the primary diagnostic. 13160 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13161 diag::note_invalid_subexpr_in_const_expr) { 13162 DiagLoc = Notes[0].first; 13163 Notes.clear(); 13164 } 13165 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13166 << var << Init->getSourceRange(); 13167 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13168 Diag(Notes[I].first, Notes[I].second); 13169 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13170 auto *Attr = var->getAttr<ConstInitAttr>(); 13171 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13172 << Init->getSourceRange(); 13173 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13174 << Attr->getRange() << Attr->isConstinit(); 13175 for (auto &it : Notes) 13176 Diag(it.first, it.second); 13177 } else if (IsGlobal && 13178 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13179 var->getLocation())) { 13180 // Warn about globals which don't have a constant initializer. Don't 13181 // warn about globals with a non-trivial destructor because we already 13182 // warned about them. 13183 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13184 if (!(RD && !RD->hasTrivialDestructor())) { 13185 // checkConstInit() here permits trivial default initialization even in 13186 // C++11 onwards, where such an initializer is not a constant initializer 13187 // but nonetheless doesn't require a global constructor. 13188 if (!checkConstInit()) 13189 Diag(var->getLocation(), diag::warn_global_constructor) 13190 << Init->getSourceRange(); 13191 } 13192 } 13193 } 13194 13195 // Require the destructor. 13196 if (!type->isDependentType()) 13197 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13198 FinalizeVarWithDestructor(var, recordType); 13199 13200 // If this variable must be emitted, add it as an initializer for the current 13201 // module. 13202 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13203 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13204 13205 // Build the bindings if this is a structured binding declaration. 13206 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13207 CheckCompleteDecompositionDeclaration(DD); 13208 } 13209 13210 /// Determines if a variable's alignment is dependent. 13211 static bool hasDependentAlignment(VarDecl *VD) { 13212 if (VD->getType()->isDependentType()) 13213 return true; 13214 for (auto *I : VD->specific_attrs<AlignedAttr>()) 13215 if (I->isAlignmentDependent()) 13216 return true; 13217 return false; 13218 } 13219 13220 /// Check if VD needs to be dllexport/dllimport due to being in a 13221 /// dllexport/import function. 13222 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13223 assert(VD->isStaticLocal()); 13224 13225 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13226 13227 // Find outermost function when VD is in lambda function. 13228 while (FD && !getDLLAttr(FD) && 13229 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13230 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13231 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13232 } 13233 13234 if (!FD) 13235 return; 13236 13237 // Static locals inherit dll attributes from their function. 13238 if (Attr *A = getDLLAttr(FD)) { 13239 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13240 NewAttr->setInherited(true); 13241 VD->addAttr(NewAttr); 13242 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13243 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13244 NewAttr->setInherited(true); 13245 VD->addAttr(NewAttr); 13246 13247 // Export this function to enforce exporting this static variable even 13248 // if it is not used in this compilation unit. 13249 if (!FD->hasAttr<DLLExportAttr>()) 13250 FD->addAttr(NewAttr); 13251 13252 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13253 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13254 NewAttr->setInherited(true); 13255 VD->addAttr(NewAttr); 13256 } 13257 } 13258 13259 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13260 /// any semantic actions necessary after any initializer has been attached. 13261 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13262 // Note that we are no longer parsing the initializer for this declaration. 13263 ParsingInitForAutoVars.erase(ThisDecl); 13264 13265 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13266 if (!VD) 13267 return; 13268 13269 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13270 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13271 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13272 if (PragmaClangBSSSection.Valid) 13273 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13274 Context, PragmaClangBSSSection.SectionName, 13275 PragmaClangBSSSection.PragmaLocation, 13276 AttributeCommonInfo::AS_Pragma)); 13277 if (PragmaClangDataSection.Valid) 13278 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13279 Context, PragmaClangDataSection.SectionName, 13280 PragmaClangDataSection.PragmaLocation, 13281 AttributeCommonInfo::AS_Pragma)); 13282 if (PragmaClangRodataSection.Valid) 13283 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13284 Context, PragmaClangRodataSection.SectionName, 13285 PragmaClangRodataSection.PragmaLocation, 13286 AttributeCommonInfo::AS_Pragma)); 13287 if (PragmaClangRelroSection.Valid) 13288 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13289 Context, PragmaClangRelroSection.SectionName, 13290 PragmaClangRelroSection.PragmaLocation, 13291 AttributeCommonInfo::AS_Pragma)); 13292 } 13293 13294 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13295 for (auto *BD : DD->bindings()) { 13296 FinalizeDeclaration(BD); 13297 } 13298 } 13299 13300 checkAttributesAfterMerging(*this, *VD); 13301 13302 // Perform TLS alignment check here after attributes attached to the variable 13303 // which may affect the alignment have been processed. Only perform the check 13304 // if the target has a maximum TLS alignment (zero means no constraints). 13305 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13306 // Protect the check so that it's not performed on dependent types and 13307 // dependent alignments (we can't determine the alignment in that case). 13308 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 13309 !VD->isInvalidDecl()) { 13310 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13311 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13312 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13313 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13314 << (unsigned)MaxAlignChars.getQuantity(); 13315 } 13316 } 13317 } 13318 13319 if (VD->isStaticLocal()) 13320 CheckStaticLocalForDllExport(VD); 13321 13322 // Perform check for initializers of device-side global variables. 13323 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13324 // 7.5). We must also apply the same checks to all __shared__ 13325 // variables whether they are local or not. CUDA also allows 13326 // constant initializers for __constant__ and __device__ variables. 13327 if (getLangOpts().CUDA) 13328 checkAllowedCUDAInitializer(VD); 13329 13330 // Grab the dllimport or dllexport attribute off of the VarDecl. 13331 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13332 13333 // Imported static data members cannot be defined out-of-line. 13334 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13335 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13336 VD->isThisDeclarationADefinition()) { 13337 // We allow definitions of dllimport class template static data members 13338 // with a warning. 13339 CXXRecordDecl *Context = 13340 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13341 bool IsClassTemplateMember = 13342 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13343 Context->getDescribedClassTemplate(); 13344 13345 Diag(VD->getLocation(), 13346 IsClassTemplateMember 13347 ? diag::warn_attribute_dllimport_static_field_definition 13348 : diag::err_attribute_dllimport_static_field_definition); 13349 Diag(IA->getLocation(), diag::note_attribute); 13350 if (!IsClassTemplateMember) 13351 VD->setInvalidDecl(); 13352 } 13353 } 13354 13355 // dllimport/dllexport variables cannot be thread local, their TLS index 13356 // isn't exported with the variable. 13357 if (DLLAttr && VD->getTLSKind()) { 13358 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13359 if (F && getDLLAttr(F)) { 13360 assert(VD->isStaticLocal()); 13361 // But if this is a static local in a dlimport/dllexport function, the 13362 // function will never be inlined, which means the var would never be 13363 // imported, so having it marked import/export is safe. 13364 } else { 13365 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13366 << DLLAttr; 13367 VD->setInvalidDecl(); 13368 } 13369 } 13370 13371 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13372 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13373 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13374 << Attr; 13375 VD->dropAttr<UsedAttr>(); 13376 } 13377 } 13378 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 13379 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13380 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13381 << Attr; 13382 VD->dropAttr<RetainAttr>(); 13383 } 13384 } 13385 13386 const DeclContext *DC = VD->getDeclContext(); 13387 // If there's a #pragma GCC visibility in scope, and this isn't a class 13388 // member, set the visibility of this variable. 13389 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13390 AddPushedVisibilityAttribute(VD); 13391 13392 // FIXME: Warn on unused var template partial specializations. 13393 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13394 MarkUnusedFileScopedDecl(VD); 13395 13396 // Now we have parsed the initializer and can update the table of magic 13397 // tag values. 13398 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13399 !VD->getType()->isIntegralOrEnumerationType()) 13400 return; 13401 13402 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13403 const Expr *MagicValueExpr = VD->getInit(); 13404 if (!MagicValueExpr) { 13405 continue; 13406 } 13407 Optional<llvm::APSInt> MagicValueInt; 13408 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13409 Diag(I->getRange().getBegin(), 13410 diag::err_type_tag_for_datatype_not_ice) 13411 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13412 continue; 13413 } 13414 if (MagicValueInt->getActiveBits() > 64) { 13415 Diag(I->getRange().getBegin(), 13416 diag::err_type_tag_for_datatype_too_large) 13417 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13418 continue; 13419 } 13420 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13421 RegisterTypeTagForDatatype(I->getArgumentKind(), 13422 MagicValue, 13423 I->getMatchingCType(), 13424 I->getLayoutCompatible(), 13425 I->getMustBeNull()); 13426 } 13427 } 13428 13429 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13430 auto *VD = dyn_cast<VarDecl>(DD); 13431 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13432 } 13433 13434 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13435 ArrayRef<Decl *> Group) { 13436 SmallVector<Decl*, 8> Decls; 13437 13438 if (DS.isTypeSpecOwned()) 13439 Decls.push_back(DS.getRepAsDecl()); 13440 13441 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13442 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13443 bool DiagnosedMultipleDecomps = false; 13444 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13445 bool DiagnosedNonDeducedAuto = false; 13446 13447 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13448 if (Decl *D = Group[i]) { 13449 // For declarators, there are some additional syntactic-ish checks we need 13450 // to perform. 13451 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13452 if (!FirstDeclaratorInGroup) 13453 FirstDeclaratorInGroup = DD; 13454 if (!FirstDecompDeclaratorInGroup) 13455 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13456 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13457 !hasDeducedAuto(DD)) 13458 FirstNonDeducedAutoInGroup = DD; 13459 13460 if (FirstDeclaratorInGroup != DD) { 13461 // A decomposition declaration cannot be combined with any other 13462 // declaration in the same group. 13463 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13464 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13465 diag::err_decomp_decl_not_alone) 13466 << FirstDeclaratorInGroup->getSourceRange() 13467 << DD->getSourceRange(); 13468 DiagnosedMultipleDecomps = true; 13469 } 13470 13471 // A declarator that uses 'auto' in any way other than to declare a 13472 // variable with a deduced type cannot be combined with any other 13473 // declarator in the same group. 13474 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13475 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13476 diag::err_auto_non_deduced_not_alone) 13477 << FirstNonDeducedAutoInGroup->getType() 13478 ->hasAutoForTrailingReturnType() 13479 << FirstDeclaratorInGroup->getSourceRange() 13480 << DD->getSourceRange(); 13481 DiagnosedNonDeducedAuto = true; 13482 } 13483 } 13484 } 13485 13486 Decls.push_back(D); 13487 } 13488 } 13489 13490 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13491 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13492 handleTagNumbering(Tag, S); 13493 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13494 getLangOpts().CPlusPlus) 13495 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13496 } 13497 } 13498 13499 return BuildDeclaratorGroup(Decls); 13500 } 13501 13502 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13503 /// group, performing any necessary semantic checking. 13504 Sema::DeclGroupPtrTy 13505 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13506 // C++14 [dcl.spec.auto]p7: (DR1347) 13507 // If the type that replaces the placeholder type is not the same in each 13508 // deduction, the program is ill-formed. 13509 if (Group.size() > 1) { 13510 QualType Deduced; 13511 VarDecl *DeducedDecl = nullptr; 13512 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13513 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13514 if (!D || D->isInvalidDecl()) 13515 break; 13516 DeducedType *DT = D->getType()->getContainedDeducedType(); 13517 if (!DT || DT->getDeducedType().isNull()) 13518 continue; 13519 if (Deduced.isNull()) { 13520 Deduced = DT->getDeducedType(); 13521 DeducedDecl = D; 13522 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13523 auto *AT = dyn_cast<AutoType>(DT); 13524 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13525 diag::err_auto_different_deductions) 13526 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13527 << DeducedDecl->getDeclName() << DT->getDeducedType() 13528 << D->getDeclName(); 13529 if (DeducedDecl->hasInit()) 13530 Dia << DeducedDecl->getInit()->getSourceRange(); 13531 if (D->getInit()) 13532 Dia << D->getInit()->getSourceRange(); 13533 D->setInvalidDecl(); 13534 break; 13535 } 13536 } 13537 } 13538 13539 ActOnDocumentableDecls(Group); 13540 13541 return DeclGroupPtrTy::make( 13542 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13543 } 13544 13545 void Sema::ActOnDocumentableDecl(Decl *D) { 13546 ActOnDocumentableDecls(D); 13547 } 13548 13549 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13550 // Don't parse the comment if Doxygen diagnostics are ignored. 13551 if (Group.empty() || !Group[0]) 13552 return; 13553 13554 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13555 Group[0]->getLocation()) && 13556 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13557 Group[0]->getLocation())) 13558 return; 13559 13560 if (Group.size() >= 2) { 13561 // This is a decl group. Normally it will contain only declarations 13562 // produced from declarator list. But in case we have any definitions or 13563 // additional declaration references: 13564 // 'typedef struct S {} S;' 13565 // 'typedef struct S *S;' 13566 // 'struct S *pS;' 13567 // FinalizeDeclaratorGroup adds these as separate declarations. 13568 Decl *MaybeTagDecl = Group[0]; 13569 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13570 Group = Group.slice(1); 13571 } 13572 } 13573 13574 // FIMXE: We assume every Decl in the group is in the same file. 13575 // This is false when preprocessor constructs the group from decls in 13576 // different files (e. g. macros or #include). 13577 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13578 } 13579 13580 /// Common checks for a parameter-declaration that should apply to both function 13581 /// parameters and non-type template parameters. 13582 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13583 // Check that there are no default arguments inside the type of this 13584 // parameter. 13585 if (getLangOpts().CPlusPlus) 13586 CheckExtraCXXDefaultArguments(D); 13587 13588 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13589 if (D.getCXXScopeSpec().isSet()) { 13590 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13591 << D.getCXXScopeSpec().getRange(); 13592 } 13593 13594 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13595 // simple identifier except [...irrelevant cases...]. 13596 switch (D.getName().getKind()) { 13597 case UnqualifiedIdKind::IK_Identifier: 13598 break; 13599 13600 case UnqualifiedIdKind::IK_OperatorFunctionId: 13601 case UnqualifiedIdKind::IK_ConversionFunctionId: 13602 case UnqualifiedIdKind::IK_LiteralOperatorId: 13603 case UnqualifiedIdKind::IK_ConstructorName: 13604 case UnqualifiedIdKind::IK_DestructorName: 13605 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13606 case UnqualifiedIdKind::IK_DeductionGuideName: 13607 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13608 << GetNameForDeclarator(D).getName(); 13609 break; 13610 13611 case UnqualifiedIdKind::IK_TemplateId: 13612 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13613 // GetNameForDeclarator would not produce a useful name in this case. 13614 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13615 break; 13616 } 13617 } 13618 13619 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13620 /// to introduce parameters into function prototype scope. 13621 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13622 const DeclSpec &DS = D.getDeclSpec(); 13623 13624 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13625 13626 // C++03 [dcl.stc]p2 also permits 'auto'. 13627 StorageClass SC = SC_None; 13628 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13629 SC = SC_Register; 13630 // In C++11, the 'register' storage class specifier is deprecated. 13631 // In C++17, it is not allowed, but we tolerate it as an extension. 13632 if (getLangOpts().CPlusPlus11) { 13633 Diag(DS.getStorageClassSpecLoc(), 13634 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13635 : diag::warn_deprecated_register) 13636 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13637 } 13638 } else if (getLangOpts().CPlusPlus && 13639 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13640 SC = SC_Auto; 13641 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13642 Diag(DS.getStorageClassSpecLoc(), 13643 diag::err_invalid_storage_class_in_func_decl); 13644 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13645 } 13646 13647 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13648 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13649 << DeclSpec::getSpecifierName(TSCS); 13650 if (DS.isInlineSpecified()) 13651 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13652 << getLangOpts().CPlusPlus17; 13653 if (DS.hasConstexprSpecifier()) 13654 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13655 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 13656 13657 DiagnoseFunctionSpecifiers(DS); 13658 13659 CheckFunctionOrTemplateParamDeclarator(S, D); 13660 13661 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13662 QualType parmDeclType = TInfo->getType(); 13663 13664 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13665 IdentifierInfo *II = D.getIdentifier(); 13666 if (II) { 13667 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13668 ForVisibleRedeclaration); 13669 LookupName(R, S); 13670 if (R.isSingleResult()) { 13671 NamedDecl *PrevDecl = R.getFoundDecl(); 13672 if (PrevDecl->isTemplateParameter()) { 13673 // Maybe we will complain about the shadowed template parameter. 13674 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13675 // Just pretend that we didn't see the previous declaration. 13676 PrevDecl = nullptr; 13677 } else if (S->isDeclScope(PrevDecl)) { 13678 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13679 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13680 13681 // Recover by removing the name 13682 II = nullptr; 13683 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13684 D.setInvalidType(true); 13685 } 13686 } 13687 } 13688 13689 // Temporarily put parameter variables in the translation unit, not 13690 // the enclosing context. This prevents them from accidentally 13691 // looking like class members in C++. 13692 ParmVarDecl *New = 13693 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13694 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13695 13696 if (D.isInvalidType()) 13697 New->setInvalidDecl(); 13698 13699 assert(S->isFunctionPrototypeScope()); 13700 assert(S->getFunctionPrototypeDepth() >= 1); 13701 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13702 S->getNextFunctionPrototypeIndex()); 13703 13704 // Add the parameter declaration into this scope. 13705 S->AddDecl(New); 13706 if (II) 13707 IdResolver.AddDecl(New); 13708 13709 ProcessDeclAttributes(S, New, D); 13710 13711 if (D.getDeclSpec().isModulePrivateSpecified()) 13712 Diag(New->getLocation(), diag::err_module_private_local) 13713 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13714 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13715 13716 if (New->hasAttr<BlocksAttr>()) { 13717 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13718 } 13719 13720 if (getLangOpts().OpenCL) 13721 deduceOpenCLAddressSpace(New); 13722 13723 return New; 13724 } 13725 13726 /// Synthesizes a variable for a parameter arising from a 13727 /// typedef. 13728 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13729 SourceLocation Loc, 13730 QualType T) { 13731 /* FIXME: setting StartLoc == Loc. 13732 Would it be worth to modify callers so as to provide proper source 13733 location for the unnamed parameters, embedding the parameter's type? */ 13734 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13735 T, Context.getTrivialTypeSourceInfo(T, Loc), 13736 SC_None, nullptr); 13737 Param->setImplicit(); 13738 return Param; 13739 } 13740 13741 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13742 // Don't diagnose unused-parameter errors in template instantiations; we 13743 // will already have done so in the template itself. 13744 if (inTemplateInstantiation()) 13745 return; 13746 13747 for (const ParmVarDecl *Parameter : Parameters) { 13748 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13749 !Parameter->hasAttr<UnusedAttr>()) { 13750 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13751 << Parameter->getDeclName(); 13752 } 13753 } 13754 } 13755 13756 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13757 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13758 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13759 return; 13760 13761 // Warn if the return value is pass-by-value and larger than the specified 13762 // threshold. 13763 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13764 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13765 if (Size > LangOpts.NumLargeByValueCopy) 13766 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 13767 } 13768 13769 // Warn if any parameter is pass-by-value and larger than the specified 13770 // threshold. 13771 for (const ParmVarDecl *Parameter : Parameters) { 13772 QualType T = Parameter->getType(); 13773 if (T->isDependentType() || !T.isPODType(Context)) 13774 continue; 13775 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13776 if (Size > LangOpts.NumLargeByValueCopy) 13777 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13778 << Parameter << Size; 13779 } 13780 } 13781 13782 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13783 SourceLocation NameLoc, IdentifierInfo *Name, 13784 QualType T, TypeSourceInfo *TSInfo, 13785 StorageClass SC) { 13786 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13787 if (getLangOpts().ObjCAutoRefCount && 13788 T.getObjCLifetime() == Qualifiers::OCL_None && 13789 T->isObjCLifetimeType()) { 13790 13791 Qualifiers::ObjCLifetime lifetime; 13792 13793 // Special cases for arrays: 13794 // - if it's const, use __unsafe_unretained 13795 // - otherwise, it's an error 13796 if (T->isArrayType()) { 13797 if (!T.isConstQualified()) { 13798 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13799 DelayedDiagnostics.add( 13800 sema::DelayedDiagnostic::makeForbiddenType( 13801 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13802 else 13803 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13804 << TSInfo->getTypeLoc().getSourceRange(); 13805 } 13806 lifetime = Qualifiers::OCL_ExplicitNone; 13807 } else { 13808 lifetime = T->getObjCARCImplicitLifetime(); 13809 } 13810 T = Context.getLifetimeQualifiedType(T, lifetime); 13811 } 13812 13813 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13814 Context.getAdjustedParameterType(T), 13815 TSInfo, SC, nullptr); 13816 13817 // Make a note if we created a new pack in the scope of a lambda, so that 13818 // we know that references to that pack must also be expanded within the 13819 // lambda scope. 13820 if (New->isParameterPack()) 13821 if (auto *LSI = getEnclosingLambda()) 13822 LSI->LocalPacks.push_back(New); 13823 13824 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13825 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13826 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13827 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13828 13829 // Parameters can not be abstract class types. 13830 // For record types, this is done by the AbstractClassUsageDiagnoser once 13831 // the class has been completely parsed. 13832 if (!CurContext->isRecord() && 13833 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13834 AbstractParamType)) 13835 New->setInvalidDecl(); 13836 13837 // Parameter declarators cannot be interface types. All ObjC objects are 13838 // passed by reference. 13839 if (T->isObjCObjectType()) { 13840 SourceLocation TypeEndLoc = 13841 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13842 Diag(NameLoc, 13843 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13844 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13845 T = Context.getObjCObjectPointerType(T); 13846 New->setType(T); 13847 } 13848 13849 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13850 // duration shall not be qualified by an address-space qualifier." 13851 // Since all parameters have automatic store duration, they can not have 13852 // an address space. 13853 if (T.getAddressSpace() != LangAS::Default && 13854 // OpenCL allows function arguments declared to be an array of a type 13855 // to be qualified with an address space. 13856 !(getLangOpts().OpenCL && 13857 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13858 Diag(NameLoc, diag::err_arg_with_address_space); 13859 New->setInvalidDecl(); 13860 } 13861 13862 // PPC MMA non-pointer types are not allowed as function argument types. 13863 if (Context.getTargetInfo().getTriple().isPPC64() && 13864 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 13865 New->setInvalidDecl(); 13866 } 13867 13868 return New; 13869 } 13870 13871 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13872 SourceLocation LocAfterDecls) { 13873 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13874 13875 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13876 // for a K&R function. 13877 if (!FTI.hasPrototype) { 13878 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13879 --i; 13880 if (FTI.Params[i].Param == nullptr) { 13881 SmallString<256> Code; 13882 llvm::raw_svector_ostream(Code) 13883 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13884 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13885 << FTI.Params[i].Ident 13886 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13887 13888 // Implicitly declare the argument as type 'int' for lack of a better 13889 // type. 13890 AttributeFactory attrs; 13891 DeclSpec DS(attrs); 13892 const char* PrevSpec; // unused 13893 unsigned DiagID; // unused 13894 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13895 DiagID, Context.getPrintingPolicy()); 13896 // Use the identifier location for the type source range. 13897 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13898 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13899 Declarator ParamD(DS, DeclaratorContext::KNRTypeList); 13900 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13901 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13902 } 13903 } 13904 } 13905 } 13906 13907 Decl * 13908 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13909 MultiTemplateParamsArg TemplateParameterLists, 13910 SkipBodyInfo *SkipBody) { 13911 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13912 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13913 Scope *ParentScope = FnBodyScope->getParent(); 13914 13915 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 13916 // we define a non-templated function definition, we will create a declaration 13917 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 13918 // The base function declaration will have the equivalent of an `omp declare 13919 // variant` annotation which specifies the mangled definition as a 13920 // specialization function under the OpenMP context defined as part of the 13921 // `omp begin declare variant`. 13922 SmallVector<FunctionDecl *, 4> Bases; 13923 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 13924 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 13925 ParentScope, D, TemplateParameterLists, Bases); 13926 13927 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 13928 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13929 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13930 13931 if (!Bases.empty()) 13932 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 13933 13934 return Dcl; 13935 } 13936 13937 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13938 Consumer.HandleInlineFunctionDefinition(D); 13939 } 13940 13941 static bool 13942 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13943 const FunctionDecl *&PossiblePrototype) { 13944 // Don't warn about invalid declarations. 13945 if (FD->isInvalidDecl()) 13946 return false; 13947 13948 // Or declarations that aren't global. 13949 if (!FD->isGlobal()) 13950 return false; 13951 13952 // Don't warn about C++ member functions. 13953 if (isa<CXXMethodDecl>(FD)) 13954 return false; 13955 13956 // Don't warn about 'main'. 13957 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13958 if (IdentifierInfo *II = FD->getIdentifier()) 13959 if (II->isStr("main") || II->isStr("efi_main")) 13960 return false; 13961 13962 // Don't warn about inline functions. 13963 if (FD->isInlined()) 13964 return false; 13965 13966 // Don't warn about function templates. 13967 if (FD->getDescribedFunctionTemplate()) 13968 return false; 13969 13970 // Don't warn about function template specializations. 13971 if (FD->isFunctionTemplateSpecialization()) 13972 return false; 13973 13974 // Don't warn for OpenCL kernels. 13975 if (FD->hasAttr<OpenCLKernelAttr>()) 13976 return false; 13977 13978 // Don't warn on explicitly deleted functions. 13979 if (FD->isDeleted()) 13980 return false; 13981 13982 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13983 Prev; Prev = Prev->getPreviousDecl()) { 13984 // Ignore any declarations that occur in function or method 13985 // scope, because they aren't visible from the header. 13986 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13987 continue; 13988 13989 PossiblePrototype = Prev; 13990 return Prev->getType()->isFunctionNoProtoType(); 13991 } 13992 13993 return true; 13994 } 13995 13996 void 13997 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13998 const FunctionDecl *EffectiveDefinition, 13999 SkipBodyInfo *SkipBody) { 14000 const FunctionDecl *Definition = EffectiveDefinition; 14001 if (!Definition && 14002 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 14003 return; 14004 14005 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 14006 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 14007 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 14008 // A merged copy of the same function, instantiated as a member of 14009 // the same class, is OK. 14010 if (declaresSameEntity(OrigFD, OrigDef) && 14011 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 14012 cast<Decl>(FD->getLexicalDeclContext()))) 14013 return; 14014 } 14015 } 14016 } 14017 14018 if (canRedefineFunction(Definition, getLangOpts())) 14019 return; 14020 14021 // Don't emit an error when this is redefinition of a typo-corrected 14022 // definition. 14023 if (TypoCorrectedFunctionDefinitions.count(Definition)) 14024 return; 14025 14026 // If we don't have a visible definition of the function, and it's inline or 14027 // a template, skip the new definition. 14028 if (SkipBody && !hasVisibleDefinition(Definition) && 14029 (Definition->getFormalLinkage() == InternalLinkage || 14030 Definition->isInlined() || 14031 Definition->getDescribedFunctionTemplate() || 14032 Definition->getNumTemplateParameterLists())) { 14033 SkipBody->ShouldSkip = true; 14034 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 14035 if (auto *TD = Definition->getDescribedFunctionTemplate()) 14036 makeMergedDefinitionVisible(TD); 14037 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 14038 return; 14039 } 14040 14041 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 14042 Definition->getStorageClass() == SC_Extern) 14043 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 14044 << FD << getLangOpts().CPlusPlus; 14045 else 14046 Diag(FD->getLocation(), diag::err_redefinition) << FD; 14047 14048 Diag(Definition->getLocation(), diag::note_previous_definition); 14049 FD->setInvalidDecl(); 14050 } 14051 14052 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 14053 Sema &S) { 14054 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 14055 14056 LambdaScopeInfo *LSI = S.PushLambdaScope(); 14057 LSI->CallOperator = CallOperator; 14058 LSI->Lambda = LambdaClass; 14059 LSI->ReturnType = CallOperator->getReturnType(); 14060 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 14061 14062 if (LCD == LCD_None) 14063 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 14064 else if (LCD == LCD_ByCopy) 14065 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 14066 else if (LCD == LCD_ByRef) 14067 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 14068 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 14069 14070 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 14071 LSI->Mutable = !CallOperator->isConst(); 14072 14073 // Add the captures to the LSI so they can be noted as already 14074 // captured within tryCaptureVar. 14075 auto I = LambdaClass->field_begin(); 14076 for (const auto &C : LambdaClass->captures()) { 14077 if (C.capturesVariable()) { 14078 VarDecl *VD = C.getCapturedVar(); 14079 if (VD->isInitCapture()) 14080 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 14081 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 14082 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 14083 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 14084 /*EllipsisLoc*/C.isPackExpansion() 14085 ? C.getEllipsisLoc() : SourceLocation(), 14086 I->getType(), /*Invalid*/false); 14087 14088 } else if (C.capturesThis()) { 14089 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 14090 C.getCaptureKind() == LCK_StarThis); 14091 } else { 14092 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14093 I->getType()); 14094 } 14095 ++I; 14096 } 14097 } 14098 14099 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14100 SkipBodyInfo *SkipBody) { 14101 if (!D) { 14102 // Parsing the function declaration failed in some way. Push on a fake scope 14103 // anyway so we can try to parse the function body. 14104 PushFunctionScope(); 14105 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14106 return D; 14107 } 14108 14109 FunctionDecl *FD = nullptr; 14110 14111 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14112 FD = FunTmpl->getTemplatedDecl(); 14113 else 14114 FD = cast<FunctionDecl>(D); 14115 14116 // Do not push if it is a lambda because one is already pushed when building 14117 // the lambda in ActOnStartOfLambdaDefinition(). 14118 if (!isLambdaCallOperator(FD)) 14119 PushExpressionEvaluationContext( 14120 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14121 : ExprEvalContexts.back().Context); 14122 14123 // Check for defining attributes before the check for redefinition. 14124 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14125 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14126 FD->dropAttr<AliasAttr>(); 14127 FD->setInvalidDecl(); 14128 } 14129 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14130 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14131 FD->dropAttr<IFuncAttr>(); 14132 FD->setInvalidDecl(); 14133 } 14134 14135 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14136 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14137 Ctor->isDefaultConstructor() && 14138 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14139 // If this is an MS ABI dllexport default constructor, instantiate any 14140 // default arguments. 14141 InstantiateDefaultCtorDefaultArgs(Ctor); 14142 } 14143 } 14144 14145 // See if this is a redefinition. If 'will have body' (or similar) is already 14146 // set, then these checks were already performed when it was set. 14147 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14148 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14149 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14150 14151 // If we're skipping the body, we're done. Don't enter the scope. 14152 if (SkipBody && SkipBody->ShouldSkip) 14153 return D; 14154 } 14155 14156 // Mark this function as "will have a body eventually". This lets users to 14157 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14158 // this function. 14159 FD->setWillHaveBody(); 14160 14161 // If we are instantiating a generic lambda call operator, push 14162 // a LambdaScopeInfo onto the function stack. But use the information 14163 // that's already been calculated (ActOnLambdaExpr) to prime the current 14164 // LambdaScopeInfo. 14165 // When the template operator is being specialized, the LambdaScopeInfo, 14166 // has to be properly restored so that tryCaptureVariable doesn't try 14167 // and capture any new variables. In addition when calculating potential 14168 // captures during transformation of nested lambdas, it is necessary to 14169 // have the LSI properly restored. 14170 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14171 assert(inTemplateInstantiation() && 14172 "There should be an active template instantiation on the stack " 14173 "when instantiating a generic lambda!"); 14174 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14175 } else { 14176 // Enter a new function scope 14177 PushFunctionScope(); 14178 } 14179 14180 // Builtin functions cannot be defined. 14181 if (unsigned BuiltinID = FD->getBuiltinID()) { 14182 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14183 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14184 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14185 FD->setInvalidDecl(); 14186 } 14187 } 14188 14189 // The return type of a function definition must be complete 14190 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14191 QualType ResultType = FD->getReturnType(); 14192 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14193 !FD->isInvalidDecl() && 14194 RequireCompleteType(FD->getLocation(), ResultType, 14195 diag::err_func_def_incomplete_result)) 14196 FD->setInvalidDecl(); 14197 14198 if (FnBodyScope) 14199 PushDeclContext(FnBodyScope, FD); 14200 14201 // Check the validity of our function parameters 14202 CheckParmsForFunctionDef(FD->parameters(), 14203 /*CheckParameterNames=*/true); 14204 14205 // Add non-parameter declarations already in the function to the current 14206 // scope. 14207 if (FnBodyScope) { 14208 for (Decl *NPD : FD->decls()) { 14209 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14210 if (!NonParmDecl) 14211 continue; 14212 assert(!isa<ParmVarDecl>(NonParmDecl) && 14213 "parameters should not be in newly created FD yet"); 14214 14215 // If the decl has a name, make it accessible in the current scope. 14216 if (NonParmDecl->getDeclName()) 14217 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14218 14219 // Similarly, dive into enums and fish their constants out, making them 14220 // accessible in this scope. 14221 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14222 for (auto *EI : ED->enumerators()) 14223 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14224 } 14225 } 14226 } 14227 14228 // Introduce our parameters into the function scope 14229 for (auto Param : FD->parameters()) { 14230 Param->setOwningFunction(FD); 14231 14232 // If this has an identifier, add it to the scope stack. 14233 if (Param->getIdentifier() && FnBodyScope) { 14234 CheckShadow(FnBodyScope, Param); 14235 14236 PushOnScopeChains(Param, FnBodyScope); 14237 } 14238 } 14239 14240 // Ensure that the function's exception specification is instantiated. 14241 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14242 ResolveExceptionSpec(D->getLocation(), FPT); 14243 14244 // dllimport cannot be applied to non-inline function definitions. 14245 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14246 !FD->isTemplateInstantiation()) { 14247 assert(!FD->hasAttr<DLLExportAttr>()); 14248 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14249 FD->setInvalidDecl(); 14250 return D; 14251 } 14252 // We want to attach documentation to original Decl (which might be 14253 // a function template). 14254 ActOnDocumentableDecl(D); 14255 if (getCurLexicalContext()->isObjCContainer() && 14256 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14257 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14258 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14259 14260 return D; 14261 } 14262 14263 /// Given the set of return statements within a function body, 14264 /// compute the variables that are subject to the named return value 14265 /// optimization. 14266 /// 14267 /// Each of the variables that is subject to the named return value 14268 /// optimization will be marked as NRVO variables in the AST, and any 14269 /// return statement that has a marked NRVO variable as its NRVO candidate can 14270 /// use the named return value optimization. 14271 /// 14272 /// This function applies a very simplistic algorithm for NRVO: if every return 14273 /// statement in the scope of a variable has the same NRVO candidate, that 14274 /// candidate is an NRVO variable. 14275 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14276 ReturnStmt **Returns = Scope->Returns.data(); 14277 14278 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14279 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14280 if (!NRVOCandidate->isNRVOVariable()) 14281 Returns[I]->setNRVOCandidate(nullptr); 14282 } 14283 } 14284 } 14285 14286 bool Sema::canDelayFunctionBody(const Declarator &D) { 14287 // We can't delay parsing the body of a constexpr function template (yet). 14288 if (D.getDeclSpec().hasConstexprSpecifier()) 14289 return false; 14290 14291 // We can't delay parsing the body of a function template with a deduced 14292 // return type (yet). 14293 if (D.getDeclSpec().hasAutoTypeSpec()) { 14294 // If the placeholder introduces a non-deduced trailing return type, 14295 // we can still delay parsing it. 14296 if (D.getNumTypeObjects()) { 14297 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14298 if (Outer.Kind == DeclaratorChunk::Function && 14299 Outer.Fun.hasTrailingReturnType()) { 14300 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14301 return Ty.isNull() || !Ty->isUndeducedType(); 14302 } 14303 } 14304 return false; 14305 } 14306 14307 return true; 14308 } 14309 14310 bool Sema::canSkipFunctionBody(Decl *D) { 14311 // We cannot skip the body of a function (or function template) which is 14312 // constexpr, since we may need to evaluate its body in order to parse the 14313 // rest of the file. 14314 // We cannot skip the body of a function with an undeduced return type, 14315 // because any callers of that function need to know the type. 14316 if (const FunctionDecl *FD = D->getAsFunction()) { 14317 if (FD->isConstexpr()) 14318 return false; 14319 // We can't simply call Type::isUndeducedType here, because inside template 14320 // auto can be deduced to a dependent type, which is not considered 14321 // "undeduced". 14322 if (FD->getReturnType()->getContainedDeducedType()) 14323 return false; 14324 } 14325 return Consumer.shouldSkipFunctionBody(D); 14326 } 14327 14328 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14329 if (!Decl) 14330 return nullptr; 14331 if (FunctionDecl *FD = Decl->getAsFunction()) 14332 FD->setHasSkippedBody(); 14333 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14334 MD->setHasSkippedBody(); 14335 return Decl; 14336 } 14337 14338 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14339 return ActOnFinishFunctionBody(D, BodyArg, false); 14340 } 14341 14342 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14343 /// body. 14344 class ExitFunctionBodyRAII { 14345 public: 14346 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14347 ~ExitFunctionBodyRAII() { 14348 if (!IsLambda) 14349 S.PopExpressionEvaluationContext(); 14350 } 14351 14352 private: 14353 Sema &S; 14354 bool IsLambda = false; 14355 }; 14356 14357 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14358 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14359 14360 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14361 if (EscapeInfo.count(BD)) 14362 return EscapeInfo[BD]; 14363 14364 bool R = false; 14365 const BlockDecl *CurBD = BD; 14366 14367 do { 14368 R = !CurBD->doesNotEscape(); 14369 if (R) 14370 break; 14371 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14372 } while (CurBD); 14373 14374 return EscapeInfo[BD] = R; 14375 }; 14376 14377 // If the location where 'self' is implicitly retained is inside a escaping 14378 // block, emit a diagnostic. 14379 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14380 S.ImplicitlyRetainedSelfLocs) 14381 if (IsOrNestedInEscapingBlock(P.second)) 14382 S.Diag(P.first, diag::warn_implicitly_retains_self) 14383 << FixItHint::CreateInsertion(P.first, "self->"); 14384 } 14385 14386 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14387 bool IsInstantiation) { 14388 FunctionScopeInfo *FSI = getCurFunction(); 14389 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14390 14391 if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>()) 14392 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14393 14394 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14395 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14396 14397 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14398 CheckCompletedCoroutineBody(FD, Body); 14399 14400 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14401 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14402 // meant to pop the context added in ActOnStartOfFunctionDef(). 14403 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14404 14405 if (FD) { 14406 FD->setBody(Body); 14407 FD->setWillHaveBody(false); 14408 14409 if (getLangOpts().CPlusPlus14) { 14410 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14411 FD->getReturnType()->isUndeducedType()) { 14412 // If the function has a deduced result type but contains no 'return' 14413 // statements, the result type as written must be exactly 'auto', and 14414 // the deduced result type is 'void'. 14415 if (!FD->getReturnType()->getAs<AutoType>()) { 14416 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14417 << FD->getReturnType(); 14418 FD->setInvalidDecl(); 14419 } else { 14420 // Substitute 'void' for the 'auto' in the type. 14421 TypeLoc ResultType = getReturnTypeLoc(FD); 14422 Context.adjustDeducedFunctionResultType( 14423 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14424 } 14425 } 14426 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14427 // In C++11, we don't use 'auto' deduction rules for lambda call 14428 // operators because we don't support return type deduction. 14429 auto *LSI = getCurLambda(); 14430 if (LSI->HasImplicitReturnType) { 14431 deduceClosureReturnType(*LSI); 14432 14433 // C++11 [expr.prim.lambda]p4: 14434 // [...] if there are no return statements in the compound-statement 14435 // [the deduced type is] the type void 14436 QualType RetType = 14437 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14438 14439 // Update the return type to the deduced type. 14440 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14441 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14442 Proto->getExtProtoInfo())); 14443 } 14444 } 14445 14446 // If the function implicitly returns zero (like 'main') or is naked, 14447 // don't complain about missing return statements. 14448 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14449 WP.disableCheckFallThrough(); 14450 14451 // MSVC permits the use of pure specifier (=0) on function definition, 14452 // defined at class scope, warn about this non-standard construct. 14453 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14454 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14455 14456 if (!FD->isInvalidDecl()) { 14457 // Don't diagnose unused parameters of defaulted or deleted functions. 14458 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14459 DiagnoseUnusedParameters(FD->parameters()); 14460 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14461 FD->getReturnType(), FD); 14462 14463 // If this is a structor, we need a vtable. 14464 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14465 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14466 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14467 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14468 14469 // Try to apply the named return value optimization. We have to check 14470 // if we can do this here because lambdas keep return statements around 14471 // to deduce an implicit return type. 14472 if (FD->getReturnType()->isRecordType() && 14473 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14474 computeNRVO(Body, FSI); 14475 } 14476 14477 // GNU warning -Wmissing-prototypes: 14478 // Warn if a global function is defined without a previous 14479 // prototype declaration. This warning is issued even if the 14480 // definition itself provides a prototype. The aim is to detect 14481 // global functions that fail to be declared in header files. 14482 const FunctionDecl *PossiblePrototype = nullptr; 14483 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14484 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14485 14486 if (PossiblePrototype) { 14487 // We found a declaration that is not a prototype, 14488 // but that could be a zero-parameter prototype 14489 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14490 TypeLoc TL = TI->getTypeLoc(); 14491 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14492 Diag(PossiblePrototype->getLocation(), 14493 diag::note_declaration_not_a_prototype) 14494 << (FD->getNumParams() != 0) 14495 << (FD->getNumParams() == 0 14496 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14497 : FixItHint{}); 14498 } 14499 } else { 14500 // Returns true if the token beginning at this Loc is `const`. 14501 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14502 const LangOptions &LangOpts) { 14503 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14504 if (LocInfo.first.isInvalid()) 14505 return false; 14506 14507 bool Invalid = false; 14508 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14509 if (Invalid) 14510 return false; 14511 14512 if (LocInfo.second > Buffer.size()) 14513 return false; 14514 14515 const char *LexStart = Buffer.data() + LocInfo.second; 14516 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14517 14518 return StartTok.consume_front("const") && 14519 (StartTok.empty() || isWhitespace(StartTok[0]) || 14520 StartTok.startswith("/*") || StartTok.startswith("//")); 14521 }; 14522 14523 auto findBeginLoc = [&]() { 14524 // If the return type has `const` qualifier, we want to insert 14525 // `static` before `const` (and not before the typename). 14526 if ((FD->getReturnType()->isAnyPointerType() && 14527 FD->getReturnType()->getPointeeType().isConstQualified()) || 14528 FD->getReturnType().isConstQualified()) { 14529 // But only do this if we can determine where the `const` is. 14530 14531 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14532 getLangOpts())) 14533 14534 return FD->getBeginLoc(); 14535 } 14536 return FD->getTypeSpecStartLoc(); 14537 }; 14538 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14539 << /* function */ 1 14540 << (FD->getStorageClass() == SC_None 14541 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14542 : FixItHint{}); 14543 } 14544 14545 // GNU warning -Wstrict-prototypes 14546 // Warn if K&R function is defined without a previous declaration. 14547 // This warning is issued only if the definition itself does not provide 14548 // a prototype. Only K&R definitions do not provide a prototype. 14549 if (!FD->hasWrittenPrototype()) { 14550 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14551 TypeLoc TL = TI->getTypeLoc(); 14552 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14553 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14554 } 14555 } 14556 14557 // Warn on CPUDispatch with an actual body. 14558 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14559 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14560 if (!CmpndBody->body_empty()) 14561 Diag(CmpndBody->body_front()->getBeginLoc(), 14562 diag::warn_dispatch_body_ignored); 14563 14564 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14565 const CXXMethodDecl *KeyFunction; 14566 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14567 MD->isVirtual() && 14568 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14569 MD == KeyFunction->getCanonicalDecl()) { 14570 // Update the key-function state if necessary for this ABI. 14571 if (FD->isInlined() && 14572 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14573 Context.setNonKeyFunction(MD); 14574 14575 // If the newly-chosen key function is already defined, then we 14576 // need to mark the vtable as used retroactively. 14577 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14578 const FunctionDecl *Definition; 14579 if (KeyFunction && KeyFunction->isDefined(Definition)) 14580 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14581 } else { 14582 // We just defined they key function; mark the vtable as used. 14583 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14584 } 14585 } 14586 } 14587 14588 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14589 "Function parsing confused"); 14590 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14591 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14592 MD->setBody(Body); 14593 if (!MD->isInvalidDecl()) { 14594 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14595 MD->getReturnType(), MD); 14596 14597 if (Body) 14598 computeNRVO(Body, FSI); 14599 } 14600 if (FSI->ObjCShouldCallSuper) { 14601 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14602 << MD->getSelector().getAsString(); 14603 FSI->ObjCShouldCallSuper = false; 14604 } 14605 if (FSI->ObjCWarnForNoDesignatedInitChain) { 14606 const ObjCMethodDecl *InitMethod = nullptr; 14607 bool isDesignated = 14608 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14609 assert(isDesignated && InitMethod); 14610 (void)isDesignated; 14611 14612 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14613 auto IFace = MD->getClassInterface(); 14614 if (!IFace) 14615 return false; 14616 auto SuperD = IFace->getSuperClass(); 14617 if (!SuperD) 14618 return false; 14619 return SuperD->getIdentifier() == 14620 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14621 }; 14622 // Don't issue this warning for unavailable inits or direct subclasses 14623 // of NSObject. 14624 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14625 Diag(MD->getLocation(), 14626 diag::warn_objc_designated_init_missing_super_call); 14627 Diag(InitMethod->getLocation(), 14628 diag::note_objc_designated_init_marked_here); 14629 } 14630 FSI->ObjCWarnForNoDesignatedInitChain = false; 14631 } 14632 if (FSI->ObjCWarnForNoInitDelegation) { 14633 // Don't issue this warning for unavaialable inits. 14634 if (!MD->isUnavailable()) 14635 Diag(MD->getLocation(), 14636 diag::warn_objc_secondary_init_missing_init_call); 14637 FSI->ObjCWarnForNoInitDelegation = false; 14638 } 14639 14640 diagnoseImplicitlyRetainedSelf(*this); 14641 } else { 14642 // Parsing the function declaration failed in some way. Pop the fake scope 14643 // we pushed on. 14644 PopFunctionScopeInfo(ActivePolicy, dcl); 14645 return nullptr; 14646 } 14647 14648 if (Body && FSI->HasPotentialAvailabilityViolations) 14649 DiagnoseUnguardedAvailabilityViolations(dcl); 14650 14651 assert(!FSI->ObjCShouldCallSuper && 14652 "This should only be set for ObjC methods, which should have been " 14653 "handled in the block above."); 14654 14655 // Verify and clean out per-function state. 14656 if (Body && (!FD || !FD->isDefaulted())) { 14657 // C++ constructors that have function-try-blocks can't have return 14658 // statements in the handlers of that block. (C++ [except.handle]p14) 14659 // Verify this. 14660 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14661 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14662 14663 // Verify that gotos and switch cases don't jump into scopes illegally. 14664 if (FSI->NeedsScopeChecking() && 14665 !PP.isCodeCompletionEnabled()) 14666 DiagnoseInvalidJumps(Body); 14667 14668 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14669 if (!Destructor->getParent()->isDependentType()) 14670 CheckDestructor(Destructor); 14671 14672 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14673 Destructor->getParent()); 14674 } 14675 14676 // If any errors have occurred, clear out any temporaries that may have 14677 // been leftover. This ensures that these temporaries won't be picked up for 14678 // deletion in some later function. 14679 if (hasUncompilableErrorOccurred() || 14680 getDiagnostics().getSuppressAllDiagnostics()) { 14681 DiscardCleanupsInEvaluationContext(); 14682 } 14683 if (!hasUncompilableErrorOccurred() && 14684 !isa<FunctionTemplateDecl>(dcl)) { 14685 // Since the body is valid, issue any analysis-based warnings that are 14686 // enabled. 14687 ActivePolicy = &WP; 14688 } 14689 14690 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14691 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14692 FD->setInvalidDecl(); 14693 14694 if (FD && FD->hasAttr<NakedAttr>()) { 14695 for (const Stmt *S : Body->children()) { 14696 // Allow local register variables without initializer as they don't 14697 // require prologue. 14698 bool RegisterVariables = false; 14699 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14700 for (const auto *Decl : DS->decls()) { 14701 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14702 RegisterVariables = 14703 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14704 if (!RegisterVariables) 14705 break; 14706 } 14707 } 14708 } 14709 if (RegisterVariables) 14710 continue; 14711 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14712 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14713 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14714 FD->setInvalidDecl(); 14715 break; 14716 } 14717 } 14718 } 14719 14720 assert(ExprCleanupObjects.size() == 14721 ExprEvalContexts.back().NumCleanupObjects && 14722 "Leftover temporaries in function"); 14723 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14724 assert(MaybeODRUseExprs.empty() && 14725 "Leftover expressions for odr-use checking"); 14726 } 14727 14728 if (!IsInstantiation) 14729 PopDeclContext(); 14730 14731 PopFunctionScopeInfo(ActivePolicy, dcl); 14732 // If any errors have occurred, clear out any temporaries that may have 14733 // been leftover. This ensures that these temporaries won't be picked up for 14734 // deletion in some later function. 14735 if (hasUncompilableErrorOccurred()) { 14736 DiscardCleanupsInEvaluationContext(); 14737 } 14738 14739 if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 14740 auto ES = getEmissionStatus(FD); 14741 if (ES == Sema::FunctionEmissionStatus::Emitted || 14742 ES == Sema::FunctionEmissionStatus::Unknown) 14743 DeclsToCheckForDeferredDiags.push_back(FD); 14744 } 14745 14746 return dcl; 14747 } 14748 14749 /// When we finish delayed parsing of an attribute, we must attach it to the 14750 /// relevant Decl. 14751 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14752 ParsedAttributes &Attrs) { 14753 // Always attach attributes to the underlying decl. 14754 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14755 D = TD->getTemplatedDecl(); 14756 ProcessDeclAttributeList(S, D, Attrs); 14757 14758 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14759 if (Method->isStatic()) 14760 checkThisInStaticMemberFunctionAttributes(Method); 14761 } 14762 14763 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14764 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14765 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14766 IdentifierInfo &II, Scope *S) { 14767 // Find the scope in which the identifier is injected and the corresponding 14768 // DeclContext. 14769 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14770 // In that case, we inject the declaration into the translation unit scope 14771 // instead. 14772 Scope *BlockScope = S; 14773 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14774 BlockScope = BlockScope->getParent(); 14775 14776 Scope *ContextScope = BlockScope; 14777 while (!ContextScope->getEntity()) 14778 ContextScope = ContextScope->getParent(); 14779 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14780 14781 // Before we produce a declaration for an implicitly defined 14782 // function, see whether there was a locally-scoped declaration of 14783 // this name as a function or variable. If so, use that 14784 // (non-visible) declaration, and complain about it. 14785 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14786 if (ExternCPrev) { 14787 // We still need to inject the function into the enclosing block scope so 14788 // that later (non-call) uses can see it. 14789 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14790 14791 // C89 footnote 38: 14792 // If in fact it is not defined as having type "function returning int", 14793 // the behavior is undefined. 14794 if (!isa<FunctionDecl>(ExternCPrev) || 14795 !Context.typesAreCompatible( 14796 cast<FunctionDecl>(ExternCPrev)->getType(), 14797 Context.getFunctionNoProtoType(Context.IntTy))) { 14798 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14799 << ExternCPrev << !getLangOpts().C99; 14800 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14801 return ExternCPrev; 14802 } 14803 } 14804 14805 // Extension in C99. Legal in C90, but warn about it. 14806 unsigned diag_id; 14807 if (II.getName().startswith("__builtin_")) 14808 diag_id = diag::warn_builtin_unknown; 14809 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14810 else if (getLangOpts().OpenCL) 14811 diag_id = diag::err_opencl_implicit_function_decl; 14812 else if (getLangOpts().C99) 14813 diag_id = diag::ext_implicit_function_decl; 14814 else 14815 diag_id = diag::warn_implicit_function_decl; 14816 Diag(Loc, diag_id) << &II; 14817 14818 // If we found a prior declaration of this function, don't bother building 14819 // another one. We've already pushed that one into scope, so there's nothing 14820 // more to do. 14821 if (ExternCPrev) 14822 return ExternCPrev; 14823 14824 // Because typo correction is expensive, only do it if the implicit 14825 // function declaration is going to be treated as an error. 14826 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14827 TypoCorrection Corrected; 14828 DeclFilterCCC<FunctionDecl> CCC{}; 14829 if (S && (Corrected = 14830 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14831 S, nullptr, CCC, CTK_NonError))) 14832 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14833 /*ErrorRecovery*/false); 14834 } 14835 14836 // Set a Declarator for the implicit definition: int foo(); 14837 const char *Dummy; 14838 AttributeFactory attrFactory; 14839 DeclSpec DS(attrFactory); 14840 unsigned DiagID; 14841 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14842 Context.getPrintingPolicy()); 14843 (void)Error; // Silence warning. 14844 assert(!Error && "Error setting up implicit decl!"); 14845 SourceLocation NoLoc; 14846 Declarator D(DS, DeclaratorContext::Block); 14847 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14848 /*IsAmbiguous=*/false, 14849 /*LParenLoc=*/NoLoc, 14850 /*Params=*/nullptr, 14851 /*NumParams=*/0, 14852 /*EllipsisLoc=*/NoLoc, 14853 /*RParenLoc=*/NoLoc, 14854 /*RefQualifierIsLvalueRef=*/true, 14855 /*RefQualifierLoc=*/NoLoc, 14856 /*MutableLoc=*/NoLoc, EST_None, 14857 /*ESpecRange=*/SourceRange(), 14858 /*Exceptions=*/nullptr, 14859 /*ExceptionRanges=*/nullptr, 14860 /*NumExceptions=*/0, 14861 /*NoexceptExpr=*/nullptr, 14862 /*ExceptionSpecTokens=*/nullptr, 14863 /*DeclsInPrototype=*/None, Loc, 14864 Loc, D), 14865 std::move(DS.getAttributes()), SourceLocation()); 14866 D.SetIdentifier(&II, Loc); 14867 14868 // Insert this function into the enclosing block scope. 14869 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14870 FD->setImplicit(); 14871 14872 AddKnownFunctionAttributes(FD); 14873 14874 return FD; 14875 } 14876 14877 /// If this function is a C++ replaceable global allocation function 14878 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14879 /// adds any function attributes that we know a priori based on the standard. 14880 /// 14881 /// We need to check for duplicate attributes both here and where user-written 14882 /// attributes are applied to declarations. 14883 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14884 FunctionDecl *FD) { 14885 if (FD->isInvalidDecl()) 14886 return; 14887 14888 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14889 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14890 return; 14891 14892 Optional<unsigned> AlignmentParam; 14893 bool IsNothrow = false; 14894 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14895 return; 14896 14897 // C++2a [basic.stc.dynamic.allocation]p4: 14898 // An allocation function that has a non-throwing exception specification 14899 // indicates failure by returning a null pointer value. Any other allocation 14900 // function never returns a null pointer value and indicates failure only by 14901 // throwing an exception [...] 14902 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14903 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14904 14905 // C++2a [basic.stc.dynamic.allocation]p2: 14906 // An allocation function attempts to allocate the requested amount of 14907 // storage. [...] If the request succeeds, the value returned by a 14908 // replaceable allocation function is a [...] pointer value p0 different 14909 // from any previously returned value p1 [...] 14910 // 14911 // However, this particular information is being added in codegen, 14912 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14913 14914 // C++2a [basic.stc.dynamic.allocation]p2: 14915 // An allocation function attempts to allocate the requested amount of 14916 // storage. If it is successful, it returns the address of the start of a 14917 // block of storage whose length in bytes is at least as large as the 14918 // requested size. 14919 if (!FD->hasAttr<AllocSizeAttr>()) { 14920 FD->addAttr(AllocSizeAttr::CreateImplicit( 14921 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14922 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14923 } 14924 14925 // C++2a [basic.stc.dynamic.allocation]p3: 14926 // For an allocation function [...], the pointer returned on a successful 14927 // call shall represent the address of storage that is aligned as follows: 14928 // (3.1) If the allocation function takes an argument of type 14929 // std::align_val_t, the storage will have the alignment 14930 // specified by the value of this argument. 14931 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14932 FD->addAttr(AllocAlignAttr::CreateImplicit( 14933 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14934 } 14935 14936 // FIXME: 14937 // C++2a [basic.stc.dynamic.allocation]p3: 14938 // For an allocation function [...], the pointer returned on a successful 14939 // call shall represent the address of storage that is aligned as follows: 14940 // (3.2) Otherwise, if the allocation function is named operator new[], 14941 // the storage is aligned for any object that does not have 14942 // new-extended alignment ([basic.align]) and is no larger than the 14943 // requested size. 14944 // (3.3) Otherwise, the storage is aligned for any object that does not 14945 // have new-extended alignment and is of the requested size. 14946 } 14947 14948 /// Adds any function attributes that we know a priori based on 14949 /// the declaration of this function. 14950 /// 14951 /// These attributes can apply both to implicitly-declared builtins 14952 /// (like __builtin___printf_chk) or to library-declared functions 14953 /// like NSLog or printf. 14954 /// 14955 /// We need to check for duplicate attributes both here and where user-written 14956 /// attributes are applied to declarations. 14957 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14958 if (FD->isInvalidDecl()) 14959 return; 14960 14961 // If this is a built-in function, map its builtin attributes to 14962 // actual attributes. 14963 if (unsigned BuiltinID = FD->getBuiltinID()) { 14964 // Handle printf-formatting attributes. 14965 unsigned FormatIdx; 14966 bool HasVAListArg; 14967 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14968 if (!FD->hasAttr<FormatAttr>()) { 14969 const char *fmt = "printf"; 14970 unsigned int NumParams = FD->getNumParams(); 14971 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14972 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14973 fmt = "NSString"; 14974 FD->addAttr(FormatAttr::CreateImplicit(Context, 14975 &Context.Idents.get(fmt), 14976 FormatIdx+1, 14977 HasVAListArg ? 0 : FormatIdx+2, 14978 FD->getLocation())); 14979 } 14980 } 14981 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14982 HasVAListArg)) { 14983 if (!FD->hasAttr<FormatAttr>()) 14984 FD->addAttr(FormatAttr::CreateImplicit(Context, 14985 &Context.Idents.get("scanf"), 14986 FormatIdx+1, 14987 HasVAListArg ? 0 : FormatIdx+2, 14988 FD->getLocation())); 14989 } 14990 14991 // Handle automatically recognized callbacks. 14992 SmallVector<int, 4> Encoding; 14993 if (!FD->hasAttr<CallbackAttr>() && 14994 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14995 FD->addAttr(CallbackAttr::CreateImplicit( 14996 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14997 14998 // Mark const if we don't care about errno and that is the only thing 14999 // preventing the function from being const. This allows IRgen to use LLVM 15000 // intrinsics for such functions. 15001 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 15002 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 15003 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15004 15005 // We make "fma" on some platforms const because we know it does not set 15006 // errno in those environments even though it could set errno based on the 15007 // C standard. 15008 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 15009 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 15010 !FD->hasAttr<ConstAttr>()) { 15011 switch (BuiltinID) { 15012 case Builtin::BI__builtin_fma: 15013 case Builtin::BI__builtin_fmaf: 15014 case Builtin::BI__builtin_fmal: 15015 case Builtin::BIfma: 15016 case Builtin::BIfmaf: 15017 case Builtin::BIfmal: 15018 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15019 break; 15020 default: 15021 break; 15022 } 15023 } 15024 15025 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 15026 !FD->hasAttr<ReturnsTwiceAttr>()) 15027 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 15028 FD->getLocation())); 15029 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 15030 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15031 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 15032 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 15033 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 15034 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15035 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 15036 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 15037 // Add the appropriate attribute, depending on the CUDA compilation mode 15038 // and which target the builtin belongs to. For example, during host 15039 // compilation, aux builtins are __device__, while the rest are __host__. 15040 if (getLangOpts().CUDAIsDevice != 15041 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 15042 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 15043 else 15044 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 15045 } 15046 } 15047 15048 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 15049 15050 // If C++ exceptions are enabled but we are told extern "C" functions cannot 15051 // throw, add an implicit nothrow attribute to any extern "C" function we come 15052 // across. 15053 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 15054 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 15055 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 15056 if (!FPT || FPT->getExceptionSpecType() == EST_None) 15057 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15058 } 15059 15060 IdentifierInfo *Name = FD->getIdentifier(); 15061 if (!Name) 15062 return; 15063 if ((!getLangOpts().CPlusPlus && 15064 FD->getDeclContext()->isTranslationUnit()) || 15065 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 15066 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 15067 LinkageSpecDecl::lang_c)) { 15068 // Okay: this could be a libc/libm/Objective-C function we know 15069 // about. 15070 } else 15071 return; 15072 15073 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 15074 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 15075 // target-specific builtins, perhaps? 15076 if (!FD->hasAttr<FormatAttr>()) 15077 FD->addAttr(FormatAttr::CreateImplicit(Context, 15078 &Context.Idents.get("printf"), 2, 15079 Name->isStr("vasprintf") ? 0 : 3, 15080 FD->getLocation())); 15081 } 15082 15083 if (Name->isStr("__CFStringMakeConstantString")) { 15084 // We already have a __builtin___CFStringMakeConstantString, 15085 // but builds that use -fno-constant-cfstrings don't go through that. 15086 if (!FD->hasAttr<FormatArgAttr>()) 15087 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 15088 FD->getLocation())); 15089 } 15090 } 15091 15092 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15093 TypeSourceInfo *TInfo) { 15094 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 15095 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15096 15097 if (!TInfo) { 15098 assert(D.isInvalidType() && "no declarator info for valid type"); 15099 TInfo = Context.getTrivialTypeSourceInfo(T); 15100 } 15101 15102 // Scope manipulation handled by caller. 15103 TypedefDecl *NewTD = 15104 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15105 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15106 15107 // Bail out immediately if we have an invalid declaration. 15108 if (D.isInvalidType()) { 15109 NewTD->setInvalidDecl(); 15110 return NewTD; 15111 } 15112 15113 if (D.getDeclSpec().isModulePrivateSpecified()) { 15114 if (CurContext->isFunctionOrMethod()) 15115 Diag(NewTD->getLocation(), diag::err_module_private_local) 15116 << 2 << NewTD 15117 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15118 << FixItHint::CreateRemoval( 15119 D.getDeclSpec().getModulePrivateSpecLoc()); 15120 else 15121 NewTD->setModulePrivate(); 15122 } 15123 15124 // C++ [dcl.typedef]p8: 15125 // If the typedef declaration defines an unnamed class (or 15126 // enum), the first typedef-name declared by the declaration 15127 // to be that class type (or enum type) is used to denote the 15128 // class type (or enum type) for linkage purposes only. 15129 // We need to check whether the type was declared in the declaration. 15130 switch (D.getDeclSpec().getTypeSpecType()) { 15131 case TST_enum: 15132 case TST_struct: 15133 case TST_interface: 15134 case TST_union: 15135 case TST_class: { 15136 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15137 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15138 break; 15139 } 15140 15141 default: 15142 break; 15143 } 15144 15145 return NewTD; 15146 } 15147 15148 /// Check that this is a valid underlying type for an enum declaration. 15149 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15150 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15151 QualType T = TI->getType(); 15152 15153 if (T->isDependentType()) 15154 return false; 15155 15156 // This doesn't use 'isIntegralType' despite the error message mentioning 15157 // integral type because isIntegralType would also allow enum types in C. 15158 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15159 if (BT->isInteger()) 15160 return false; 15161 15162 if (T->isExtIntType()) 15163 return false; 15164 15165 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15166 } 15167 15168 /// Check whether this is a valid redeclaration of a previous enumeration. 15169 /// \return true if the redeclaration was invalid. 15170 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15171 QualType EnumUnderlyingTy, bool IsFixed, 15172 const EnumDecl *Prev) { 15173 if (IsScoped != Prev->isScoped()) { 15174 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15175 << Prev->isScoped(); 15176 Diag(Prev->getLocation(), diag::note_previous_declaration); 15177 return true; 15178 } 15179 15180 if (IsFixed && Prev->isFixed()) { 15181 if (!EnumUnderlyingTy->isDependentType() && 15182 !Prev->getIntegerType()->isDependentType() && 15183 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15184 Prev->getIntegerType())) { 15185 // TODO: Highlight the underlying type of the redeclaration. 15186 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15187 << EnumUnderlyingTy << Prev->getIntegerType(); 15188 Diag(Prev->getLocation(), diag::note_previous_declaration) 15189 << Prev->getIntegerTypeRange(); 15190 return true; 15191 } 15192 } else if (IsFixed != Prev->isFixed()) { 15193 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15194 << Prev->isFixed(); 15195 Diag(Prev->getLocation(), diag::note_previous_declaration); 15196 return true; 15197 } 15198 15199 return false; 15200 } 15201 15202 /// Get diagnostic %select index for tag kind for 15203 /// redeclaration diagnostic message. 15204 /// WARNING: Indexes apply to particular diagnostics only! 15205 /// 15206 /// \returns diagnostic %select index. 15207 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15208 switch (Tag) { 15209 case TTK_Struct: return 0; 15210 case TTK_Interface: return 1; 15211 case TTK_Class: return 2; 15212 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15213 } 15214 } 15215 15216 /// Determine if tag kind is a class-key compatible with 15217 /// class for redeclaration (class, struct, or __interface). 15218 /// 15219 /// \returns true iff the tag kind is compatible. 15220 static bool isClassCompatTagKind(TagTypeKind Tag) 15221 { 15222 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15223 } 15224 15225 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15226 TagTypeKind TTK) { 15227 if (isa<TypedefDecl>(PrevDecl)) 15228 return NTK_Typedef; 15229 else if (isa<TypeAliasDecl>(PrevDecl)) 15230 return NTK_TypeAlias; 15231 else if (isa<ClassTemplateDecl>(PrevDecl)) 15232 return NTK_Template; 15233 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15234 return NTK_TypeAliasTemplate; 15235 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15236 return NTK_TemplateTemplateArgument; 15237 switch (TTK) { 15238 case TTK_Struct: 15239 case TTK_Interface: 15240 case TTK_Class: 15241 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15242 case TTK_Union: 15243 return NTK_NonUnion; 15244 case TTK_Enum: 15245 return NTK_NonEnum; 15246 } 15247 llvm_unreachable("invalid TTK"); 15248 } 15249 15250 /// Determine whether a tag with a given kind is acceptable 15251 /// as a redeclaration of the given tag declaration. 15252 /// 15253 /// \returns true if the new tag kind is acceptable, false otherwise. 15254 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15255 TagTypeKind NewTag, bool isDefinition, 15256 SourceLocation NewTagLoc, 15257 const IdentifierInfo *Name) { 15258 // C++ [dcl.type.elab]p3: 15259 // The class-key or enum keyword present in the 15260 // elaborated-type-specifier shall agree in kind with the 15261 // declaration to which the name in the elaborated-type-specifier 15262 // refers. This rule also applies to the form of 15263 // elaborated-type-specifier that declares a class-name or 15264 // friend class since it can be construed as referring to the 15265 // definition of the class. Thus, in any 15266 // elaborated-type-specifier, the enum keyword shall be used to 15267 // refer to an enumeration (7.2), the union class-key shall be 15268 // used to refer to a union (clause 9), and either the class or 15269 // struct class-key shall be used to refer to a class (clause 9) 15270 // declared using the class or struct class-key. 15271 TagTypeKind OldTag = Previous->getTagKind(); 15272 if (OldTag != NewTag && 15273 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15274 return false; 15275 15276 // Tags are compatible, but we might still want to warn on mismatched tags. 15277 // Non-class tags can't be mismatched at this point. 15278 if (!isClassCompatTagKind(NewTag)) 15279 return true; 15280 15281 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15282 // by our warning analysis. We don't want to warn about mismatches with (eg) 15283 // declarations in system headers that are designed to be specialized, but if 15284 // a user asks us to warn, we should warn if their code contains mismatched 15285 // declarations. 15286 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15287 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15288 Loc); 15289 }; 15290 if (IsIgnoredLoc(NewTagLoc)) 15291 return true; 15292 15293 auto IsIgnored = [&](const TagDecl *Tag) { 15294 return IsIgnoredLoc(Tag->getLocation()); 15295 }; 15296 while (IsIgnored(Previous)) { 15297 Previous = Previous->getPreviousDecl(); 15298 if (!Previous) 15299 return true; 15300 OldTag = Previous->getTagKind(); 15301 } 15302 15303 bool isTemplate = false; 15304 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15305 isTemplate = Record->getDescribedClassTemplate(); 15306 15307 if (inTemplateInstantiation()) { 15308 if (OldTag != NewTag) { 15309 // In a template instantiation, do not offer fix-its for tag mismatches 15310 // since they usually mess up the template instead of fixing the problem. 15311 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15312 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15313 << getRedeclDiagFromTagKind(OldTag); 15314 // FIXME: Note previous location? 15315 } 15316 return true; 15317 } 15318 15319 if (isDefinition) { 15320 // On definitions, check all previous tags and issue a fix-it for each 15321 // one that doesn't match the current tag. 15322 if (Previous->getDefinition()) { 15323 // Don't suggest fix-its for redefinitions. 15324 return true; 15325 } 15326 15327 bool previousMismatch = false; 15328 for (const TagDecl *I : Previous->redecls()) { 15329 if (I->getTagKind() != NewTag) { 15330 // Ignore previous declarations for which the warning was disabled. 15331 if (IsIgnored(I)) 15332 continue; 15333 15334 if (!previousMismatch) { 15335 previousMismatch = true; 15336 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15337 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15338 << getRedeclDiagFromTagKind(I->getTagKind()); 15339 } 15340 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15341 << getRedeclDiagFromTagKind(NewTag) 15342 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15343 TypeWithKeyword::getTagTypeKindName(NewTag)); 15344 } 15345 } 15346 return true; 15347 } 15348 15349 // Identify the prevailing tag kind: this is the kind of the definition (if 15350 // there is a non-ignored definition), or otherwise the kind of the prior 15351 // (non-ignored) declaration. 15352 const TagDecl *PrevDef = Previous->getDefinition(); 15353 if (PrevDef && IsIgnored(PrevDef)) 15354 PrevDef = nullptr; 15355 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15356 if (Redecl->getTagKind() != NewTag) { 15357 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15358 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15359 << getRedeclDiagFromTagKind(OldTag); 15360 Diag(Redecl->getLocation(), diag::note_previous_use); 15361 15362 // If there is a previous definition, suggest a fix-it. 15363 if (PrevDef) { 15364 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15365 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15366 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15367 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15368 } 15369 } 15370 15371 return true; 15372 } 15373 15374 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15375 /// from an outer enclosing namespace or file scope inside a friend declaration. 15376 /// This should provide the commented out code in the following snippet: 15377 /// namespace N { 15378 /// struct X; 15379 /// namespace M { 15380 /// struct Y { friend struct /*N::*/ X; }; 15381 /// } 15382 /// } 15383 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15384 SourceLocation NameLoc) { 15385 // While the decl is in a namespace, do repeated lookup of that name and see 15386 // if we get the same namespace back. If we do not, continue until 15387 // translation unit scope, at which point we have a fully qualified NNS. 15388 SmallVector<IdentifierInfo *, 4> Namespaces; 15389 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15390 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15391 // This tag should be declared in a namespace, which can only be enclosed by 15392 // other namespaces. Bail if there's an anonymous namespace in the chain. 15393 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15394 if (!Namespace || Namespace->isAnonymousNamespace()) 15395 return FixItHint(); 15396 IdentifierInfo *II = Namespace->getIdentifier(); 15397 Namespaces.push_back(II); 15398 NamedDecl *Lookup = SemaRef.LookupSingleName( 15399 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15400 if (Lookup == Namespace) 15401 break; 15402 } 15403 15404 // Once we have all the namespaces, reverse them to go outermost first, and 15405 // build an NNS. 15406 SmallString<64> Insertion; 15407 llvm::raw_svector_ostream OS(Insertion); 15408 if (DC->isTranslationUnit()) 15409 OS << "::"; 15410 std::reverse(Namespaces.begin(), Namespaces.end()); 15411 for (auto *II : Namespaces) 15412 OS << II->getName() << "::"; 15413 return FixItHint::CreateInsertion(NameLoc, Insertion); 15414 } 15415 15416 /// Determine whether a tag originally declared in context \p OldDC can 15417 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15418 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15419 /// using-declaration). 15420 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15421 DeclContext *NewDC) { 15422 OldDC = OldDC->getRedeclContext(); 15423 NewDC = NewDC->getRedeclContext(); 15424 15425 if (OldDC->Equals(NewDC)) 15426 return true; 15427 15428 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15429 // encloses the other). 15430 if (S.getLangOpts().MSVCCompat && 15431 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15432 return true; 15433 15434 return false; 15435 } 15436 15437 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15438 /// former case, Name will be non-null. In the later case, Name will be null. 15439 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15440 /// reference/declaration/definition of a tag. 15441 /// 15442 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15443 /// trailing-type-specifier) other than one in an alias-declaration. 15444 /// 15445 /// \param SkipBody If non-null, will be set to indicate if the caller should 15446 /// skip the definition of this tag and treat it as if it were a declaration. 15447 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15448 SourceLocation KWLoc, CXXScopeSpec &SS, 15449 IdentifierInfo *Name, SourceLocation NameLoc, 15450 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15451 SourceLocation ModulePrivateLoc, 15452 MultiTemplateParamsArg TemplateParameterLists, 15453 bool &OwnedDecl, bool &IsDependent, 15454 SourceLocation ScopedEnumKWLoc, 15455 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15456 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15457 SkipBodyInfo *SkipBody) { 15458 // If this is not a definition, it must have a name. 15459 IdentifierInfo *OrigName = Name; 15460 assert((Name != nullptr || TUK == TUK_Definition) && 15461 "Nameless record must be a definition!"); 15462 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15463 15464 OwnedDecl = false; 15465 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15466 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15467 15468 // FIXME: Check member specializations more carefully. 15469 bool isMemberSpecialization = false; 15470 bool Invalid = false; 15471 15472 // We only need to do this matching if we have template parameters 15473 // or a scope specifier, which also conveniently avoids this work 15474 // for non-C++ cases. 15475 if (TemplateParameterLists.size() > 0 || 15476 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15477 if (TemplateParameterList *TemplateParams = 15478 MatchTemplateParametersToScopeSpecifier( 15479 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15480 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15481 if (Kind == TTK_Enum) { 15482 Diag(KWLoc, diag::err_enum_template); 15483 return nullptr; 15484 } 15485 15486 if (TemplateParams->size() > 0) { 15487 // This is a declaration or definition of a class template (which may 15488 // be a member of another template). 15489 15490 if (Invalid) 15491 return nullptr; 15492 15493 OwnedDecl = false; 15494 DeclResult Result = CheckClassTemplate( 15495 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15496 AS, ModulePrivateLoc, 15497 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15498 TemplateParameterLists.data(), SkipBody); 15499 return Result.get(); 15500 } else { 15501 // The "template<>" header is extraneous. 15502 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15503 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15504 isMemberSpecialization = true; 15505 } 15506 } 15507 15508 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15509 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15510 return nullptr; 15511 } 15512 15513 // Figure out the underlying type if this a enum declaration. We need to do 15514 // this early, because it's needed to detect if this is an incompatible 15515 // redeclaration. 15516 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15517 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15518 15519 if (Kind == TTK_Enum) { 15520 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15521 // No underlying type explicitly specified, or we failed to parse the 15522 // type, default to int. 15523 EnumUnderlying = Context.IntTy.getTypePtr(); 15524 } else if (UnderlyingType.get()) { 15525 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15526 // integral type; any cv-qualification is ignored. 15527 TypeSourceInfo *TI = nullptr; 15528 GetTypeFromParser(UnderlyingType.get(), &TI); 15529 EnumUnderlying = TI; 15530 15531 if (CheckEnumUnderlyingType(TI)) 15532 // Recover by falling back to int. 15533 EnumUnderlying = Context.IntTy.getTypePtr(); 15534 15535 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15536 UPPC_FixedUnderlyingType)) 15537 EnumUnderlying = Context.IntTy.getTypePtr(); 15538 15539 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15540 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15541 // of 'int'. However, if this is an unfixed forward declaration, don't set 15542 // the underlying type unless the user enables -fms-compatibility. This 15543 // makes unfixed forward declared enums incomplete and is more conforming. 15544 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15545 EnumUnderlying = Context.IntTy.getTypePtr(); 15546 } 15547 } 15548 15549 DeclContext *SearchDC = CurContext; 15550 DeclContext *DC = CurContext; 15551 bool isStdBadAlloc = false; 15552 bool isStdAlignValT = false; 15553 15554 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15555 if (TUK == TUK_Friend || TUK == TUK_Reference) 15556 Redecl = NotForRedeclaration; 15557 15558 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15559 /// implemented asks for structural equivalence checking, the returned decl 15560 /// here is passed back to the parser, allowing the tag body to be parsed. 15561 auto createTagFromNewDecl = [&]() -> TagDecl * { 15562 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15563 // If there is an identifier, use the location of the identifier as the 15564 // location of the decl, otherwise use the location of the struct/union 15565 // keyword. 15566 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15567 TagDecl *New = nullptr; 15568 15569 if (Kind == TTK_Enum) { 15570 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15571 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15572 // If this is an undefined enum, bail. 15573 if (TUK != TUK_Definition && !Invalid) 15574 return nullptr; 15575 if (EnumUnderlying) { 15576 EnumDecl *ED = cast<EnumDecl>(New); 15577 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15578 ED->setIntegerTypeSourceInfo(TI); 15579 else 15580 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15581 ED->setPromotionType(ED->getIntegerType()); 15582 } 15583 } else { // struct/union 15584 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15585 nullptr); 15586 } 15587 15588 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15589 // Add alignment attributes if necessary; these attributes are checked 15590 // when the ASTContext lays out the structure. 15591 // 15592 // It is important for implementing the correct semantics that this 15593 // happen here (in ActOnTag). The #pragma pack stack is 15594 // maintained as a result of parser callbacks which can occur at 15595 // many points during the parsing of a struct declaration (because 15596 // the #pragma tokens are effectively skipped over during the 15597 // parsing of the struct). 15598 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15599 AddAlignmentAttributesForRecord(RD); 15600 AddMsStructLayoutForRecord(RD); 15601 } 15602 } 15603 New->setLexicalDeclContext(CurContext); 15604 return New; 15605 }; 15606 15607 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15608 if (Name && SS.isNotEmpty()) { 15609 // We have a nested-name tag ('struct foo::bar'). 15610 15611 // Check for invalid 'foo::'. 15612 if (SS.isInvalid()) { 15613 Name = nullptr; 15614 goto CreateNewDecl; 15615 } 15616 15617 // If this is a friend or a reference to a class in a dependent 15618 // context, don't try to make a decl for it. 15619 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15620 DC = computeDeclContext(SS, false); 15621 if (!DC) { 15622 IsDependent = true; 15623 return nullptr; 15624 } 15625 } else { 15626 DC = computeDeclContext(SS, true); 15627 if (!DC) { 15628 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15629 << SS.getRange(); 15630 return nullptr; 15631 } 15632 } 15633 15634 if (RequireCompleteDeclContext(SS, DC)) 15635 return nullptr; 15636 15637 SearchDC = DC; 15638 // Look-up name inside 'foo::'. 15639 LookupQualifiedName(Previous, DC); 15640 15641 if (Previous.isAmbiguous()) 15642 return nullptr; 15643 15644 if (Previous.empty()) { 15645 // Name lookup did not find anything. However, if the 15646 // nested-name-specifier refers to the current instantiation, 15647 // and that current instantiation has any dependent base 15648 // classes, we might find something at instantiation time: treat 15649 // this as a dependent elaborated-type-specifier. 15650 // But this only makes any sense for reference-like lookups. 15651 if (Previous.wasNotFoundInCurrentInstantiation() && 15652 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15653 IsDependent = true; 15654 return nullptr; 15655 } 15656 15657 // A tag 'foo::bar' must already exist. 15658 Diag(NameLoc, diag::err_not_tag_in_scope) 15659 << Kind << Name << DC << SS.getRange(); 15660 Name = nullptr; 15661 Invalid = true; 15662 goto CreateNewDecl; 15663 } 15664 } else if (Name) { 15665 // C++14 [class.mem]p14: 15666 // If T is the name of a class, then each of the following shall have a 15667 // name different from T: 15668 // -- every member of class T that is itself a type 15669 if (TUK != TUK_Reference && TUK != TUK_Friend && 15670 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15671 return nullptr; 15672 15673 // If this is a named struct, check to see if there was a previous forward 15674 // declaration or definition. 15675 // FIXME: We're looking into outer scopes here, even when we 15676 // shouldn't be. Doing so can result in ambiguities that we 15677 // shouldn't be diagnosing. 15678 LookupName(Previous, S); 15679 15680 // When declaring or defining a tag, ignore ambiguities introduced 15681 // by types using'ed into this scope. 15682 if (Previous.isAmbiguous() && 15683 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15684 LookupResult::Filter F = Previous.makeFilter(); 15685 while (F.hasNext()) { 15686 NamedDecl *ND = F.next(); 15687 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15688 SearchDC->getRedeclContext())) 15689 F.erase(); 15690 } 15691 F.done(); 15692 } 15693 15694 // C++11 [namespace.memdef]p3: 15695 // If the name in a friend declaration is neither qualified nor 15696 // a template-id and the declaration is a function or an 15697 // elaborated-type-specifier, the lookup to determine whether 15698 // the entity has been previously declared shall not consider 15699 // any scopes outside the innermost enclosing namespace. 15700 // 15701 // MSVC doesn't implement the above rule for types, so a friend tag 15702 // declaration may be a redeclaration of a type declared in an enclosing 15703 // scope. They do implement this rule for friend functions. 15704 // 15705 // Does it matter that this should be by scope instead of by 15706 // semantic context? 15707 if (!Previous.empty() && TUK == TUK_Friend) { 15708 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15709 LookupResult::Filter F = Previous.makeFilter(); 15710 bool FriendSawTagOutsideEnclosingNamespace = false; 15711 while (F.hasNext()) { 15712 NamedDecl *ND = F.next(); 15713 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15714 if (DC->isFileContext() && 15715 !EnclosingNS->Encloses(ND->getDeclContext())) { 15716 if (getLangOpts().MSVCCompat) 15717 FriendSawTagOutsideEnclosingNamespace = true; 15718 else 15719 F.erase(); 15720 } 15721 } 15722 F.done(); 15723 15724 // Diagnose this MSVC extension in the easy case where lookup would have 15725 // unambiguously found something outside the enclosing namespace. 15726 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15727 NamedDecl *ND = Previous.getFoundDecl(); 15728 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15729 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15730 } 15731 } 15732 15733 // Note: there used to be some attempt at recovery here. 15734 if (Previous.isAmbiguous()) 15735 return nullptr; 15736 15737 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15738 // FIXME: This makes sure that we ignore the contexts associated 15739 // with C structs, unions, and enums when looking for a matching 15740 // tag declaration or definition. See the similar lookup tweak 15741 // in Sema::LookupName; is there a better way to deal with this? 15742 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15743 SearchDC = SearchDC->getParent(); 15744 } 15745 } 15746 15747 if (Previous.isSingleResult() && 15748 Previous.getFoundDecl()->isTemplateParameter()) { 15749 // Maybe we will complain about the shadowed template parameter. 15750 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15751 // Just pretend that we didn't see the previous declaration. 15752 Previous.clear(); 15753 } 15754 15755 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15756 DC->Equals(getStdNamespace())) { 15757 if (Name->isStr("bad_alloc")) { 15758 // This is a declaration of or a reference to "std::bad_alloc". 15759 isStdBadAlloc = true; 15760 15761 // If std::bad_alloc has been implicitly declared (but made invisible to 15762 // name lookup), fill in this implicit declaration as the previous 15763 // declaration, so that the declarations get chained appropriately. 15764 if (Previous.empty() && StdBadAlloc) 15765 Previous.addDecl(getStdBadAlloc()); 15766 } else if (Name->isStr("align_val_t")) { 15767 isStdAlignValT = true; 15768 if (Previous.empty() && StdAlignValT) 15769 Previous.addDecl(getStdAlignValT()); 15770 } 15771 } 15772 15773 // If we didn't find a previous declaration, and this is a reference 15774 // (or friend reference), move to the correct scope. In C++, we 15775 // also need to do a redeclaration lookup there, just in case 15776 // there's a shadow friend decl. 15777 if (Name && Previous.empty() && 15778 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15779 if (Invalid) goto CreateNewDecl; 15780 assert(SS.isEmpty()); 15781 15782 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15783 // C++ [basic.scope.pdecl]p5: 15784 // -- for an elaborated-type-specifier of the form 15785 // 15786 // class-key identifier 15787 // 15788 // if the elaborated-type-specifier is used in the 15789 // decl-specifier-seq or parameter-declaration-clause of a 15790 // function defined in namespace scope, the identifier is 15791 // declared as a class-name in the namespace that contains 15792 // the declaration; otherwise, except as a friend 15793 // declaration, the identifier is declared in the smallest 15794 // non-class, non-function-prototype scope that contains the 15795 // declaration. 15796 // 15797 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15798 // C structs and unions. 15799 // 15800 // It is an error in C++ to declare (rather than define) an enum 15801 // type, including via an elaborated type specifier. We'll 15802 // diagnose that later; for now, declare the enum in the same 15803 // scope as we would have picked for any other tag type. 15804 // 15805 // GNU C also supports this behavior as part of its incomplete 15806 // enum types extension, while GNU C++ does not. 15807 // 15808 // Find the context where we'll be declaring the tag. 15809 // FIXME: We would like to maintain the current DeclContext as the 15810 // lexical context, 15811 SearchDC = getTagInjectionContext(SearchDC); 15812 15813 // Find the scope where we'll be declaring the tag. 15814 S = getTagInjectionScope(S, getLangOpts()); 15815 } else { 15816 assert(TUK == TUK_Friend); 15817 // C++ [namespace.memdef]p3: 15818 // If a friend declaration in a non-local class first declares a 15819 // class or function, the friend class or function is a member of 15820 // the innermost enclosing namespace. 15821 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15822 } 15823 15824 // In C++, we need to do a redeclaration lookup to properly 15825 // diagnose some problems. 15826 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15827 // hidden declaration so that we don't get ambiguity errors when using a 15828 // type declared by an elaborated-type-specifier. In C that is not correct 15829 // and we should instead merge compatible types found by lookup. 15830 if (getLangOpts().CPlusPlus) { 15831 // FIXME: This can perform qualified lookups into function contexts, 15832 // which are meaningless. 15833 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15834 LookupQualifiedName(Previous, SearchDC); 15835 } else { 15836 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15837 LookupName(Previous, S); 15838 } 15839 } 15840 15841 // If we have a known previous declaration to use, then use it. 15842 if (Previous.empty() && SkipBody && SkipBody->Previous) 15843 Previous.addDecl(SkipBody->Previous); 15844 15845 if (!Previous.empty()) { 15846 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15847 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15848 15849 // It's okay to have a tag decl in the same scope as a typedef 15850 // which hides a tag decl in the same scope. Finding this 15851 // insanity with a redeclaration lookup can only actually happen 15852 // in C++. 15853 // 15854 // This is also okay for elaborated-type-specifiers, which is 15855 // technically forbidden by the current standard but which is 15856 // okay according to the likely resolution of an open issue; 15857 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15858 if (getLangOpts().CPlusPlus) { 15859 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15860 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15861 TagDecl *Tag = TT->getDecl(); 15862 if (Tag->getDeclName() == Name && 15863 Tag->getDeclContext()->getRedeclContext() 15864 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15865 PrevDecl = Tag; 15866 Previous.clear(); 15867 Previous.addDecl(Tag); 15868 Previous.resolveKind(); 15869 } 15870 } 15871 } 15872 } 15873 15874 // If this is a redeclaration of a using shadow declaration, it must 15875 // declare a tag in the same context. In MSVC mode, we allow a 15876 // redefinition if either context is within the other. 15877 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15878 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15879 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15880 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15881 !(OldTag && isAcceptableTagRedeclContext( 15882 *this, OldTag->getDeclContext(), SearchDC))) { 15883 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15884 Diag(Shadow->getTargetDecl()->getLocation(), 15885 diag::note_using_decl_target); 15886 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15887 << 0; 15888 // Recover by ignoring the old declaration. 15889 Previous.clear(); 15890 goto CreateNewDecl; 15891 } 15892 } 15893 15894 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15895 // If this is a use of a previous tag, or if the tag is already declared 15896 // in the same scope (so that the definition/declaration completes or 15897 // rementions the tag), reuse the decl. 15898 if (TUK == TUK_Reference || TUK == TUK_Friend || 15899 isDeclInScope(DirectPrevDecl, SearchDC, S, 15900 SS.isNotEmpty() || isMemberSpecialization)) { 15901 // Make sure that this wasn't declared as an enum and now used as a 15902 // struct or something similar. 15903 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15904 TUK == TUK_Definition, KWLoc, 15905 Name)) { 15906 bool SafeToContinue 15907 = (PrevTagDecl->getTagKind() != TTK_Enum && 15908 Kind != TTK_Enum); 15909 if (SafeToContinue) 15910 Diag(KWLoc, diag::err_use_with_wrong_tag) 15911 << Name 15912 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15913 PrevTagDecl->getKindName()); 15914 else 15915 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15916 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15917 15918 if (SafeToContinue) 15919 Kind = PrevTagDecl->getTagKind(); 15920 else { 15921 // Recover by making this an anonymous redefinition. 15922 Name = nullptr; 15923 Previous.clear(); 15924 Invalid = true; 15925 } 15926 } 15927 15928 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15929 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15930 if (TUK == TUK_Reference || TUK == TUK_Friend) 15931 return PrevTagDecl; 15932 15933 QualType EnumUnderlyingTy; 15934 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15935 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15936 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15937 EnumUnderlyingTy = QualType(T, 0); 15938 15939 // All conflicts with previous declarations are recovered by 15940 // returning the previous declaration, unless this is a definition, 15941 // in which case we want the caller to bail out. 15942 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15943 ScopedEnum, EnumUnderlyingTy, 15944 IsFixed, PrevEnum)) 15945 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15946 } 15947 15948 // C++11 [class.mem]p1: 15949 // A member shall not be declared twice in the member-specification, 15950 // except that a nested class or member class template can be declared 15951 // and then later defined. 15952 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15953 S->isDeclScope(PrevDecl)) { 15954 Diag(NameLoc, diag::ext_member_redeclared); 15955 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15956 } 15957 15958 if (!Invalid) { 15959 // If this is a use, just return the declaration we found, unless 15960 // we have attributes. 15961 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15962 if (!Attrs.empty()) { 15963 // FIXME: Diagnose these attributes. For now, we create a new 15964 // declaration to hold them. 15965 } else if (TUK == TUK_Reference && 15966 (PrevTagDecl->getFriendObjectKind() == 15967 Decl::FOK_Undeclared || 15968 PrevDecl->getOwningModule() != getCurrentModule()) && 15969 SS.isEmpty()) { 15970 // This declaration is a reference to an existing entity, but 15971 // has different visibility from that entity: it either makes 15972 // a friend visible or it makes a type visible in a new module. 15973 // In either case, create a new declaration. We only do this if 15974 // the declaration would have meant the same thing if no prior 15975 // declaration were found, that is, if it was found in the same 15976 // scope where we would have injected a declaration. 15977 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15978 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15979 return PrevTagDecl; 15980 // This is in the injected scope, create a new declaration in 15981 // that scope. 15982 S = getTagInjectionScope(S, getLangOpts()); 15983 } else { 15984 return PrevTagDecl; 15985 } 15986 } 15987 15988 // Diagnose attempts to redefine a tag. 15989 if (TUK == TUK_Definition) { 15990 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15991 // If we're defining a specialization and the previous definition 15992 // is from an implicit instantiation, don't emit an error 15993 // here; we'll catch this in the general case below. 15994 bool IsExplicitSpecializationAfterInstantiation = false; 15995 if (isMemberSpecialization) { 15996 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15997 IsExplicitSpecializationAfterInstantiation = 15998 RD->getTemplateSpecializationKind() != 15999 TSK_ExplicitSpecialization; 16000 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 16001 IsExplicitSpecializationAfterInstantiation = 16002 ED->getTemplateSpecializationKind() != 16003 TSK_ExplicitSpecialization; 16004 } 16005 16006 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 16007 // not keep more that one definition around (merge them). However, 16008 // ensure the decl passes the structural compatibility check in 16009 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 16010 NamedDecl *Hidden = nullptr; 16011 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 16012 // There is a definition of this tag, but it is not visible. We 16013 // explicitly make use of C++'s one definition rule here, and 16014 // assume that this definition is identical to the hidden one 16015 // we already have. Make the existing definition visible and 16016 // use it in place of this one. 16017 if (!getLangOpts().CPlusPlus) { 16018 // Postpone making the old definition visible until after we 16019 // complete parsing the new one and do the structural 16020 // comparison. 16021 SkipBody->CheckSameAsPrevious = true; 16022 SkipBody->New = createTagFromNewDecl(); 16023 SkipBody->Previous = Def; 16024 return Def; 16025 } else { 16026 SkipBody->ShouldSkip = true; 16027 SkipBody->Previous = Def; 16028 makeMergedDefinitionVisible(Hidden); 16029 // Carry on and handle it like a normal definition. We'll 16030 // skip starting the definitiion later. 16031 } 16032 } else if (!IsExplicitSpecializationAfterInstantiation) { 16033 // A redeclaration in function prototype scope in C isn't 16034 // visible elsewhere, so merely issue a warning. 16035 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 16036 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 16037 else 16038 Diag(NameLoc, diag::err_redefinition) << Name; 16039 notePreviousDefinition(Def, 16040 NameLoc.isValid() ? NameLoc : KWLoc); 16041 // If this is a redefinition, recover by making this 16042 // struct be anonymous, which will make any later 16043 // references get the previous definition. 16044 Name = nullptr; 16045 Previous.clear(); 16046 Invalid = true; 16047 } 16048 } else { 16049 // If the type is currently being defined, complain 16050 // about a nested redefinition. 16051 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 16052 if (TD->isBeingDefined()) { 16053 Diag(NameLoc, diag::err_nested_redefinition) << Name; 16054 Diag(PrevTagDecl->getLocation(), 16055 diag::note_previous_definition); 16056 Name = nullptr; 16057 Previous.clear(); 16058 Invalid = true; 16059 } 16060 } 16061 16062 // Okay, this is definition of a previously declared or referenced 16063 // tag. We're going to create a new Decl for it. 16064 } 16065 16066 // Okay, we're going to make a redeclaration. If this is some kind 16067 // of reference, make sure we build the redeclaration in the same DC 16068 // as the original, and ignore the current access specifier. 16069 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16070 SearchDC = PrevTagDecl->getDeclContext(); 16071 AS = AS_none; 16072 } 16073 } 16074 // If we get here we have (another) forward declaration or we 16075 // have a definition. Just create a new decl. 16076 16077 } else { 16078 // If we get here, this is a definition of a new tag type in a nested 16079 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 16080 // new decl/type. We set PrevDecl to NULL so that the entities 16081 // have distinct types. 16082 Previous.clear(); 16083 } 16084 // If we get here, we're going to create a new Decl. If PrevDecl 16085 // is non-NULL, it's a definition of the tag declared by 16086 // PrevDecl. If it's NULL, we have a new definition. 16087 16088 // Otherwise, PrevDecl is not a tag, but was found with tag 16089 // lookup. This is only actually possible in C++, where a few 16090 // things like templates still live in the tag namespace. 16091 } else { 16092 // Use a better diagnostic if an elaborated-type-specifier 16093 // found the wrong kind of type on the first 16094 // (non-redeclaration) lookup. 16095 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16096 !Previous.isForRedeclaration()) { 16097 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16098 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16099 << Kind; 16100 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16101 Invalid = true; 16102 16103 // Otherwise, only diagnose if the declaration is in scope. 16104 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16105 SS.isNotEmpty() || isMemberSpecialization)) { 16106 // do nothing 16107 16108 // Diagnose implicit declarations introduced by elaborated types. 16109 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16110 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16111 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16112 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16113 Invalid = true; 16114 16115 // Otherwise it's a declaration. Call out a particularly common 16116 // case here. 16117 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16118 unsigned Kind = 0; 16119 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16120 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16121 << Name << Kind << TND->getUnderlyingType(); 16122 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16123 Invalid = true; 16124 16125 // Otherwise, diagnose. 16126 } else { 16127 // The tag name clashes with something else in the target scope, 16128 // issue an error and recover by making this tag be anonymous. 16129 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16130 notePreviousDefinition(PrevDecl, NameLoc); 16131 Name = nullptr; 16132 Invalid = true; 16133 } 16134 16135 // The existing declaration isn't relevant to us; we're in a 16136 // new scope, so clear out the previous declaration. 16137 Previous.clear(); 16138 } 16139 } 16140 16141 CreateNewDecl: 16142 16143 TagDecl *PrevDecl = nullptr; 16144 if (Previous.isSingleResult()) 16145 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16146 16147 // If there is an identifier, use the location of the identifier as the 16148 // location of the decl, otherwise use the location of the struct/union 16149 // keyword. 16150 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16151 16152 // Otherwise, create a new declaration. If there is a previous 16153 // declaration of the same entity, the two will be linked via 16154 // PrevDecl. 16155 TagDecl *New; 16156 16157 if (Kind == TTK_Enum) { 16158 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16159 // enum X { A, B, C } D; D should chain to X. 16160 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16161 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16162 ScopedEnumUsesClassTag, IsFixed); 16163 16164 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16165 StdAlignValT = cast<EnumDecl>(New); 16166 16167 // If this is an undefined enum, warn. 16168 if (TUK != TUK_Definition && !Invalid) { 16169 TagDecl *Def; 16170 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16171 // C++0x: 7.2p2: opaque-enum-declaration. 16172 // Conflicts are diagnosed above. Do nothing. 16173 } 16174 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16175 Diag(Loc, diag::ext_forward_ref_enum_def) 16176 << New; 16177 Diag(Def->getLocation(), diag::note_previous_definition); 16178 } else { 16179 unsigned DiagID = diag::ext_forward_ref_enum; 16180 if (getLangOpts().MSVCCompat) 16181 DiagID = diag::ext_ms_forward_ref_enum; 16182 else if (getLangOpts().CPlusPlus) 16183 DiagID = diag::err_forward_ref_enum; 16184 Diag(Loc, DiagID); 16185 } 16186 } 16187 16188 if (EnumUnderlying) { 16189 EnumDecl *ED = cast<EnumDecl>(New); 16190 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16191 ED->setIntegerTypeSourceInfo(TI); 16192 else 16193 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16194 ED->setPromotionType(ED->getIntegerType()); 16195 assert(ED->isComplete() && "enum with type should be complete"); 16196 } 16197 } else { 16198 // struct/union/class 16199 16200 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16201 // struct X { int A; } D; D should chain to X. 16202 if (getLangOpts().CPlusPlus) { 16203 // FIXME: Look for a way to use RecordDecl for simple structs. 16204 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16205 cast_or_null<CXXRecordDecl>(PrevDecl)); 16206 16207 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16208 StdBadAlloc = cast<CXXRecordDecl>(New); 16209 } else 16210 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16211 cast_or_null<RecordDecl>(PrevDecl)); 16212 } 16213 16214 // C++11 [dcl.type]p3: 16215 // A type-specifier-seq shall not define a class or enumeration [...]. 16216 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16217 TUK == TUK_Definition) { 16218 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16219 << Context.getTagDeclType(New); 16220 Invalid = true; 16221 } 16222 16223 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16224 DC->getDeclKind() == Decl::Enum) { 16225 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16226 << Context.getTagDeclType(New); 16227 Invalid = true; 16228 } 16229 16230 // Maybe add qualifier info. 16231 if (SS.isNotEmpty()) { 16232 if (SS.isSet()) { 16233 // If this is either a declaration or a definition, check the 16234 // nested-name-specifier against the current context. 16235 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16236 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16237 isMemberSpecialization)) 16238 Invalid = true; 16239 16240 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16241 if (TemplateParameterLists.size() > 0) { 16242 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16243 } 16244 } 16245 else 16246 Invalid = true; 16247 } 16248 16249 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16250 // Add alignment attributes if necessary; these attributes are checked when 16251 // the ASTContext lays out the structure. 16252 // 16253 // It is important for implementing the correct semantics that this 16254 // happen here (in ActOnTag). The #pragma pack stack is 16255 // maintained as a result of parser callbacks which can occur at 16256 // many points during the parsing of a struct declaration (because 16257 // the #pragma tokens are effectively skipped over during the 16258 // parsing of the struct). 16259 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16260 AddAlignmentAttributesForRecord(RD); 16261 AddMsStructLayoutForRecord(RD); 16262 } 16263 } 16264 16265 if (ModulePrivateLoc.isValid()) { 16266 if (isMemberSpecialization) 16267 Diag(New->getLocation(), diag::err_module_private_specialization) 16268 << 2 16269 << FixItHint::CreateRemoval(ModulePrivateLoc); 16270 // __module_private__ does not apply to local classes. However, we only 16271 // diagnose this as an error when the declaration specifiers are 16272 // freestanding. Here, we just ignore the __module_private__. 16273 else if (!SearchDC->isFunctionOrMethod()) 16274 New->setModulePrivate(); 16275 } 16276 16277 // If this is a specialization of a member class (of a class template), 16278 // check the specialization. 16279 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16280 Invalid = true; 16281 16282 // If we're declaring or defining a tag in function prototype scope in C, 16283 // note that this type can only be used within the function and add it to 16284 // the list of decls to inject into the function definition scope. 16285 if ((Name || Kind == TTK_Enum) && 16286 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16287 if (getLangOpts().CPlusPlus) { 16288 // C++ [dcl.fct]p6: 16289 // Types shall not be defined in return or parameter types. 16290 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16291 Diag(Loc, diag::err_type_defined_in_param_type) 16292 << Name; 16293 Invalid = true; 16294 } 16295 } else if (!PrevDecl) { 16296 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16297 } 16298 } 16299 16300 if (Invalid) 16301 New->setInvalidDecl(); 16302 16303 // Set the lexical context. If the tag has a C++ scope specifier, the 16304 // lexical context will be different from the semantic context. 16305 New->setLexicalDeclContext(CurContext); 16306 16307 // Mark this as a friend decl if applicable. 16308 // In Microsoft mode, a friend declaration also acts as a forward 16309 // declaration so we always pass true to setObjectOfFriendDecl to make 16310 // the tag name visible. 16311 if (TUK == TUK_Friend) 16312 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16313 16314 // Set the access specifier. 16315 if (!Invalid && SearchDC->isRecord()) 16316 SetMemberAccessSpecifier(New, PrevDecl, AS); 16317 16318 if (PrevDecl) 16319 CheckRedeclarationModuleOwnership(New, PrevDecl); 16320 16321 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16322 New->startDefinition(); 16323 16324 ProcessDeclAttributeList(S, New, Attrs); 16325 AddPragmaAttributes(S, New); 16326 16327 // If this has an identifier, add it to the scope stack. 16328 if (TUK == TUK_Friend) { 16329 // We might be replacing an existing declaration in the lookup tables; 16330 // if so, borrow its access specifier. 16331 if (PrevDecl) 16332 New->setAccess(PrevDecl->getAccess()); 16333 16334 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16335 DC->makeDeclVisibleInContext(New); 16336 if (Name) // can be null along some error paths 16337 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16338 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16339 } else if (Name) { 16340 S = getNonFieldDeclScope(S); 16341 PushOnScopeChains(New, S, true); 16342 } else { 16343 CurContext->addDecl(New); 16344 } 16345 16346 // If this is the C FILE type, notify the AST context. 16347 if (IdentifierInfo *II = New->getIdentifier()) 16348 if (!New->isInvalidDecl() && 16349 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16350 II->isStr("FILE")) 16351 Context.setFILEDecl(New); 16352 16353 if (PrevDecl) 16354 mergeDeclAttributes(New, PrevDecl); 16355 16356 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16357 inferGslOwnerPointerAttribute(CXXRD); 16358 16359 // If there's a #pragma GCC visibility in scope, set the visibility of this 16360 // record. 16361 AddPushedVisibilityAttribute(New); 16362 16363 if (isMemberSpecialization && !New->isInvalidDecl()) 16364 CompleteMemberSpecialization(New, Previous); 16365 16366 OwnedDecl = true; 16367 // In C++, don't return an invalid declaration. We can't recover well from 16368 // the cases where we make the type anonymous. 16369 if (Invalid && getLangOpts().CPlusPlus) { 16370 if (New->isBeingDefined()) 16371 if (auto RD = dyn_cast<RecordDecl>(New)) 16372 RD->completeDefinition(); 16373 return nullptr; 16374 } else if (SkipBody && SkipBody->ShouldSkip) { 16375 return SkipBody->Previous; 16376 } else { 16377 return New; 16378 } 16379 } 16380 16381 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16382 AdjustDeclIfTemplate(TagD); 16383 TagDecl *Tag = cast<TagDecl>(TagD); 16384 16385 // Enter the tag context. 16386 PushDeclContext(S, Tag); 16387 16388 ActOnDocumentableDecl(TagD); 16389 16390 // If there's a #pragma GCC visibility in scope, set the visibility of this 16391 // record. 16392 AddPushedVisibilityAttribute(Tag); 16393 } 16394 16395 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16396 SkipBodyInfo &SkipBody) { 16397 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16398 return false; 16399 16400 // Make the previous decl visible. 16401 makeMergedDefinitionVisible(SkipBody.Previous); 16402 return true; 16403 } 16404 16405 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16406 assert(isa<ObjCContainerDecl>(IDecl) && 16407 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16408 DeclContext *OCD = cast<DeclContext>(IDecl); 16409 assert(OCD->getLexicalParent() == CurContext && 16410 "The next DeclContext should be lexically contained in the current one."); 16411 CurContext = OCD; 16412 return IDecl; 16413 } 16414 16415 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16416 SourceLocation FinalLoc, 16417 bool IsFinalSpelledSealed, 16418 SourceLocation LBraceLoc) { 16419 AdjustDeclIfTemplate(TagD); 16420 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16421 16422 FieldCollector->StartClass(); 16423 16424 if (!Record->getIdentifier()) 16425 return; 16426 16427 if (FinalLoc.isValid()) 16428 Record->addAttr(FinalAttr::Create( 16429 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16430 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16431 16432 // C++ [class]p2: 16433 // [...] The class-name is also inserted into the scope of the 16434 // class itself; this is known as the injected-class-name. For 16435 // purposes of access checking, the injected-class-name is treated 16436 // as if it were a public member name. 16437 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16438 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16439 Record->getLocation(), Record->getIdentifier(), 16440 /*PrevDecl=*/nullptr, 16441 /*DelayTypeCreation=*/true); 16442 Context.getTypeDeclType(InjectedClassName, Record); 16443 InjectedClassName->setImplicit(); 16444 InjectedClassName->setAccess(AS_public); 16445 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16446 InjectedClassName->setDescribedClassTemplate(Template); 16447 PushOnScopeChains(InjectedClassName, S); 16448 assert(InjectedClassName->isInjectedClassName() && 16449 "Broken injected-class-name"); 16450 } 16451 16452 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16453 SourceRange BraceRange) { 16454 AdjustDeclIfTemplate(TagD); 16455 TagDecl *Tag = cast<TagDecl>(TagD); 16456 Tag->setBraceRange(BraceRange); 16457 16458 // Make sure we "complete" the definition even it is invalid. 16459 if (Tag->isBeingDefined()) { 16460 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16461 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16462 RD->completeDefinition(); 16463 } 16464 16465 if (isa<CXXRecordDecl>(Tag)) { 16466 FieldCollector->FinishClass(); 16467 } 16468 16469 // Exit this scope of this tag's definition. 16470 PopDeclContext(); 16471 16472 if (getCurLexicalContext()->isObjCContainer() && 16473 Tag->getDeclContext()->isFileContext()) 16474 Tag->setTopLevelDeclInObjCContainer(); 16475 16476 // Notify the consumer that we've defined a tag. 16477 if (!Tag->isInvalidDecl()) 16478 Consumer.HandleTagDeclDefinition(Tag); 16479 } 16480 16481 void Sema::ActOnObjCContainerFinishDefinition() { 16482 // Exit this scope of this interface definition. 16483 PopDeclContext(); 16484 } 16485 16486 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16487 assert(DC == CurContext && "Mismatch of container contexts"); 16488 OriginalLexicalContext = DC; 16489 ActOnObjCContainerFinishDefinition(); 16490 } 16491 16492 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16493 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16494 OriginalLexicalContext = nullptr; 16495 } 16496 16497 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16498 AdjustDeclIfTemplate(TagD); 16499 TagDecl *Tag = cast<TagDecl>(TagD); 16500 Tag->setInvalidDecl(); 16501 16502 // Make sure we "complete" the definition even it is invalid. 16503 if (Tag->isBeingDefined()) { 16504 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16505 RD->completeDefinition(); 16506 } 16507 16508 // We're undoing ActOnTagStartDefinition here, not 16509 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16510 // the FieldCollector. 16511 16512 PopDeclContext(); 16513 } 16514 16515 // Note that FieldName may be null for anonymous bitfields. 16516 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16517 IdentifierInfo *FieldName, 16518 QualType FieldTy, bool IsMsStruct, 16519 Expr *BitWidth, bool *ZeroWidth) { 16520 assert(BitWidth); 16521 if (BitWidth->containsErrors()) 16522 return ExprError(); 16523 16524 // Default to true; that shouldn't confuse checks for emptiness 16525 if (ZeroWidth) 16526 *ZeroWidth = true; 16527 16528 // C99 6.7.2.1p4 - verify the field type. 16529 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16530 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16531 // Handle incomplete and sizeless types with a specific error. 16532 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16533 diag::err_field_incomplete_or_sizeless)) 16534 return ExprError(); 16535 if (FieldName) 16536 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16537 << FieldName << FieldTy << BitWidth->getSourceRange(); 16538 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16539 << FieldTy << BitWidth->getSourceRange(); 16540 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16541 UPPC_BitFieldWidth)) 16542 return ExprError(); 16543 16544 // If the bit-width is type- or value-dependent, don't try to check 16545 // it now. 16546 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16547 return BitWidth; 16548 16549 llvm::APSInt Value; 16550 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 16551 if (ICE.isInvalid()) 16552 return ICE; 16553 BitWidth = ICE.get(); 16554 16555 if (Value != 0 && ZeroWidth) 16556 *ZeroWidth = false; 16557 16558 // Zero-width bitfield is ok for anonymous field. 16559 if (Value == 0 && FieldName) 16560 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16561 16562 if (Value.isSigned() && Value.isNegative()) { 16563 if (FieldName) 16564 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16565 << FieldName << Value.toString(10); 16566 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16567 << Value.toString(10); 16568 } 16569 16570 // The size of the bit-field must not exceed our maximum permitted object 16571 // size. 16572 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 16573 return Diag(FieldLoc, diag::err_bitfield_too_wide) 16574 << !FieldName << FieldName << Value.toString(10); 16575 } 16576 16577 if (!FieldTy->isDependentType()) { 16578 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16579 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16580 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16581 16582 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16583 // ABI. 16584 bool CStdConstraintViolation = 16585 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16586 bool MSBitfieldViolation = 16587 Value.ugt(TypeStorageSize) && 16588 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16589 if (CStdConstraintViolation || MSBitfieldViolation) { 16590 unsigned DiagWidth = 16591 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16592 if (FieldName) 16593 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16594 << FieldName << Value.toString(10) 16595 << !CStdConstraintViolation << DiagWidth; 16596 16597 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16598 << Value.toString(10) << !CStdConstraintViolation 16599 << DiagWidth; 16600 } 16601 16602 // Warn on types where the user might conceivably expect to get all 16603 // specified bits as value bits: that's all integral types other than 16604 // 'bool'. 16605 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 16606 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16607 << FieldName << Value.toString(10) 16608 << (unsigned)TypeWidth; 16609 } 16610 } 16611 16612 return BitWidth; 16613 } 16614 16615 /// ActOnField - Each field of a C struct/union is passed into this in order 16616 /// to create a FieldDecl object for it. 16617 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16618 Declarator &D, Expr *BitfieldWidth) { 16619 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16620 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16621 /*InitStyle=*/ICIS_NoInit, AS_public); 16622 return Res; 16623 } 16624 16625 /// HandleField - Analyze a field of a C struct or a C++ data member. 16626 /// 16627 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16628 SourceLocation DeclStart, 16629 Declarator &D, Expr *BitWidth, 16630 InClassInitStyle InitStyle, 16631 AccessSpecifier AS) { 16632 if (D.isDecompositionDeclarator()) { 16633 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16634 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16635 << Decomp.getSourceRange(); 16636 return nullptr; 16637 } 16638 16639 IdentifierInfo *II = D.getIdentifier(); 16640 SourceLocation Loc = DeclStart; 16641 if (II) Loc = D.getIdentifierLoc(); 16642 16643 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16644 QualType T = TInfo->getType(); 16645 if (getLangOpts().CPlusPlus) { 16646 CheckExtraCXXDefaultArguments(D); 16647 16648 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16649 UPPC_DataMemberType)) { 16650 D.setInvalidType(); 16651 T = Context.IntTy; 16652 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16653 } 16654 } 16655 16656 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16657 16658 if (D.getDeclSpec().isInlineSpecified()) 16659 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16660 << getLangOpts().CPlusPlus17; 16661 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16662 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16663 diag::err_invalid_thread) 16664 << DeclSpec::getSpecifierName(TSCS); 16665 16666 // Check to see if this name was declared as a member previously 16667 NamedDecl *PrevDecl = nullptr; 16668 LookupResult Previous(*this, II, Loc, LookupMemberName, 16669 ForVisibleRedeclaration); 16670 LookupName(Previous, S); 16671 switch (Previous.getResultKind()) { 16672 case LookupResult::Found: 16673 case LookupResult::FoundUnresolvedValue: 16674 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16675 break; 16676 16677 case LookupResult::FoundOverloaded: 16678 PrevDecl = Previous.getRepresentativeDecl(); 16679 break; 16680 16681 case LookupResult::NotFound: 16682 case LookupResult::NotFoundInCurrentInstantiation: 16683 case LookupResult::Ambiguous: 16684 break; 16685 } 16686 Previous.suppressDiagnostics(); 16687 16688 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16689 // Maybe we will complain about the shadowed template parameter. 16690 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16691 // Just pretend that we didn't see the previous declaration. 16692 PrevDecl = nullptr; 16693 } 16694 16695 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16696 PrevDecl = nullptr; 16697 16698 bool Mutable 16699 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16700 SourceLocation TSSL = D.getBeginLoc(); 16701 FieldDecl *NewFD 16702 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16703 TSSL, AS, PrevDecl, &D); 16704 16705 if (NewFD->isInvalidDecl()) 16706 Record->setInvalidDecl(); 16707 16708 if (D.getDeclSpec().isModulePrivateSpecified()) 16709 NewFD->setModulePrivate(); 16710 16711 if (NewFD->isInvalidDecl() && PrevDecl) { 16712 // Don't introduce NewFD into scope; there's already something 16713 // with the same name in the same scope. 16714 } else if (II) { 16715 PushOnScopeChains(NewFD, S); 16716 } else 16717 Record->addDecl(NewFD); 16718 16719 return NewFD; 16720 } 16721 16722 /// Build a new FieldDecl and check its well-formedness. 16723 /// 16724 /// This routine builds a new FieldDecl given the fields name, type, 16725 /// record, etc. \p PrevDecl should refer to any previous declaration 16726 /// with the same name and in the same scope as the field to be 16727 /// created. 16728 /// 16729 /// \returns a new FieldDecl. 16730 /// 16731 /// \todo The Declarator argument is a hack. It will be removed once 16732 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16733 TypeSourceInfo *TInfo, 16734 RecordDecl *Record, SourceLocation Loc, 16735 bool Mutable, Expr *BitWidth, 16736 InClassInitStyle InitStyle, 16737 SourceLocation TSSL, 16738 AccessSpecifier AS, NamedDecl *PrevDecl, 16739 Declarator *D) { 16740 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16741 bool InvalidDecl = false; 16742 if (D) InvalidDecl = D->isInvalidType(); 16743 16744 // If we receive a broken type, recover by assuming 'int' and 16745 // marking this declaration as invalid. 16746 if (T.isNull() || T->containsErrors()) { 16747 InvalidDecl = true; 16748 T = Context.IntTy; 16749 } 16750 16751 QualType EltTy = Context.getBaseElementType(T); 16752 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16753 if (RequireCompleteSizedType(Loc, EltTy, 16754 diag::err_field_incomplete_or_sizeless)) { 16755 // Fields of incomplete type force their record to be invalid. 16756 Record->setInvalidDecl(); 16757 InvalidDecl = true; 16758 } else { 16759 NamedDecl *Def; 16760 EltTy->isIncompleteType(&Def); 16761 if (Def && Def->isInvalidDecl()) { 16762 Record->setInvalidDecl(); 16763 InvalidDecl = true; 16764 } 16765 } 16766 } 16767 16768 // TR 18037 does not allow fields to be declared with address space 16769 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16770 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16771 Diag(Loc, diag::err_field_with_address_space); 16772 Record->setInvalidDecl(); 16773 InvalidDecl = true; 16774 } 16775 16776 if (LangOpts.OpenCL) { 16777 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16778 // used as structure or union field: image, sampler, event or block types. 16779 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16780 T->isBlockPointerType()) { 16781 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16782 Record->setInvalidDecl(); 16783 InvalidDecl = true; 16784 } 16785 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16786 if (BitWidth) { 16787 Diag(Loc, diag::err_opencl_bitfields); 16788 InvalidDecl = true; 16789 } 16790 } 16791 16792 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16793 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16794 T.hasQualifiers()) { 16795 InvalidDecl = true; 16796 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16797 } 16798 16799 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16800 // than a variably modified type. 16801 if (!InvalidDecl && T->isVariablyModifiedType()) { 16802 if (!tryToFixVariablyModifiedVarType( 16803 TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 16804 InvalidDecl = true; 16805 } 16806 16807 // Fields can not have abstract class types 16808 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16809 diag::err_abstract_type_in_decl, 16810 AbstractFieldType)) 16811 InvalidDecl = true; 16812 16813 bool ZeroWidth = false; 16814 if (InvalidDecl) 16815 BitWidth = nullptr; 16816 // If this is declared as a bit-field, check the bit-field. 16817 if (BitWidth) { 16818 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16819 &ZeroWidth).get(); 16820 if (!BitWidth) { 16821 InvalidDecl = true; 16822 BitWidth = nullptr; 16823 ZeroWidth = false; 16824 } 16825 } 16826 16827 // Check that 'mutable' is consistent with the type of the declaration. 16828 if (!InvalidDecl && Mutable) { 16829 unsigned DiagID = 0; 16830 if (T->isReferenceType()) 16831 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16832 : diag::err_mutable_reference; 16833 else if (T.isConstQualified()) 16834 DiagID = diag::err_mutable_const; 16835 16836 if (DiagID) { 16837 SourceLocation ErrLoc = Loc; 16838 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16839 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16840 Diag(ErrLoc, DiagID); 16841 if (DiagID != diag::ext_mutable_reference) { 16842 Mutable = false; 16843 InvalidDecl = true; 16844 } 16845 } 16846 } 16847 16848 // C++11 [class.union]p8 (DR1460): 16849 // At most one variant member of a union may have a 16850 // brace-or-equal-initializer. 16851 if (InitStyle != ICIS_NoInit) 16852 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16853 16854 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16855 BitWidth, Mutable, InitStyle); 16856 if (InvalidDecl) 16857 NewFD->setInvalidDecl(); 16858 16859 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16860 Diag(Loc, diag::err_duplicate_member) << II; 16861 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16862 NewFD->setInvalidDecl(); 16863 } 16864 16865 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16866 if (Record->isUnion()) { 16867 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16868 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16869 if (RDecl->getDefinition()) { 16870 // C++ [class.union]p1: An object of a class with a non-trivial 16871 // constructor, a non-trivial copy constructor, a non-trivial 16872 // destructor, or a non-trivial copy assignment operator 16873 // cannot be a member of a union, nor can an array of such 16874 // objects. 16875 if (CheckNontrivialField(NewFD)) 16876 NewFD->setInvalidDecl(); 16877 } 16878 } 16879 16880 // C++ [class.union]p1: If a union contains a member of reference type, 16881 // the program is ill-formed, except when compiling with MSVC extensions 16882 // enabled. 16883 if (EltTy->isReferenceType()) { 16884 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16885 diag::ext_union_member_of_reference_type : 16886 diag::err_union_member_of_reference_type) 16887 << NewFD->getDeclName() << EltTy; 16888 if (!getLangOpts().MicrosoftExt) 16889 NewFD->setInvalidDecl(); 16890 } 16891 } 16892 } 16893 16894 // FIXME: We need to pass in the attributes given an AST 16895 // representation, not a parser representation. 16896 if (D) { 16897 // FIXME: The current scope is almost... but not entirely... correct here. 16898 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16899 16900 if (NewFD->hasAttrs()) 16901 CheckAlignasUnderalignment(NewFD); 16902 } 16903 16904 // In auto-retain/release, infer strong retension for fields of 16905 // retainable type. 16906 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16907 NewFD->setInvalidDecl(); 16908 16909 if (T.isObjCGCWeak()) 16910 Diag(Loc, diag::warn_attribute_weak_on_field); 16911 16912 // PPC MMA non-pointer types are not allowed as field types. 16913 if (Context.getTargetInfo().getTriple().isPPC64() && 16914 CheckPPCMMAType(T, NewFD->getLocation())) 16915 NewFD->setInvalidDecl(); 16916 16917 NewFD->setAccess(AS); 16918 return NewFD; 16919 } 16920 16921 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16922 assert(FD); 16923 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16924 16925 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16926 return false; 16927 16928 QualType EltTy = Context.getBaseElementType(FD->getType()); 16929 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16930 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16931 if (RDecl->getDefinition()) { 16932 // We check for copy constructors before constructors 16933 // because otherwise we'll never get complaints about 16934 // copy constructors. 16935 16936 CXXSpecialMember member = CXXInvalid; 16937 // We're required to check for any non-trivial constructors. Since the 16938 // implicit default constructor is suppressed if there are any 16939 // user-declared constructors, we just need to check that there is a 16940 // trivial default constructor and a trivial copy constructor. (We don't 16941 // worry about move constructors here, since this is a C++98 check.) 16942 if (RDecl->hasNonTrivialCopyConstructor()) 16943 member = CXXCopyConstructor; 16944 else if (!RDecl->hasTrivialDefaultConstructor()) 16945 member = CXXDefaultConstructor; 16946 else if (RDecl->hasNonTrivialCopyAssignment()) 16947 member = CXXCopyAssignment; 16948 else if (RDecl->hasNonTrivialDestructor()) 16949 member = CXXDestructor; 16950 16951 if (member != CXXInvalid) { 16952 if (!getLangOpts().CPlusPlus11 && 16953 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16954 // Objective-C++ ARC: it is an error to have a non-trivial field of 16955 // a union. However, system headers in Objective-C programs 16956 // occasionally have Objective-C lifetime objects within unions, 16957 // and rather than cause the program to fail, we make those 16958 // members unavailable. 16959 SourceLocation Loc = FD->getLocation(); 16960 if (getSourceManager().isInSystemHeader(Loc)) { 16961 if (!FD->hasAttr<UnavailableAttr>()) 16962 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16963 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16964 return false; 16965 } 16966 } 16967 16968 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16969 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16970 diag::err_illegal_union_or_anon_struct_member) 16971 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16972 DiagnoseNontrivial(RDecl, member); 16973 return !getLangOpts().CPlusPlus11; 16974 } 16975 } 16976 } 16977 16978 return false; 16979 } 16980 16981 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16982 /// AST enum value. 16983 static ObjCIvarDecl::AccessControl 16984 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16985 switch (ivarVisibility) { 16986 default: llvm_unreachable("Unknown visitibility kind"); 16987 case tok::objc_private: return ObjCIvarDecl::Private; 16988 case tok::objc_public: return ObjCIvarDecl::Public; 16989 case tok::objc_protected: return ObjCIvarDecl::Protected; 16990 case tok::objc_package: return ObjCIvarDecl::Package; 16991 } 16992 } 16993 16994 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16995 /// in order to create an IvarDecl object for it. 16996 Decl *Sema::ActOnIvar(Scope *S, 16997 SourceLocation DeclStart, 16998 Declarator &D, Expr *BitfieldWidth, 16999 tok::ObjCKeywordKind Visibility) { 17000 17001 IdentifierInfo *II = D.getIdentifier(); 17002 Expr *BitWidth = (Expr*)BitfieldWidth; 17003 SourceLocation Loc = DeclStart; 17004 if (II) Loc = D.getIdentifierLoc(); 17005 17006 // FIXME: Unnamed fields can be handled in various different ways, for 17007 // example, unnamed unions inject all members into the struct namespace! 17008 17009 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17010 QualType T = TInfo->getType(); 17011 17012 if (BitWidth) { 17013 // 6.7.2.1p3, 6.7.2.1p4 17014 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 17015 if (!BitWidth) 17016 D.setInvalidType(); 17017 } else { 17018 // Not a bitfield. 17019 17020 // validate II. 17021 17022 } 17023 if (T->isReferenceType()) { 17024 Diag(Loc, diag::err_ivar_reference_type); 17025 D.setInvalidType(); 17026 } 17027 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17028 // than a variably modified type. 17029 else if (T->isVariablyModifiedType()) { 17030 if (!tryToFixVariablyModifiedVarType( 17031 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 17032 D.setInvalidType(); 17033 } 17034 17035 // Get the visibility (access control) for this ivar. 17036 ObjCIvarDecl::AccessControl ac = 17037 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 17038 : ObjCIvarDecl::None; 17039 // Must set ivar's DeclContext to its enclosing interface. 17040 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 17041 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 17042 return nullptr; 17043 ObjCContainerDecl *EnclosingContext; 17044 if (ObjCImplementationDecl *IMPDecl = 17045 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17046 if (LangOpts.ObjCRuntime.isFragile()) { 17047 // Case of ivar declared in an implementation. Context is that of its class. 17048 EnclosingContext = IMPDecl->getClassInterface(); 17049 assert(EnclosingContext && "Implementation has no class interface!"); 17050 } 17051 else 17052 EnclosingContext = EnclosingDecl; 17053 } else { 17054 if (ObjCCategoryDecl *CDecl = 17055 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17056 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 17057 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 17058 return nullptr; 17059 } 17060 } 17061 EnclosingContext = EnclosingDecl; 17062 } 17063 17064 // Construct the decl. 17065 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 17066 DeclStart, Loc, II, T, 17067 TInfo, ac, (Expr *)BitfieldWidth); 17068 17069 if (II) { 17070 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 17071 ForVisibleRedeclaration); 17072 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 17073 && !isa<TagDecl>(PrevDecl)) { 17074 Diag(Loc, diag::err_duplicate_member) << II; 17075 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17076 NewID->setInvalidDecl(); 17077 } 17078 } 17079 17080 // Process attributes attached to the ivar. 17081 ProcessDeclAttributes(S, NewID, D); 17082 17083 if (D.isInvalidType()) 17084 NewID->setInvalidDecl(); 17085 17086 // In ARC, infer 'retaining' for ivars of retainable type. 17087 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 17088 NewID->setInvalidDecl(); 17089 17090 if (D.getDeclSpec().isModulePrivateSpecified()) 17091 NewID->setModulePrivate(); 17092 17093 if (II) { 17094 // FIXME: When interfaces are DeclContexts, we'll need to add 17095 // these to the interface. 17096 S->AddDecl(NewID); 17097 IdResolver.AddDecl(NewID); 17098 } 17099 17100 if (LangOpts.ObjCRuntime.isNonFragile() && 17101 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17102 Diag(Loc, diag::warn_ivars_in_interface); 17103 17104 return NewID; 17105 } 17106 17107 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17108 /// class and class extensions. For every class \@interface and class 17109 /// extension \@interface, if the last ivar is a bitfield of any type, 17110 /// then add an implicit `char :0` ivar to the end of that interface. 17111 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17112 SmallVectorImpl<Decl *> &AllIvarDecls) { 17113 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17114 return; 17115 17116 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17117 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17118 17119 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17120 return; 17121 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17122 if (!ID) { 17123 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17124 if (!CD->IsClassExtension()) 17125 return; 17126 } 17127 // No need to add this to end of @implementation. 17128 else 17129 return; 17130 } 17131 // All conditions are met. Add a new bitfield to the tail end of ivars. 17132 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17133 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17134 17135 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17136 DeclLoc, DeclLoc, nullptr, 17137 Context.CharTy, 17138 Context.getTrivialTypeSourceInfo(Context.CharTy, 17139 DeclLoc), 17140 ObjCIvarDecl::Private, BW, 17141 true); 17142 AllIvarDecls.push_back(Ivar); 17143 } 17144 17145 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17146 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17147 SourceLocation RBrac, 17148 const ParsedAttributesView &Attrs) { 17149 assert(EnclosingDecl && "missing record or interface decl"); 17150 17151 // If this is an Objective-C @implementation or category and we have 17152 // new fields here we should reset the layout of the interface since 17153 // it will now change. 17154 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17155 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17156 switch (DC->getKind()) { 17157 default: break; 17158 case Decl::ObjCCategory: 17159 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17160 break; 17161 case Decl::ObjCImplementation: 17162 Context. 17163 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17164 break; 17165 } 17166 } 17167 17168 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17169 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17170 17171 // Start counting up the number of named members; make sure to include 17172 // members of anonymous structs and unions in the total. 17173 unsigned NumNamedMembers = 0; 17174 if (Record) { 17175 for (const auto *I : Record->decls()) { 17176 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17177 if (IFD->getDeclName()) 17178 ++NumNamedMembers; 17179 } 17180 } 17181 17182 // Verify that all the fields are okay. 17183 SmallVector<FieldDecl*, 32> RecFields; 17184 17185 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17186 i != end; ++i) { 17187 FieldDecl *FD = cast<FieldDecl>(*i); 17188 17189 // Get the type for the field. 17190 const Type *FDTy = FD->getType().getTypePtr(); 17191 17192 if (!FD->isAnonymousStructOrUnion()) { 17193 // Remember all fields written by the user. 17194 RecFields.push_back(FD); 17195 } 17196 17197 // If the field is already invalid for some reason, don't emit more 17198 // diagnostics about it. 17199 if (FD->isInvalidDecl()) { 17200 EnclosingDecl->setInvalidDecl(); 17201 continue; 17202 } 17203 17204 // C99 6.7.2.1p2: 17205 // A structure or union shall not contain a member with 17206 // incomplete or function type (hence, a structure shall not 17207 // contain an instance of itself, but may contain a pointer to 17208 // an instance of itself), except that the last member of a 17209 // structure with more than one named member may have incomplete 17210 // array type; such a structure (and any union containing, 17211 // possibly recursively, a member that is such a structure) 17212 // shall not be a member of a structure or an element of an 17213 // array. 17214 bool IsLastField = (i + 1 == Fields.end()); 17215 if (FDTy->isFunctionType()) { 17216 // Field declared as a function. 17217 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17218 << FD->getDeclName(); 17219 FD->setInvalidDecl(); 17220 EnclosingDecl->setInvalidDecl(); 17221 continue; 17222 } else if (FDTy->isIncompleteArrayType() && 17223 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17224 if (Record) { 17225 // Flexible array member. 17226 // Microsoft and g++ is more permissive regarding flexible array. 17227 // It will accept flexible array in union and also 17228 // as the sole element of a struct/class. 17229 unsigned DiagID = 0; 17230 if (!Record->isUnion() && !IsLastField) { 17231 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17232 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17233 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17234 FD->setInvalidDecl(); 17235 EnclosingDecl->setInvalidDecl(); 17236 continue; 17237 } else if (Record->isUnion()) 17238 DiagID = getLangOpts().MicrosoftExt 17239 ? diag::ext_flexible_array_union_ms 17240 : getLangOpts().CPlusPlus 17241 ? diag::ext_flexible_array_union_gnu 17242 : diag::err_flexible_array_union; 17243 else if (NumNamedMembers < 1) 17244 DiagID = getLangOpts().MicrosoftExt 17245 ? diag::ext_flexible_array_empty_aggregate_ms 17246 : getLangOpts().CPlusPlus 17247 ? diag::ext_flexible_array_empty_aggregate_gnu 17248 : diag::err_flexible_array_empty_aggregate; 17249 17250 if (DiagID) 17251 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17252 << Record->getTagKind(); 17253 // While the layout of types that contain virtual bases is not specified 17254 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17255 // virtual bases after the derived members. This would make a flexible 17256 // array member declared at the end of an object not adjacent to the end 17257 // of the type. 17258 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17259 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17260 << FD->getDeclName() << Record->getTagKind(); 17261 if (!getLangOpts().C99) 17262 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17263 << FD->getDeclName() << Record->getTagKind(); 17264 17265 // If the element type has a non-trivial destructor, we would not 17266 // implicitly destroy the elements, so disallow it for now. 17267 // 17268 // FIXME: GCC allows this. We should probably either implicitly delete 17269 // the destructor of the containing class, or just allow this. 17270 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17271 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17272 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17273 << FD->getDeclName() << FD->getType(); 17274 FD->setInvalidDecl(); 17275 EnclosingDecl->setInvalidDecl(); 17276 continue; 17277 } 17278 // Okay, we have a legal flexible array member at the end of the struct. 17279 Record->setHasFlexibleArrayMember(true); 17280 } else { 17281 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17282 // unless they are followed by another ivar. That check is done 17283 // elsewhere, after synthesized ivars are known. 17284 } 17285 } else if (!FDTy->isDependentType() && 17286 RequireCompleteSizedType( 17287 FD->getLocation(), FD->getType(), 17288 diag::err_field_incomplete_or_sizeless)) { 17289 // Incomplete type 17290 FD->setInvalidDecl(); 17291 EnclosingDecl->setInvalidDecl(); 17292 continue; 17293 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17294 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17295 // A type which contains a flexible array member is considered to be a 17296 // flexible array member. 17297 Record->setHasFlexibleArrayMember(true); 17298 if (!Record->isUnion()) { 17299 // If this is a struct/class and this is not the last element, reject 17300 // it. Note that GCC supports variable sized arrays in the middle of 17301 // structures. 17302 if (!IsLastField) 17303 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17304 << FD->getDeclName() << FD->getType(); 17305 else { 17306 // We support flexible arrays at the end of structs in 17307 // other structs as an extension. 17308 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17309 << FD->getDeclName(); 17310 } 17311 } 17312 } 17313 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17314 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17315 diag::err_abstract_type_in_decl, 17316 AbstractIvarType)) { 17317 // Ivars can not have abstract class types 17318 FD->setInvalidDecl(); 17319 } 17320 if (Record && FDTTy->getDecl()->hasObjectMember()) 17321 Record->setHasObjectMember(true); 17322 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17323 Record->setHasVolatileMember(true); 17324 } else if (FDTy->isObjCObjectType()) { 17325 /// A field cannot be an Objective-c object 17326 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17327 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17328 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17329 FD->setType(T); 17330 } else if (Record && Record->isUnion() && 17331 FD->getType().hasNonTrivialObjCLifetime() && 17332 getSourceManager().isInSystemHeader(FD->getLocation()) && 17333 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17334 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17335 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17336 // For backward compatibility, fields of C unions declared in system 17337 // headers that have non-trivial ObjC ownership qualifications are marked 17338 // as unavailable unless the qualifier is explicit and __strong. This can 17339 // break ABI compatibility between programs compiled with ARC and MRR, but 17340 // is a better option than rejecting programs using those unions under 17341 // ARC. 17342 FD->addAttr(UnavailableAttr::CreateImplicit( 17343 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17344 FD->getLocation())); 17345 } else if (getLangOpts().ObjC && 17346 getLangOpts().getGC() != LangOptions::NonGC && Record && 17347 !Record->hasObjectMember()) { 17348 if (FD->getType()->isObjCObjectPointerType() || 17349 FD->getType().isObjCGCStrong()) 17350 Record->setHasObjectMember(true); 17351 else if (Context.getAsArrayType(FD->getType())) { 17352 QualType BaseType = Context.getBaseElementType(FD->getType()); 17353 if (BaseType->isRecordType() && 17354 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17355 Record->setHasObjectMember(true); 17356 else if (BaseType->isObjCObjectPointerType() || 17357 BaseType.isObjCGCStrong()) 17358 Record->setHasObjectMember(true); 17359 } 17360 } 17361 17362 if (Record && !getLangOpts().CPlusPlus && 17363 !shouldIgnoreForRecordTriviality(FD)) { 17364 QualType FT = FD->getType(); 17365 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17366 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17367 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17368 Record->isUnion()) 17369 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17370 } 17371 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17372 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17373 Record->setNonTrivialToPrimitiveCopy(true); 17374 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17375 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17376 } 17377 if (FT.isDestructedType()) { 17378 Record->setNonTrivialToPrimitiveDestroy(true); 17379 Record->setParamDestroyedInCallee(true); 17380 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17381 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17382 } 17383 17384 if (const auto *RT = FT->getAs<RecordType>()) { 17385 if (RT->getDecl()->getArgPassingRestrictions() == 17386 RecordDecl::APK_CanNeverPassInRegs) 17387 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17388 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17389 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17390 } 17391 17392 if (Record && FD->getType().isVolatileQualified()) 17393 Record->setHasVolatileMember(true); 17394 // Keep track of the number of named members. 17395 if (FD->getIdentifier()) 17396 ++NumNamedMembers; 17397 } 17398 17399 // Okay, we successfully defined 'Record'. 17400 if (Record) { 17401 bool Completed = false; 17402 if (CXXRecord) { 17403 if (!CXXRecord->isInvalidDecl()) { 17404 // Set access bits correctly on the directly-declared conversions. 17405 for (CXXRecordDecl::conversion_iterator 17406 I = CXXRecord->conversion_begin(), 17407 E = CXXRecord->conversion_end(); I != E; ++I) 17408 I.setAccess((*I)->getAccess()); 17409 } 17410 17411 // Add any implicitly-declared members to this class. 17412 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17413 17414 if (!CXXRecord->isDependentType()) { 17415 if (!CXXRecord->isInvalidDecl()) { 17416 // If we have virtual base classes, we may end up finding multiple 17417 // final overriders for a given virtual function. Check for this 17418 // problem now. 17419 if (CXXRecord->getNumVBases()) { 17420 CXXFinalOverriderMap FinalOverriders; 17421 CXXRecord->getFinalOverriders(FinalOverriders); 17422 17423 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17424 MEnd = FinalOverriders.end(); 17425 M != MEnd; ++M) { 17426 for (OverridingMethods::iterator SO = M->second.begin(), 17427 SOEnd = M->second.end(); 17428 SO != SOEnd; ++SO) { 17429 assert(SO->second.size() > 0 && 17430 "Virtual function without overriding functions?"); 17431 if (SO->second.size() == 1) 17432 continue; 17433 17434 // C++ [class.virtual]p2: 17435 // In a derived class, if a virtual member function of a base 17436 // class subobject has more than one final overrider the 17437 // program is ill-formed. 17438 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17439 << (const NamedDecl *)M->first << Record; 17440 Diag(M->first->getLocation(), 17441 diag::note_overridden_virtual_function); 17442 for (OverridingMethods::overriding_iterator 17443 OM = SO->second.begin(), 17444 OMEnd = SO->second.end(); 17445 OM != OMEnd; ++OM) 17446 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17447 << (const NamedDecl *)M->first << OM->Method->getParent(); 17448 17449 Record->setInvalidDecl(); 17450 } 17451 } 17452 CXXRecord->completeDefinition(&FinalOverriders); 17453 Completed = true; 17454 } 17455 } 17456 } 17457 } 17458 17459 if (!Completed) 17460 Record->completeDefinition(); 17461 17462 // Handle attributes before checking the layout. 17463 ProcessDeclAttributeList(S, Record, Attrs); 17464 17465 // We may have deferred checking for a deleted destructor. Check now. 17466 if (CXXRecord) { 17467 auto *Dtor = CXXRecord->getDestructor(); 17468 if (Dtor && Dtor->isImplicit() && 17469 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17470 CXXRecord->setImplicitDestructorIsDeleted(); 17471 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17472 } 17473 } 17474 17475 if (Record->hasAttrs()) { 17476 CheckAlignasUnderalignment(Record); 17477 17478 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17479 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17480 IA->getRange(), IA->getBestCase(), 17481 IA->getInheritanceModel()); 17482 } 17483 17484 // Check if the structure/union declaration is a type that can have zero 17485 // size in C. For C this is a language extension, for C++ it may cause 17486 // compatibility problems. 17487 bool CheckForZeroSize; 17488 if (!getLangOpts().CPlusPlus) { 17489 CheckForZeroSize = true; 17490 } else { 17491 // For C++ filter out types that cannot be referenced in C code. 17492 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17493 CheckForZeroSize = 17494 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17495 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 17496 CXXRecord->isCLike(); 17497 } 17498 if (CheckForZeroSize) { 17499 bool ZeroSize = true; 17500 bool IsEmpty = true; 17501 unsigned NonBitFields = 0; 17502 for (RecordDecl::field_iterator I = Record->field_begin(), 17503 E = Record->field_end(); 17504 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17505 IsEmpty = false; 17506 if (I->isUnnamedBitfield()) { 17507 if (!I->isZeroLengthBitField(Context)) 17508 ZeroSize = false; 17509 } else { 17510 ++NonBitFields; 17511 QualType FieldType = I->getType(); 17512 if (FieldType->isIncompleteType() || 17513 !Context.getTypeSizeInChars(FieldType).isZero()) 17514 ZeroSize = false; 17515 } 17516 } 17517 17518 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17519 // allowed in C++, but warn if its declaration is inside 17520 // extern "C" block. 17521 if (ZeroSize) { 17522 Diag(RecLoc, getLangOpts().CPlusPlus ? 17523 diag::warn_zero_size_struct_union_in_extern_c : 17524 diag::warn_zero_size_struct_union_compat) 17525 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17526 } 17527 17528 // Structs without named members are extension in C (C99 6.7.2.1p7), 17529 // but are accepted by GCC. 17530 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17531 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17532 diag::ext_no_named_members_in_struct_union) 17533 << Record->isUnion(); 17534 } 17535 } 17536 } else { 17537 ObjCIvarDecl **ClsFields = 17538 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17539 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17540 ID->setEndOfDefinitionLoc(RBrac); 17541 // Add ivar's to class's DeclContext. 17542 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17543 ClsFields[i]->setLexicalDeclContext(ID); 17544 ID->addDecl(ClsFields[i]); 17545 } 17546 // Must enforce the rule that ivars in the base classes may not be 17547 // duplicates. 17548 if (ID->getSuperClass()) 17549 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17550 } else if (ObjCImplementationDecl *IMPDecl = 17551 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17552 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17553 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17554 // Ivar declared in @implementation never belongs to the implementation. 17555 // Only it is in implementation's lexical context. 17556 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17557 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17558 IMPDecl->setIvarLBraceLoc(LBrac); 17559 IMPDecl->setIvarRBraceLoc(RBrac); 17560 } else if (ObjCCategoryDecl *CDecl = 17561 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17562 // case of ivars in class extension; all other cases have been 17563 // reported as errors elsewhere. 17564 // FIXME. Class extension does not have a LocEnd field. 17565 // CDecl->setLocEnd(RBrac); 17566 // Add ivar's to class extension's DeclContext. 17567 // Diagnose redeclaration of private ivars. 17568 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17569 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17570 if (IDecl) { 17571 if (const ObjCIvarDecl *ClsIvar = 17572 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17573 Diag(ClsFields[i]->getLocation(), 17574 diag::err_duplicate_ivar_declaration); 17575 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17576 continue; 17577 } 17578 for (const auto *Ext : IDecl->known_extensions()) { 17579 if (const ObjCIvarDecl *ClsExtIvar 17580 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17581 Diag(ClsFields[i]->getLocation(), 17582 diag::err_duplicate_ivar_declaration); 17583 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17584 continue; 17585 } 17586 } 17587 } 17588 ClsFields[i]->setLexicalDeclContext(CDecl); 17589 CDecl->addDecl(ClsFields[i]); 17590 } 17591 CDecl->setIvarLBraceLoc(LBrac); 17592 CDecl->setIvarRBraceLoc(RBrac); 17593 } 17594 } 17595 } 17596 17597 /// Determine whether the given integral value is representable within 17598 /// the given type T. 17599 static bool isRepresentableIntegerValue(ASTContext &Context, 17600 llvm::APSInt &Value, 17601 QualType T) { 17602 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17603 "Integral type required!"); 17604 unsigned BitWidth = Context.getIntWidth(T); 17605 17606 if (Value.isUnsigned() || Value.isNonNegative()) { 17607 if (T->isSignedIntegerOrEnumerationType()) 17608 --BitWidth; 17609 return Value.getActiveBits() <= BitWidth; 17610 } 17611 return Value.getMinSignedBits() <= BitWidth; 17612 } 17613 17614 // Given an integral type, return the next larger integral type 17615 // (or a NULL type of no such type exists). 17616 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17617 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17618 // enum checking below. 17619 assert((T->isIntegralType(Context) || 17620 T->isEnumeralType()) && "Integral type required!"); 17621 const unsigned NumTypes = 4; 17622 QualType SignedIntegralTypes[NumTypes] = { 17623 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17624 }; 17625 QualType UnsignedIntegralTypes[NumTypes] = { 17626 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17627 Context.UnsignedLongLongTy 17628 }; 17629 17630 unsigned BitWidth = Context.getTypeSize(T); 17631 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17632 : UnsignedIntegralTypes; 17633 for (unsigned I = 0; I != NumTypes; ++I) 17634 if (Context.getTypeSize(Types[I]) > BitWidth) 17635 return Types[I]; 17636 17637 return QualType(); 17638 } 17639 17640 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17641 EnumConstantDecl *LastEnumConst, 17642 SourceLocation IdLoc, 17643 IdentifierInfo *Id, 17644 Expr *Val) { 17645 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17646 llvm::APSInt EnumVal(IntWidth); 17647 QualType EltTy; 17648 17649 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17650 Val = nullptr; 17651 17652 if (Val) 17653 Val = DefaultLvalueConversion(Val).get(); 17654 17655 if (Val) { 17656 if (Enum->isDependentType() || Val->isTypeDependent()) 17657 EltTy = Context.DependentTy; 17658 else { 17659 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 17660 // underlying type, but do allow it in all other contexts. 17661 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17662 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17663 // constant-expression in the enumerator-definition shall be a converted 17664 // constant expression of the underlying type. 17665 EltTy = Enum->getIntegerType(); 17666 ExprResult Converted = 17667 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17668 CCEK_Enumerator); 17669 if (Converted.isInvalid()) 17670 Val = nullptr; 17671 else 17672 Val = Converted.get(); 17673 } else if (!Val->isValueDependent() && 17674 !(Val = 17675 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 17676 .get())) { 17677 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17678 } else { 17679 if (Enum->isComplete()) { 17680 EltTy = Enum->getIntegerType(); 17681 17682 // In Obj-C and Microsoft mode, require the enumeration value to be 17683 // representable in the underlying type of the enumeration. In C++11, 17684 // we perform a non-narrowing conversion as part of converted constant 17685 // expression checking. 17686 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17687 if (Context.getTargetInfo() 17688 .getTriple() 17689 .isWindowsMSVCEnvironment()) { 17690 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17691 } else { 17692 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17693 } 17694 } 17695 17696 // Cast to the underlying type. 17697 Val = ImpCastExprToType(Val, EltTy, 17698 EltTy->isBooleanType() ? CK_IntegralToBoolean 17699 : CK_IntegralCast) 17700 .get(); 17701 } else if (getLangOpts().CPlusPlus) { 17702 // C++11 [dcl.enum]p5: 17703 // If the underlying type is not fixed, the type of each enumerator 17704 // is the type of its initializing value: 17705 // - If an initializer is specified for an enumerator, the 17706 // initializing value has the same type as the expression. 17707 EltTy = Val->getType(); 17708 } else { 17709 // C99 6.7.2.2p2: 17710 // The expression that defines the value of an enumeration constant 17711 // shall be an integer constant expression that has a value 17712 // representable as an int. 17713 17714 // Complain if the value is not representable in an int. 17715 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17716 Diag(IdLoc, diag::ext_enum_value_not_int) 17717 << EnumVal.toString(10) << Val->getSourceRange() 17718 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17719 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17720 // Force the type of the expression to 'int'. 17721 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17722 } 17723 EltTy = Val->getType(); 17724 } 17725 } 17726 } 17727 } 17728 17729 if (!Val) { 17730 if (Enum->isDependentType()) 17731 EltTy = Context.DependentTy; 17732 else if (!LastEnumConst) { 17733 // C++0x [dcl.enum]p5: 17734 // If the underlying type is not fixed, the type of each enumerator 17735 // is the type of its initializing value: 17736 // - If no initializer is specified for the first enumerator, the 17737 // initializing value has an unspecified integral type. 17738 // 17739 // GCC uses 'int' for its unspecified integral type, as does 17740 // C99 6.7.2.2p3. 17741 if (Enum->isFixed()) { 17742 EltTy = Enum->getIntegerType(); 17743 } 17744 else { 17745 EltTy = Context.IntTy; 17746 } 17747 } else { 17748 // Assign the last value + 1. 17749 EnumVal = LastEnumConst->getInitVal(); 17750 ++EnumVal; 17751 EltTy = LastEnumConst->getType(); 17752 17753 // Check for overflow on increment. 17754 if (EnumVal < LastEnumConst->getInitVal()) { 17755 // C++0x [dcl.enum]p5: 17756 // If the underlying type is not fixed, the type of each enumerator 17757 // is the type of its initializing value: 17758 // 17759 // - Otherwise the type of the initializing value is the same as 17760 // the type of the initializing value of the preceding enumerator 17761 // unless the incremented value is not representable in that type, 17762 // in which case the type is an unspecified integral type 17763 // sufficient to contain the incremented value. If no such type 17764 // exists, the program is ill-formed. 17765 QualType T = getNextLargerIntegralType(Context, EltTy); 17766 if (T.isNull() || Enum->isFixed()) { 17767 // There is no integral type larger enough to represent this 17768 // value. Complain, then allow the value to wrap around. 17769 EnumVal = LastEnumConst->getInitVal(); 17770 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17771 ++EnumVal; 17772 if (Enum->isFixed()) 17773 // When the underlying type is fixed, this is ill-formed. 17774 Diag(IdLoc, diag::err_enumerator_wrapped) 17775 << EnumVal.toString(10) 17776 << EltTy; 17777 else 17778 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17779 << EnumVal.toString(10); 17780 } else { 17781 EltTy = T; 17782 } 17783 17784 // Retrieve the last enumerator's value, extent that type to the 17785 // type that is supposed to be large enough to represent the incremented 17786 // value, then increment. 17787 EnumVal = LastEnumConst->getInitVal(); 17788 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17789 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17790 ++EnumVal; 17791 17792 // If we're not in C++, diagnose the overflow of enumerator values, 17793 // which in C99 means that the enumerator value is not representable in 17794 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17795 // permits enumerator values that are representable in some larger 17796 // integral type. 17797 if (!getLangOpts().CPlusPlus && !T.isNull()) 17798 Diag(IdLoc, diag::warn_enum_value_overflow); 17799 } else if (!getLangOpts().CPlusPlus && 17800 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17801 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17802 Diag(IdLoc, diag::ext_enum_value_not_int) 17803 << EnumVal.toString(10) << 1; 17804 } 17805 } 17806 } 17807 17808 if (!EltTy->isDependentType()) { 17809 // Make the enumerator value match the signedness and size of the 17810 // enumerator's type. 17811 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17812 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17813 } 17814 17815 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17816 Val, EnumVal); 17817 } 17818 17819 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17820 SourceLocation IILoc) { 17821 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17822 !getLangOpts().CPlusPlus) 17823 return SkipBodyInfo(); 17824 17825 // We have an anonymous enum definition. Look up the first enumerator to 17826 // determine if we should merge the definition with an existing one and 17827 // skip the body. 17828 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17829 forRedeclarationInCurContext()); 17830 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17831 if (!PrevECD) 17832 return SkipBodyInfo(); 17833 17834 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17835 NamedDecl *Hidden; 17836 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17837 SkipBodyInfo Skip; 17838 Skip.Previous = Hidden; 17839 return Skip; 17840 } 17841 17842 return SkipBodyInfo(); 17843 } 17844 17845 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17846 SourceLocation IdLoc, IdentifierInfo *Id, 17847 const ParsedAttributesView &Attrs, 17848 SourceLocation EqualLoc, Expr *Val) { 17849 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17850 EnumConstantDecl *LastEnumConst = 17851 cast_or_null<EnumConstantDecl>(lastEnumConst); 17852 17853 // The scope passed in may not be a decl scope. Zip up the scope tree until 17854 // we find one that is. 17855 S = getNonFieldDeclScope(S); 17856 17857 // Verify that there isn't already something declared with this name in this 17858 // scope. 17859 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17860 LookupName(R, S); 17861 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17862 17863 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17864 // Maybe we will complain about the shadowed template parameter. 17865 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17866 // Just pretend that we didn't see the previous declaration. 17867 PrevDecl = nullptr; 17868 } 17869 17870 // C++ [class.mem]p15: 17871 // If T is the name of a class, then each of the following shall have a name 17872 // different from T: 17873 // - every enumerator of every member of class T that is an unscoped 17874 // enumerated type 17875 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17876 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17877 DeclarationNameInfo(Id, IdLoc)); 17878 17879 EnumConstantDecl *New = 17880 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17881 if (!New) 17882 return nullptr; 17883 17884 if (PrevDecl) { 17885 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17886 // Check for other kinds of shadowing not already handled. 17887 CheckShadow(New, PrevDecl, R); 17888 } 17889 17890 // When in C++, we may get a TagDecl with the same name; in this case the 17891 // enum constant will 'hide' the tag. 17892 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17893 "Received TagDecl when not in C++!"); 17894 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17895 if (isa<EnumConstantDecl>(PrevDecl)) 17896 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17897 else 17898 Diag(IdLoc, diag::err_redefinition) << Id; 17899 notePreviousDefinition(PrevDecl, IdLoc); 17900 return nullptr; 17901 } 17902 } 17903 17904 // Process attributes. 17905 ProcessDeclAttributeList(S, New, Attrs); 17906 AddPragmaAttributes(S, New); 17907 17908 // Register this decl in the current scope stack. 17909 New->setAccess(TheEnumDecl->getAccess()); 17910 PushOnScopeChains(New, S); 17911 17912 ActOnDocumentableDecl(New); 17913 17914 return New; 17915 } 17916 17917 // Returns true when the enum initial expression does not trigger the 17918 // duplicate enum warning. A few common cases are exempted as follows: 17919 // Element2 = Element1 17920 // Element2 = Element1 + 1 17921 // Element2 = Element1 - 1 17922 // Where Element2 and Element1 are from the same enum. 17923 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17924 Expr *InitExpr = ECD->getInitExpr(); 17925 if (!InitExpr) 17926 return true; 17927 InitExpr = InitExpr->IgnoreImpCasts(); 17928 17929 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17930 if (!BO->isAdditiveOp()) 17931 return true; 17932 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17933 if (!IL) 17934 return true; 17935 if (IL->getValue() != 1) 17936 return true; 17937 17938 InitExpr = BO->getLHS(); 17939 } 17940 17941 // This checks if the elements are from the same enum. 17942 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17943 if (!DRE) 17944 return true; 17945 17946 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17947 if (!EnumConstant) 17948 return true; 17949 17950 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17951 Enum) 17952 return true; 17953 17954 return false; 17955 } 17956 17957 // Emits a warning when an element is implicitly set a value that 17958 // a previous element has already been set to. 17959 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17960 EnumDecl *Enum, QualType EnumType) { 17961 // Avoid anonymous enums 17962 if (!Enum->getIdentifier()) 17963 return; 17964 17965 // Only check for small enums. 17966 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17967 return; 17968 17969 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17970 return; 17971 17972 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17973 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17974 17975 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17976 17977 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 17978 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17979 17980 // Use int64_t as a key to avoid needing special handling for map keys. 17981 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17982 llvm::APSInt Val = D->getInitVal(); 17983 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17984 }; 17985 17986 DuplicatesVector DupVector; 17987 ValueToVectorMap EnumMap; 17988 17989 // Populate the EnumMap with all values represented by enum constants without 17990 // an initializer. 17991 for (auto *Element : Elements) { 17992 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17993 17994 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17995 // this constant. Skip this enum since it may be ill-formed. 17996 if (!ECD) { 17997 return; 17998 } 17999 18000 // Constants with initalizers are handled in the next loop. 18001 if (ECD->getInitExpr()) 18002 continue; 18003 18004 // Duplicate values are handled in the next loop. 18005 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 18006 } 18007 18008 if (EnumMap.size() == 0) 18009 return; 18010 18011 // Create vectors for any values that has duplicates. 18012 for (auto *Element : Elements) { 18013 // The last loop returned if any constant was null. 18014 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 18015 if (!ValidDuplicateEnum(ECD, Enum)) 18016 continue; 18017 18018 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 18019 if (Iter == EnumMap.end()) 18020 continue; 18021 18022 DeclOrVector& Entry = Iter->second; 18023 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 18024 // Ensure constants are different. 18025 if (D == ECD) 18026 continue; 18027 18028 // Create new vector and push values onto it. 18029 auto Vec = std::make_unique<ECDVector>(); 18030 Vec->push_back(D); 18031 Vec->push_back(ECD); 18032 18033 // Update entry to point to the duplicates vector. 18034 Entry = Vec.get(); 18035 18036 // Store the vector somewhere we can consult later for quick emission of 18037 // diagnostics. 18038 DupVector.emplace_back(std::move(Vec)); 18039 continue; 18040 } 18041 18042 ECDVector *Vec = Entry.get<ECDVector*>(); 18043 // Make sure constants are not added more than once. 18044 if (*Vec->begin() == ECD) 18045 continue; 18046 18047 Vec->push_back(ECD); 18048 } 18049 18050 // Emit diagnostics. 18051 for (const auto &Vec : DupVector) { 18052 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 18053 18054 // Emit warning for one enum constant. 18055 auto *FirstECD = Vec->front(); 18056 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 18057 << FirstECD << FirstECD->getInitVal().toString(10) 18058 << FirstECD->getSourceRange(); 18059 18060 // Emit one note for each of the remaining enum constants with 18061 // the same value. 18062 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 18063 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 18064 << ECD << ECD->getInitVal().toString(10) 18065 << ECD->getSourceRange(); 18066 } 18067 } 18068 18069 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 18070 bool AllowMask) const { 18071 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 18072 assert(ED->isCompleteDefinition() && "expected enum definition"); 18073 18074 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 18075 llvm::APInt &FlagBits = R.first->second; 18076 18077 if (R.second) { 18078 for (auto *E : ED->enumerators()) { 18079 const auto &EVal = E->getInitVal(); 18080 // Only single-bit enumerators introduce new flag values. 18081 if (EVal.isPowerOf2()) 18082 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 18083 } 18084 } 18085 18086 // A value is in a flag enum if either its bits are a subset of the enum's 18087 // flag bits (the first condition) or we are allowing masks and the same is 18088 // true of its complement (the second condition). When masks are allowed, we 18089 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 18090 // 18091 // While it's true that any value could be used as a mask, the assumption is 18092 // that a mask will have all of the insignificant bits set. Anything else is 18093 // likely a logic error. 18094 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18095 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18096 } 18097 18098 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18099 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18100 const ParsedAttributesView &Attrs) { 18101 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18102 QualType EnumType = Context.getTypeDeclType(Enum); 18103 18104 ProcessDeclAttributeList(S, Enum, Attrs); 18105 18106 if (Enum->isDependentType()) { 18107 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18108 EnumConstantDecl *ECD = 18109 cast_or_null<EnumConstantDecl>(Elements[i]); 18110 if (!ECD) continue; 18111 18112 ECD->setType(EnumType); 18113 } 18114 18115 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18116 return; 18117 } 18118 18119 // TODO: If the result value doesn't fit in an int, it must be a long or long 18120 // long value. ISO C does not support this, but GCC does as an extension, 18121 // emit a warning. 18122 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18123 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18124 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18125 18126 // Verify that all the values are okay, compute the size of the values, and 18127 // reverse the list. 18128 unsigned NumNegativeBits = 0; 18129 unsigned NumPositiveBits = 0; 18130 18131 // Keep track of whether all elements have type int. 18132 bool AllElementsInt = true; 18133 18134 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18135 EnumConstantDecl *ECD = 18136 cast_or_null<EnumConstantDecl>(Elements[i]); 18137 if (!ECD) continue; // Already issued a diagnostic. 18138 18139 const llvm::APSInt &InitVal = ECD->getInitVal(); 18140 18141 // Keep track of the size of positive and negative values. 18142 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18143 NumPositiveBits = std::max(NumPositiveBits, 18144 (unsigned)InitVal.getActiveBits()); 18145 else 18146 NumNegativeBits = std::max(NumNegativeBits, 18147 (unsigned)InitVal.getMinSignedBits()); 18148 18149 // Keep track of whether every enum element has type int (very common). 18150 if (AllElementsInt) 18151 AllElementsInt = ECD->getType() == Context.IntTy; 18152 } 18153 18154 // Figure out the type that should be used for this enum. 18155 QualType BestType; 18156 unsigned BestWidth; 18157 18158 // C++0x N3000 [conv.prom]p3: 18159 // An rvalue of an unscoped enumeration type whose underlying 18160 // type is not fixed can be converted to an rvalue of the first 18161 // of the following types that can represent all the values of 18162 // the enumeration: int, unsigned int, long int, unsigned long 18163 // int, long long int, or unsigned long long int. 18164 // C99 6.4.4.3p2: 18165 // An identifier declared as an enumeration constant has type int. 18166 // The C99 rule is modified by a gcc extension 18167 QualType BestPromotionType; 18168 18169 bool Packed = Enum->hasAttr<PackedAttr>(); 18170 // -fshort-enums is the equivalent to specifying the packed attribute on all 18171 // enum definitions. 18172 if (LangOpts.ShortEnums) 18173 Packed = true; 18174 18175 // If the enum already has a type because it is fixed or dictated by the 18176 // target, promote that type instead of analyzing the enumerators. 18177 if (Enum->isComplete()) { 18178 BestType = Enum->getIntegerType(); 18179 if (BestType->isPromotableIntegerType()) 18180 BestPromotionType = Context.getPromotedIntegerType(BestType); 18181 else 18182 BestPromotionType = BestType; 18183 18184 BestWidth = Context.getIntWidth(BestType); 18185 } 18186 else if (NumNegativeBits) { 18187 // If there is a negative value, figure out the smallest integer type (of 18188 // int/long/longlong) that fits. 18189 // If it's packed, check also if it fits a char or a short. 18190 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18191 BestType = Context.SignedCharTy; 18192 BestWidth = CharWidth; 18193 } else if (Packed && NumNegativeBits <= ShortWidth && 18194 NumPositiveBits < ShortWidth) { 18195 BestType = Context.ShortTy; 18196 BestWidth = ShortWidth; 18197 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18198 BestType = Context.IntTy; 18199 BestWidth = IntWidth; 18200 } else { 18201 BestWidth = Context.getTargetInfo().getLongWidth(); 18202 18203 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18204 BestType = Context.LongTy; 18205 } else { 18206 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18207 18208 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18209 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18210 BestType = Context.LongLongTy; 18211 } 18212 } 18213 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18214 } else { 18215 // If there is no negative value, figure out the smallest type that fits 18216 // all of the enumerator values. 18217 // If it's packed, check also if it fits a char or a short. 18218 if (Packed && NumPositiveBits <= CharWidth) { 18219 BestType = Context.UnsignedCharTy; 18220 BestPromotionType = Context.IntTy; 18221 BestWidth = CharWidth; 18222 } else if (Packed && NumPositiveBits <= ShortWidth) { 18223 BestType = Context.UnsignedShortTy; 18224 BestPromotionType = Context.IntTy; 18225 BestWidth = ShortWidth; 18226 } else if (NumPositiveBits <= IntWidth) { 18227 BestType = Context.UnsignedIntTy; 18228 BestWidth = IntWidth; 18229 BestPromotionType 18230 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18231 ? Context.UnsignedIntTy : Context.IntTy; 18232 } else if (NumPositiveBits <= 18233 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18234 BestType = Context.UnsignedLongTy; 18235 BestPromotionType 18236 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18237 ? Context.UnsignedLongTy : Context.LongTy; 18238 } else { 18239 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18240 assert(NumPositiveBits <= BestWidth && 18241 "How could an initializer get larger than ULL?"); 18242 BestType = Context.UnsignedLongLongTy; 18243 BestPromotionType 18244 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18245 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18246 } 18247 } 18248 18249 // Loop over all of the enumerator constants, changing their types to match 18250 // the type of the enum if needed. 18251 for (auto *D : Elements) { 18252 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18253 if (!ECD) continue; // Already issued a diagnostic. 18254 18255 // Standard C says the enumerators have int type, but we allow, as an 18256 // extension, the enumerators to be larger than int size. If each 18257 // enumerator value fits in an int, type it as an int, otherwise type it the 18258 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18259 // that X has type 'int', not 'unsigned'. 18260 18261 // Determine whether the value fits into an int. 18262 llvm::APSInt InitVal = ECD->getInitVal(); 18263 18264 // If it fits into an integer type, force it. Otherwise force it to match 18265 // the enum decl type. 18266 QualType NewTy; 18267 unsigned NewWidth; 18268 bool NewSign; 18269 if (!getLangOpts().CPlusPlus && 18270 !Enum->isFixed() && 18271 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18272 NewTy = Context.IntTy; 18273 NewWidth = IntWidth; 18274 NewSign = true; 18275 } else if (ECD->getType() == BestType) { 18276 // Already the right type! 18277 if (getLangOpts().CPlusPlus) 18278 // C++ [dcl.enum]p4: Following the closing brace of an 18279 // enum-specifier, each enumerator has the type of its 18280 // enumeration. 18281 ECD->setType(EnumType); 18282 continue; 18283 } else { 18284 NewTy = BestType; 18285 NewWidth = BestWidth; 18286 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18287 } 18288 18289 // Adjust the APSInt value. 18290 InitVal = InitVal.extOrTrunc(NewWidth); 18291 InitVal.setIsSigned(NewSign); 18292 ECD->setInitVal(InitVal); 18293 18294 // Adjust the Expr initializer and type. 18295 if (ECD->getInitExpr() && 18296 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18297 ECD->setInitExpr(ImplicitCastExpr::Create( 18298 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18299 /*base paths*/ nullptr, VK_RValue, FPOptionsOverride())); 18300 if (getLangOpts().CPlusPlus) 18301 // C++ [dcl.enum]p4: Following the closing brace of an 18302 // enum-specifier, each enumerator has the type of its 18303 // enumeration. 18304 ECD->setType(EnumType); 18305 else 18306 ECD->setType(NewTy); 18307 } 18308 18309 Enum->completeDefinition(BestType, BestPromotionType, 18310 NumPositiveBits, NumNegativeBits); 18311 18312 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18313 18314 if (Enum->isClosedFlag()) { 18315 for (Decl *D : Elements) { 18316 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18317 if (!ECD) continue; // Already issued a diagnostic. 18318 18319 llvm::APSInt InitVal = ECD->getInitVal(); 18320 if (InitVal != 0 && !InitVal.isPowerOf2() && 18321 !IsValueInFlagEnum(Enum, InitVal, true)) 18322 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18323 << ECD << Enum; 18324 } 18325 } 18326 18327 // Now that the enum type is defined, ensure it's not been underaligned. 18328 if (Enum->hasAttrs()) 18329 CheckAlignasUnderalignment(Enum); 18330 } 18331 18332 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18333 SourceLocation StartLoc, 18334 SourceLocation EndLoc) { 18335 StringLiteral *AsmString = cast<StringLiteral>(expr); 18336 18337 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18338 AsmString, StartLoc, 18339 EndLoc); 18340 CurContext->addDecl(New); 18341 return New; 18342 } 18343 18344 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18345 IdentifierInfo* AliasName, 18346 SourceLocation PragmaLoc, 18347 SourceLocation NameLoc, 18348 SourceLocation AliasNameLoc) { 18349 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18350 LookupOrdinaryName); 18351 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18352 AttributeCommonInfo::AS_Pragma); 18353 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18354 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18355 18356 // If a declaration that: 18357 // 1) declares a function or a variable 18358 // 2) has external linkage 18359 // already exists, add a label attribute to it. 18360 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18361 if (isDeclExternC(PrevDecl)) 18362 PrevDecl->addAttr(Attr); 18363 else 18364 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18365 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18366 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18367 } else 18368 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18369 } 18370 18371 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18372 SourceLocation PragmaLoc, 18373 SourceLocation NameLoc) { 18374 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18375 18376 if (PrevDecl) { 18377 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18378 } else { 18379 (void)WeakUndeclaredIdentifiers.insert( 18380 std::pair<IdentifierInfo*,WeakInfo> 18381 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18382 } 18383 } 18384 18385 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18386 IdentifierInfo* AliasName, 18387 SourceLocation PragmaLoc, 18388 SourceLocation NameLoc, 18389 SourceLocation AliasNameLoc) { 18390 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18391 LookupOrdinaryName); 18392 WeakInfo W = WeakInfo(Name, NameLoc); 18393 18394 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18395 if (!PrevDecl->hasAttr<AliasAttr>()) 18396 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18397 DeclApplyPragmaWeak(TUScope, ND, W); 18398 } else { 18399 (void)WeakUndeclaredIdentifiers.insert( 18400 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18401 } 18402 } 18403 18404 Decl *Sema::getObjCDeclContext() const { 18405 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18406 } 18407 18408 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18409 bool Final) { 18410 assert(FD && "Expected non-null FunctionDecl"); 18411 18412 // SYCL functions can be template, so we check if they have appropriate 18413 // attribute prior to checking if it is a template. 18414 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18415 return FunctionEmissionStatus::Emitted; 18416 18417 // Templates are emitted when they're instantiated. 18418 if (FD->isDependentContext()) 18419 return FunctionEmissionStatus::TemplateDiscarded; 18420 18421 // Check whether this function is an externally visible definition. 18422 auto IsEmittedForExternalSymbol = [this, FD]() { 18423 // We have to check the GVA linkage of the function's *definition* -- if we 18424 // only have a declaration, we don't know whether or not the function will 18425 // be emitted, because (say) the definition could include "inline". 18426 FunctionDecl *Def = FD->getDefinition(); 18427 18428 return Def && !isDiscardableGVALinkage( 18429 getASTContext().GetGVALinkageForFunction(Def)); 18430 }; 18431 18432 if (LangOpts.OpenMPIsDevice) { 18433 // In OpenMP device mode we will not emit host only functions, or functions 18434 // we don't need due to their linkage. 18435 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18436 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18437 // DevTy may be changed later by 18438 // #pragma omp declare target to(*) device_type(*). 18439 // Therefore DevTyhaving no value does not imply host. The emission status 18440 // will be checked again at the end of compilation unit with Final = true. 18441 if (DevTy.hasValue()) 18442 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18443 return FunctionEmissionStatus::OMPDiscarded; 18444 // If we have an explicit value for the device type, or we are in a target 18445 // declare context, we need to emit all extern and used symbols. 18446 if (isInOpenMPDeclareTargetContext() || DevTy.hasValue()) 18447 if (IsEmittedForExternalSymbol()) 18448 return FunctionEmissionStatus::Emitted; 18449 // Device mode only emits what it must, if it wasn't tagged yet and needed, 18450 // we'll omit it. 18451 if (Final) 18452 return FunctionEmissionStatus::OMPDiscarded; 18453 } else if (LangOpts.OpenMP > 45) { 18454 // In OpenMP host compilation prior to 5.0 everything was an emitted host 18455 // function. In 5.0, no_host was introduced which might cause a function to 18456 // be ommitted. 18457 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18458 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18459 if (DevTy.hasValue()) 18460 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 18461 return FunctionEmissionStatus::OMPDiscarded; 18462 } 18463 18464 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 18465 return FunctionEmissionStatus::Emitted; 18466 18467 if (LangOpts.CUDA) { 18468 // When compiling for device, host functions are never emitted. Similarly, 18469 // when compiling for host, device and global functions are never emitted. 18470 // (Technically, we do emit a host-side stub for global functions, but this 18471 // doesn't count for our purposes here.) 18472 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18473 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18474 return FunctionEmissionStatus::CUDADiscarded; 18475 if (!LangOpts.CUDAIsDevice && 18476 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18477 return FunctionEmissionStatus::CUDADiscarded; 18478 18479 if (IsEmittedForExternalSymbol()) 18480 return FunctionEmissionStatus::Emitted; 18481 } 18482 18483 // Otherwise, the function is known-emitted if it's in our set of 18484 // known-emitted functions. 18485 return FunctionEmissionStatus::Unknown; 18486 } 18487 18488 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18489 // Host-side references to a __global__ function refer to the stub, so the 18490 // function itself is never emitted and therefore should not be marked. 18491 // If we have host fn calls kernel fn calls host+device, the HD function 18492 // does not get instantiated on the host. We model this by omitting at the 18493 // call to the kernel from the callgraph. This ensures that, when compiling 18494 // for host, only HD functions actually called from the host get marked as 18495 // known-emitted. 18496 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18497 IdentifyCUDATarget(Callee) == CFT_Global; 18498 } 18499