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 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2544 const InheritableAttr *Attr, 2545 Sema::AvailabilityMergeKind AMK) { 2546 // This function copies an attribute Attr from a previous declaration to the 2547 // new declaration D if the new declaration doesn't itself have that attribute 2548 // yet or if that attribute allows duplicates. 2549 // If you're adding a new attribute that requires logic different from 2550 // "use explicit attribute on decl if present, else use attribute from 2551 // previous decl", for example if the attribute needs to be consistent 2552 // between redeclarations, you need to call a custom merge function here. 2553 InheritableAttr *NewAttr = nullptr; 2554 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2555 NewAttr = S.mergeAvailabilityAttr( 2556 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2557 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2558 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2559 AA->getPriority()); 2560 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2561 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2562 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2563 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2564 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2565 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2566 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2567 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2568 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2569 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2570 FA->getFirstArg()); 2571 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2572 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2573 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2574 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2575 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2576 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2577 IA->getInheritanceModel()); 2578 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2579 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2580 &S.Context.Idents.get(AA->getSpelling())); 2581 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2582 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2583 isa<CUDAGlobalAttr>(Attr))) { 2584 // CUDA target attributes are part of function signature for 2585 // overloading purposes and must not be merged. 2586 return false; 2587 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2588 NewAttr = S.mergeMinSizeAttr(D, *MA); 2589 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2590 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2591 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2592 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2593 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2594 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2595 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2596 NewAttr = S.mergeCommonAttr(D, *CommonA); 2597 else if (isa<AlignedAttr>(Attr)) 2598 // AlignedAttrs are handled separately, because we need to handle all 2599 // such attributes on a declaration at the same time. 2600 NewAttr = nullptr; 2601 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2602 (AMK == Sema::AMK_Override || 2603 AMK == Sema::AMK_ProtocolImplementation)) 2604 NewAttr = nullptr; 2605 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2606 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2607 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2608 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2609 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2610 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2611 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2612 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2613 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2614 NewAttr = S.mergeImportNameAttr(D, *INA); 2615 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 2616 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 2617 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 2618 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 2619 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2620 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2621 2622 if (NewAttr) { 2623 NewAttr->setInherited(true); 2624 D->addAttr(NewAttr); 2625 if (isa<MSInheritanceAttr>(NewAttr)) 2626 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2627 return true; 2628 } 2629 2630 return false; 2631 } 2632 2633 static const NamedDecl *getDefinition(const Decl *D) { 2634 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2635 return TD->getDefinition(); 2636 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2637 const VarDecl *Def = VD->getDefinition(); 2638 if (Def) 2639 return Def; 2640 return VD->getActingDefinition(); 2641 } 2642 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2643 const FunctionDecl *Def = nullptr; 2644 if (FD->isDefined(Def, true)) 2645 return Def; 2646 } 2647 return nullptr; 2648 } 2649 2650 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2651 for (const auto *Attribute : D->attrs()) 2652 if (Attribute->getKind() == Kind) 2653 return true; 2654 return false; 2655 } 2656 2657 /// checkNewAttributesAfterDef - If we already have a definition, check that 2658 /// there are no new attributes in this declaration. 2659 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2660 if (!New->hasAttrs()) 2661 return; 2662 2663 const NamedDecl *Def = getDefinition(Old); 2664 if (!Def || Def == New) 2665 return; 2666 2667 AttrVec &NewAttributes = New->getAttrs(); 2668 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2669 const Attr *NewAttribute = NewAttributes[I]; 2670 2671 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2672 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2673 Sema::SkipBodyInfo SkipBody; 2674 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2675 2676 // If we're skipping this definition, drop the "alias" attribute. 2677 if (SkipBody.ShouldSkip) { 2678 NewAttributes.erase(NewAttributes.begin() + I); 2679 --E; 2680 continue; 2681 } 2682 } else { 2683 VarDecl *VD = cast<VarDecl>(New); 2684 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2685 VarDecl::TentativeDefinition 2686 ? diag::err_alias_after_tentative 2687 : diag::err_redefinition; 2688 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2689 if (Diag == diag::err_redefinition) 2690 S.notePreviousDefinition(Def, VD->getLocation()); 2691 else 2692 S.Diag(Def->getLocation(), diag::note_previous_definition); 2693 VD->setInvalidDecl(); 2694 } 2695 ++I; 2696 continue; 2697 } 2698 2699 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2700 // Tentative definitions are only interesting for the alias check above. 2701 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2702 ++I; 2703 continue; 2704 } 2705 } 2706 2707 if (hasAttribute(Def, NewAttribute->getKind())) { 2708 ++I; 2709 continue; // regular attr merging will take care of validating this. 2710 } 2711 2712 if (isa<C11NoReturnAttr>(NewAttribute)) { 2713 // C's _Noreturn is allowed to be added to a function after it is defined. 2714 ++I; 2715 continue; 2716 } else if (isa<UuidAttr>(NewAttribute)) { 2717 // msvc will allow a subsequent definition to add an uuid to a class 2718 ++I; 2719 continue; 2720 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2721 if (AA->isAlignas()) { 2722 // C++11 [dcl.align]p6: 2723 // if any declaration of an entity has an alignment-specifier, 2724 // every defining declaration of that entity shall specify an 2725 // equivalent alignment. 2726 // C11 6.7.5/7: 2727 // If the definition of an object does not have an alignment 2728 // specifier, any other declaration of that object shall also 2729 // have no alignment specifier. 2730 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2731 << AA; 2732 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2733 << AA; 2734 NewAttributes.erase(NewAttributes.begin() + I); 2735 --E; 2736 continue; 2737 } 2738 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2739 // If there is a C definition followed by a redeclaration with this 2740 // attribute then there are two different definitions. In C++, prefer the 2741 // standard diagnostics. 2742 if (!S.getLangOpts().CPlusPlus) { 2743 S.Diag(NewAttribute->getLocation(), 2744 diag::err_loader_uninitialized_redeclaration); 2745 S.Diag(Def->getLocation(), diag::note_previous_definition); 2746 NewAttributes.erase(NewAttributes.begin() + I); 2747 --E; 2748 continue; 2749 } 2750 } else if (isa<SelectAnyAttr>(NewAttribute) && 2751 cast<VarDecl>(New)->isInline() && 2752 !cast<VarDecl>(New)->isInlineSpecified()) { 2753 // Don't warn about applying selectany to implicitly inline variables. 2754 // Older compilers and language modes would require the use of selectany 2755 // to make such variables inline, and it would have no effect if we 2756 // honored it. 2757 ++I; 2758 continue; 2759 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2760 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2761 // declarations after defintions. 2762 ++I; 2763 continue; 2764 } 2765 2766 S.Diag(NewAttribute->getLocation(), 2767 diag::warn_attribute_precede_definition); 2768 S.Diag(Def->getLocation(), diag::note_previous_definition); 2769 NewAttributes.erase(NewAttributes.begin() + I); 2770 --E; 2771 } 2772 } 2773 2774 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2775 const ConstInitAttr *CIAttr, 2776 bool AttrBeforeInit) { 2777 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2778 2779 // Figure out a good way to write this specifier on the old declaration. 2780 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2781 // enough of the attribute list spelling information to extract that without 2782 // heroics. 2783 std::string SuitableSpelling; 2784 if (S.getLangOpts().CPlusPlus20) 2785 SuitableSpelling = std::string( 2786 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2787 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2788 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2789 InsertLoc, {tok::l_square, tok::l_square, 2790 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2791 S.PP.getIdentifierInfo("require_constant_initialization"), 2792 tok::r_square, tok::r_square})); 2793 if (SuitableSpelling.empty()) 2794 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2795 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2796 S.PP.getIdentifierInfo("require_constant_initialization"), 2797 tok::r_paren, tok::r_paren})); 2798 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2799 SuitableSpelling = "constinit"; 2800 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2801 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2802 if (SuitableSpelling.empty()) 2803 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2804 SuitableSpelling += " "; 2805 2806 if (AttrBeforeInit) { 2807 // extern constinit int a; 2808 // int a = 0; // error (missing 'constinit'), accepted as extension 2809 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2810 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2811 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2812 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2813 } else { 2814 // int a = 0; 2815 // constinit extern int a; // error (missing 'constinit') 2816 S.Diag(CIAttr->getLocation(), 2817 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2818 : diag::warn_require_const_init_added_too_late) 2819 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2820 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2821 << CIAttr->isConstinit() 2822 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2823 } 2824 } 2825 2826 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2827 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2828 AvailabilityMergeKind AMK) { 2829 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2830 UsedAttr *NewAttr = OldAttr->clone(Context); 2831 NewAttr->setInherited(true); 2832 New->addAttr(NewAttr); 2833 } 2834 2835 if (!Old->hasAttrs() && !New->hasAttrs()) 2836 return; 2837 2838 // [dcl.constinit]p1: 2839 // If the [constinit] specifier is applied to any declaration of a 2840 // variable, it shall be applied to the initializing declaration. 2841 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2842 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2843 if (bool(OldConstInit) != bool(NewConstInit)) { 2844 const auto *OldVD = cast<VarDecl>(Old); 2845 auto *NewVD = cast<VarDecl>(New); 2846 2847 // Find the initializing declaration. Note that we might not have linked 2848 // the new declaration into the redeclaration chain yet. 2849 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2850 if (!InitDecl && 2851 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2852 InitDecl = NewVD; 2853 2854 if (InitDecl == NewVD) { 2855 // This is the initializing declaration. If it would inherit 'constinit', 2856 // that's ill-formed. (Note that we do not apply this to the attribute 2857 // form). 2858 if (OldConstInit && OldConstInit->isConstinit()) 2859 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2860 /*AttrBeforeInit=*/true); 2861 } else if (NewConstInit) { 2862 // This is the first time we've been told that this declaration should 2863 // have a constant initializer. If we already saw the initializing 2864 // declaration, this is too late. 2865 if (InitDecl && InitDecl != NewVD) { 2866 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2867 /*AttrBeforeInit=*/false); 2868 NewVD->dropAttr<ConstInitAttr>(); 2869 } 2870 } 2871 } 2872 2873 // Attributes declared post-definition are currently ignored. 2874 checkNewAttributesAfterDef(*this, New, Old); 2875 2876 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2877 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2878 if (!OldA->isEquivalent(NewA)) { 2879 // This redeclaration changes __asm__ label. 2880 Diag(New->getLocation(), diag::err_different_asm_label); 2881 Diag(OldA->getLocation(), diag::note_previous_declaration); 2882 } 2883 } else if (Old->isUsed()) { 2884 // This redeclaration adds an __asm__ label to a declaration that has 2885 // already been ODR-used. 2886 Diag(New->getLocation(), diag::err_late_asm_label_name) 2887 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2888 } 2889 } 2890 2891 // Re-declaration cannot add abi_tag's. 2892 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2893 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2894 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2895 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2896 NewTag) == OldAbiTagAttr->tags_end()) { 2897 Diag(NewAbiTagAttr->getLocation(), 2898 diag::err_new_abi_tag_on_redeclaration) 2899 << NewTag; 2900 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2901 } 2902 } 2903 } else { 2904 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2905 Diag(Old->getLocation(), diag::note_previous_declaration); 2906 } 2907 } 2908 2909 // This redeclaration adds a section attribute. 2910 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2911 if (auto *VD = dyn_cast<VarDecl>(New)) { 2912 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2913 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2914 Diag(Old->getLocation(), diag::note_previous_declaration); 2915 } 2916 } 2917 } 2918 2919 // Redeclaration adds code-seg attribute. 2920 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2921 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2922 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2923 Diag(New->getLocation(), diag::warn_mismatched_section) 2924 << 0 /*codeseg*/; 2925 Diag(Old->getLocation(), diag::note_previous_declaration); 2926 } 2927 2928 if (!Old->hasAttrs()) 2929 return; 2930 2931 bool foundAny = New->hasAttrs(); 2932 2933 // Ensure that any moving of objects within the allocated map is done before 2934 // we process them. 2935 if (!foundAny) New->setAttrs(AttrVec()); 2936 2937 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2938 // Ignore deprecated/unavailable/availability attributes if requested. 2939 AvailabilityMergeKind LocalAMK = AMK_None; 2940 if (isa<DeprecatedAttr>(I) || 2941 isa<UnavailableAttr>(I) || 2942 isa<AvailabilityAttr>(I)) { 2943 switch (AMK) { 2944 case AMK_None: 2945 continue; 2946 2947 case AMK_Redeclaration: 2948 case AMK_Override: 2949 case AMK_ProtocolImplementation: 2950 LocalAMK = AMK; 2951 break; 2952 } 2953 } 2954 2955 // Already handled. 2956 if (isa<UsedAttr>(I)) 2957 continue; 2958 2959 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2960 foundAny = true; 2961 } 2962 2963 if (mergeAlignedAttrs(*this, New, Old)) 2964 foundAny = true; 2965 2966 if (!foundAny) New->dropAttrs(); 2967 } 2968 2969 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2970 /// to the new one. 2971 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2972 const ParmVarDecl *oldDecl, 2973 Sema &S) { 2974 // C++11 [dcl.attr.depend]p2: 2975 // The first declaration of a function shall specify the 2976 // carries_dependency attribute for its declarator-id if any declaration 2977 // of the function specifies the carries_dependency attribute. 2978 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2979 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2980 S.Diag(CDA->getLocation(), 2981 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2982 // Find the first declaration of the parameter. 2983 // FIXME: Should we build redeclaration chains for function parameters? 2984 const FunctionDecl *FirstFD = 2985 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2986 const ParmVarDecl *FirstVD = 2987 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2988 S.Diag(FirstVD->getLocation(), 2989 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2990 } 2991 2992 if (!oldDecl->hasAttrs()) 2993 return; 2994 2995 bool foundAny = newDecl->hasAttrs(); 2996 2997 // Ensure that any moving of objects within the allocated map is 2998 // done before we process them. 2999 if (!foundAny) newDecl->setAttrs(AttrVec()); 3000 3001 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3002 if (!DeclHasAttr(newDecl, I)) { 3003 InheritableAttr *newAttr = 3004 cast<InheritableParamAttr>(I->clone(S.Context)); 3005 newAttr->setInherited(true); 3006 newDecl->addAttr(newAttr); 3007 foundAny = true; 3008 } 3009 } 3010 3011 if (!foundAny) newDecl->dropAttrs(); 3012 } 3013 3014 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3015 const ParmVarDecl *OldParam, 3016 Sema &S) { 3017 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3018 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3019 if (*Oldnullability != *Newnullability) { 3020 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3021 << DiagNullabilityKind( 3022 *Newnullability, 3023 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3024 != 0)) 3025 << DiagNullabilityKind( 3026 *Oldnullability, 3027 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3028 != 0)); 3029 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3030 } 3031 } else { 3032 QualType NewT = NewParam->getType(); 3033 NewT = S.Context.getAttributedType( 3034 AttributedType::getNullabilityAttrKind(*Oldnullability), 3035 NewT, NewT); 3036 NewParam->setType(NewT); 3037 } 3038 } 3039 } 3040 3041 namespace { 3042 3043 /// Used in MergeFunctionDecl to keep track of function parameters in 3044 /// C. 3045 struct GNUCompatibleParamWarning { 3046 ParmVarDecl *OldParm; 3047 ParmVarDecl *NewParm; 3048 QualType PromotedType; 3049 }; 3050 3051 } // end anonymous namespace 3052 3053 // Determine whether the previous declaration was a definition, implicit 3054 // declaration, or a declaration. 3055 template <typename T> 3056 static std::pair<diag::kind, SourceLocation> 3057 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3058 diag::kind PrevDiag; 3059 SourceLocation OldLocation = Old->getLocation(); 3060 if (Old->isThisDeclarationADefinition()) 3061 PrevDiag = diag::note_previous_definition; 3062 else if (Old->isImplicit()) { 3063 PrevDiag = diag::note_previous_implicit_declaration; 3064 if (OldLocation.isInvalid()) 3065 OldLocation = New->getLocation(); 3066 } else 3067 PrevDiag = diag::note_previous_declaration; 3068 return std::make_pair(PrevDiag, OldLocation); 3069 } 3070 3071 /// canRedefineFunction - checks if a function can be redefined. Currently, 3072 /// only extern inline functions can be redefined, and even then only in 3073 /// GNU89 mode. 3074 static bool canRedefineFunction(const FunctionDecl *FD, 3075 const LangOptions& LangOpts) { 3076 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3077 !LangOpts.CPlusPlus && 3078 FD->isInlineSpecified() && 3079 FD->getStorageClass() == SC_Extern); 3080 } 3081 3082 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3083 const AttributedType *AT = T->getAs<AttributedType>(); 3084 while (AT && !AT->isCallingConv()) 3085 AT = AT->getModifiedType()->getAs<AttributedType>(); 3086 return AT; 3087 } 3088 3089 template <typename T> 3090 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3091 const DeclContext *DC = Old->getDeclContext(); 3092 if (DC->isRecord()) 3093 return false; 3094 3095 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3096 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3097 return true; 3098 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3099 return true; 3100 return false; 3101 } 3102 3103 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3104 static bool isExternC(VarTemplateDecl *) { return false; } 3105 3106 /// Check whether a redeclaration of an entity introduced by a 3107 /// using-declaration is valid, given that we know it's not an overload 3108 /// (nor a hidden tag declaration). 3109 template<typename ExpectedDecl> 3110 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3111 ExpectedDecl *New) { 3112 // C++11 [basic.scope.declarative]p4: 3113 // Given a set of declarations in a single declarative region, each of 3114 // which specifies the same unqualified name, 3115 // -- they shall all refer to the same entity, or all refer to functions 3116 // and function templates; or 3117 // -- exactly one declaration shall declare a class name or enumeration 3118 // name that is not a typedef name and the other declarations shall all 3119 // refer to the same variable or enumerator, or all refer to functions 3120 // and function templates; in this case the class name or enumeration 3121 // name is hidden (3.3.10). 3122 3123 // C++11 [namespace.udecl]p14: 3124 // If a function declaration in namespace scope or block scope has the 3125 // same name and the same parameter-type-list as a function introduced 3126 // by a using-declaration, and the declarations do not declare the same 3127 // function, the program is ill-formed. 3128 3129 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3130 if (Old && 3131 !Old->getDeclContext()->getRedeclContext()->Equals( 3132 New->getDeclContext()->getRedeclContext()) && 3133 !(isExternC(Old) && isExternC(New))) 3134 Old = nullptr; 3135 3136 if (!Old) { 3137 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3138 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3139 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3140 return true; 3141 } 3142 return false; 3143 } 3144 3145 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3146 const FunctionDecl *B) { 3147 assert(A->getNumParams() == B->getNumParams()); 3148 3149 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3150 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3151 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3152 if (AttrA == AttrB) 3153 return true; 3154 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3155 AttrA->isDynamic() == AttrB->isDynamic(); 3156 }; 3157 3158 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3159 } 3160 3161 /// If necessary, adjust the semantic declaration context for a qualified 3162 /// declaration to name the correct inline namespace within the qualifier. 3163 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3164 DeclaratorDecl *OldD) { 3165 // The only case where we need to update the DeclContext is when 3166 // redeclaration lookup for a qualified name finds a declaration 3167 // in an inline namespace within the context named by the qualifier: 3168 // 3169 // inline namespace N { int f(); } 3170 // int ::f(); // Sema DC needs adjusting from :: to N::. 3171 // 3172 // For unqualified declarations, the semantic context *can* change 3173 // along the redeclaration chain (for local extern declarations, 3174 // extern "C" declarations, and friend declarations in particular). 3175 if (!NewD->getQualifier()) 3176 return; 3177 3178 // NewD is probably already in the right context. 3179 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3180 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3181 if (NamedDC->Equals(SemaDC)) 3182 return; 3183 3184 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3185 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3186 "unexpected context for redeclaration"); 3187 3188 auto *LexDC = NewD->getLexicalDeclContext(); 3189 auto FixSemaDC = [=](NamedDecl *D) { 3190 if (!D) 3191 return; 3192 D->setDeclContext(SemaDC); 3193 D->setLexicalDeclContext(LexDC); 3194 }; 3195 3196 FixSemaDC(NewD); 3197 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3198 FixSemaDC(FD->getDescribedFunctionTemplate()); 3199 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3200 FixSemaDC(VD->getDescribedVarTemplate()); 3201 } 3202 3203 /// MergeFunctionDecl - We just parsed a function 'New' from 3204 /// declarator D which has the same name and scope as a previous 3205 /// declaration 'Old'. Figure out how to resolve this situation, 3206 /// merging decls or emitting diagnostics as appropriate. 3207 /// 3208 /// In C++, New and Old must be declarations that are not 3209 /// overloaded. Use IsOverload to determine whether New and Old are 3210 /// overloaded, and to select the Old declaration that New should be 3211 /// merged with. 3212 /// 3213 /// Returns true if there was an error, false otherwise. 3214 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3215 Scope *S, bool MergeTypeWithOld) { 3216 // Verify the old decl was also a function. 3217 FunctionDecl *Old = OldD->getAsFunction(); 3218 if (!Old) { 3219 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3220 if (New->getFriendObjectKind()) { 3221 Diag(New->getLocation(), diag::err_using_decl_friend); 3222 Diag(Shadow->getTargetDecl()->getLocation(), 3223 diag::note_using_decl_target); 3224 Diag(Shadow->getUsingDecl()->getLocation(), 3225 diag::note_using_decl) << 0; 3226 return true; 3227 } 3228 3229 // Check whether the two declarations might declare the same function. 3230 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3231 return true; 3232 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3233 } else { 3234 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3235 << New->getDeclName(); 3236 notePreviousDefinition(OldD, New->getLocation()); 3237 return true; 3238 } 3239 } 3240 3241 // If the old declaration was found in an inline namespace and the new 3242 // declaration was qualified, update the DeclContext to match. 3243 adjustDeclContextForDeclaratorDecl(New, Old); 3244 3245 // If the old declaration is invalid, just give up here. 3246 if (Old->isInvalidDecl()) 3247 return true; 3248 3249 // Disallow redeclaration of some builtins. 3250 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3251 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3252 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3253 << Old << Old->getType(); 3254 return true; 3255 } 3256 3257 diag::kind PrevDiag; 3258 SourceLocation OldLocation; 3259 std::tie(PrevDiag, OldLocation) = 3260 getNoteDiagForInvalidRedeclaration(Old, New); 3261 3262 // Don't complain about this if we're in GNU89 mode and the old function 3263 // is an extern inline function. 3264 // Don't complain about specializations. They are not supposed to have 3265 // storage classes. 3266 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3267 New->getStorageClass() == SC_Static && 3268 Old->hasExternalFormalLinkage() && 3269 !New->getTemplateSpecializationInfo() && 3270 !canRedefineFunction(Old, getLangOpts())) { 3271 if (getLangOpts().MicrosoftExt) { 3272 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3273 Diag(OldLocation, PrevDiag); 3274 } else { 3275 Diag(New->getLocation(), diag::err_static_non_static) << New; 3276 Diag(OldLocation, PrevDiag); 3277 return true; 3278 } 3279 } 3280 3281 if (New->hasAttr<InternalLinkageAttr>() && 3282 !Old->hasAttr<InternalLinkageAttr>()) { 3283 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3284 << New->getDeclName(); 3285 notePreviousDefinition(Old, New->getLocation()); 3286 New->dropAttr<InternalLinkageAttr>(); 3287 } 3288 3289 if (CheckRedeclarationModuleOwnership(New, Old)) 3290 return true; 3291 3292 if (!getLangOpts().CPlusPlus) { 3293 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3294 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3295 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3296 << New << OldOvl; 3297 3298 // Try our best to find a decl that actually has the overloadable 3299 // attribute for the note. In most cases (e.g. programs with only one 3300 // broken declaration/definition), this won't matter. 3301 // 3302 // FIXME: We could do this if we juggled some extra state in 3303 // OverloadableAttr, rather than just removing it. 3304 const Decl *DiagOld = Old; 3305 if (OldOvl) { 3306 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3307 const auto *A = D->getAttr<OverloadableAttr>(); 3308 return A && !A->isImplicit(); 3309 }); 3310 // If we've implicitly added *all* of the overloadable attrs to this 3311 // chain, emitting a "previous redecl" note is pointless. 3312 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3313 } 3314 3315 if (DiagOld) 3316 Diag(DiagOld->getLocation(), 3317 diag::note_attribute_overloadable_prev_overload) 3318 << OldOvl; 3319 3320 if (OldOvl) 3321 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3322 else 3323 New->dropAttr<OverloadableAttr>(); 3324 } 3325 } 3326 3327 // If a function is first declared with a calling convention, but is later 3328 // declared or defined without one, all following decls assume the calling 3329 // convention of the first. 3330 // 3331 // It's OK if a function is first declared without a calling convention, 3332 // but is later declared or defined with the default calling convention. 3333 // 3334 // To test if either decl has an explicit calling convention, we look for 3335 // AttributedType sugar nodes on the type as written. If they are missing or 3336 // were canonicalized away, we assume the calling convention was implicit. 3337 // 3338 // Note also that we DO NOT return at this point, because we still have 3339 // other tests to run. 3340 QualType OldQType = Context.getCanonicalType(Old->getType()); 3341 QualType NewQType = Context.getCanonicalType(New->getType()); 3342 const FunctionType *OldType = cast<FunctionType>(OldQType); 3343 const FunctionType *NewType = cast<FunctionType>(NewQType); 3344 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3345 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3346 bool RequiresAdjustment = false; 3347 3348 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3349 FunctionDecl *First = Old->getFirstDecl(); 3350 const FunctionType *FT = 3351 First->getType().getCanonicalType()->castAs<FunctionType>(); 3352 FunctionType::ExtInfo FI = FT->getExtInfo(); 3353 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3354 if (!NewCCExplicit) { 3355 // Inherit the CC from the previous declaration if it was specified 3356 // there but not here. 3357 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3358 RequiresAdjustment = true; 3359 } else if (Old->getBuiltinID()) { 3360 // Builtin attribute isn't propagated to the new one yet at this point, 3361 // so we check if the old one is a builtin. 3362 3363 // Calling Conventions on a Builtin aren't really useful and setting a 3364 // default calling convention and cdecl'ing some builtin redeclarations is 3365 // common, so warn and ignore the calling convention on the redeclaration. 3366 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3367 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3368 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3369 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3370 RequiresAdjustment = true; 3371 } else { 3372 // Calling conventions aren't compatible, so complain. 3373 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3374 Diag(New->getLocation(), diag::err_cconv_change) 3375 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3376 << !FirstCCExplicit 3377 << (!FirstCCExplicit ? "" : 3378 FunctionType::getNameForCallConv(FI.getCC())); 3379 3380 // Put the note on the first decl, since it is the one that matters. 3381 Diag(First->getLocation(), diag::note_previous_declaration); 3382 return true; 3383 } 3384 } 3385 3386 // FIXME: diagnose the other way around? 3387 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3388 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3389 RequiresAdjustment = true; 3390 } 3391 3392 // Merge regparm attribute. 3393 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3394 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3395 if (NewTypeInfo.getHasRegParm()) { 3396 Diag(New->getLocation(), diag::err_regparm_mismatch) 3397 << NewType->getRegParmType() 3398 << OldType->getRegParmType(); 3399 Diag(OldLocation, diag::note_previous_declaration); 3400 return true; 3401 } 3402 3403 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3404 RequiresAdjustment = true; 3405 } 3406 3407 // Merge ns_returns_retained attribute. 3408 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3409 if (NewTypeInfo.getProducesResult()) { 3410 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3411 << "'ns_returns_retained'"; 3412 Diag(OldLocation, diag::note_previous_declaration); 3413 return true; 3414 } 3415 3416 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3417 RequiresAdjustment = true; 3418 } 3419 3420 if (OldTypeInfo.getNoCallerSavedRegs() != 3421 NewTypeInfo.getNoCallerSavedRegs()) { 3422 if (NewTypeInfo.getNoCallerSavedRegs()) { 3423 AnyX86NoCallerSavedRegistersAttr *Attr = 3424 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3425 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3426 Diag(OldLocation, diag::note_previous_declaration); 3427 return true; 3428 } 3429 3430 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3431 RequiresAdjustment = true; 3432 } 3433 3434 if (RequiresAdjustment) { 3435 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3436 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3437 New->setType(QualType(AdjustedType, 0)); 3438 NewQType = Context.getCanonicalType(New->getType()); 3439 } 3440 3441 // If this redeclaration makes the function inline, we may need to add it to 3442 // UndefinedButUsed. 3443 if (!Old->isInlined() && New->isInlined() && 3444 !New->hasAttr<GNUInlineAttr>() && 3445 !getLangOpts().GNUInline && 3446 Old->isUsed(false) && 3447 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3448 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3449 SourceLocation())); 3450 3451 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3452 // about it. 3453 if (New->hasAttr<GNUInlineAttr>() && 3454 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3455 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3456 } 3457 3458 // If pass_object_size params don't match up perfectly, this isn't a valid 3459 // redeclaration. 3460 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3461 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3462 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3463 << New->getDeclName(); 3464 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3465 return true; 3466 } 3467 3468 if (getLangOpts().CPlusPlus) { 3469 // C++1z [over.load]p2 3470 // Certain function declarations cannot be overloaded: 3471 // -- Function declarations that differ only in the return type, 3472 // the exception specification, or both cannot be overloaded. 3473 3474 // Check the exception specifications match. This may recompute the type of 3475 // both Old and New if it resolved exception specifications, so grab the 3476 // types again after this. Because this updates the type, we do this before 3477 // any of the other checks below, which may update the "de facto" NewQType 3478 // but do not necessarily update the type of New. 3479 if (CheckEquivalentExceptionSpec(Old, New)) 3480 return true; 3481 OldQType = Context.getCanonicalType(Old->getType()); 3482 NewQType = Context.getCanonicalType(New->getType()); 3483 3484 // Go back to the type source info to compare the declared return types, 3485 // per C++1y [dcl.type.auto]p13: 3486 // Redeclarations or specializations of a function or function template 3487 // with a declared return type that uses a placeholder type shall also 3488 // use that placeholder, not a deduced type. 3489 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3490 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3491 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3492 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3493 OldDeclaredReturnType)) { 3494 QualType ResQT; 3495 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3496 OldDeclaredReturnType->isObjCObjectPointerType()) 3497 // FIXME: This does the wrong thing for a deduced return type. 3498 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3499 if (ResQT.isNull()) { 3500 if (New->isCXXClassMember() && New->isOutOfLine()) 3501 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3502 << New << New->getReturnTypeSourceRange(); 3503 else 3504 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3505 << New->getReturnTypeSourceRange(); 3506 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3507 << Old->getReturnTypeSourceRange(); 3508 return true; 3509 } 3510 else 3511 NewQType = ResQT; 3512 } 3513 3514 QualType OldReturnType = OldType->getReturnType(); 3515 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3516 if (OldReturnType != NewReturnType) { 3517 // If this function has a deduced return type and has already been 3518 // defined, copy the deduced value from the old declaration. 3519 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3520 if (OldAT && OldAT->isDeduced()) { 3521 New->setType( 3522 SubstAutoType(New->getType(), 3523 OldAT->isDependentType() ? Context.DependentTy 3524 : OldAT->getDeducedType())); 3525 NewQType = Context.getCanonicalType( 3526 SubstAutoType(NewQType, 3527 OldAT->isDependentType() ? Context.DependentTy 3528 : OldAT->getDeducedType())); 3529 } 3530 } 3531 3532 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3533 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3534 if (OldMethod && NewMethod) { 3535 // Preserve triviality. 3536 NewMethod->setTrivial(OldMethod->isTrivial()); 3537 3538 // MSVC allows explicit template specialization at class scope: 3539 // 2 CXXMethodDecls referring to the same function will be injected. 3540 // We don't want a redeclaration error. 3541 bool IsClassScopeExplicitSpecialization = 3542 OldMethod->isFunctionTemplateSpecialization() && 3543 NewMethod->isFunctionTemplateSpecialization(); 3544 bool isFriend = NewMethod->getFriendObjectKind(); 3545 3546 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3547 !IsClassScopeExplicitSpecialization) { 3548 // -- Member function declarations with the same name and the 3549 // same parameter types cannot be overloaded if any of them 3550 // is a static member function declaration. 3551 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3552 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3553 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3554 return true; 3555 } 3556 3557 // C++ [class.mem]p1: 3558 // [...] A member shall not be declared twice in the 3559 // member-specification, except that a nested class or member 3560 // class template can be declared and then later defined. 3561 if (!inTemplateInstantiation()) { 3562 unsigned NewDiag; 3563 if (isa<CXXConstructorDecl>(OldMethod)) 3564 NewDiag = diag::err_constructor_redeclared; 3565 else if (isa<CXXDestructorDecl>(NewMethod)) 3566 NewDiag = diag::err_destructor_redeclared; 3567 else if (isa<CXXConversionDecl>(NewMethod)) 3568 NewDiag = diag::err_conv_function_redeclared; 3569 else 3570 NewDiag = diag::err_member_redeclared; 3571 3572 Diag(New->getLocation(), NewDiag); 3573 } else { 3574 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3575 << New << New->getType(); 3576 } 3577 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3578 return true; 3579 3580 // Complain if this is an explicit declaration of a special 3581 // member that was initially declared implicitly. 3582 // 3583 // As an exception, it's okay to befriend such methods in order 3584 // to permit the implicit constructor/destructor/operator calls. 3585 } else if (OldMethod->isImplicit()) { 3586 if (isFriend) { 3587 NewMethod->setImplicit(); 3588 } else { 3589 Diag(NewMethod->getLocation(), 3590 diag::err_definition_of_implicitly_declared_member) 3591 << New << getSpecialMember(OldMethod); 3592 return true; 3593 } 3594 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3595 Diag(NewMethod->getLocation(), 3596 diag::err_definition_of_explicitly_defaulted_member) 3597 << getSpecialMember(OldMethod); 3598 return true; 3599 } 3600 } 3601 3602 // C++11 [dcl.attr.noreturn]p1: 3603 // The first declaration of a function shall specify the noreturn 3604 // attribute if any declaration of that function specifies the noreturn 3605 // attribute. 3606 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3607 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3608 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3609 Diag(Old->getFirstDecl()->getLocation(), 3610 diag::note_noreturn_missing_first_decl); 3611 } 3612 3613 // C++11 [dcl.attr.depend]p2: 3614 // The first declaration of a function shall specify the 3615 // carries_dependency attribute for its declarator-id if any declaration 3616 // of the function specifies the carries_dependency attribute. 3617 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3618 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3619 Diag(CDA->getLocation(), 3620 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3621 Diag(Old->getFirstDecl()->getLocation(), 3622 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3623 } 3624 3625 // (C++98 8.3.5p3): 3626 // All declarations for a function shall agree exactly in both the 3627 // return type and the parameter-type-list. 3628 // We also want to respect all the extended bits except noreturn. 3629 3630 // noreturn should now match unless the old type info didn't have it. 3631 QualType OldQTypeForComparison = OldQType; 3632 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3633 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3634 const FunctionType *OldTypeForComparison 3635 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3636 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3637 assert(OldQTypeForComparison.isCanonical()); 3638 } 3639 3640 if (haveIncompatibleLanguageLinkages(Old, New)) { 3641 // As a special case, retain the language linkage from previous 3642 // declarations of a friend function as an extension. 3643 // 3644 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3645 // and is useful because there's otherwise no way to specify language 3646 // linkage within class scope. 3647 // 3648 // Check cautiously as the friend object kind isn't yet complete. 3649 if (New->getFriendObjectKind() != Decl::FOK_None) { 3650 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3651 Diag(OldLocation, PrevDiag); 3652 } else { 3653 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3654 Diag(OldLocation, PrevDiag); 3655 return true; 3656 } 3657 } 3658 3659 // If the function types are compatible, merge the declarations. Ignore the 3660 // exception specifier because it was already checked above in 3661 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3662 // about incompatible types under -fms-compatibility. 3663 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3664 NewQType)) 3665 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3666 3667 // If the types are imprecise (due to dependent constructs in friends or 3668 // local extern declarations), it's OK if they differ. We'll check again 3669 // during instantiation. 3670 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3671 return false; 3672 3673 // Fall through for conflicting redeclarations and redefinitions. 3674 } 3675 3676 // C: Function types need to be compatible, not identical. This handles 3677 // duplicate function decls like "void f(int); void f(enum X);" properly. 3678 if (!getLangOpts().CPlusPlus && 3679 Context.typesAreCompatible(OldQType, NewQType)) { 3680 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3681 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3682 const FunctionProtoType *OldProto = nullptr; 3683 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3684 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3685 // The old declaration provided a function prototype, but the 3686 // new declaration does not. Merge in the prototype. 3687 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3688 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3689 NewQType = 3690 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3691 OldProto->getExtProtoInfo()); 3692 New->setType(NewQType); 3693 New->setHasInheritedPrototype(); 3694 3695 // Synthesize parameters with the same types. 3696 SmallVector<ParmVarDecl*, 16> Params; 3697 for (const auto &ParamType : OldProto->param_types()) { 3698 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3699 SourceLocation(), nullptr, 3700 ParamType, /*TInfo=*/nullptr, 3701 SC_None, nullptr); 3702 Param->setScopeInfo(0, Params.size()); 3703 Param->setImplicit(); 3704 Params.push_back(Param); 3705 } 3706 3707 New->setParams(Params); 3708 } 3709 3710 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3711 } 3712 3713 // Check if the function types are compatible when pointer size address 3714 // spaces are ignored. 3715 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3716 return false; 3717 3718 // GNU C permits a K&R definition to follow a prototype declaration 3719 // if the declared types of the parameters in the K&R definition 3720 // match the types in the prototype declaration, even when the 3721 // promoted types of the parameters from the K&R definition differ 3722 // from the types in the prototype. GCC then keeps the types from 3723 // the prototype. 3724 // 3725 // If a variadic prototype is followed by a non-variadic K&R definition, 3726 // the K&R definition becomes variadic. This is sort of an edge case, but 3727 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3728 // C99 6.9.1p8. 3729 if (!getLangOpts().CPlusPlus && 3730 Old->hasPrototype() && !New->hasPrototype() && 3731 New->getType()->getAs<FunctionProtoType>() && 3732 Old->getNumParams() == New->getNumParams()) { 3733 SmallVector<QualType, 16> ArgTypes; 3734 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3735 const FunctionProtoType *OldProto 3736 = Old->getType()->getAs<FunctionProtoType>(); 3737 const FunctionProtoType *NewProto 3738 = New->getType()->getAs<FunctionProtoType>(); 3739 3740 // Determine whether this is the GNU C extension. 3741 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3742 NewProto->getReturnType()); 3743 bool LooseCompatible = !MergedReturn.isNull(); 3744 for (unsigned Idx = 0, End = Old->getNumParams(); 3745 LooseCompatible && Idx != End; ++Idx) { 3746 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3747 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3748 if (Context.typesAreCompatible(OldParm->getType(), 3749 NewProto->getParamType(Idx))) { 3750 ArgTypes.push_back(NewParm->getType()); 3751 } else if (Context.typesAreCompatible(OldParm->getType(), 3752 NewParm->getType(), 3753 /*CompareUnqualified=*/true)) { 3754 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3755 NewProto->getParamType(Idx) }; 3756 Warnings.push_back(Warn); 3757 ArgTypes.push_back(NewParm->getType()); 3758 } else 3759 LooseCompatible = false; 3760 } 3761 3762 if (LooseCompatible) { 3763 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3764 Diag(Warnings[Warn].NewParm->getLocation(), 3765 diag::ext_param_promoted_not_compatible_with_prototype) 3766 << Warnings[Warn].PromotedType 3767 << Warnings[Warn].OldParm->getType(); 3768 if (Warnings[Warn].OldParm->getLocation().isValid()) 3769 Diag(Warnings[Warn].OldParm->getLocation(), 3770 diag::note_previous_declaration); 3771 } 3772 3773 if (MergeTypeWithOld) 3774 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3775 OldProto->getExtProtoInfo())); 3776 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3777 } 3778 3779 // Fall through to diagnose conflicting types. 3780 } 3781 3782 // A function that has already been declared has been redeclared or 3783 // defined with a different type; show an appropriate diagnostic. 3784 3785 // If the previous declaration was an implicitly-generated builtin 3786 // declaration, then at the very least we should use a specialized note. 3787 unsigned BuiltinID; 3788 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3789 // If it's actually a library-defined builtin function like 'malloc' 3790 // or 'printf', just warn about the incompatible redeclaration. 3791 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3792 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3793 Diag(OldLocation, diag::note_previous_builtin_declaration) 3794 << Old << Old->getType(); 3795 return false; 3796 } 3797 3798 PrevDiag = diag::note_previous_builtin_declaration; 3799 } 3800 3801 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3802 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3803 return true; 3804 } 3805 3806 /// Completes the merge of two function declarations that are 3807 /// known to be compatible. 3808 /// 3809 /// This routine handles the merging of attributes and other 3810 /// properties of function declarations from the old declaration to 3811 /// the new declaration, once we know that New is in fact a 3812 /// redeclaration of Old. 3813 /// 3814 /// \returns false 3815 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3816 Scope *S, bool MergeTypeWithOld) { 3817 // Merge the attributes 3818 mergeDeclAttributes(New, Old); 3819 3820 // Merge "pure" flag. 3821 if (Old->isPure()) 3822 New->setPure(); 3823 3824 // Merge "used" flag. 3825 if (Old->getMostRecentDecl()->isUsed(false)) 3826 New->setIsUsed(); 3827 3828 // Merge attributes from the parameters. These can mismatch with K&R 3829 // declarations. 3830 if (New->getNumParams() == Old->getNumParams()) 3831 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3832 ParmVarDecl *NewParam = New->getParamDecl(i); 3833 ParmVarDecl *OldParam = Old->getParamDecl(i); 3834 mergeParamDeclAttributes(NewParam, OldParam, *this); 3835 mergeParamDeclTypes(NewParam, OldParam, *this); 3836 } 3837 3838 if (getLangOpts().CPlusPlus) 3839 return MergeCXXFunctionDecl(New, Old, S); 3840 3841 // Merge the function types so the we get the composite types for the return 3842 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3843 // was visible. 3844 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3845 if (!Merged.isNull() && MergeTypeWithOld) 3846 New->setType(Merged); 3847 3848 return false; 3849 } 3850 3851 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3852 ObjCMethodDecl *oldMethod) { 3853 // Merge the attributes, including deprecated/unavailable 3854 AvailabilityMergeKind MergeKind = 3855 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3856 ? AMK_ProtocolImplementation 3857 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3858 : AMK_Override; 3859 3860 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3861 3862 // Merge attributes from the parameters. 3863 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3864 oe = oldMethod->param_end(); 3865 for (ObjCMethodDecl::param_iterator 3866 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3867 ni != ne && oi != oe; ++ni, ++oi) 3868 mergeParamDeclAttributes(*ni, *oi, *this); 3869 3870 CheckObjCMethodOverride(newMethod, oldMethod); 3871 } 3872 3873 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3874 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3875 3876 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3877 ? diag::err_redefinition_different_type 3878 : diag::err_redeclaration_different_type) 3879 << New->getDeclName() << New->getType() << Old->getType(); 3880 3881 diag::kind PrevDiag; 3882 SourceLocation OldLocation; 3883 std::tie(PrevDiag, OldLocation) 3884 = getNoteDiagForInvalidRedeclaration(Old, New); 3885 S.Diag(OldLocation, PrevDiag); 3886 New->setInvalidDecl(); 3887 } 3888 3889 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3890 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3891 /// emitting diagnostics as appropriate. 3892 /// 3893 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3894 /// to here in AddInitializerToDecl. We can't check them before the initializer 3895 /// is attached. 3896 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3897 bool MergeTypeWithOld) { 3898 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3899 return; 3900 3901 QualType MergedT; 3902 if (getLangOpts().CPlusPlus) { 3903 if (New->getType()->isUndeducedType()) { 3904 // We don't know what the new type is until the initializer is attached. 3905 return; 3906 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3907 // These could still be something that needs exception specs checked. 3908 return MergeVarDeclExceptionSpecs(New, Old); 3909 } 3910 // C++ [basic.link]p10: 3911 // [...] the types specified by all declarations referring to a given 3912 // object or function shall be identical, except that declarations for an 3913 // array object can specify array types that differ by the presence or 3914 // absence of a major array bound (8.3.4). 3915 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3916 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3917 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3918 3919 // We are merging a variable declaration New into Old. If it has an array 3920 // bound, and that bound differs from Old's bound, we should diagnose the 3921 // mismatch. 3922 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3923 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3924 PrevVD = PrevVD->getPreviousDecl()) { 3925 QualType PrevVDTy = PrevVD->getType(); 3926 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3927 continue; 3928 3929 if (!Context.hasSameType(New->getType(), PrevVDTy)) 3930 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3931 } 3932 } 3933 3934 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3935 if (Context.hasSameType(OldArray->getElementType(), 3936 NewArray->getElementType())) 3937 MergedT = New->getType(); 3938 } 3939 // FIXME: Check visibility. New is hidden but has a complete type. If New 3940 // has no array bound, it should not inherit one from Old, if Old is not 3941 // visible. 3942 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3943 if (Context.hasSameType(OldArray->getElementType(), 3944 NewArray->getElementType())) 3945 MergedT = Old->getType(); 3946 } 3947 } 3948 else if (New->getType()->isObjCObjectPointerType() && 3949 Old->getType()->isObjCObjectPointerType()) { 3950 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3951 Old->getType()); 3952 } 3953 } else { 3954 // C 6.2.7p2: 3955 // All declarations that refer to the same object or function shall have 3956 // compatible type. 3957 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3958 } 3959 if (MergedT.isNull()) { 3960 // It's OK if we couldn't merge types if either type is dependent, for a 3961 // block-scope variable. In other cases (static data members of class 3962 // templates, variable templates, ...), we require the types to be 3963 // equivalent. 3964 // FIXME: The C++ standard doesn't say anything about this. 3965 if ((New->getType()->isDependentType() || 3966 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3967 // If the old type was dependent, we can't merge with it, so the new type 3968 // becomes dependent for now. We'll reproduce the original type when we 3969 // instantiate the TypeSourceInfo for the variable. 3970 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3971 New->setType(Context.DependentTy); 3972 return; 3973 } 3974 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3975 } 3976 3977 // Don't actually update the type on the new declaration if the old 3978 // declaration was an extern declaration in a different scope. 3979 if (MergeTypeWithOld) 3980 New->setType(MergedT); 3981 } 3982 3983 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3984 LookupResult &Previous) { 3985 // C11 6.2.7p4: 3986 // For an identifier with internal or external linkage declared 3987 // in a scope in which a prior declaration of that identifier is 3988 // visible, if the prior declaration specifies internal or 3989 // external linkage, the type of the identifier at the later 3990 // declaration becomes the composite type. 3991 // 3992 // If the variable isn't visible, we do not merge with its type. 3993 if (Previous.isShadowed()) 3994 return false; 3995 3996 if (S.getLangOpts().CPlusPlus) { 3997 // C++11 [dcl.array]p3: 3998 // If there is a preceding declaration of the entity in the same 3999 // scope in which the bound was specified, an omitted array bound 4000 // is taken to be the same as in that earlier declaration. 4001 return NewVD->isPreviousDeclInSameBlockScope() || 4002 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4003 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4004 } else { 4005 // If the old declaration was function-local, don't merge with its 4006 // type unless we're in the same function. 4007 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4008 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4009 } 4010 } 4011 4012 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4013 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4014 /// situation, merging decls or emitting diagnostics as appropriate. 4015 /// 4016 /// Tentative definition rules (C99 6.9.2p2) are checked by 4017 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4018 /// definitions here, since the initializer hasn't been attached. 4019 /// 4020 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4021 // If the new decl is already invalid, don't do any other checking. 4022 if (New->isInvalidDecl()) 4023 return; 4024 4025 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4026 return; 4027 4028 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4029 4030 // Verify the old decl was also a variable or variable template. 4031 VarDecl *Old = nullptr; 4032 VarTemplateDecl *OldTemplate = nullptr; 4033 if (Previous.isSingleResult()) { 4034 if (NewTemplate) { 4035 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4036 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4037 4038 if (auto *Shadow = 4039 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4040 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4041 return New->setInvalidDecl(); 4042 } else { 4043 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4044 4045 if (auto *Shadow = 4046 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4047 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4048 return New->setInvalidDecl(); 4049 } 4050 } 4051 if (!Old) { 4052 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4053 << New->getDeclName(); 4054 notePreviousDefinition(Previous.getRepresentativeDecl(), 4055 New->getLocation()); 4056 return New->setInvalidDecl(); 4057 } 4058 4059 // If the old declaration was found in an inline namespace and the new 4060 // declaration was qualified, update the DeclContext to match. 4061 adjustDeclContextForDeclaratorDecl(New, Old); 4062 4063 // Ensure the template parameters are compatible. 4064 if (NewTemplate && 4065 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4066 OldTemplate->getTemplateParameters(), 4067 /*Complain=*/true, TPL_TemplateMatch)) 4068 return New->setInvalidDecl(); 4069 4070 // C++ [class.mem]p1: 4071 // A member shall not be declared twice in the member-specification [...] 4072 // 4073 // Here, we need only consider static data members. 4074 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4075 Diag(New->getLocation(), diag::err_duplicate_member) 4076 << New->getIdentifier(); 4077 Diag(Old->getLocation(), diag::note_previous_declaration); 4078 New->setInvalidDecl(); 4079 } 4080 4081 mergeDeclAttributes(New, Old); 4082 // Warn if an already-declared variable is made a weak_import in a subsequent 4083 // declaration 4084 if (New->hasAttr<WeakImportAttr>() && 4085 Old->getStorageClass() == SC_None && 4086 !Old->hasAttr<WeakImportAttr>()) { 4087 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4088 notePreviousDefinition(Old, New->getLocation()); 4089 // Remove weak_import attribute on new declaration. 4090 New->dropAttr<WeakImportAttr>(); 4091 } 4092 4093 if (New->hasAttr<InternalLinkageAttr>() && 4094 !Old->hasAttr<InternalLinkageAttr>()) { 4095 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4096 << New->getDeclName(); 4097 notePreviousDefinition(Old, New->getLocation()); 4098 New->dropAttr<InternalLinkageAttr>(); 4099 } 4100 4101 // Merge the types. 4102 VarDecl *MostRecent = Old->getMostRecentDecl(); 4103 if (MostRecent != Old) { 4104 MergeVarDeclTypes(New, MostRecent, 4105 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4106 if (New->isInvalidDecl()) 4107 return; 4108 } 4109 4110 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4111 if (New->isInvalidDecl()) 4112 return; 4113 4114 diag::kind PrevDiag; 4115 SourceLocation OldLocation; 4116 std::tie(PrevDiag, OldLocation) = 4117 getNoteDiagForInvalidRedeclaration(Old, New); 4118 4119 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4120 if (New->getStorageClass() == SC_Static && 4121 !New->isStaticDataMember() && 4122 Old->hasExternalFormalLinkage()) { 4123 if (getLangOpts().MicrosoftExt) { 4124 Diag(New->getLocation(), diag::ext_static_non_static) 4125 << New->getDeclName(); 4126 Diag(OldLocation, PrevDiag); 4127 } else { 4128 Diag(New->getLocation(), diag::err_static_non_static) 4129 << New->getDeclName(); 4130 Diag(OldLocation, PrevDiag); 4131 return New->setInvalidDecl(); 4132 } 4133 } 4134 // C99 6.2.2p4: 4135 // For an identifier declared with the storage-class specifier 4136 // extern in a scope in which a prior declaration of that 4137 // identifier is visible,23) if the prior declaration specifies 4138 // internal or external linkage, the linkage of the identifier at 4139 // the later declaration is the same as the linkage specified at 4140 // the prior declaration. If no prior declaration is visible, or 4141 // if the prior declaration specifies no linkage, then the 4142 // identifier has external linkage. 4143 if (New->hasExternalStorage() && Old->hasLinkage()) 4144 /* Okay */; 4145 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4146 !New->isStaticDataMember() && 4147 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4148 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4149 Diag(OldLocation, PrevDiag); 4150 return New->setInvalidDecl(); 4151 } 4152 4153 // Check if extern is followed by non-extern and vice-versa. 4154 if (New->hasExternalStorage() && 4155 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4156 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4157 Diag(OldLocation, PrevDiag); 4158 return New->setInvalidDecl(); 4159 } 4160 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4161 !New->hasExternalStorage()) { 4162 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4163 Diag(OldLocation, PrevDiag); 4164 return New->setInvalidDecl(); 4165 } 4166 4167 if (CheckRedeclarationModuleOwnership(New, Old)) 4168 return; 4169 4170 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4171 4172 // FIXME: The test for external storage here seems wrong? We still 4173 // need to check for mismatches. 4174 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4175 // Don't complain about out-of-line definitions of static members. 4176 !(Old->getLexicalDeclContext()->isRecord() && 4177 !New->getLexicalDeclContext()->isRecord())) { 4178 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4179 Diag(OldLocation, PrevDiag); 4180 return New->setInvalidDecl(); 4181 } 4182 4183 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4184 if (VarDecl *Def = Old->getDefinition()) { 4185 // C++1z [dcl.fcn.spec]p4: 4186 // If the definition of a variable appears in a translation unit before 4187 // its first declaration as inline, the program is ill-formed. 4188 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4189 Diag(Def->getLocation(), diag::note_previous_definition); 4190 } 4191 } 4192 4193 // If this redeclaration makes the variable inline, we may need to add it to 4194 // UndefinedButUsed. 4195 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4196 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4197 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4198 SourceLocation())); 4199 4200 if (New->getTLSKind() != Old->getTLSKind()) { 4201 if (!Old->getTLSKind()) { 4202 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4203 Diag(OldLocation, PrevDiag); 4204 } else if (!New->getTLSKind()) { 4205 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4206 Diag(OldLocation, PrevDiag); 4207 } else { 4208 // Do not allow redeclaration to change the variable between requiring 4209 // static and dynamic initialization. 4210 // FIXME: GCC allows this, but uses the TLS keyword on the first 4211 // declaration to determine the kind. Do we need to be compatible here? 4212 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4213 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4214 Diag(OldLocation, PrevDiag); 4215 } 4216 } 4217 4218 // C++ doesn't have tentative definitions, so go right ahead and check here. 4219 if (getLangOpts().CPlusPlus && 4220 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4221 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4222 Old->getCanonicalDecl()->isConstexpr()) { 4223 // This definition won't be a definition any more once it's been merged. 4224 Diag(New->getLocation(), 4225 diag::warn_deprecated_redundant_constexpr_static_def); 4226 } else if (VarDecl *Def = Old->getDefinition()) { 4227 if (checkVarDeclRedefinition(Def, New)) 4228 return; 4229 } 4230 } 4231 4232 if (haveIncompatibleLanguageLinkages(Old, New)) { 4233 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4234 Diag(OldLocation, PrevDiag); 4235 New->setInvalidDecl(); 4236 return; 4237 } 4238 4239 // Merge "used" flag. 4240 if (Old->getMostRecentDecl()->isUsed(false)) 4241 New->setIsUsed(); 4242 4243 // Keep a chain of previous declarations. 4244 New->setPreviousDecl(Old); 4245 if (NewTemplate) 4246 NewTemplate->setPreviousDecl(OldTemplate); 4247 4248 // Inherit access appropriately. 4249 New->setAccess(Old->getAccess()); 4250 if (NewTemplate) 4251 NewTemplate->setAccess(New->getAccess()); 4252 4253 if (Old->isInline()) 4254 New->setImplicitlyInline(); 4255 } 4256 4257 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4258 SourceManager &SrcMgr = getSourceManager(); 4259 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4260 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4261 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4262 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4263 auto &HSI = PP.getHeaderSearchInfo(); 4264 StringRef HdrFilename = 4265 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4266 4267 auto noteFromModuleOrInclude = [&](Module *Mod, 4268 SourceLocation IncLoc) -> bool { 4269 // Redefinition errors with modules are common with non modular mapped 4270 // headers, example: a non-modular header H in module A that also gets 4271 // included directly in a TU. Pointing twice to the same header/definition 4272 // is confusing, try to get better diagnostics when modules is on. 4273 if (IncLoc.isValid()) { 4274 if (Mod) { 4275 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4276 << HdrFilename.str() << Mod->getFullModuleName(); 4277 if (!Mod->DefinitionLoc.isInvalid()) 4278 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4279 << Mod->getFullModuleName(); 4280 } else { 4281 Diag(IncLoc, diag::note_redefinition_include_same_file) 4282 << HdrFilename.str(); 4283 } 4284 return true; 4285 } 4286 4287 return false; 4288 }; 4289 4290 // Is it the same file and same offset? Provide more information on why 4291 // this leads to a redefinition error. 4292 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4293 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4294 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4295 bool EmittedDiag = 4296 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4297 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4298 4299 // If the header has no guards, emit a note suggesting one. 4300 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4301 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4302 4303 if (EmittedDiag) 4304 return; 4305 } 4306 4307 // Redefinition coming from different files or couldn't do better above. 4308 if (Old->getLocation().isValid()) 4309 Diag(Old->getLocation(), diag::note_previous_definition); 4310 } 4311 4312 /// We've just determined that \p Old and \p New both appear to be definitions 4313 /// of the same variable. Either diagnose or fix the problem. 4314 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4315 if (!hasVisibleDefinition(Old) && 4316 (New->getFormalLinkage() == InternalLinkage || 4317 New->isInline() || 4318 New->getDescribedVarTemplate() || 4319 New->getNumTemplateParameterLists() || 4320 New->getDeclContext()->isDependentContext())) { 4321 // The previous definition is hidden, and multiple definitions are 4322 // permitted (in separate TUs). Demote this to a declaration. 4323 New->demoteThisDefinitionToDeclaration(); 4324 4325 // Make the canonical definition visible. 4326 if (auto *OldTD = Old->getDescribedVarTemplate()) 4327 makeMergedDefinitionVisible(OldTD); 4328 makeMergedDefinitionVisible(Old); 4329 return false; 4330 } else { 4331 Diag(New->getLocation(), diag::err_redefinition) << New; 4332 notePreviousDefinition(Old, New->getLocation()); 4333 New->setInvalidDecl(); 4334 return true; 4335 } 4336 } 4337 4338 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4339 /// no declarator (e.g. "struct foo;") is parsed. 4340 Decl * 4341 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4342 RecordDecl *&AnonRecord) { 4343 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4344 AnonRecord); 4345 } 4346 4347 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4348 // disambiguate entities defined in different scopes. 4349 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4350 // compatibility. 4351 // We will pick our mangling number depending on which version of MSVC is being 4352 // targeted. 4353 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4354 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4355 ? S->getMSCurManglingNumber() 4356 : S->getMSLastManglingNumber(); 4357 } 4358 4359 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4360 if (!Context.getLangOpts().CPlusPlus) 4361 return; 4362 4363 if (isa<CXXRecordDecl>(Tag->getParent())) { 4364 // If this tag is the direct child of a class, number it if 4365 // it is anonymous. 4366 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4367 return; 4368 MangleNumberingContext &MCtx = 4369 Context.getManglingNumberContext(Tag->getParent()); 4370 Context.setManglingNumber( 4371 Tag, MCtx.getManglingNumber( 4372 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4373 return; 4374 } 4375 4376 // If this tag isn't a direct child of a class, number it if it is local. 4377 MangleNumberingContext *MCtx; 4378 Decl *ManglingContextDecl; 4379 std::tie(MCtx, ManglingContextDecl) = 4380 getCurrentMangleNumberContext(Tag->getDeclContext()); 4381 if (MCtx) { 4382 Context.setManglingNumber( 4383 Tag, MCtx->getManglingNumber( 4384 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4385 } 4386 } 4387 4388 namespace { 4389 struct NonCLikeKind { 4390 enum { 4391 None, 4392 BaseClass, 4393 DefaultMemberInit, 4394 Lambda, 4395 Friend, 4396 OtherMember, 4397 Invalid, 4398 } Kind = None; 4399 SourceRange Range; 4400 4401 explicit operator bool() { return Kind != None; } 4402 }; 4403 } 4404 4405 /// Determine whether a class is C-like, according to the rules of C++ 4406 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4407 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4408 if (RD->isInvalidDecl()) 4409 return {NonCLikeKind::Invalid, {}}; 4410 4411 // C++ [dcl.typedef]p9: [P1766R1] 4412 // An unnamed class with a typedef name for linkage purposes shall not 4413 // 4414 // -- have any base classes 4415 if (RD->getNumBases()) 4416 return {NonCLikeKind::BaseClass, 4417 SourceRange(RD->bases_begin()->getBeginLoc(), 4418 RD->bases_end()[-1].getEndLoc())}; 4419 bool Invalid = false; 4420 for (Decl *D : RD->decls()) { 4421 // Don't complain about things we already diagnosed. 4422 if (D->isInvalidDecl()) { 4423 Invalid = true; 4424 continue; 4425 } 4426 4427 // -- have any [...] default member initializers 4428 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4429 if (FD->hasInClassInitializer()) { 4430 auto *Init = FD->getInClassInitializer(); 4431 return {NonCLikeKind::DefaultMemberInit, 4432 Init ? Init->getSourceRange() : D->getSourceRange()}; 4433 } 4434 continue; 4435 } 4436 4437 // FIXME: We don't allow friend declarations. This violates the wording of 4438 // P1766, but not the intent. 4439 if (isa<FriendDecl>(D)) 4440 return {NonCLikeKind::Friend, D->getSourceRange()}; 4441 4442 // -- declare any members other than non-static data members, member 4443 // enumerations, or member classes, 4444 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4445 isa<EnumDecl>(D)) 4446 continue; 4447 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4448 if (!MemberRD) { 4449 if (D->isImplicit()) 4450 continue; 4451 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4452 } 4453 4454 // -- contain a lambda-expression, 4455 if (MemberRD->isLambda()) 4456 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4457 4458 // and all member classes shall also satisfy these requirements 4459 // (recursively). 4460 if (MemberRD->isThisDeclarationADefinition()) { 4461 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4462 return Kind; 4463 } 4464 } 4465 4466 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4467 } 4468 4469 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4470 TypedefNameDecl *NewTD) { 4471 if (TagFromDeclSpec->isInvalidDecl()) 4472 return; 4473 4474 // Do nothing if the tag already has a name for linkage purposes. 4475 if (TagFromDeclSpec->hasNameForLinkage()) 4476 return; 4477 4478 // A well-formed anonymous tag must always be a TUK_Definition. 4479 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4480 4481 // The type must match the tag exactly; no qualifiers allowed. 4482 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4483 Context.getTagDeclType(TagFromDeclSpec))) { 4484 if (getLangOpts().CPlusPlus) 4485 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4486 return; 4487 } 4488 4489 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4490 // An unnamed class with a typedef name for linkage purposes shall [be 4491 // C-like]. 4492 // 4493 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4494 // shouldn't happen, but there are constructs that the language rule doesn't 4495 // disallow for which we can't reasonably avoid computing linkage early. 4496 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4497 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4498 : NonCLikeKind(); 4499 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4500 if (NonCLike || ChangesLinkage) { 4501 if (NonCLike.Kind == NonCLikeKind::Invalid) 4502 return; 4503 4504 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4505 if (ChangesLinkage) { 4506 // If the linkage changes, we can't accept this as an extension. 4507 if (NonCLike.Kind == NonCLikeKind::None) 4508 DiagID = diag::err_typedef_changes_linkage; 4509 else 4510 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4511 } 4512 4513 SourceLocation FixitLoc = 4514 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4515 llvm::SmallString<40> TextToInsert; 4516 TextToInsert += ' '; 4517 TextToInsert += NewTD->getIdentifier()->getName(); 4518 4519 Diag(FixitLoc, DiagID) 4520 << isa<TypeAliasDecl>(NewTD) 4521 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4522 if (NonCLike.Kind != NonCLikeKind::None) { 4523 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4524 << NonCLike.Kind - 1 << NonCLike.Range; 4525 } 4526 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4527 << NewTD << isa<TypeAliasDecl>(NewTD); 4528 4529 if (ChangesLinkage) 4530 return; 4531 } 4532 4533 // Otherwise, set this as the anon-decl typedef for the tag. 4534 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4535 } 4536 4537 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4538 switch (T) { 4539 case DeclSpec::TST_class: 4540 return 0; 4541 case DeclSpec::TST_struct: 4542 return 1; 4543 case DeclSpec::TST_interface: 4544 return 2; 4545 case DeclSpec::TST_union: 4546 return 3; 4547 case DeclSpec::TST_enum: 4548 return 4; 4549 default: 4550 llvm_unreachable("unexpected type specifier"); 4551 } 4552 } 4553 4554 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4555 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4556 /// parameters to cope with template friend declarations. 4557 Decl * 4558 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4559 MultiTemplateParamsArg TemplateParams, 4560 bool IsExplicitInstantiation, 4561 RecordDecl *&AnonRecord) { 4562 Decl *TagD = nullptr; 4563 TagDecl *Tag = nullptr; 4564 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4565 DS.getTypeSpecType() == DeclSpec::TST_struct || 4566 DS.getTypeSpecType() == DeclSpec::TST_interface || 4567 DS.getTypeSpecType() == DeclSpec::TST_union || 4568 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4569 TagD = DS.getRepAsDecl(); 4570 4571 if (!TagD) // We probably had an error 4572 return nullptr; 4573 4574 // Note that the above type specs guarantee that the 4575 // type rep is a Decl, whereas in many of the others 4576 // it's a Type. 4577 if (isa<TagDecl>(TagD)) 4578 Tag = cast<TagDecl>(TagD); 4579 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4580 Tag = CTD->getTemplatedDecl(); 4581 } 4582 4583 if (Tag) { 4584 handleTagNumbering(Tag, S); 4585 Tag->setFreeStanding(); 4586 if (Tag->isInvalidDecl()) 4587 return Tag; 4588 } 4589 4590 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4591 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4592 // or incomplete types shall not be restrict-qualified." 4593 if (TypeQuals & DeclSpec::TQ_restrict) 4594 Diag(DS.getRestrictSpecLoc(), 4595 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4596 << DS.getSourceRange(); 4597 } 4598 4599 if (DS.isInlineSpecified()) 4600 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4601 << getLangOpts().CPlusPlus17; 4602 4603 if (DS.hasConstexprSpecifier()) { 4604 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4605 // and definitions of functions and variables. 4606 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4607 // the declaration of a function or function template 4608 if (Tag) 4609 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4610 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4611 << static_cast<int>(DS.getConstexprSpecifier()); 4612 else 4613 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4614 << static_cast<int>(DS.getConstexprSpecifier()); 4615 // Don't emit warnings after this error. 4616 return TagD; 4617 } 4618 4619 DiagnoseFunctionSpecifiers(DS); 4620 4621 if (DS.isFriendSpecified()) { 4622 // If we're dealing with a decl but not a TagDecl, assume that 4623 // whatever routines created it handled the friendship aspect. 4624 if (TagD && !Tag) 4625 return nullptr; 4626 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4627 } 4628 4629 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4630 bool IsExplicitSpecialization = 4631 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4632 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4633 !IsExplicitInstantiation && !IsExplicitSpecialization && 4634 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4635 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4636 // nested-name-specifier unless it is an explicit instantiation 4637 // or an explicit specialization. 4638 // 4639 // FIXME: We allow class template partial specializations here too, per the 4640 // obvious intent of DR1819. 4641 // 4642 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4643 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4644 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4645 return nullptr; 4646 } 4647 4648 // Track whether this decl-specifier declares anything. 4649 bool DeclaresAnything = true; 4650 4651 // Handle anonymous struct definitions. 4652 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4653 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4654 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4655 if (getLangOpts().CPlusPlus || 4656 Record->getDeclContext()->isRecord()) { 4657 // If CurContext is a DeclContext that can contain statements, 4658 // RecursiveASTVisitor won't visit the decls that 4659 // BuildAnonymousStructOrUnion() will put into CurContext. 4660 // Also store them here so that they can be part of the 4661 // DeclStmt that gets created in this case. 4662 // FIXME: Also return the IndirectFieldDecls created by 4663 // BuildAnonymousStructOr union, for the same reason? 4664 if (CurContext->isFunctionOrMethod()) 4665 AnonRecord = Record; 4666 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4667 Context.getPrintingPolicy()); 4668 } 4669 4670 DeclaresAnything = false; 4671 } 4672 } 4673 4674 // C11 6.7.2.1p2: 4675 // A struct-declaration that does not declare an anonymous structure or 4676 // anonymous union shall contain a struct-declarator-list. 4677 // 4678 // This rule also existed in C89 and C99; the grammar for struct-declaration 4679 // did not permit a struct-declaration without a struct-declarator-list. 4680 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4681 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4682 // Check for Microsoft C extension: anonymous struct/union member. 4683 // Handle 2 kinds of anonymous struct/union: 4684 // struct STRUCT; 4685 // union UNION; 4686 // and 4687 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4688 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4689 if ((Tag && Tag->getDeclName()) || 4690 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4691 RecordDecl *Record = nullptr; 4692 if (Tag) 4693 Record = dyn_cast<RecordDecl>(Tag); 4694 else if (const RecordType *RT = 4695 DS.getRepAsType().get()->getAsStructureType()) 4696 Record = RT->getDecl(); 4697 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4698 Record = UT->getDecl(); 4699 4700 if (Record && getLangOpts().MicrosoftExt) { 4701 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4702 << Record->isUnion() << DS.getSourceRange(); 4703 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4704 } 4705 4706 DeclaresAnything = false; 4707 } 4708 } 4709 4710 // Skip all the checks below if we have a type error. 4711 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4712 (TagD && TagD->isInvalidDecl())) 4713 return TagD; 4714 4715 if (getLangOpts().CPlusPlus && 4716 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4717 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4718 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4719 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4720 DeclaresAnything = false; 4721 4722 if (!DS.isMissingDeclaratorOk()) { 4723 // Customize diagnostic for a typedef missing a name. 4724 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4725 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4726 << DS.getSourceRange(); 4727 else 4728 DeclaresAnything = false; 4729 } 4730 4731 if (DS.isModulePrivateSpecified() && 4732 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4733 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4734 << Tag->getTagKind() 4735 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4736 4737 ActOnDocumentableDecl(TagD); 4738 4739 // C 6.7/2: 4740 // A declaration [...] shall declare at least a declarator [...], a tag, 4741 // or the members of an enumeration. 4742 // C++ [dcl.dcl]p3: 4743 // [If there are no declarators], and except for the declaration of an 4744 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4745 // names into the program, or shall redeclare a name introduced by a 4746 // previous declaration. 4747 if (!DeclaresAnything) { 4748 // In C, we allow this as a (popular) extension / bug. Don't bother 4749 // producing further diagnostics for redundant qualifiers after this. 4750 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 4751 ? diag::err_no_declarators 4752 : diag::ext_no_declarators) 4753 << DS.getSourceRange(); 4754 return TagD; 4755 } 4756 4757 // C++ [dcl.stc]p1: 4758 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4759 // init-declarator-list of the declaration shall not be empty. 4760 // C++ [dcl.fct.spec]p1: 4761 // If a cv-qualifier appears in a decl-specifier-seq, the 4762 // init-declarator-list of the declaration shall not be empty. 4763 // 4764 // Spurious qualifiers here appear to be valid in C. 4765 unsigned DiagID = diag::warn_standalone_specifier; 4766 if (getLangOpts().CPlusPlus) 4767 DiagID = diag::ext_standalone_specifier; 4768 4769 // Note that a linkage-specification sets a storage class, but 4770 // 'extern "C" struct foo;' is actually valid and not theoretically 4771 // useless. 4772 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4773 if (SCS == DeclSpec::SCS_mutable) 4774 // Since mutable is not a viable storage class specifier in C, there is 4775 // no reason to treat it as an extension. Instead, diagnose as an error. 4776 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4777 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4778 Diag(DS.getStorageClassSpecLoc(), DiagID) 4779 << DeclSpec::getSpecifierName(SCS); 4780 } 4781 4782 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4783 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4784 << DeclSpec::getSpecifierName(TSCS); 4785 if (DS.getTypeQualifiers()) { 4786 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4787 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4788 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4789 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4790 // Restrict is covered above. 4791 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4792 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4793 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4794 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4795 } 4796 4797 // Warn about ignored type attributes, for example: 4798 // __attribute__((aligned)) struct A; 4799 // Attributes should be placed after tag to apply to type declaration. 4800 if (!DS.getAttributes().empty()) { 4801 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4802 if (TypeSpecType == DeclSpec::TST_class || 4803 TypeSpecType == DeclSpec::TST_struct || 4804 TypeSpecType == DeclSpec::TST_interface || 4805 TypeSpecType == DeclSpec::TST_union || 4806 TypeSpecType == DeclSpec::TST_enum) { 4807 for (const ParsedAttr &AL : DS.getAttributes()) 4808 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4809 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4810 } 4811 } 4812 4813 return TagD; 4814 } 4815 4816 /// We are trying to inject an anonymous member into the given scope; 4817 /// check if there's an existing declaration that can't be overloaded. 4818 /// 4819 /// \return true if this is a forbidden redeclaration 4820 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4821 Scope *S, 4822 DeclContext *Owner, 4823 DeclarationName Name, 4824 SourceLocation NameLoc, 4825 bool IsUnion) { 4826 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4827 Sema::ForVisibleRedeclaration); 4828 if (!SemaRef.LookupName(R, S)) return false; 4829 4830 // Pick a representative declaration. 4831 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4832 assert(PrevDecl && "Expected a non-null Decl"); 4833 4834 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4835 return false; 4836 4837 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4838 << IsUnion << Name; 4839 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4840 4841 return true; 4842 } 4843 4844 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4845 /// anonymous struct or union AnonRecord into the owning context Owner 4846 /// and scope S. This routine will be invoked just after we realize 4847 /// that an unnamed union or struct is actually an anonymous union or 4848 /// struct, e.g., 4849 /// 4850 /// @code 4851 /// union { 4852 /// int i; 4853 /// float f; 4854 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4855 /// // f into the surrounding scope.x 4856 /// @endcode 4857 /// 4858 /// This routine is recursive, injecting the names of nested anonymous 4859 /// structs/unions into the owning context and scope as well. 4860 static bool 4861 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4862 RecordDecl *AnonRecord, AccessSpecifier AS, 4863 SmallVectorImpl<NamedDecl *> &Chaining) { 4864 bool Invalid = false; 4865 4866 // Look every FieldDecl and IndirectFieldDecl with a name. 4867 for (auto *D : AnonRecord->decls()) { 4868 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4869 cast<NamedDecl>(D)->getDeclName()) { 4870 ValueDecl *VD = cast<ValueDecl>(D); 4871 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4872 VD->getLocation(), 4873 AnonRecord->isUnion())) { 4874 // C++ [class.union]p2: 4875 // The names of the members of an anonymous union shall be 4876 // distinct from the names of any other entity in the 4877 // scope in which the anonymous union is declared. 4878 Invalid = true; 4879 } else { 4880 // C++ [class.union]p2: 4881 // For the purpose of name lookup, after the anonymous union 4882 // definition, the members of the anonymous union are 4883 // considered to have been defined in the scope in which the 4884 // anonymous union is declared. 4885 unsigned OldChainingSize = Chaining.size(); 4886 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4887 Chaining.append(IF->chain_begin(), IF->chain_end()); 4888 else 4889 Chaining.push_back(VD); 4890 4891 assert(Chaining.size() >= 2); 4892 NamedDecl **NamedChain = 4893 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4894 for (unsigned i = 0; i < Chaining.size(); i++) 4895 NamedChain[i] = Chaining[i]; 4896 4897 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4898 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4899 VD->getType(), {NamedChain, Chaining.size()}); 4900 4901 for (const auto *Attr : VD->attrs()) 4902 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4903 4904 IndirectField->setAccess(AS); 4905 IndirectField->setImplicit(); 4906 SemaRef.PushOnScopeChains(IndirectField, S); 4907 4908 // That includes picking up the appropriate access specifier. 4909 if (AS != AS_none) IndirectField->setAccess(AS); 4910 4911 Chaining.resize(OldChainingSize); 4912 } 4913 } 4914 } 4915 4916 return Invalid; 4917 } 4918 4919 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4920 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4921 /// illegal input values are mapped to SC_None. 4922 static StorageClass 4923 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4924 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4925 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4926 "Parser allowed 'typedef' as storage class VarDecl."); 4927 switch (StorageClassSpec) { 4928 case DeclSpec::SCS_unspecified: return SC_None; 4929 case DeclSpec::SCS_extern: 4930 if (DS.isExternInLinkageSpec()) 4931 return SC_None; 4932 return SC_Extern; 4933 case DeclSpec::SCS_static: return SC_Static; 4934 case DeclSpec::SCS_auto: return SC_Auto; 4935 case DeclSpec::SCS_register: return SC_Register; 4936 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4937 // Illegal SCSs map to None: error reporting is up to the caller. 4938 case DeclSpec::SCS_mutable: // Fall through. 4939 case DeclSpec::SCS_typedef: return SC_None; 4940 } 4941 llvm_unreachable("unknown storage class specifier"); 4942 } 4943 4944 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4945 assert(Record->hasInClassInitializer()); 4946 4947 for (const auto *I : Record->decls()) { 4948 const auto *FD = dyn_cast<FieldDecl>(I); 4949 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4950 FD = IFD->getAnonField(); 4951 if (FD && FD->hasInClassInitializer()) 4952 return FD->getLocation(); 4953 } 4954 4955 llvm_unreachable("couldn't find in-class initializer"); 4956 } 4957 4958 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4959 SourceLocation DefaultInitLoc) { 4960 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4961 return; 4962 4963 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4964 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4965 } 4966 4967 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4968 CXXRecordDecl *AnonUnion) { 4969 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4970 return; 4971 4972 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4973 } 4974 4975 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4976 /// anonymous structure or union. Anonymous unions are a C++ feature 4977 /// (C++ [class.union]) and a C11 feature; anonymous structures 4978 /// are a C11 feature and GNU C++ extension. 4979 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4980 AccessSpecifier AS, 4981 RecordDecl *Record, 4982 const PrintingPolicy &Policy) { 4983 DeclContext *Owner = Record->getDeclContext(); 4984 4985 // Diagnose whether this anonymous struct/union is an extension. 4986 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4987 Diag(Record->getLocation(), diag::ext_anonymous_union); 4988 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4989 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4990 else if (!Record->isUnion() && !getLangOpts().C11) 4991 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4992 4993 // C and C++ require different kinds of checks for anonymous 4994 // structs/unions. 4995 bool Invalid = false; 4996 if (getLangOpts().CPlusPlus) { 4997 const char *PrevSpec = nullptr; 4998 if (Record->isUnion()) { 4999 // C++ [class.union]p6: 5000 // C++17 [class.union.anon]p2: 5001 // Anonymous unions declared in a named namespace or in the 5002 // global namespace shall be declared static. 5003 unsigned DiagID; 5004 DeclContext *OwnerScope = Owner->getRedeclContext(); 5005 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5006 (OwnerScope->isTranslationUnit() || 5007 (OwnerScope->isNamespace() && 5008 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5009 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5010 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5011 5012 // Recover by adding 'static'. 5013 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5014 PrevSpec, DiagID, Policy); 5015 } 5016 // C++ [class.union]p6: 5017 // A storage class is not allowed in a declaration of an 5018 // anonymous union in a class scope. 5019 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5020 isa<RecordDecl>(Owner)) { 5021 Diag(DS.getStorageClassSpecLoc(), 5022 diag::err_anonymous_union_with_storage_spec) 5023 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5024 5025 // Recover by removing the storage specifier. 5026 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5027 SourceLocation(), 5028 PrevSpec, DiagID, Context.getPrintingPolicy()); 5029 } 5030 } 5031 5032 // Ignore const/volatile/restrict qualifiers. 5033 if (DS.getTypeQualifiers()) { 5034 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5035 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5036 << Record->isUnion() << "const" 5037 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5038 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5039 Diag(DS.getVolatileSpecLoc(), 5040 diag::ext_anonymous_struct_union_qualified) 5041 << Record->isUnion() << "volatile" 5042 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5043 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5044 Diag(DS.getRestrictSpecLoc(), 5045 diag::ext_anonymous_struct_union_qualified) 5046 << Record->isUnion() << "restrict" 5047 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5048 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5049 Diag(DS.getAtomicSpecLoc(), 5050 diag::ext_anonymous_struct_union_qualified) 5051 << Record->isUnion() << "_Atomic" 5052 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5053 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5054 Diag(DS.getUnalignedSpecLoc(), 5055 diag::ext_anonymous_struct_union_qualified) 5056 << Record->isUnion() << "__unaligned" 5057 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5058 5059 DS.ClearTypeQualifiers(); 5060 } 5061 5062 // C++ [class.union]p2: 5063 // The member-specification of an anonymous union shall only 5064 // define non-static data members. [Note: nested types and 5065 // functions cannot be declared within an anonymous union. ] 5066 for (auto *Mem : Record->decls()) { 5067 // Ignore invalid declarations; we already diagnosed them. 5068 if (Mem->isInvalidDecl()) 5069 continue; 5070 5071 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5072 // C++ [class.union]p3: 5073 // An anonymous union shall not have private or protected 5074 // members (clause 11). 5075 assert(FD->getAccess() != AS_none); 5076 if (FD->getAccess() != AS_public) { 5077 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5078 << Record->isUnion() << (FD->getAccess() == AS_protected); 5079 Invalid = true; 5080 } 5081 5082 // C++ [class.union]p1 5083 // An object of a class with a non-trivial constructor, a non-trivial 5084 // copy constructor, a non-trivial destructor, or a non-trivial copy 5085 // assignment operator cannot be a member of a union, nor can an 5086 // array of such objects. 5087 if (CheckNontrivialField(FD)) 5088 Invalid = true; 5089 } else if (Mem->isImplicit()) { 5090 // Any implicit members are fine. 5091 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5092 // This is a type that showed up in an 5093 // elaborated-type-specifier inside the anonymous struct or 5094 // union, but which actually declares a type outside of the 5095 // anonymous struct or union. It's okay. 5096 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5097 if (!MemRecord->isAnonymousStructOrUnion() && 5098 MemRecord->getDeclName()) { 5099 // Visual C++ allows type definition in anonymous struct or union. 5100 if (getLangOpts().MicrosoftExt) 5101 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5102 << Record->isUnion(); 5103 else { 5104 // This is a nested type declaration. 5105 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5106 << Record->isUnion(); 5107 Invalid = true; 5108 } 5109 } else { 5110 // This is an anonymous type definition within another anonymous type. 5111 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5112 // not part of standard C++. 5113 Diag(MemRecord->getLocation(), 5114 diag::ext_anonymous_record_with_anonymous_type) 5115 << Record->isUnion(); 5116 } 5117 } else if (isa<AccessSpecDecl>(Mem)) { 5118 // Any access specifier is fine. 5119 } else if (isa<StaticAssertDecl>(Mem)) { 5120 // In C++1z, static_assert declarations are also fine. 5121 } else { 5122 // We have something that isn't a non-static data 5123 // member. Complain about it. 5124 unsigned DK = diag::err_anonymous_record_bad_member; 5125 if (isa<TypeDecl>(Mem)) 5126 DK = diag::err_anonymous_record_with_type; 5127 else if (isa<FunctionDecl>(Mem)) 5128 DK = diag::err_anonymous_record_with_function; 5129 else if (isa<VarDecl>(Mem)) 5130 DK = diag::err_anonymous_record_with_static; 5131 5132 // Visual C++ allows type definition in anonymous struct or union. 5133 if (getLangOpts().MicrosoftExt && 5134 DK == diag::err_anonymous_record_with_type) 5135 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5136 << Record->isUnion(); 5137 else { 5138 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5139 Invalid = true; 5140 } 5141 } 5142 } 5143 5144 // C++11 [class.union]p8 (DR1460): 5145 // At most one variant member of a union may have a 5146 // brace-or-equal-initializer. 5147 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5148 Owner->isRecord()) 5149 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5150 cast<CXXRecordDecl>(Record)); 5151 } 5152 5153 if (!Record->isUnion() && !Owner->isRecord()) { 5154 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5155 << getLangOpts().CPlusPlus; 5156 Invalid = true; 5157 } 5158 5159 // C++ [dcl.dcl]p3: 5160 // [If there are no declarators], and except for the declaration of an 5161 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5162 // names into the program 5163 // C++ [class.mem]p2: 5164 // each such member-declaration shall either declare at least one member 5165 // name of the class or declare at least one unnamed bit-field 5166 // 5167 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5168 if (getLangOpts().CPlusPlus && Record->field_empty()) 5169 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5170 5171 // Mock up a declarator. 5172 Declarator Dc(DS, DeclaratorContext::Member); 5173 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5174 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5175 5176 // Create a declaration for this anonymous struct/union. 5177 NamedDecl *Anon = nullptr; 5178 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5179 Anon = FieldDecl::Create( 5180 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5181 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5182 /*BitWidth=*/nullptr, /*Mutable=*/false, 5183 /*InitStyle=*/ICIS_NoInit); 5184 Anon->setAccess(AS); 5185 ProcessDeclAttributes(S, Anon, Dc); 5186 5187 if (getLangOpts().CPlusPlus) 5188 FieldCollector->Add(cast<FieldDecl>(Anon)); 5189 } else { 5190 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5191 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5192 if (SCSpec == DeclSpec::SCS_mutable) { 5193 // mutable can only appear on non-static class members, so it's always 5194 // an error here 5195 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5196 Invalid = true; 5197 SC = SC_None; 5198 } 5199 5200 assert(DS.getAttributes().empty() && "No attribute expected"); 5201 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5202 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5203 Context.getTypeDeclType(Record), TInfo, SC); 5204 5205 // Default-initialize the implicit variable. This initialization will be 5206 // trivial in almost all cases, except if a union member has an in-class 5207 // initializer: 5208 // union { int n = 0; }; 5209 ActOnUninitializedDecl(Anon); 5210 } 5211 Anon->setImplicit(); 5212 5213 // Mark this as an anonymous struct/union type. 5214 Record->setAnonymousStructOrUnion(true); 5215 5216 // Add the anonymous struct/union object to the current 5217 // context. We'll be referencing this object when we refer to one of 5218 // its members. 5219 Owner->addDecl(Anon); 5220 5221 // Inject the members of the anonymous struct/union into the owning 5222 // context and into the identifier resolver chain for name lookup 5223 // purposes. 5224 SmallVector<NamedDecl*, 2> Chain; 5225 Chain.push_back(Anon); 5226 5227 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5228 Invalid = true; 5229 5230 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5231 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5232 MangleNumberingContext *MCtx; 5233 Decl *ManglingContextDecl; 5234 std::tie(MCtx, ManglingContextDecl) = 5235 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5236 if (MCtx) { 5237 Context.setManglingNumber( 5238 NewVD, MCtx->getManglingNumber( 5239 NewVD, getMSManglingNumber(getLangOpts(), S))); 5240 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5241 } 5242 } 5243 } 5244 5245 if (Invalid) 5246 Anon->setInvalidDecl(); 5247 5248 return Anon; 5249 } 5250 5251 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5252 /// Microsoft C anonymous structure. 5253 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5254 /// Example: 5255 /// 5256 /// struct A { int a; }; 5257 /// struct B { struct A; int b; }; 5258 /// 5259 /// void foo() { 5260 /// B var; 5261 /// var.a = 3; 5262 /// } 5263 /// 5264 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5265 RecordDecl *Record) { 5266 assert(Record && "expected a record!"); 5267 5268 // Mock up a declarator. 5269 Declarator Dc(DS, DeclaratorContext::TypeName); 5270 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5271 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5272 5273 auto *ParentDecl = cast<RecordDecl>(CurContext); 5274 QualType RecTy = Context.getTypeDeclType(Record); 5275 5276 // Create a declaration for this anonymous struct. 5277 NamedDecl *Anon = 5278 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5279 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5280 /*BitWidth=*/nullptr, /*Mutable=*/false, 5281 /*InitStyle=*/ICIS_NoInit); 5282 Anon->setImplicit(); 5283 5284 // Add the anonymous struct object to the current context. 5285 CurContext->addDecl(Anon); 5286 5287 // Inject the members of the anonymous struct into the current 5288 // context and into the identifier resolver chain for name lookup 5289 // purposes. 5290 SmallVector<NamedDecl*, 2> Chain; 5291 Chain.push_back(Anon); 5292 5293 RecordDecl *RecordDef = Record->getDefinition(); 5294 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5295 diag::err_field_incomplete_or_sizeless) || 5296 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5297 AS_none, Chain)) { 5298 Anon->setInvalidDecl(); 5299 ParentDecl->setInvalidDecl(); 5300 } 5301 5302 return Anon; 5303 } 5304 5305 /// GetNameForDeclarator - Determine the full declaration name for the 5306 /// given Declarator. 5307 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5308 return GetNameFromUnqualifiedId(D.getName()); 5309 } 5310 5311 /// Retrieves the declaration name from a parsed unqualified-id. 5312 DeclarationNameInfo 5313 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5314 DeclarationNameInfo NameInfo; 5315 NameInfo.setLoc(Name.StartLocation); 5316 5317 switch (Name.getKind()) { 5318 5319 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5320 case UnqualifiedIdKind::IK_Identifier: 5321 NameInfo.setName(Name.Identifier); 5322 return NameInfo; 5323 5324 case UnqualifiedIdKind::IK_DeductionGuideName: { 5325 // C++ [temp.deduct.guide]p3: 5326 // The simple-template-id shall name a class template specialization. 5327 // The template-name shall be the same identifier as the template-name 5328 // of the simple-template-id. 5329 // These together intend to imply that the template-name shall name a 5330 // class template. 5331 // FIXME: template<typename T> struct X {}; 5332 // template<typename T> using Y = X<T>; 5333 // Y(int) -> Y<int>; 5334 // satisfies these rules but does not name a class template. 5335 TemplateName TN = Name.TemplateName.get().get(); 5336 auto *Template = TN.getAsTemplateDecl(); 5337 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5338 Diag(Name.StartLocation, 5339 diag::err_deduction_guide_name_not_class_template) 5340 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5341 if (Template) 5342 Diag(Template->getLocation(), diag::note_template_decl_here); 5343 return DeclarationNameInfo(); 5344 } 5345 5346 NameInfo.setName( 5347 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5348 return NameInfo; 5349 } 5350 5351 case UnqualifiedIdKind::IK_OperatorFunctionId: 5352 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5353 Name.OperatorFunctionId.Operator)); 5354 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc = 5355 Name.OperatorFunctionId.SymbolLocations[0].getRawEncoding(); 5356 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5357 = Name.EndLocation.getRawEncoding(); 5358 return NameInfo; 5359 5360 case UnqualifiedIdKind::IK_LiteralOperatorId: 5361 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5362 Name.Identifier)); 5363 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5364 return NameInfo; 5365 5366 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5367 TypeSourceInfo *TInfo; 5368 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5369 if (Ty.isNull()) 5370 return DeclarationNameInfo(); 5371 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5372 Context.getCanonicalType(Ty))); 5373 NameInfo.setNamedTypeInfo(TInfo); 5374 return NameInfo; 5375 } 5376 5377 case UnqualifiedIdKind::IK_ConstructorName: { 5378 TypeSourceInfo *TInfo; 5379 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5380 if (Ty.isNull()) 5381 return DeclarationNameInfo(); 5382 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5383 Context.getCanonicalType(Ty))); 5384 NameInfo.setNamedTypeInfo(TInfo); 5385 return NameInfo; 5386 } 5387 5388 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5389 // In well-formed code, we can only have a constructor 5390 // template-id that refers to the current context, so go there 5391 // to find the actual type being constructed. 5392 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5393 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5394 return DeclarationNameInfo(); 5395 5396 // Determine the type of the class being constructed. 5397 QualType CurClassType = Context.getTypeDeclType(CurClass); 5398 5399 // FIXME: Check two things: that the template-id names the same type as 5400 // CurClassType, and that the template-id does not occur when the name 5401 // was qualified. 5402 5403 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5404 Context.getCanonicalType(CurClassType))); 5405 // FIXME: should we retrieve TypeSourceInfo? 5406 NameInfo.setNamedTypeInfo(nullptr); 5407 return NameInfo; 5408 } 5409 5410 case UnqualifiedIdKind::IK_DestructorName: { 5411 TypeSourceInfo *TInfo; 5412 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5413 if (Ty.isNull()) 5414 return DeclarationNameInfo(); 5415 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5416 Context.getCanonicalType(Ty))); 5417 NameInfo.setNamedTypeInfo(TInfo); 5418 return NameInfo; 5419 } 5420 5421 case UnqualifiedIdKind::IK_TemplateId: { 5422 TemplateName TName = Name.TemplateId->Template.get(); 5423 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5424 return Context.getNameForTemplate(TName, TNameLoc); 5425 } 5426 5427 } // switch (Name.getKind()) 5428 5429 llvm_unreachable("Unknown name kind"); 5430 } 5431 5432 static QualType getCoreType(QualType Ty) { 5433 do { 5434 if (Ty->isPointerType() || Ty->isReferenceType()) 5435 Ty = Ty->getPointeeType(); 5436 else if (Ty->isArrayType()) 5437 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5438 else 5439 return Ty.withoutLocalFastQualifiers(); 5440 } while (true); 5441 } 5442 5443 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5444 /// and Definition have "nearly" matching parameters. This heuristic is 5445 /// used to improve diagnostics in the case where an out-of-line function 5446 /// definition doesn't match any declaration within the class or namespace. 5447 /// Also sets Params to the list of indices to the parameters that differ 5448 /// between the declaration and the definition. If hasSimilarParameters 5449 /// returns true and Params is empty, then all of the parameters match. 5450 static bool hasSimilarParameters(ASTContext &Context, 5451 FunctionDecl *Declaration, 5452 FunctionDecl *Definition, 5453 SmallVectorImpl<unsigned> &Params) { 5454 Params.clear(); 5455 if (Declaration->param_size() != Definition->param_size()) 5456 return false; 5457 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5458 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5459 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5460 5461 // The parameter types are identical 5462 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5463 continue; 5464 5465 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5466 QualType DefParamBaseTy = getCoreType(DefParamTy); 5467 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5468 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5469 5470 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5471 (DeclTyName && DeclTyName == DefTyName)) 5472 Params.push_back(Idx); 5473 else // The two parameters aren't even close 5474 return false; 5475 } 5476 5477 return true; 5478 } 5479 5480 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5481 /// declarator needs to be rebuilt in the current instantiation. 5482 /// Any bits of declarator which appear before the name are valid for 5483 /// consideration here. That's specifically the type in the decl spec 5484 /// and the base type in any member-pointer chunks. 5485 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5486 DeclarationName Name) { 5487 // The types we specifically need to rebuild are: 5488 // - typenames, typeofs, and decltypes 5489 // - types which will become injected class names 5490 // Of course, we also need to rebuild any type referencing such a 5491 // type. It's safest to just say "dependent", but we call out a 5492 // few cases here. 5493 5494 DeclSpec &DS = D.getMutableDeclSpec(); 5495 switch (DS.getTypeSpecType()) { 5496 case DeclSpec::TST_typename: 5497 case DeclSpec::TST_typeofType: 5498 case DeclSpec::TST_underlyingType: 5499 case DeclSpec::TST_atomic: { 5500 // Grab the type from the parser. 5501 TypeSourceInfo *TSI = nullptr; 5502 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5503 if (T.isNull() || !T->isInstantiationDependentType()) break; 5504 5505 // Make sure there's a type source info. This isn't really much 5506 // of a waste; most dependent types should have type source info 5507 // attached already. 5508 if (!TSI) 5509 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5510 5511 // Rebuild the type in the current instantiation. 5512 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5513 if (!TSI) return true; 5514 5515 // Store the new type back in the decl spec. 5516 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5517 DS.UpdateTypeRep(LocType); 5518 break; 5519 } 5520 5521 case DeclSpec::TST_decltype: 5522 case DeclSpec::TST_typeofExpr: { 5523 Expr *E = DS.getRepAsExpr(); 5524 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5525 if (Result.isInvalid()) return true; 5526 DS.UpdateExprRep(Result.get()); 5527 break; 5528 } 5529 5530 default: 5531 // Nothing to do for these decl specs. 5532 break; 5533 } 5534 5535 // It doesn't matter what order we do this in. 5536 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5537 DeclaratorChunk &Chunk = D.getTypeObject(I); 5538 5539 // The only type information in the declarator which can come 5540 // before the declaration name is the base type of a member 5541 // pointer. 5542 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5543 continue; 5544 5545 // Rebuild the scope specifier in-place. 5546 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5547 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5548 return true; 5549 } 5550 5551 return false; 5552 } 5553 5554 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5555 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 5556 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5557 5558 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5559 Dcl && Dcl->getDeclContext()->isFileContext()) 5560 Dcl->setTopLevelDeclInObjCContainer(); 5561 5562 if (getLangOpts().OpenCL) 5563 setCurrentOpenCLExtensionForDecl(Dcl); 5564 5565 return Dcl; 5566 } 5567 5568 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5569 /// If T is the name of a class, then each of the following shall have a 5570 /// name different from T: 5571 /// - every static data member of class T; 5572 /// - every member function of class T 5573 /// - every member of class T that is itself a type; 5574 /// \returns true if the declaration name violates these rules. 5575 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5576 DeclarationNameInfo NameInfo) { 5577 DeclarationName Name = NameInfo.getName(); 5578 5579 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5580 while (Record && Record->isAnonymousStructOrUnion()) 5581 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5582 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5583 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5584 return true; 5585 } 5586 5587 return false; 5588 } 5589 5590 /// Diagnose a declaration whose declarator-id has the given 5591 /// nested-name-specifier. 5592 /// 5593 /// \param SS The nested-name-specifier of the declarator-id. 5594 /// 5595 /// \param DC The declaration context to which the nested-name-specifier 5596 /// resolves. 5597 /// 5598 /// \param Name The name of the entity being declared. 5599 /// 5600 /// \param Loc The location of the name of the entity being declared. 5601 /// 5602 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5603 /// we're declaring an explicit / partial specialization / instantiation. 5604 /// 5605 /// \returns true if we cannot safely recover from this error, false otherwise. 5606 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5607 DeclarationName Name, 5608 SourceLocation Loc, bool IsTemplateId) { 5609 DeclContext *Cur = CurContext; 5610 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5611 Cur = Cur->getParent(); 5612 5613 // If the user provided a superfluous scope specifier that refers back to the 5614 // class in which the entity is already declared, diagnose and ignore it. 5615 // 5616 // class X { 5617 // void X::f(); 5618 // }; 5619 // 5620 // Note, it was once ill-formed to give redundant qualification in all 5621 // contexts, but that rule was removed by DR482. 5622 if (Cur->Equals(DC)) { 5623 if (Cur->isRecord()) { 5624 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5625 : diag::err_member_extra_qualification) 5626 << Name << FixItHint::CreateRemoval(SS.getRange()); 5627 SS.clear(); 5628 } else { 5629 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5630 } 5631 return false; 5632 } 5633 5634 // Check whether the qualifying scope encloses the scope of the original 5635 // declaration. For a template-id, we perform the checks in 5636 // CheckTemplateSpecializationScope. 5637 if (!Cur->Encloses(DC) && !IsTemplateId) { 5638 if (Cur->isRecord()) 5639 Diag(Loc, diag::err_member_qualification) 5640 << Name << SS.getRange(); 5641 else if (isa<TranslationUnitDecl>(DC)) 5642 Diag(Loc, diag::err_invalid_declarator_global_scope) 5643 << Name << SS.getRange(); 5644 else if (isa<FunctionDecl>(Cur)) 5645 Diag(Loc, diag::err_invalid_declarator_in_function) 5646 << Name << SS.getRange(); 5647 else if (isa<BlockDecl>(Cur)) 5648 Diag(Loc, diag::err_invalid_declarator_in_block) 5649 << Name << SS.getRange(); 5650 else 5651 Diag(Loc, diag::err_invalid_declarator_scope) 5652 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5653 5654 return true; 5655 } 5656 5657 if (Cur->isRecord()) { 5658 // Cannot qualify members within a class. 5659 Diag(Loc, diag::err_member_qualification) 5660 << Name << SS.getRange(); 5661 SS.clear(); 5662 5663 // C++ constructors and destructors with incorrect scopes can break 5664 // our AST invariants by having the wrong underlying types. If 5665 // that's the case, then drop this declaration entirely. 5666 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5667 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5668 !Context.hasSameType(Name.getCXXNameType(), 5669 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5670 return true; 5671 5672 return false; 5673 } 5674 5675 // C++11 [dcl.meaning]p1: 5676 // [...] "The nested-name-specifier of the qualified declarator-id shall 5677 // not begin with a decltype-specifer" 5678 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5679 while (SpecLoc.getPrefix()) 5680 SpecLoc = SpecLoc.getPrefix(); 5681 if (dyn_cast_or_null<DecltypeType>( 5682 SpecLoc.getNestedNameSpecifier()->getAsType())) 5683 Diag(Loc, diag::err_decltype_in_declarator) 5684 << SpecLoc.getTypeLoc().getSourceRange(); 5685 5686 return false; 5687 } 5688 5689 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5690 MultiTemplateParamsArg TemplateParamLists) { 5691 // TODO: consider using NameInfo for diagnostic. 5692 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5693 DeclarationName Name = NameInfo.getName(); 5694 5695 // All of these full declarators require an identifier. If it doesn't have 5696 // one, the ParsedFreeStandingDeclSpec action should be used. 5697 if (D.isDecompositionDeclarator()) { 5698 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5699 } else if (!Name) { 5700 if (!D.isInvalidType()) // Reject this if we think it is valid. 5701 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5702 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5703 return nullptr; 5704 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5705 return nullptr; 5706 5707 // The scope passed in may not be a decl scope. Zip up the scope tree until 5708 // we find one that is. 5709 while ((S->getFlags() & Scope::DeclScope) == 0 || 5710 (S->getFlags() & Scope::TemplateParamScope) != 0) 5711 S = S->getParent(); 5712 5713 DeclContext *DC = CurContext; 5714 if (D.getCXXScopeSpec().isInvalid()) 5715 D.setInvalidType(); 5716 else if (D.getCXXScopeSpec().isSet()) { 5717 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5718 UPPC_DeclarationQualifier)) 5719 return nullptr; 5720 5721 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5722 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5723 if (!DC || isa<EnumDecl>(DC)) { 5724 // If we could not compute the declaration context, it's because the 5725 // declaration context is dependent but does not refer to a class, 5726 // class template, or class template partial specialization. Complain 5727 // and return early, to avoid the coming semantic disaster. 5728 Diag(D.getIdentifierLoc(), 5729 diag::err_template_qualified_declarator_no_match) 5730 << D.getCXXScopeSpec().getScopeRep() 5731 << D.getCXXScopeSpec().getRange(); 5732 return nullptr; 5733 } 5734 bool IsDependentContext = DC->isDependentContext(); 5735 5736 if (!IsDependentContext && 5737 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5738 return nullptr; 5739 5740 // If a class is incomplete, do not parse entities inside it. 5741 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5742 Diag(D.getIdentifierLoc(), 5743 diag::err_member_def_undefined_record) 5744 << Name << DC << D.getCXXScopeSpec().getRange(); 5745 return nullptr; 5746 } 5747 if (!D.getDeclSpec().isFriendSpecified()) { 5748 if (diagnoseQualifiedDeclaration( 5749 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5750 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5751 if (DC->isRecord()) 5752 return nullptr; 5753 5754 D.setInvalidType(); 5755 } 5756 } 5757 5758 // Check whether we need to rebuild the type of the given 5759 // declaration in the current instantiation. 5760 if (EnteringContext && IsDependentContext && 5761 TemplateParamLists.size() != 0) { 5762 ContextRAII SavedContext(*this, DC); 5763 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5764 D.setInvalidType(); 5765 } 5766 } 5767 5768 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5769 QualType R = TInfo->getType(); 5770 5771 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5772 UPPC_DeclarationType)) 5773 D.setInvalidType(); 5774 5775 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5776 forRedeclarationInCurContext()); 5777 5778 // See if this is a redefinition of a variable in the same scope. 5779 if (!D.getCXXScopeSpec().isSet()) { 5780 bool IsLinkageLookup = false; 5781 bool CreateBuiltins = false; 5782 5783 // If the declaration we're planning to build will be a function 5784 // or object with linkage, then look for another declaration with 5785 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5786 // 5787 // If the declaration we're planning to build will be declared with 5788 // external linkage in the translation unit, create any builtin with 5789 // the same name. 5790 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5791 /* Do nothing*/; 5792 else if (CurContext->isFunctionOrMethod() && 5793 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5794 R->isFunctionType())) { 5795 IsLinkageLookup = true; 5796 CreateBuiltins = 5797 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5798 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5799 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5800 CreateBuiltins = true; 5801 5802 if (IsLinkageLookup) { 5803 Previous.clear(LookupRedeclarationWithLinkage); 5804 Previous.setRedeclarationKind(ForExternalRedeclaration); 5805 } 5806 5807 LookupName(Previous, S, CreateBuiltins); 5808 } else { // Something like "int foo::x;" 5809 LookupQualifiedName(Previous, DC); 5810 5811 // C++ [dcl.meaning]p1: 5812 // When the declarator-id is qualified, the declaration shall refer to a 5813 // previously declared member of the class or namespace to which the 5814 // qualifier refers (or, in the case of a namespace, of an element of the 5815 // inline namespace set of that namespace (7.3.1)) or to a specialization 5816 // thereof; [...] 5817 // 5818 // Note that we already checked the context above, and that we do not have 5819 // enough information to make sure that Previous contains the declaration 5820 // we want to match. For example, given: 5821 // 5822 // class X { 5823 // void f(); 5824 // void f(float); 5825 // }; 5826 // 5827 // void X::f(int) { } // ill-formed 5828 // 5829 // In this case, Previous will point to the overload set 5830 // containing the two f's declared in X, but neither of them 5831 // matches. 5832 5833 // C++ [dcl.meaning]p1: 5834 // [...] the member shall not merely have been introduced by a 5835 // using-declaration in the scope of the class or namespace nominated by 5836 // the nested-name-specifier of the declarator-id. 5837 RemoveUsingDecls(Previous); 5838 } 5839 5840 if (Previous.isSingleResult() && 5841 Previous.getFoundDecl()->isTemplateParameter()) { 5842 // Maybe we will complain about the shadowed template parameter. 5843 if (!D.isInvalidType()) 5844 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5845 Previous.getFoundDecl()); 5846 5847 // Just pretend that we didn't see the previous declaration. 5848 Previous.clear(); 5849 } 5850 5851 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5852 // Forget that the previous declaration is the injected-class-name. 5853 Previous.clear(); 5854 5855 // In C++, the previous declaration we find might be a tag type 5856 // (class or enum). In this case, the new declaration will hide the 5857 // tag type. Note that this applies to functions, function templates, and 5858 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5859 if (Previous.isSingleTagDecl() && 5860 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5861 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5862 Previous.clear(); 5863 5864 // Check that there are no default arguments other than in the parameters 5865 // of a function declaration (C++ only). 5866 if (getLangOpts().CPlusPlus) 5867 CheckExtraCXXDefaultArguments(D); 5868 5869 NamedDecl *New; 5870 5871 bool AddToScope = true; 5872 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5873 if (TemplateParamLists.size()) { 5874 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5875 return nullptr; 5876 } 5877 5878 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5879 } else if (R->isFunctionType()) { 5880 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5881 TemplateParamLists, 5882 AddToScope); 5883 } else { 5884 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5885 AddToScope); 5886 } 5887 5888 if (!New) 5889 return nullptr; 5890 5891 // If this has an identifier and is not a function template specialization, 5892 // add it to the scope stack. 5893 if (New->getDeclName() && AddToScope) 5894 PushOnScopeChains(New, S); 5895 5896 if (isInOpenMPDeclareTargetContext()) 5897 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5898 5899 return New; 5900 } 5901 5902 /// Helper method to turn variable array types into constant array 5903 /// types in certain situations which would otherwise be errors (for 5904 /// GCC compatibility). 5905 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5906 ASTContext &Context, 5907 bool &SizeIsNegative, 5908 llvm::APSInt &Oversized) { 5909 // This method tries to turn a variable array into a constant 5910 // array even when the size isn't an ICE. This is necessary 5911 // for compatibility with code that depends on gcc's buggy 5912 // constant expression folding, like struct {char x[(int)(char*)2];} 5913 SizeIsNegative = false; 5914 Oversized = 0; 5915 5916 if (T->isDependentType()) 5917 return QualType(); 5918 5919 QualifierCollector Qs; 5920 const Type *Ty = Qs.strip(T); 5921 5922 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5923 QualType Pointee = PTy->getPointeeType(); 5924 QualType FixedType = 5925 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5926 Oversized); 5927 if (FixedType.isNull()) return FixedType; 5928 FixedType = Context.getPointerType(FixedType); 5929 return Qs.apply(Context, FixedType); 5930 } 5931 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5932 QualType Inner = PTy->getInnerType(); 5933 QualType FixedType = 5934 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5935 Oversized); 5936 if (FixedType.isNull()) return FixedType; 5937 FixedType = Context.getParenType(FixedType); 5938 return Qs.apply(Context, FixedType); 5939 } 5940 5941 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5942 if (!VLATy) 5943 return QualType(); 5944 5945 QualType ElemTy = VLATy->getElementType(); 5946 if (ElemTy->isVariablyModifiedType()) { 5947 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 5948 SizeIsNegative, Oversized); 5949 if (ElemTy.isNull()) 5950 return QualType(); 5951 } 5952 5953 Expr::EvalResult Result; 5954 if (!VLATy->getSizeExpr() || 5955 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5956 return QualType(); 5957 5958 llvm::APSInt Res = Result.Val.getInt(); 5959 5960 // Check whether the array size is negative. 5961 if (Res.isSigned() && Res.isNegative()) { 5962 SizeIsNegative = true; 5963 return QualType(); 5964 } 5965 5966 // Check whether the array is too large to be addressed. 5967 unsigned ActiveSizeBits = 5968 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 5969 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 5970 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 5971 : Res.getActiveBits(); 5972 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5973 Oversized = Res; 5974 return QualType(); 5975 } 5976 5977 QualType FoldedArrayType = Context.getConstantArrayType( 5978 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 5979 return Qs.apply(Context, FoldedArrayType); 5980 } 5981 5982 static void 5983 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5984 SrcTL = SrcTL.getUnqualifiedLoc(); 5985 DstTL = DstTL.getUnqualifiedLoc(); 5986 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5987 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5988 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5989 DstPTL.getPointeeLoc()); 5990 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5991 return; 5992 } 5993 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5994 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5995 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5996 DstPTL.getInnerLoc()); 5997 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5998 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5999 return; 6000 } 6001 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6002 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6003 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6004 TypeLoc DstElemTL = DstATL.getElementLoc(); 6005 if (VariableArrayTypeLoc SrcElemATL = 6006 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6007 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6008 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6009 } else { 6010 DstElemTL.initializeFullCopy(SrcElemTL); 6011 } 6012 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6013 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6014 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6015 } 6016 6017 /// Helper method to turn variable array types into constant array 6018 /// types in certain situations which would otherwise be errors (for 6019 /// GCC compatibility). 6020 static TypeSourceInfo* 6021 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6022 ASTContext &Context, 6023 bool &SizeIsNegative, 6024 llvm::APSInt &Oversized) { 6025 QualType FixedTy 6026 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6027 SizeIsNegative, Oversized); 6028 if (FixedTy.isNull()) 6029 return nullptr; 6030 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6031 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6032 FixedTInfo->getTypeLoc()); 6033 return FixedTInfo; 6034 } 6035 6036 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6037 /// true if we were successful. 6038 static bool tryToFixVariablyModifiedVarType(Sema &S, TypeSourceInfo *&TInfo, 6039 QualType &T, SourceLocation Loc, 6040 unsigned FailedFoldDiagID) { 6041 bool SizeIsNegative; 6042 llvm::APSInt Oversized; 6043 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6044 TInfo, S.Context, SizeIsNegative, Oversized); 6045 if (FixedTInfo) { 6046 S.Diag(Loc, diag::ext_vla_folded_to_constant); 6047 TInfo = FixedTInfo; 6048 T = FixedTInfo->getType(); 6049 return true; 6050 } 6051 6052 if (SizeIsNegative) 6053 S.Diag(Loc, diag::err_typecheck_negative_array_size); 6054 else if (Oversized.getBoolValue()) 6055 S.Diag(Loc, diag::err_array_too_large) << Oversized.toString(10); 6056 else if (FailedFoldDiagID) 6057 S.Diag(Loc, FailedFoldDiagID); 6058 return false; 6059 } 6060 6061 /// Register the given locally-scoped extern "C" declaration so 6062 /// that it can be found later for redeclarations. We include any extern "C" 6063 /// declaration that is not visible in the translation unit here, not just 6064 /// function-scope declarations. 6065 void 6066 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6067 if (!getLangOpts().CPlusPlus && 6068 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6069 // Don't need to track declarations in the TU in C. 6070 return; 6071 6072 // Note that we have a locally-scoped external with this name. 6073 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6074 } 6075 6076 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6077 // FIXME: We can have multiple results via __attribute__((overloadable)). 6078 auto Result = Context.getExternCContextDecl()->lookup(Name); 6079 return Result.empty() ? nullptr : *Result.begin(); 6080 } 6081 6082 /// Diagnose function specifiers on a declaration of an identifier that 6083 /// does not identify a function. 6084 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6085 // FIXME: We should probably indicate the identifier in question to avoid 6086 // confusion for constructs like "virtual int a(), b;" 6087 if (DS.isVirtualSpecified()) 6088 Diag(DS.getVirtualSpecLoc(), 6089 diag::err_virtual_non_function); 6090 6091 if (DS.hasExplicitSpecifier()) 6092 Diag(DS.getExplicitSpecLoc(), 6093 diag::err_explicit_non_function); 6094 6095 if (DS.isNoreturnSpecified()) 6096 Diag(DS.getNoreturnSpecLoc(), 6097 diag::err_noreturn_non_function); 6098 } 6099 6100 NamedDecl* 6101 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6102 TypeSourceInfo *TInfo, LookupResult &Previous) { 6103 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6104 if (D.getCXXScopeSpec().isSet()) { 6105 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6106 << D.getCXXScopeSpec().getRange(); 6107 D.setInvalidType(); 6108 // Pretend we didn't see the scope specifier. 6109 DC = CurContext; 6110 Previous.clear(); 6111 } 6112 6113 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6114 6115 if (D.getDeclSpec().isInlineSpecified()) 6116 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6117 << getLangOpts().CPlusPlus17; 6118 if (D.getDeclSpec().hasConstexprSpecifier()) 6119 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6120 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6121 6122 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6123 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6124 Diag(D.getName().StartLocation, 6125 diag::err_deduction_guide_invalid_specifier) 6126 << "typedef"; 6127 else 6128 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6129 << D.getName().getSourceRange(); 6130 return nullptr; 6131 } 6132 6133 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6134 if (!NewTD) return nullptr; 6135 6136 // Handle attributes prior to checking for duplicates in MergeVarDecl 6137 ProcessDeclAttributes(S, NewTD, D); 6138 6139 CheckTypedefForVariablyModifiedType(S, NewTD); 6140 6141 bool Redeclaration = D.isRedeclaration(); 6142 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6143 D.setRedeclaration(Redeclaration); 6144 return ND; 6145 } 6146 6147 void 6148 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6149 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6150 // then it shall have block scope. 6151 // Note that variably modified types must be fixed before merging the decl so 6152 // that redeclarations will match. 6153 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6154 QualType T = TInfo->getType(); 6155 if (T->isVariablyModifiedType()) { 6156 setFunctionHasBranchProtectedScope(); 6157 6158 if (S->getFnParent() == nullptr) { 6159 bool SizeIsNegative; 6160 llvm::APSInt Oversized; 6161 TypeSourceInfo *FixedTInfo = 6162 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6163 SizeIsNegative, 6164 Oversized); 6165 if (FixedTInfo) { 6166 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6167 NewTD->setTypeSourceInfo(FixedTInfo); 6168 } else { 6169 if (SizeIsNegative) 6170 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6171 else if (T->isVariableArrayType()) 6172 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6173 else if (Oversized.getBoolValue()) 6174 Diag(NewTD->getLocation(), diag::err_array_too_large) 6175 << Oversized.toString(10); 6176 else 6177 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6178 NewTD->setInvalidDecl(); 6179 } 6180 } 6181 } 6182 } 6183 6184 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6185 /// declares a typedef-name, either using the 'typedef' type specifier or via 6186 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6187 NamedDecl* 6188 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6189 LookupResult &Previous, bool &Redeclaration) { 6190 6191 // Find the shadowed declaration before filtering for scope. 6192 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6193 6194 // Merge the decl with the existing one if appropriate. If the decl is 6195 // in an outer scope, it isn't the same thing. 6196 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6197 /*AllowInlineNamespace*/false); 6198 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6199 if (!Previous.empty()) { 6200 Redeclaration = true; 6201 MergeTypedefNameDecl(S, NewTD, Previous); 6202 } else { 6203 inferGslPointerAttribute(NewTD); 6204 } 6205 6206 if (ShadowedDecl && !Redeclaration) 6207 CheckShadow(NewTD, ShadowedDecl, Previous); 6208 6209 // If this is the C FILE type, notify the AST context. 6210 if (IdentifierInfo *II = NewTD->getIdentifier()) 6211 if (!NewTD->isInvalidDecl() && 6212 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6213 if (II->isStr("FILE")) 6214 Context.setFILEDecl(NewTD); 6215 else if (II->isStr("jmp_buf")) 6216 Context.setjmp_bufDecl(NewTD); 6217 else if (II->isStr("sigjmp_buf")) 6218 Context.setsigjmp_bufDecl(NewTD); 6219 else if (II->isStr("ucontext_t")) 6220 Context.setucontext_tDecl(NewTD); 6221 } 6222 6223 return NewTD; 6224 } 6225 6226 /// Determines whether the given declaration is an out-of-scope 6227 /// previous declaration. 6228 /// 6229 /// This routine should be invoked when name lookup has found a 6230 /// previous declaration (PrevDecl) that is not in the scope where a 6231 /// new declaration by the same name is being introduced. If the new 6232 /// declaration occurs in a local scope, previous declarations with 6233 /// linkage may still be considered previous declarations (C99 6234 /// 6.2.2p4-5, C++ [basic.link]p6). 6235 /// 6236 /// \param PrevDecl the previous declaration found by name 6237 /// lookup 6238 /// 6239 /// \param DC the context in which the new declaration is being 6240 /// declared. 6241 /// 6242 /// \returns true if PrevDecl is an out-of-scope previous declaration 6243 /// for a new delcaration with the same name. 6244 static bool 6245 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6246 ASTContext &Context) { 6247 if (!PrevDecl) 6248 return false; 6249 6250 if (!PrevDecl->hasLinkage()) 6251 return false; 6252 6253 if (Context.getLangOpts().CPlusPlus) { 6254 // C++ [basic.link]p6: 6255 // If there is a visible declaration of an entity with linkage 6256 // having the same name and type, ignoring entities declared 6257 // outside the innermost enclosing namespace scope, the block 6258 // scope declaration declares that same entity and receives the 6259 // linkage of the previous declaration. 6260 DeclContext *OuterContext = DC->getRedeclContext(); 6261 if (!OuterContext->isFunctionOrMethod()) 6262 // This rule only applies to block-scope declarations. 6263 return false; 6264 6265 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6266 if (PrevOuterContext->isRecord()) 6267 // We found a member function: ignore it. 6268 return false; 6269 6270 // Find the innermost enclosing namespace for the new and 6271 // previous declarations. 6272 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6273 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6274 6275 // The previous declaration is in a different namespace, so it 6276 // isn't the same function. 6277 if (!OuterContext->Equals(PrevOuterContext)) 6278 return false; 6279 } 6280 6281 return true; 6282 } 6283 6284 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6285 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6286 if (!SS.isSet()) return; 6287 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6288 } 6289 6290 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6291 QualType type = decl->getType(); 6292 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6293 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6294 // Various kinds of declaration aren't allowed to be __autoreleasing. 6295 unsigned kind = -1U; 6296 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6297 if (var->hasAttr<BlocksAttr>()) 6298 kind = 0; // __block 6299 else if (!var->hasLocalStorage()) 6300 kind = 1; // global 6301 } else if (isa<ObjCIvarDecl>(decl)) { 6302 kind = 3; // ivar 6303 } else if (isa<FieldDecl>(decl)) { 6304 kind = 2; // field 6305 } 6306 6307 if (kind != -1U) { 6308 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6309 << kind; 6310 } 6311 } else if (lifetime == Qualifiers::OCL_None) { 6312 // Try to infer lifetime. 6313 if (!type->isObjCLifetimeType()) 6314 return false; 6315 6316 lifetime = type->getObjCARCImplicitLifetime(); 6317 type = Context.getLifetimeQualifiedType(type, lifetime); 6318 decl->setType(type); 6319 } 6320 6321 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6322 // Thread-local variables cannot have lifetime. 6323 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6324 var->getTLSKind()) { 6325 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6326 << var->getType(); 6327 return true; 6328 } 6329 } 6330 6331 return false; 6332 } 6333 6334 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6335 if (Decl->getType().hasAddressSpace()) 6336 return; 6337 if (Decl->getType()->isDependentType()) 6338 return; 6339 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6340 QualType Type = Var->getType(); 6341 if (Type->isSamplerT() || Type->isVoidType()) 6342 return; 6343 LangAS ImplAS = LangAS::opencl_private; 6344 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6345 Var->hasGlobalStorage()) 6346 ImplAS = LangAS::opencl_global; 6347 // If the original type from a decayed type is an array type and that array 6348 // type has no address space yet, deduce it now. 6349 if (auto DT = dyn_cast<DecayedType>(Type)) { 6350 auto OrigTy = DT->getOriginalType(); 6351 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6352 // Add the address space to the original array type and then propagate 6353 // that to the element type through `getAsArrayType`. 6354 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6355 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6356 // Re-generate the decayed type. 6357 Type = Context.getDecayedType(OrigTy); 6358 } 6359 } 6360 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6361 // Apply any qualifiers (including address space) from the array type to 6362 // the element type. This implements C99 6.7.3p8: "If the specification of 6363 // an array type includes any type qualifiers, the element type is so 6364 // qualified, not the array type." 6365 if (Type->isArrayType()) 6366 Type = QualType(Context.getAsArrayType(Type), 0); 6367 Decl->setType(Type); 6368 } 6369 } 6370 6371 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6372 // Ensure that an auto decl is deduced otherwise the checks below might cache 6373 // the wrong linkage. 6374 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6375 6376 // 'weak' only applies to declarations with external linkage. 6377 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6378 if (!ND.isExternallyVisible()) { 6379 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6380 ND.dropAttr<WeakAttr>(); 6381 } 6382 } 6383 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6384 if (ND.isExternallyVisible()) { 6385 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6386 ND.dropAttr<WeakRefAttr>(); 6387 ND.dropAttr<AliasAttr>(); 6388 } 6389 } 6390 6391 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6392 if (VD->hasInit()) { 6393 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6394 assert(VD->isThisDeclarationADefinition() && 6395 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6396 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6397 VD->dropAttr<AliasAttr>(); 6398 } 6399 } 6400 } 6401 6402 // 'selectany' only applies to externally visible variable declarations. 6403 // It does not apply to functions. 6404 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6405 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6406 S.Diag(Attr->getLocation(), 6407 diag::err_attribute_selectany_non_extern_data); 6408 ND.dropAttr<SelectAnyAttr>(); 6409 } 6410 } 6411 6412 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6413 auto *VD = dyn_cast<VarDecl>(&ND); 6414 bool IsAnonymousNS = false; 6415 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6416 if (VD) { 6417 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6418 while (NS && !IsAnonymousNS) { 6419 IsAnonymousNS = NS->isAnonymousNamespace(); 6420 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6421 } 6422 } 6423 // dll attributes require external linkage. Static locals may have external 6424 // linkage but still cannot be explicitly imported or exported. 6425 // In Microsoft mode, a variable defined in anonymous namespace must have 6426 // external linkage in order to be exported. 6427 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6428 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6429 (!AnonNSInMicrosoftMode && 6430 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6431 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6432 << &ND << Attr; 6433 ND.setInvalidDecl(); 6434 } 6435 } 6436 6437 // Virtual functions cannot be marked as 'notail'. 6438 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6439 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6440 if (MD->isVirtual()) { 6441 S.Diag(ND.getLocation(), 6442 diag::err_invalid_attribute_on_virtual_function) 6443 << Attr; 6444 ND.dropAttr<NotTailCalledAttr>(); 6445 } 6446 6447 // Check the attributes on the function type, if any. 6448 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6449 // Don't declare this variable in the second operand of the for-statement; 6450 // GCC miscompiles that by ending its lifetime before evaluating the 6451 // third operand. See gcc.gnu.org/PR86769. 6452 AttributedTypeLoc ATL; 6453 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6454 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6455 TL = ATL.getModifiedLoc()) { 6456 // The [[lifetimebound]] attribute can be applied to the implicit object 6457 // parameter of a non-static member function (other than a ctor or dtor) 6458 // by applying it to the function type. 6459 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6460 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6461 if (!MD || MD->isStatic()) { 6462 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6463 << !MD << A->getRange(); 6464 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6465 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6466 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6467 } 6468 } 6469 } 6470 } 6471 } 6472 6473 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6474 NamedDecl *NewDecl, 6475 bool IsSpecialization, 6476 bool IsDefinition) { 6477 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6478 return; 6479 6480 bool IsTemplate = false; 6481 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6482 OldDecl = OldTD->getTemplatedDecl(); 6483 IsTemplate = true; 6484 if (!IsSpecialization) 6485 IsDefinition = false; 6486 } 6487 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6488 NewDecl = NewTD->getTemplatedDecl(); 6489 IsTemplate = true; 6490 } 6491 6492 if (!OldDecl || !NewDecl) 6493 return; 6494 6495 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6496 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6497 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6498 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6499 6500 // dllimport and dllexport are inheritable attributes so we have to exclude 6501 // inherited attribute instances. 6502 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6503 (NewExportAttr && !NewExportAttr->isInherited()); 6504 6505 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6506 // the only exception being explicit specializations. 6507 // Implicitly generated declarations are also excluded for now because there 6508 // is no other way to switch these to use dllimport or dllexport. 6509 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6510 6511 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6512 // Allow with a warning for free functions and global variables. 6513 bool JustWarn = false; 6514 if (!OldDecl->isCXXClassMember()) { 6515 auto *VD = dyn_cast<VarDecl>(OldDecl); 6516 if (VD && !VD->getDescribedVarTemplate()) 6517 JustWarn = true; 6518 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6519 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6520 JustWarn = true; 6521 } 6522 6523 // We cannot change a declaration that's been used because IR has already 6524 // been emitted. Dllimported functions will still work though (modulo 6525 // address equality) as they can use the thunk. 6526 if (OldDecl->isUsed()) 6527 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6528 JustWarn = false; 6529 6530 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6531 : diag::err_attribute_dll_redeclaration; 6532 S.Diag(NewDecl->getLocation(), DiagID) 6533 << NewDecl 6534 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6535 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6536 if (!JustWarn) { 6537 NewDecl->setInvalidDecl(); 6538 return; 6539 } 6540 } 6541 6542 // A redeclaration is not allowed to drop a dllimport attribute, the only 6543 // exceptions being inline function definitions (except for function 6544 // templates), local extern declarations, qualified friend declarations or 6545 // special MSVC extension: in the last case, the declaration is treated as if 6546 // it were marked dllexport. 6547 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6548 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 6549 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6550 // Ignore static data because out-of-line definitions are diagnosed 6551 // separately. 6552 IsStaticDataMember = VD->isStaticDataMember(); 6553 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6554 VarDecl::DeclarationOnly; 6555 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6556 IsInline = FD->isInlined(); 6557 IsQualifiedFriend = FD->getQualifier() && 6558 FD->getFriendObjectKind() == Decl::FOK_Declared; 6559 } 6560 6561 if (OldImportAttr && !HasNewAttr && 6562 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 6563 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6564 if (IsMicrosoftABI && IsDefinition) { 6565 S.Diag(NewDecl->getLocation(), 6566 diag::warn_redeclaration_without_import_attribute) 6567 << NewDecl; 6568 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6569 NewDecl->dropAttr<DLLImportAttr>(); 6570 NewDecl->addAttr( 6571 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6572 } else { 6573 S.Diag(NewDecl->getLocation(), 6574 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6575 << NewDecl << OldImportAttr; 6576 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6577 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6578 OldDecl->dropAttr<DLLImportAttr>(); 6579 NewDecl->dropAttr<DLLImportAttr>(); 6580 } 6581 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 6582 // In MinGW, seeing a function declared inline drops the dllimport 6583 // attribute. 6584 OldDecl->dropAttr<DLLImportAttr>(); 6585 NewDecl->dropAttr<DLLImportAttr>(); 6586 S.Diag(NewDecl->getLocation(), 6587 diag::warn_dllimport_dropped_from_inline_function) 6588 << NewDecl << OldImportAttr; 6589 } 6590 6591 // A specialization of a class template member function is processed here 6592 // since it's a redeclaration. If the parent class is dllexport, the 6593 // specialization inherits that attribute. This doesn't happen automatically 6594 // since the parent class isn't instantiated until later. 6595 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6596 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6597 !NewImportAttr && !NewExportAttr) { 6598 if (const DLLExportAttr *ParentExportAttr = 6599 MD->getParent()->getAttr<DLLExportAttr>()) { 6600 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6601 NewAttr->setInherited(true); 6602 NewDecl->addAttr(NewAttr); 6603 } 6604 } 6605 } 6606 } 6607 6608 /// Given that we are within the definition of the given function, 6609 /// will that definition behave like C99's 'inline', where the 6610 /// definition is discarded except for optimization purposes? 6611 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6612 // Try to avoid calling GetGVALinkageForFunction. 6613 6614 // All cases of this require the 'inline' keyword. 6615 if (!FD->isInlined()) return false; 6616 6617 // This is only possible in C++ with the gnu_inline attribute. 6618 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6619 return false; 6620 6621 // Okay, go ahead and call the relatively-more-expensive function. 6622 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6623 } 6624 6625 /// Determine whether a variable is extern "C" prior to attaching 6626 /// an initializer. We can't just call isExternC() here, because that 6627 /// will also compute and cache whether the declaration is externally 6628 /// visible, which might change when we attach the initializer. 6629 /// 6630 /// This can only be used if the declaration is known to not be a 6631 /// redeclaration of an internal linkage declaration. 6632 /// 6633 /// For instance: 6634 /// 6635 /// auto x = []{}; 6636 /// 6637 /// Attaching the initializer here makes this declaration not externally 6638 /// visible, because its type has internal linkage. 6639 /// 6640 /// FIXME: This is a hack. 6641 template<typename T> 6642 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6643 if (S.getLangOpts().CPlusPlus) { 6644 // In C++, the overloadable attribute negates the effects of extern "C". 6645 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6646 return false; 6647 6648 // So do CUDA's host/device attributes. 6649 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6650 D->template hasAttr<CUDAHostAttr>())) 6651 return false; 6652 } 6653 return D->isExternC(); 6654 } 6655 6656 static bool shouldConsiderLinkage(const VarDecl *VD) { 6657 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6658 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6659 isa<OMPDeclareMapperDecl>(DC)) 6660 return VD->hasExternalStorage(); 6661 if (DC->isFileContext()) 6662 return true; 6663 if (DC->isRecord()) 6664 return false; 6665 if (isa<RequiresExprBodyDecl>(DC)) 6666 return false; 6667 llvm_unreachable("Unexpected context"); 6668 } 6669 6670 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6671 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6672 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6673 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6674 return true; 6675 if (DC->isRecord()) 6676 return false; 6677 llvm_unreachable("Unexpected context"); 6678 } 6679 6680 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6681 ParsedAttr::Kind Kind) { 6682 // Check decl attributes on the DeclSpec. 6683 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6684 return true; 6685 6686 // Walk the declarator structure, checking decl attributes that were in a type 6687 // position to the decl itself. 6688 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6689 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6690 return true; 6691 } 6692 6693 // Finally, check attributes on the decl itself. 6694 return PD.getAttributes().hasAttribute(Kind); 6695 } 6696 6697 /// Adjust the \c DeclContext for a function or variable that might be a 6698 /// function-local external declaration. 6699 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6700 if (!DC->isFunctionOrMethod()) 6701 return false; 6702 6703 // If this is a local extern function or variable declared within a function 6704 // template, don't add it into the enclosing namespace scope until it is 6705 // instantiated; it might have a dependent type right now. 6706 if (DC->isDependentContext()) 6707 return true; 6708 6709 // C++11 [basic.link]p7: 6710 // When a block scope declaration of an entity with linkage is not found to 6711 // refer to some other declaration, then that entity is a member of the 6712 // innermost enclosing namespace. 6713 // 6714 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6715 // semantically-enclosing namespace, not a lexically-enclosing one. 6716 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6717 DC = DC->getParent(); 6718 return true; 6719 } 6720 6721 /// Returns true if given declaration has external C language linkage. 6722 static bool isDeclExternC(const Decl *D) { 6723 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6724 return FD->isExternC(); 6725 if (const auto *VD = dyn_cast<VarDecl>(D)) 6726 return VD->isExternC(); 6727 6728 llvm_unreachable("Unknown type of decl!"); 6729 } 6730 /// Returns true if there hasn't been any invalid type diagnosed. 6731 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, 6732 DeclContext *DC, QualType R) { 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(D.getIdentifierLoc(), 6738 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6739 << R; 6740 D.setInvalidType(); 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 (NULL == S->getParent()) { 6750 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6751 Se.Diag(D.getIdentifierLoc(), 6752 diag::err_invalid_type_for_program_scope_var) 6753 << R; 6754 D.setInvalidType(); 6755 return false; 6756 } 6757 } 6758 6759 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6760 if (!Se.getOpenCLOptions().isEnabled("__cl_clang_function_pointers")) { 6761 QualType NR = R; 6762 while (NR->isPointerType() || NR->isMemberFunctionPointerType()) { 6763 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType()) { 6764 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6765 D.setInvalidType(); 6766 return false; 6767 } 6768 NR = NR->getPointeeType(); 6769 } 6770 } 6771 6772 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6773 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6774 // half array type (unless the cl_khr_fp16 extension is enabled). 6775 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6776 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6777 D.setInvalidType(); 6778 return false; 6779 } 6780 } 6781 6782 // OpenCL v1.2 s6.9.r: 6783 // The event type cannot be used with the __local, __constant and __global 6784 // address space qualifiers. 6785 if (R->isEventT()) { 6786 if (R.getAddressSpace() != LangAS::opencl_private) { 6787 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6788 D.setInvalidType(); 6789 return false; 6790 } 6791 } 6792 6793 // C++ for OpenCL does not allow the thread_local storage qualifier. 6794 // OpenCL C does not support thread_local either, and 6795 // also reject all other thread storage class specifiers. 6796 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6797 if (TSC != TSCS_unspecified) { 6798 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; 6799 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6800 diag::err_opencl_unknown_type_specifier) 6801 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() 6802 << DeclSpec::getSpecifierName(TSC) << 1; 6803 D.setInvalidType(); 6804 return false; 6805 } 6806 6807 if (R->isSamplerT()) { 6808 // OpenCL v1.2 s6.9.b p4: 6809 // The sampler type cannot be used with the __local and __global address 6810 // space qualifiers. 6811 if (R.getAddressSpace() == LangAS::opencl_local || 6812 R.getAddressSpace() == LangAS::opencl_global) { 6813 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6814 D.setInvalidType(); 6815 } 6816 6817 // OpenCL v1.2 s6.12.14.1: 6818 // A global sampler must be declared with either the constant address 6819 // space qualifier or with the const qualifier. 6820 if (DC->isTranslationUnit() && 6821 !(R.getAddressSpace() == LangAS::opencl_constant || 6822 R.isConstQualified())) { 6823 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6824 D.setInvalidType(); 6825 } 6826 if (D.isInvalidType()) 6827 return false; 6828 } 6829 return true; 6830 } 6831 6832 NamedDecl *Sema::ActOnVariableDeclarator( 6833 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6834 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6835 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6836 QualType R = TInfo->getType(); 6837 DeclarationName Name = GetNameForDeclarator(D).getName(); 6838 6839 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6840 6841 if (D.isDecompositionDeclarator()) { 6842 // Take the name of the first declarator as our name for diagnostic 6843 // purposes. 6844 auto &Decomp = D.getDecompositionDeclarator(); 6845 if (!Decomp.bindings().empty()) { 6846 II = Decomp.bindings()[0].Name; 6847 Name = II; 6848 } 6849 } else if (!II) { 6850 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6851 return nullptr; 6852 } 6853 6854 6855 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6856 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6857 6858 // dllimport globals without explicit storage class are treated as extern. We 6859 // have to change the storage class this early to get the right DeclContext. 6860 if (SC == SC_None && !DC->isRecord() && 6861 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6862 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6863 SC = SC_Extern; 6864 6865 DeclContext *OriginalDC = DC; 6866 bool IsLocalExternDecl = SC == SC_Extern && 6867 adjustContextForLocalExternDecl(DC); 6868 6869 if (SCSpec == DeclSpec::SCS_mutable) { 6870 // mutable can only appear on non-static class members, so it's always 6871 // an error here 6872 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6873 D.setInvalidType(); 6874 SC = SC_None; 6875 } 6876 6877 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6878 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6879 D.getDeclSpec().getStorageClassSpecLoc())) { 6880 // In C++11, the 'register' storage class specifier is deprecated. 6881 // Suppress the warning in system macros, it's used in macros in some 6882 // popular C system headers, such as in glibc's htonl() macro. 6883 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6884 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6885 : diag::warn_deprecated_register) 6886 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6887 } 6888 6889 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6890 6891 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6892 // C99 6.9p2: The storage-class specifiers auto and register shall not 6893 // appear in the declaration specifiers in an external declaration. 6894 // Global Register+Asm is a GNU extension we support. 6895 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6896 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6897 D.setInvalidType(); 6898 } 6899 } 6900 6901 // If this variable has a variable-modified type and an initializer, try to 6902 // fold to a constant-sized type. This is otherwise invalid. 6903 if (D.hasInitializer() && R->isVariablyModifiedType()) 6904 tryToFixVariablyModifiedVarType(*this, TInfo, R, D.getIdentifierLoc(), 6905 /*DiagID=*/0); 6906 6907 bool IsMemberSpecialization = false; 6908 bool IsVariableTemplateSpecialization = false; 6909 bool IsPartialSpecialization = false; 6910 bool IsVariableTemplate = false; 6911 VarDecl *NewVD = nullptr; 6912 VarTemplateDecl *NewTemplate = nullptr; 6913 TemplateParameterList *TemplateParams = nullptr; 6914 if (!getLangOpts().CPlusPlus) { 6915 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6916 II, R, TInfo, SC); 6917 6918 if (R->getContainedDeducedType()) 6919 ParsingInitForAutoVars.insert(NewVD); 6920 6921 if (D.isInvalidType()) 6922 NewVD->setInvalidDecl(); 6923 6924 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6925 NewVD->hasLocalStorage()) 6926 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6927 NTCUC_AutoVar, NTCUK_Destruct); 6928 } else { 6929 bool Invalid = false; 6930 6931 if (DC->isRecord() && !CurContext->isRecord()) { 6932 // This is an out-of-line definition of a static data member. 6933 switch (SC) { 6934 case SC_None: 6935 break; 6936 case SC_Static: 6937 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6938 diag::err_static_out_of_line) 6939 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6940 break; 6941 case SC_Auto: 6942 case SC_Register: 6943 case SC_Extern: 6944 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6945 // to names of variables declared in a block or to function parameters. 6946 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6947 // of class members 6948 6949 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6950 diag::err_storage_class_for_static_member) 6951 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6952 break; 6953 case SC_PrivateExtern: 6954 llvm_unreachable("C storage class in c++!"); 6955 } 6956 } 6957 6958 if (SC == SC_Static && CurContext->isRecord()) { 6959 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6960 // Walk up the enclosing DeclContexts to check for any that are 6961 // incompatible with static data members. 6962 const DeclContext *FunctionOrMethod = nullptr; 6963 const CXXRecordDecl *AnonStruct = nullptr; 6964 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 6965 if (Ctxt->isFunctionOrMethod()) { 6966 FunctionOrMethod = Ctxt; 6967 break; 6968 } 6969 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 6970 if (ParentDecl && !ParentDecl->getDeclName()) { 6971 AnonStruct = ParentDecl; 6972 break; 6973 } 6974 } 6975 if (FunctionOrMethod) { 6976 // C++ [class.static.data]p5: A local class shall not have static data 6977 // members. 6978 Diag(D.getIdentifierLoc(), 6979 diag::err_static_data_member_not_allowed_in_local_class) 6980 << Name << RD->getDeclName() << RD->getTagKind(); 6981 } else if (AnonStruct) { 6982 // C++ [class.static.data]p4: Unnamed classes and classes contained 6983 // directly or indirectly within unnamed classes shall not contain 6984 // static data members. 6985 Diag(D.getIdentifierLoc(), 6986 diag::err_static_data_member_not_allowed_in_anon_struct) 6987 << Name << AnonStruct->getTagKind(); 6988 Invalid = true; 6989 } else if (RD->isUnion()) { 6990 // C++98 [class.union]p1: If a union contains a static data member, 6991 // the program is ill-formed. C++11 drops this restriction. 6992 Diag(D.getIdentifierLoc(), 6993 getLangOpts().CPlusPlus11 6994 ? diag::warn_cxx98_compat_static_data_member_in_union 6995 : diag::ext_static_data_member_in_union) << Name; 6996 } 6997 } 6998 } 6999 7000 // Match up the template parameter lists with the scope specifier, then 7001 // determine whether we have a template or a template specialization. 7002 bool InvalidScope = false; 7003 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7004 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7005 D.getCXXScopeSpec(), 7006 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7007 ? D.getName().TemplateId 7008 : nullptr, 7009 TemplateParamLists, 7010 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7011 Invalid |= InvalidScope; 7012 7013 if (TemplateParams) { 7014 if (!TemplateParams->size() && 7015 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7016 // There is an extraneous 'template<>' for this variable. Complain 7017 // about it, but allow the declaration of the variable. 7018 Diag(TemplateParams->getTemplateLoc(), 7019 diag::err_template_variable_noparams) 7020 << II 7021 << SourceRange(TemplateParams->getTemplateLoc(), 7022 TemplateParams->getRAngleLoc()); 7023 TemplateParams = nullptr; 7024 } else { 7025 // Check that we can declare a template here. 7026 if (CheckTemplateDeclScope(S, TemplateParams)) 7027 return nullptr; 7028 7029 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7030 // This is an explicit specialization or a partial specialization. 7031 IsVariableTemplateSpecialization = true; 7032 IsPartialSpecialization = TemplateParams->size() > 0; 7033 } else { // if (TemplateParams->size() > 0) 7034 // This is a template declaration. 7035 IsVariableTemplate = true; 7036 7037 // Only C++1y supports variable templates (N3651). 7038 Diag(D.getIdentifierLoc(), 7039 getLangOpts().CPlusPlus14 7040 ? diag::warn_cxx11_compat_variable_template 7041 : diag::ext_variable_template); 7042 } 7043 } 7044 } else { 7045 // Check that we can declare a member specialization here. 7046 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7047 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7048 return nullptr; 7049 assert((Invalid || 7050 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7051 "should have a 'template<>' for this decl"); 7052 } 7053 7054 if (IsVariableTemplateSpecialization) { 7055 SourceLocation TemplateKWLoc = 7056 TemplateParamLists.size() > 0 7057 ? TemplateParamLists[0]->getTemplateLoc() 7058 : SourceLocation(); 7059 DeclResult Res = ActOnVarTemplateSpecialization( 7060 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7061 IsPartialSpecialization); 7062 if (Res.isInvalid()) 7063 return nullptr; 7064 NewVD = cast<VarDecl>(Res.get()); 7065 AddToScope = false; 7066 } else if (D.isDecompositionDeclarator()) { 7067 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7068 D.getIdentifierLoc(), R, TInfo, SC, 7069 Bindings); 7070 } else 7071 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7072 D.getIdentifierLoc(), II, R, TInfo, SC); 7073 7074 // If this is supposed to be a variable template, create it as such. 7075 if (IsVariableTemplate) { 7076 NewTemplate = 7077 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7078 TemplateParams, NewVD); 7079 NewVD->setDescribedVarTemplate(NewTemplate); 7080 } 7081 7082 // If this decl has an auto type in need of deduction, make a note of the 7083 // Decl so we can diagnose uses of it in its own initializer. 7084 if (R->getContainedDeducedType()) 7085 ParsingInitForAutoVars.insert(NewVD); 7086 7087 if (D.isInvalidType() || Invalid) { 7088 NewVD->setInvalidDecl(); 7089 if (NewTemplate) 7090 NewTemplate->setInvalidDecl(); 7091 } 7092 7093 SetNestedNameSpecifier(*this, NewVD, D); 7094 7095 // If we have any template parameter lists that don't directly belong to 7096 // the variable (matching the scope specifier), store them. 7097 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7098 if (TemplateParamLists.size() > VDTemplateParamLists) 7099 NewVD->setTemplateParameterListsInfo( 7100 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7101 } 7102 7103 if (D.getDeclSpec().isInlineSpecified()) { 7104 if (!getLangOpts().CPlusPlus) { 7105 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7106 << 0; 7107 } else if (CurContext->isFunctionOrMethod()) { 7108 // 'inline' is not allowed on block scope variable declaration. 7109 Diag(D.getDeclSpec().getInlineSpecLoc(), 7110 diag::err_inline_declaration_block_scope) << Name 7111 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7112 } else { 7113 Diag(D.getDeclSpec().getInlineSpecLoc(), 7114 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7115 : diag::ext_inline_variable); 7116 NewVD->setInlineSpecified(); 7117 } 7118 } 7119 7120 // Set the lexical context. If the declarator has a C++ scope specifier, the 7121 // lexical context will be different from the semantic context. 7122 NewVD->setLexicalDeclContext(CurContext); 7123 if (NewTemplate) 7124 NewTemplate->setLexicalDeclContext(CurContext); 7125 7126 if (IsLocalExternDecl) { 7127 if (D.isDecompositionDeclarator()) 7128 for (auto *B : Bindings) 7129 B->setLocalExternDecl(); 7130 else 7131 NewVD->setLocalExternDecl(); 7132 } 7133 7134 bool EmitTLSUnsupportedError = false; 7135 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7136 // C++11 [dcl.stc]p4: 7137 // When thread_local is applied to a variable of block scope the 7138 // storage-class-specifier static is implied if it does not appear 7139 // explicitly. 7140 // Core issue: 'static' is not implied if the variable is declared 7141 // 'extern'. 7142 if (NewVD->hasLocalStorage() && 7143 (SCSpec != DeclSpec::SCS_unspecified || 7144 TSCS != DeclSpec::TSCS_thread_local || 7145 !DC->isFunctionOrMethod())) 7146 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7147 diag::err_thread_non_global) 7148 << DeclSpec::getSpecifierName(TSCS); 7149 else if (!Context.getTargetInfo().isTLSSupported()) { 7150 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7151 getLangOpts().SYCLIsDevice) { 7152 // Postpone error emission until we've collected attributes required to 7153 // figure out whether it's a host or device variable and whether the 7154 // error should be ignored. 7155 EmitTLSUnsupportedError = true; 7156 // We still need to mark the variable as TLS so it shows up in AST with 7157 // proper storage class for other tools to use even if we're not going 7158 // to emit any code for it. 7159 NewVD->setTSCSpec(TSCS); 7160 } else 7161 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7162 diag::err_thread_unsupported); 7163 } else 7164 NewVD->setTSCSpec(TSCS); 7165 } 7166 7167 switch (D.getDeclSpec().getConstexprSpecifier()) { 7168 case ConstexprSpecKind::Unspecified: 7169 break; 7170 7171 case ConstexprSpecKind::Consteval: 7172 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7173 diag::err_constexpr_wrong_decl_kind) 7174 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7175 LLVM_FALLTHROUGH; 7176 7177 case ConstexprSpecKind::Constexpr: 7178 NewVD->setConstexpr(true); 7179 MaybeAddCUDAConstantAttr(NewVD); 7180 // C++1z [dcl.spec.constexpr]p1: 7181 // A static data member declared with the constexpr specifier is 7182 // implicitly an inline variable. 7183 if (NewVD->isStaticDataMember() && 7184 (getLangOpts().CPlusPlus17 || 7185 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7186 NewVD->setImplicitlyInline(); 7187 break; 7188 7189 case ConstexprSpecKind::Constinit: 7190 if (!NewVD->hasGlobalStorage()) 7191 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7192 diag::err_constinit_local_variable); 7193 else 7194 NewVD->addAttr(ConstInitAttr::Create( 7195 Context, D.getDeclSpec().getConstexprSpecLoc(), 7196 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7197 break; 7198 } 7199 7200 // C99 6.7.4p3 7201 // An inline definition of a function with external linkage shall 7202 // not contain a definition of a modifiable object with static or 7203 // thread storage duration... 7204 // We only apply this when the function is required to be defined 7205 // elsewhere, i.e. when the function is not 'extern inline'. Note 7206 // that a local variable with thread storage duration still has to 7207 // be marked 'static'. Also note that it's possible to get these 7208 // semantics in C++ using __attribute__((gnu_inline)). 7209 if (SC == SC_Static && S->getFnParent() != nullptr && 7210 !NewVD->getType().isConstQualified()) { 7211 FunctionDecl *CurFD = getCurFunctionDecl(); 7212 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7213 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7214 diag::warn_static_local_in_extern_inline); 7215 MaybeSuggestAddingStaticToDecl(CurFD); 7216 } 7217 } 7218 7219 if (D.getDeclSpec().isModulePrivateSpecified()) { 7220 if (IsVariableTemplateSpecialization) 7221 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7222 << (IsPartialSpecialization ? 1 : 0) 7223 << FixItHint::CreateRemoval( 7224 D.getDeclSpec().getModulePrivateSpecLoc()); 7225 else if (IsMemberSpecialization) 7226 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7227 << 2 7228 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7229 else if (NewVD->hasLocalStorage()) 7230 Diag(NewVD->getLocation(), diag::err_module_private_local) 7231 << 0 << NewVD 7232 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7233 << FixItHint::CreateRemoval( 7234 D.getDeclSpec().getModulePrivateSpecLoc()); 7235 else { 7236 NewVD->setModulePrivate(); 7237 if (NewTemplate) 7238 NewTemplate->setModulePrivate(); 7239 for (auto *B : Bindings) 7240 B->setModulePrivate(); 7241 } 7242 } 7243 7244 if (getLangOpts().OpenCL) { 7245 7246 deduceOpenCLAddressSpace(NewVD); 7247 7248 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); 7249 } 7250 7251 // Handle attributes prior to checking for duplicates in MergeVarDecl 7252 ProcessDeclAttributes(S, NewVD, D); 7253 7254 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7255 getLangOpts().SYCLIsDevice) { 7256 if (EmitTLSUnsupportedError && 7257 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7258 (getLangOpts().OpenMPIsDevice && 7259 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7260 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7261 diag::err_thread_unsupported); 7262 7263 if (EmitTLSUnsupportedError && 7264 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7265 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7266 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7267 // storage [duration]." 7268 if (SC == SC_None && S->getFnParent() != nullptr && 7269 (NewVD->hasAttr<CUDASharedAttr>() || 7270 NewVD->hasAttr<CUDAConstantAttr>())) { 7271 NewVD->setStorageClass(SC_Static); 7272 } 7273 } 7274 7275 // Ensure that dllimport globals without explicit storage class are treated as 7276 // extern. The storage class is set above using parsed attributes. Now we can 7277 // check the VarDecl itself. 7278 assert(!NewVD->hasAttr<DLLImportAttr>() || 7279 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7280 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7281 7282 // In auto-retain/release, infer strong retension for variables of 7283 // retainable type. 7284 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7285 NewVD->setInvalidDecl(); 7286 7287 // Handle GNU asm-label extension (encoded as an attribute). 7288 if (Expr *E = (Expr*)D.getAsmLabel()) { 7289 // The parser guarantees this is a string. 7290 StringLiteral *SE = cast<StringLiteral>(E); 7291 StringRef Label = SE->getString(); 7292 if (S->getFnParent() != nullptr) { 7293 switch (SC) { 7294 case SC_None: 7295 case SC_Auto: 7296 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7297 break; 7298 case SC_Register: 7299 // Local Named register 7300 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7301 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7302 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7303 break; 7304 case SC_Static: 7305 case SC_Extern: 7306 case SC_PrivateExtern: 7307 break; 7308 } 7309 } else if (SC == SC_Register) { 7310 // Global Named register 7311 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7312 const auto &TI = Context.getTargetInfo(); 7313 bool HasSizeMismatch; 7314 7315 if (!TI.isValidGCCRegisterName(Label)) 7316 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7317 else if (!TI.validateGlobalRegisterVariable(Label, 7318 Context.getTypeSize(R), 7319 HasSizeMismatch)) 7320 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7321 else if (HasSizeMismatch) 7322 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7323 } 7324 7325 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7326 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7327 NewVD->setInvalidDecl(true); 7328 } 7329 } 7330 7331 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7332 /*IsLiteralLabel=*/true, 7333 SE->getStrTokenLoc(0))); 7334 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7335 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7336 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7337 if (I != ExtnameUndeclaredIdentifiers.end()) { 7338 if (isDeclExternC(NewVD)) { 7339 NewVD->addAttr(I->second); 7340 ExtnameUndeclaredIdentifiers.erase(I); 7341 } else 7342 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7343 << /*Variable*/1 << NewVD; 7344 } 7345 } 7346 7347 // Find the shadowed declaration before filtering for scope. 7348 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7349 ? getShadowedDeclaration(NewVD, Previous) 7350 : nullptr; 7351 7352 // Don't consider existing declarations that are in a different 7353 // scope and are out-of-semantic-context declarations (if the new 7354 // declaration has linkage). 7355 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7356 D.getCXXScopeSpec().isNotEmpty() || 7357 IsMemberSpecialization || 7358 IsVariableTemplateSpecialization); 7359 7360 // Check whether the previous declaration is in the same block scope. This 7361 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7362 if (getLangOpts().CPlusPlus && 7363 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7364 NewVD->setPreviousDeclInSameBlockScope( 7365 Previous.isSingleResult() && !Previous.isShadowed() && 7366 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7367 7368 if (!getLangOpts().CPlusPlus) { 7369 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7370 } else { 7371 // If this is an explicit specialization of a static data member, check it. 7372 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7373 CheckMemberSpecialization(NewVD, Previous)) 7374 NewVD->setInvalidDecl(); 7375 7376 // Merge the decl with the existing one if appropriate. 7377 if (!Previous.empty()) { 7378 if (Previous.isSingleResult() && 7379 isa<FieldDecl>(Previous.getFoundDecl()) && 7380 D.getCXXScopeSpec().isSet()) { 7381 // The user tried to define a non-static data member 7382 // out-of-line (C++ [dcl.meaning]p1). 7383 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7384 << D.getCXXScopeSpec().getRange(); 7385 Previous.clear(); 7386 NewVD->setInvalidDecl(); 7387 } 7388 } else if (D.getCXXScopeSpec().isSet()) { 7389 // No previous declaration in the qualifying scope. 7390 Diag(D.getIdentifierLoc(), diag::err_no_member) 7391 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7392 << D.getCXXScopeSpec().getRange(); 7393 NewVD->setInvalidDecl(); 7394 } 7395 7396 if (!IsVariableTemplateSpecialization) 7397 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7398 7399 if (NewTemplate) { 7400 VarTemplateDecl *PrevVarTemplate = 7401 NewVD->getPreviousDecl() 7402 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7403 : nullptr; 7404 7405 // Check the template parameter list of this declaration, possibly 7406 // merging in the template parameter list from the previous variable 7407 // template declaration. 7408 if (CheckTemplateParameterList( 7409 TemplateParams, 7410 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7411 : nullptr, 7412 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7413 DC->isDependentContext()) 7414 ? TPC_ClassTemplateMember 7415 : TPC_VarTemplate)) 7416 NewVD->setInvalidDecl(); 7417 7418 // If we are providing an explicit specialization of a static variable 7419 // template, make a note of that. 7420 if (PrevVarTemplate && 7421 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7422 PrevVarTemplate->setMemberSpecialization(); 7423 } 7424 } 7425 7426 // Diagnose shadowed variables iff this isn't a redeclaration. 7427 if (ShadowedDecl && !D.isRedeclaration()) 7428 CheckShadow(NewVD, ShadowedDecl, Previous); 7429 7430 ProcessPragmaWeak(S, NewVD); 7431 7432 // If this is the first declaration of an extern C variable, update 7433 // the map of such variables. 7434 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7435 isIncompleteDeclExternC(*this, NewVD)) 7436 RegisterLocallyScopedExternCDecl(NewVD, S); 7437 7438 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7439 MangleNumberingContext *MCtx; 7440 Decl *ManglingContextDecl; 7441 std::tie(MCtx, ManglingContextDecl) = 7442 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7443 if (MCtx) { 7444 Context.setManglingNumber( 7445 NewVD, MCtx->getManglingNumber( 7446 NewVD, getMSManglingNumber(getLangOpts(), S))); 7447 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7448 } 7449 } 7450 7451 // Special handling of variable named 'main'. 7452 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7453 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7454 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7455 7456 // C++ [basic.start.main]p3 7457 // A program that declares a variable main at global scope is ill-formed. 7458 if (getLangOpts().CPlusPlus) 7459 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7460 7461 // In C, and external-linkage variable named main results in undefined 7462 // behavior. 7463 else if (NewVD->hasExternalFormalLinkage()) 7464 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7465 } 7466 7467 if (D.isRedeclaration() && !Previous.empty()) { 7468 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7469 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7470 D.isFunctionDefinition()); 7471 } 7472 7473 if (NewTemplate) { 7474 if (NewVD->isInvalidDecl()) 7475 NewTemplate->setInvalidDecl(); 7476 ActOnDocumentableDecl(NewTemplate); 7477 return NewTemplate; 7478 } 7479 7480 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7481 CompleteMemberSpecialization(NewVD, Previous); 7482 7483 return NewVD; 7484 } 7485 7486 /// Enum describing the %select options in diag::warn_decl_shadow. 7487 enum ShadowedDeclKind { 7488 SDK_Local, 7489 SDK_Global, 7490 SDK_StaticMember, 7491 SDK_Field, 7492 SDK_Typedef, 7493 SDK_Using 7494 }; 7495 7496 /// Determine what kind of declaration we're shadowing. 7497 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7498 const DeclContext *OldDC) { 7499 if (isa<TypeAliasDecl>(ShadowedDecl)) 7500 return SDK_Using; 7501 else if (isa<TypedefDecl>(ShadowedDecl)) 7502 return SDK_Typedef; 7503 else if (isa<RecordDecl>(OldDC)) 7504 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7505 7506 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7507 } 7508 7509 /// Return the location of the capture if the given lambda captures the given 7510 /// variable \p VD, or an invalid source location otherwise. 7511 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7512 const VarDecl *VD) { 7513 for (const Capture &Capture : LSI->Captures) { 7514 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7515 return Capture.getLocation(); 7516 } 7517 return SourceLocation(); 7518 } 7519 7520 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7521 const LookupResult &R) { 7522 // Only diagnose if we're shadowing an unambiguous field or variable. 7523 if (R.getResultKind() != LookupResult::Found) 7524 return false; 7525 7526 // Return false if warning is ignored. 7527 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7528 } 7529 7530 /// Return the declaration shadowed by the given variable \p D, or null 7531 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7532 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7533 const LookupResult &R) { 7534 if (!shouldWarnIfShadowedDecl(Diags, R)) 7535 return nullptr; 7536 7537 // Don't diagnose declarations at file scope. 7538 if (D->hasGlobalStorage()) 7539 return nullptr; 7540 7541 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7542 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7543 ? ShadowedDecl 7544 : nullptr; 7545 } 7546 7547 /// Return the declaration shadowed by the given typedef \p D, or null 7548 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7549 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7550 const LookupResult &R) { 7551 // Don't warn if typedef declaration is part of a class 7552 if (D->getDeclContext()->isRecord()) 7553 return nullptr; 7554 7555 if (!shouldWarnIfShadowedDecl(Diags, R)) 7556 return nullptr; 7557 7558 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7559 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7560 } 7561 7562 /// Diagnose variable or built-in function shadowing. Implements 7563 /// -Wshadow. 7564 /// 7565 /// This method is called whenever a VarDecl is added to a "useful" 7566 /// scope. 7567 /// 7568 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7569 /// \param R the lookup of the name 7570 /// 7571 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7572 const LookupResult &R) { 7573 DeclContext *NewDC = D->getDeclContext(); 7574 7575 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7576 // Fields are not shadowed by variables in C++ static methods. 7577 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7578 if (MD->isStatic()) 7579 return; 7580 7581 // Fields shadowed by constructor parameters are a special case. Usually 7582 // the constructor initializes the field with the parameter. 7583 if (isa<CXXConstructorDecl>(NewDC)) 7584 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7585 // Remember that this was shadowed so we can either warn about its 7586 // modification or its existence depending on warning settings. 7587 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7588 return; 7589 } 7590 } 7591 7592 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7593 if (shadowedVar->isExternC()) { 7594 // For shadowing external vars, make sure that we point to the global 7595 // declaration, not a locally scoped extern declaration. 7596 for (auto I : shadowedVar->redecls()) 7597 if (I->isFileVarDecl()) { 7598 ShadowedDecl = I; 7599 break; 7600 } 7601 } 7602 7603 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7604 7605 unsigned WarningDiag = diag::warn_decl_shadow; 7606 SourceLocation CaptureLoc; 7607 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7608 isa<CXXMethodDecl>(NewDC)) { 7609 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7610 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7611 if (RD->getLambdaCaptureDefault() == LCD_None) { 7612 // Try to avoid warnings for lambdas with an explicit capture list. 7613 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7614 // Warn only when the lambda captures the shadowed decl explicitly. 7615 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7616 if (CaptureLoc.isInvalid()) 7617 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7618 } else { 7619 // Remember that this was shadowed so we can avoid the warning if the 7620 // shadowed decl isn't captured and the warning settings allow it. 7621 cast<LambdaScopeInfo>(getCurFunction()) 7622 ->ShadowingDecls.push_back( 7623 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7624 return; 7625 } 7626 } 7627 7628 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7629 // A variable can't shadow a local variable in an enclosing scope, if 7630 // they are separated by a non-capturing declaration context. 7631 for (DeclContext *ParentDC = NewDC; 7632 ParentDC && !ParentDC->Equals(OldDC); 7633 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7634 // Only block literals, captured statements, and lambda expressions 7635 // can capture; other scopes don't. 7636 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7637 !isLambdaCallOperator(ParentDC)) { 7638 return; 7639 } 7640 } 7641 } 7642 } 7643 } 7644 7645 // Only warn about certain kinds of shadowing for class members. 7646 if (NewDC && NewDC->isRecord()) { 7647 // In particular, don't warn about shadowing non-class members. 7648 if (!OldDC->isRecord()) 7649 return; 7650 7651 // TODO: should we warn about static data members shadowing 7652 // static data members from base classes? 7653 7654 // TODO: don't diagnose for inaccessible shadowed members. 7655 // This is hard to do perfectly because we might friend the 7656 // shadowing context, but that's just a false negative. 7657 } 7658 7659 7660 DeclarationName Name = R.getLookupName(); 7661 7662 // Emit warning and note. 7663 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7664 return; 7665 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7666 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7667 if (!CaptureLoc.isInvalid()) 7668 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7669 << Name << /*explicitly*/ 1; 7670 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7671 } 7672 7673 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7674 /// when these variables are captured by the lambda. 7675 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7676 for (const auto &Shadow : LSI->ShadowingDecls) { 7677 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7678 // Try to avoid the warning when the shadowed decl isn't captured. 7679 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7680 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7681 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7682 ? diag::warn_decl_shadow_uncaptured_local 7683 : diag::warn_decl_shadow) 7684 << Shadow.VD->getDeclName() 7685 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7686 if (!CaptureLoc.isInvalid()) 7687 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7688 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7689 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7690 } 7691 } 7692 7693 /// Check -Wshadow without the advantage of a previous lookup. 7694 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7695 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7696 return; 7697 7698 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7699 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7700 LookupName(R, S); 7701 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7702 CheckShadow(D, ShadowedDecl, R); 7703 } 7704 7705 /// Check if 'E', which is an expression that is about to be modified, refers 7706 /// to a constructor parameter that shadows a field. 7707 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7708 // Quickly ignore expressions that can't be shadowing ctor parameters. 7709 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7710 return; 7711 E = E->IgnoreParenImpCasts(); 7712 auto *DRE = dyn_cast<DeclRefExpr>(E); 7713 if (!DRE) 7714 return; 7715 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7716 auto I = ShadowingDecls.find(D); 7717 if (I == ShadowingDecls.end()) 7718 return; 7719 const NamedDecl *ShadowedDecl = I->second; 7720 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7721 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7722 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7723 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7724 7725 // Avoid issuing multiple warnings about the same decl. 7726 ShadowingDecls.erase(I); 7727 } 7728 7729 /// Check for conflict between this global or extern "C" declaration and 7730 /// previous global or extern "C" declarations. This is only used in C++. 7731 template<typename T> 7732 static bool checkGlobalOrExternCConflict( 7733 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7734 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7735 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7736 7737 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7738 // The common case: this global doesn't conflict with any extern "C" 7739 // declaration. 7740 return false; 7741 } 7742 7743 if (Prev) { 7744 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7745 // Both the old and new declarations have C language linkage. This is a 7746 // redeclaration. 7747 Previous.clear(); 7748 Previous.addDecl(Prev); 7749 return true; 7750 } 7751 7752 // This is a global, non-extern "C" declaration, and there is a previous 7753 // non-global extern "C" declaration. Diagnose if this is a variable 7754 // declaration. 7755 if (!isa<VarDecl>(ND)) 7756 return false; 7757 } else { 7758 // The declaration is extern "C". Check for any declaration in the 7759 // translation unit which might conflict. 7760 if (IsGlobal) { 7761 // We have already performed the lookup into the translation unit. 7762 IsGlobal = false; 7763 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7764 I != E; ++I) { 7765 if (isa<VarDecl>(*I)) { 7766 Prev = *I; 7767 break; 7768 } 7769 } 7770 } else { 7771 DeclContext::lookup_result R = 7772 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7773 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7774 I != E; ++I) { 7775 if (isa<VarDecl>(*I)) { 7776 Prev = *I; 7777 break; 7778 } 7779 // FIXME: If we have any other entity with this name in global scope, 7780 // the declaration is ill-formed, but that is a defect: it breaks the 7781 // 'stat' hack, for instance. Only variables can have mangled name 7782 // clashes with extern "C" declarations, so only they deserve a 7783 // diagnostic. 7784 } 7785 } 7786 7787 if (!Prev) 7788 return false; 7789 } 7790 7791 // Use the first declaration's location to ensure we point at something which 7792 // is lexically inside an extern "C" linkage-spec. 7793 assert(Prev && "should have found a previous declaration to diagnose"); 7794 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7795 Prev = FD->getFirstDecl(); 7796 else 7797 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7798 7799 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7800 << IsGlobal << ND; 7801 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7802 << IsGlobal; 7803 return false; 7804 } 7805 7806 /// Apply special rules for handling extern "C" declarations. Returns \c true 7807 /// if we have found that this is a redeclaration of some prior entity. 7808 /// 7809 /// Per C++ [dcl.link]p6: 7810 /// Two declarations [for a function or variable] with C language linkage 7811 /// with the same name that appear in different scopes refer to the same 7812 /// [entity]. An entity with C language linkage shall not be declared with 7813 /// the same name as an entity in global scope. 7814 template<typename T> 7815 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7816 LookupResult &Previous) { 7817 if (!S.getLangOpts().CPlusPlus) { 7818 // In C, when declaring a global variable, look for a corresponding 'extern' 7819 // variable declared in function scope. We don't need this in C++, because 7820 // we find local extern decls in the surrounding file-scope DeclContext. 7821 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7822 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7823 Previous.clear(); 7824 Previous.addDecl(Prev); 7825 return true; 7826 } 7827 } 7828 return false; 7829 } 7830 7831 // A declaration in the translation unit can conflict with an extern "C" 7832 // declaration. 7833 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7834 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7835 7836 // An extern "C" declaration can conflict with a declaration in the 7837 // translation unit or can be a redeclaration of an extern "C" declaration 7838 // in another scope. 7839 if (isIncompleteDeclExternC(S,ND)) 7840 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7841 7842 // Neither global nor extern "C": nothing to do. 7843 return false; 7844 } 7845 7846 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7847 // If the decl is already known invalid, don't check it. 7848 if (NewVD->isInvalidDecl()) 7849 return; 7850 7851 QualType T = NewVD->getType(); 7852 7853 // Defer checking an 'auto' type until its initializer is attached. 7854 if (T->isUndeducedType()) 7855 return; 7856 7857 if (NewVD->hasAttrs()) 7858 CheckAlignasUnderalignment(NewVD); 7859 7860 if (T->isObjCObjectType()) { 7861 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7862 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7863 T = Context.getObjCObjectPointerType(T); 7864 NewVD->setType(T); 7865 } 7866 7867 // Emit an error if an address space was applied to decl with local storage. 7868 // This includes arrays of objects with address space qualifiers, but not 7869 // automatic variables that point to other address spaces. 7870 // ISO/IEC TR 18037 S5.1.2 7871 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7872 T.getAddressSpace() != LangAS::Default) { 7873 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7874 NewVD->setInvalidDecl(); 7875 return; 7876 } 7877 7878 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7879 // scope. 7880 if (getLangOpts().OpenCLVersion == 120 && 7881 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7882 NewVD->isStaticLocal()) { 7883 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7884 NewVD->setInvalidDecl(); 7885 return; 7886 } 7887 7888 if (getLangOpts().OpenCL) { 7889 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7890 if (NewVD->hasAttr<BlocksAttr>()) { 7891 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7892 return; 7893 } 7894 7895 if (T->isBlockPointerType()) { 7896 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7897 // can't use 'extern' storage class. 7898 if (!T.isConstQualified()) { 7899 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7900 << 0 /*const*/; 7901 NewVD->setInvalidDecl(); 7902 return; 7903 } 7904 if (NewVD->hasExternalStorage()) { 7905 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7906 NewVD->setInvalidDecl(); 7907 return; 7908 } 7909 } 7910 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7911 // __constant address space. 7912 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7913 // variables inside a function can also be declared in the global 7914 // address space. 7915 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7916 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7917 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7918 NewVD->hasExternalStorage()) { 7919 if (!T->isSamplerT() && 7920 !T->isDependentType() && 7921 !(T.getAddressSpace() == LangAS::opencl_constant || 7922 (T.getAddressSpace() == LangAS::opencl_global && 7923 (getLangOpts().OpenCLVersion == 200 || 7924 getLangOpts().OpenCLCPlusPlus)))) { 7925 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7926 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7927 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7928 << Scope << "global or constant"; 7929 else 7930 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7931 << Scope << "constant"; 7932 NewVD->setInvalidDecl(); 7933 return; 7934 } 7935 } else { 7936 if (T.getAddressSpace() == LangAS::opencl_global) { 7937 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7938 << 1 /*is any function*/ << "global"; 7939 NewVD->setInvalidDecl(); 7940 return; 7941 } 7942 if (T.getAddressSpace() == LangAS::opencl_constant || 7943 T.getAddressSpace() == LangAS::opencl_local) { 7944 FunctionDecl *FD = getCurFunctionDecl(); 7945 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7946 // in functions. 7947 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7948 if (T.getAddressSpace() == LangAS::opencl_constant) 7949 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7950 << 0 /*non-kernel only*/ << "constant"; 7951 else 7952 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7953 << 0 /*non-kernel only*/ << "local"; 7954 NewVD->setInvalidDecl(); 7955 return; 7956 } 7957 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7958 // in the outermost scope of a kernel function. 7959 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7960 if (!getCurScope()->isFunctionScope()) { 7961 if (T.getAddressSpace() == LangAS::opencl_constant) 7962 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7963 << "constant"; 7964 else 7965 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7966 << "local"; 7967 NewVD->setInvalidDecl(); 7968 return; 7969 } 7970 } 7971 } else if (T.getAddressSpace() != LangAS::opencl_private && 7972 // If we are parsing a template we didn't deduce an addr 7973 // space yet. 7974 T.getAddressSpace() != LangAS::Default) { 7975 // Do not allow other address spaces on automatic variable. 7976 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7977 NewVD->setInvalidDecl(); 7978 return; 7979 } 7980 } 7981 } 7982 7983 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7984 && !NewVD->hasAttr<BlocksAttr>()) { 7985 if (getLangOpts().getGC() != LangOptions::NonGC) 7986 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7987 else { 7988 assert(!getLangOpts().ObjCAutoRefCount); 7989 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7990 } 7991 } 7992 7993 bool isVM = T->isVariablyModifiedType(); 7994 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7995 NewVD->hasAttr<BlocksAttr>()) 7996 setFunctionHasBranchProtectedScope(); 7997 7998 if ((isVM && NewVD->hasLinkage()) || 7999 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8000 bool SizeIsNegative; 8001 llvm::APSInt Oversized; 8002 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8003 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8004 QualType FixedT; 8005 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8006 FixedT = FixedTInfo->getType(); 8007 else if (FixedTInfo) { 8008 // Type and type-as-written are canonically different. We need to fix up 8009 // both types separately. 8010 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8011 Oversized); 8012 } 8013 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8014 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8015 // FIXME: This won't give the correct result for 8016 // int a[10][n]; 8017 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8018 8019 if (NewVD->isFileVarDecl()) 8020 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8021 << SizeRange; 8022 else if (NewVD->isStaticLocal()) 8023 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8024 << SizeRange; 8025 else 8026 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8027 << SizeRange; 8028 NewVD->setInvalidDecl(); 8029 return; 8030 } 8031 8032 if (!FixedTInfo) { 8033 if (NewVD->isFileVarDecl()) 8034 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8035 else 8036 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8037 NewVD->setInvalidDecl(); 8038 return; 8039 } 8040 8041 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8042 NewVD->setType(FixedT); 8043 NewVD->setTypeSourceInfo(FixedTInfo); 8044 } 8045 8046 if (T->isVoidType()) { 8047 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8048 // of objects and functions. 8049 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8050 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8051 << T; 8052 NewVD->setInvalidDecl(); 8053 return; 8054 } 8055 } 8056 8057 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8058 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8059 NewVD->setInvalidDecl(); 8060 return; 8061 } 8062 8063 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8064 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8065 NewVD->setInvalidDecl(); 8066 return; 8067 } 8068 8069 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8070 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8071 NewVD->setInvalidDecl(); 8072 return; 8073 } 8074 8075 if (NewVD->isConstexpr() && !T->isDependentType() && 8076 RequireLiteralType(NewVD->getLocation(), T, 8077 diag::err_constexpr_var_non_literal)) { 8078 NewVD->setInvalidDecl(); 8079 return; 8080 } 8081 8082 // PPC MMA non-pointer types are not allowed as non-local variable types. 8083 if (Context.getTargetInfo().getTriple().isPPC64() && 8084 !NewVD->isLocalVarDecl() && 8085 CheckPPCMMAType(T, NewVD->getLocation())) { 8086 NewVD->setInvalidDecl(); 8087 return; 8088 } 8089 } 8090 8091 /// Perform semantic checking on a newly-created variable 8092 /// declaration. 8093 /// 8094 /// This routine performs all of the type-checking required for a 8095 /// variable declaration once it has been built. It is used both to 8096 /// check variables after they have been parsed and their declarators 8097 /// have been translated into a declaration, and to check variables 8098 /// that have been instantiated from a template. 8099 /// 8100 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8101 /// 8102 /// Returns true if the variable declaration is a redeclaration. 8103 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8104 CheckVariableDeclarationType(NewVD); 8105 8106 // If the decl is already known invalid, don't check it. 8107 if (NewVD->isInvalidDecl()) 8108 return false; 8109 8110 // If we did not find anything by this name, look for a non-visible 8111 // extern "C" declaration with the same name. 8112 if (Previous.empty() && 8113 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8114 Previous.setShadowed(); 8115 8116 if (!Previous.empty()) { 8117 MergeVarDecl(NewVD, Previous); 8118 return true; 8119 } 8120 return false; 8121 } 8122 8123 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8124 /// and if so, check that it's a valid override and remember it. 8125 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8126 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8127 8128 // Look for methods in base classes that this method might override. 8129 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8130 /*DetectVirtual=*/false); 8131 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8132 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8133 DeclarationName Name = MD->getDeclName(); 8134 8135 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8136 // We really want to find the base class destructor here. 8137 QualType T = Context.getTypeDeclType(BaseRecord); 8138 CanQualType CT = Context.getCanonicalType(T); 8139 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8140 } 8141 8142 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8143 CXXMethodDecl *BaseMD = 8144 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8145 if (!BaseMD || !BaseMD->isVirtual() || 8146 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8147 /*ConsiderCudaAttrs=*/true, 8148 // C++2a [class.virtual]p2 does not consider requires 8149 // clauses when overriding. 8150 /*ConsiderRequiresClauses=*/false)) 8151 continue; 8152 8153 if (Overridden.insert(BaseMD).second) { 8154 MD->addOverriddenMethod(BaseMD); 8155 CheckOverridingFunctionReturnType(MD, BaseMD); 8156 CheckOverridingFunctionAttributes(MD, BaseMD); 8157 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8158 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8159 } 8160 8161 // A method can only override one function from each base class. We 8162 // don't track indirectly overridden methods from bases of bases. 8163 return true; 8164 } 8165 8166 return false; 8167 }; 8168 8169 DC->lookupInBases(VisitBase, Paths); 8170 return !Overridden.empty(); 8171 } 8172 8173 namespace { 8174 // Struct for holding all of the extra arguments needed by 8175 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8176 struct ActOnFDArgs { 8177 Scope *S; 8178 Declarator &D; 8179 MultiTemplateParamsArg TemplateParamLists; 8180 bool AddToScope; 8181 }; 8182 } // end anonymous namespace 8183 8184 namespace { 8185 8186 // Callback to only accept typo corrections that have a non-zero edit distance. 8187 // Also only accept corrections that have the same parent decl. 8188 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8189 public: 8190 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8191 CXXRecordDecl *Parent) 8192 : Context(Context), OriginalFD(TypoFD), 8193 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8194 8195 bool ValidateCandidate(const TypoCorrection &candidate) override { 8196 if (candidate.getEditDistance() == 0) 8197 return false; 8198 8199 SmallVector<unsigned, 1> MismatchedParams; 8200 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8201 CDeclEnd = candidate.end(); 8202 CDecl != CDeclEnd; ++CDecl) { 8203 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8204 8205 if (FD && !FD->hasBody() && 8206 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8207 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8208 CXXRecordDecl *Parent = MD->getParent(); 8209 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8210 return true; 8211 } else if (!ExpectedParent) { 8212 return true; 8213 } 8214 } 8215 } 8216 8217 return false; 8218 } 8219 8220 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8221 return std::make_unique<DifferentNameValidatorCCC>(*this); 8222 } 8223 8224 private: 8225 ASTContext &Context; 8226 FunctionDecl *OriginalFD; 8227 CXXRecordDecl *ExpectedParent; 8228 }; 8229 8230 } // end anonymous namespace 8231 8232 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8233 TypoCorrectedFunctionDefinitions.insert(F); 8234 } 8235 8236 /// Generate diagnostics for an invalid function redeclaration. 8237 /// 8238 /// This routine handles generating the diagnostic messages for an invalid 8239 /// function redeclaration, including finding possible similar declarations 8240 /// or performing typo correction if there are no previous declarations with 8241 /// the same name. 8242 /// 8243 /// Returns a NamedDecl iff typo correction was performed and substituting in 8244 /// the new declaration name does not cause new errors. 8245 static NamedDecl *DiagnoseInvalidRedeclaration( 8246 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8247 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8248 DeclarationName Name = NewFD->getDeclName(); 8249 DeclContext *NewDC = NewFD->getDeclContext(); 8250 SmallVector<unsigned, 1> MismatchedParams; 8251 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8252 TypoCorrection Correction; 8253 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8254 unsigned DiagMsg = 8255 IsLocalFriend ? diag::err_no_matching_local_friend : 8256 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8257 diag::err_member_decl_does_not_match; 8258 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8259 IsLocalFriend ? Sema::LookupLocalFriendName 8260 : Sema::LookupOrdinaryName, 8261 Sema::ForVisibleRedeclaration); 8262 8263 NewFD->setInvalidDecl(); 8264 if (IsLocalFriend) 8265 SemaRef.LookupName(Prev, S); 8266 else 8267 SemaRef.LookupQualifiedName(Prev, NewDC); 8268 assert(!Prev.isAmbiguous() && 8269 "Cannot have an ambiguity in previous-declaration lookup"); 8270 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8271 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8272 MD ? MD->getParent() : nullptr); 8273 if (!Prev.empty()) { 8274 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8275 Func != FuncEnd; ++Func) { 8276 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8277 if (FD && 8278 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8279 // Add 1 to the index so that 0 can mean the mismatch didn't 8280 // involve a parameter 8281 unsigned ParamNum = 8282 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8283 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8284 } 8285 } 8286 // If the qualified name lookup yielded nothing, try typo correction 8287 } else if ((Correction = SemaRef.CorrectTypo( 8288 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8289 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8290 IsLocalFriend ? nullptr : NewDC))) { 8291 // Set up everything for the call to ActOnFunctionDeclarator 8292 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8293 ExtraArgs.D.getIdentifierLoc()); 8294 Previous.clear(); 8295 Previous.setLookupName(Correction.getCorrection()); 8296 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8297 CDeclEnd = Correction.end(); 8298 CDecl != CDeclEnd; ++CDecl) { 8299 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8300 if (FD && !FD->hasBody() && 8301 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8302 Previous.addDecl(FD); 8303 } 8304 } 8305 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8306 8307 NamedDecl *Result; 8308 // Retry building the function declaration with the new previous 8309 // declarations, and with errors suppressed. 8310 { 8311 // Trap errors. 8312 Sema::SFINAETrap Trap(SemaRef); 8313 8314 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8315 // pieces need to verify the typo-corrected C++ declaration and hopefully 8316 // eliminate the need for the parameter pack ExtraArgs. 8317 Result = SemaRef.ActOnFunctionDeclarator( 8318 ExtraArgs.S, ExtraArgs.D, 8319 Correction.getCorrectionDecl()->getDeclContext(), 8320 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8321 ExtraArgs.AddToScope); 8322 8323 if (Trap.hasErrorOccurred()) 8324 Result = nullptr; 8325 } 8326 8327 if (Result) { 8328 // Determine which correction we picked. 8329 Decl *Canonical = Result->getCanonicalDecl(); 8330 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8331 I != E; ++I) 8332 if ((*I)->getCanonicalDecl() == Canonical) 8333 Correction.setCorrectionDecl(*I); 8334 8335 // Let Sema know about the correction. 8336 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8337 SemaRef.diagnoseTypo( 8338 Correction, 8339 SemaRef.PDiag(IsLocalFriend 8340 ? diag::err_no_matching_local_friend_suggest 8341 : diag::err_member_decl_does_not_match_suggest) 8342 << Name << NewDC << IsDefinition); 8343 return Result; 8344 } 8345 8346 // Pretend the typo correction never occurred 8347 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8348 ExtraArgs.D.getIdentifierLoc()); 8349 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8350 Previous.clear(); 8351 Previous.setLookupName(Name); 8352 } 8353 8354 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8355 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8356 8357 bool NewFDisConst = false; 8358 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8359 NewFDisConst = NewMD->isConst(); 8360 8361 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8362 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8363 NearMatch != NearMatchEnd; ++NearMatch) { 8364 FunctionDecl *FD = NearMatch->first; 8365 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8366 bool FDisConst = MD && MD->isConst(); 8367 bool IsMember = MD || !IsLocalFriend; 8368 8369 // FIXME: These notes are poorly worded for the local friend case. 8370 if (unsigned Idx = NearMatch->second) { 8371 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8372 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8373 if (Loc.isInvalid()) Loc = FD->getLocation(); 8374 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8375 : diag::note_local_decl_close_param_match) 8376 << Idx << FDParam->getType() 8377 << NewFD->getParamDecl(Idx - 1)->getType(); 8378 } else if (FDisConst != NewFDisConst) { 8379 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8380 << NewFDisConst << FD->getSourceRange().getEnd(); 8381 } else 8382 SemaRef.Diag(FD->getLocation(), 8383 IsMember ? diag::note_member_def_close_match 8384 : diag::note_local_decl_close_match); 8385 } 8386 return nullptr; 8387 } 8388 8389 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8390 switch (D.getDeclSpec().getStorageClassSpec()) { 8391 default: llvm_unreachable("Unknown storage class!"); 8392 case DeclSpec::SCS_auto: 8393 case DeclSpec::SCS_register: 8394 case DeclSpec::SCS_mutable: 8395 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8396 diag::err_typecheck_sclass_func); 8397 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8398 D.setInvalidType(); 8399 break; 8400 case DeclSpec::SCS_unspecified: break; 8401 case DeclSpec::SCS_extern: 8402 if (D.getDeclSpec().isExternInLinkageSpec()) 8403 return SC_None; 8404 return SC_Extern; 8405 case DeclSpec::SCS_static: { 8406 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8407 // C99 6.7.1p5: 8408 // The declaration of an identifier for a function that has 8409 // block scope shall have no explicit storage-class specifier 8410 // other than extern 8411 // See also (C++ [dcl.stc]p4). 8412 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8413 diag::err_static_block_func); 8414 break; 8415 } else 8416 return SC_Static; 8417 } 8418 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8419 } 8420 8421 // No explicit storage class has already been returned 8422 return SC_None; 8423 } 8424 8425 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8426 DeclContext *DC, QualType &R, 8427 TypeSourceInfo *TInfo, 8428 StorageClass SC, 8429 bool &IsVirtualOkay) { 8430 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8431 DeclarationName Name = NameInfo.getName(); 8432 8433 FunctionDecl *NewFD = nullptr; 8434 bool isInline = D.getDeclSpec().isInlineSpecified(); 8435 8436 if (!SemaRef.getLangOpts().CPlusPlus) { 8437 // Determine whether the function was written with a 8438 // prototype. This true when: 8439 // - there is a prototype in the declarator, or 8440 // - the type R of the function is some kind of typedef or other non- 8441 // attributed reference to a type name (which eventually refers to a 8442 // function type). 8443 bool HasPrototype = 8444 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8445 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8446 8447 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8448 R, TInfo, SC, isInline, HasPrototype, 8449 ConstexprSpecKind::Unspecified, 8450 /*TrailingRequiresClause=*/nullptr); 8451 if (D.isInvalidType()) 8452 NewFD->setInvalidDecl(); 8453 8454 return NewFD; 8455 } 8456 8457 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8458 8459 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8460 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8461 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8462 diag::err_constexpr_wrong_decl_kind) 8463 << static_cast<int>(ConstexprKind); 8464 ConstexprKind = ConstexprSpecKind::Unspecified; 8465 D.getMutableDeclSpec().ClearConstexprSpec(); 8466 } 8467 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8468 8469 // Check that the return type is not an abstract class type. 8470 // For record types, this is done by the AbstractClassUsageDiagnoser once 8471 // the class has been completely parsed. 8472 if (!DC->isRecord() && 8473 SemaRef.RequireNonAbstractType( 8474 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8475 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8476 D.setInvalidType(); 8477 8478 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8479 // This is a C++ constructor declaration. 8480 assert(DC->isRecord() && 8481 "Constructors can only be declared in a member context"); 8482 8483 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8484 return CXXConstructorDecl::Create( 8485 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8486 TInfo, ExplicitSpecifier, isInline, 8487 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8488 TrailingRequiresClause); 8489 8490 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8491 // This is a C++ destructor declaration. 8492 if (DC->isRecord()) { 8493 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8494 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8495 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8496 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8497 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8498 TrailingRequiresClause); 8499 8500 // If the destructor needs an implicit exception specification, set it 8501 // now. FIXME: It'd be nice to be able to create the right type to start 8502 // with, but the type needs to reference the destructor declaration. 8503 if (SemaRef.getLangOpts().CPlusPlus11) 8504 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8505 8506 IsVirtualOkay = true; 8507 return NewDD; 8508 8509 } else { 8510 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8511 D.setInvalidType(); 8512 8513 // Create a FunctionDecl to satisfy the function definition parsing 8514 // code path. 8515 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8516 D.getIdentifierLoc(), Name, R, TInfo, SC, 8517 isInline, 8518 /*hasPrototype=*/true, ConstexprKind, 8519 TrailingRequiresClause); 8520 } 8521 8522 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8523 if (!DC->isRecord()) { 8524 SemaRef.Diag(D.getIdentifierLoc(), 8525 diag::err_conv_function_not_member); 8526 return nullptr; 8527 } 8528 8529 SemaRef.CheckConversionDeclarator(D, R, SC); 8530 if (D.isInvalidType()) 8531 return nullptr; 8532 8533 IsVirtualOkay = true; 8534 return CXXConversionDecl::Create( 8535 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8536 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8537 TrailingRequiresClause); 8538 8539 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8540 if (TrailingRequiresClause) 8541 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8542 diag::err_trailing_requires_clause_on_deduction_guide) 8543 << TrailingRequiresClause->getSourceRange(); 8544 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8545 8546 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8547 ExplicitSpecifier, NameInfo, R, TInfo, 8548 D.getEndLoc()); 8549 } else if (DC->isRecord()) { 8550 // If the name of the function is the same as the name of the record, 8551 // then this must be an invalid constructor that has a return type. 8552 // (The parser checks for a return type and makes the declarator a 8553 // constructor if it has no return type). 8554 if (Name.getAsIdentifierInfo() && 8555 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8556 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8557 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8558 << SourceRange(D.getIdentifierLoc()); 8559 return nullptr; 8560 } 8561 8562 // This is a C++ method declaration. 8563 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8564 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8565 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8566 TrailingRequiresClause); 8567 IsVirtualOkay = !Ret->isStatic(); 8568 return Ret; 8569 } else { 8570 bool isFriend = 8571 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8572 if (!isFriend && SemaRef.CurContext->isRecord()) 8573 return nullptr; 8574 8575 // Determine whether the function was written with a 8576 // prototype. This true when: 8577 // - we're in C++ (where every function has a prototype), 8578 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8579 R, TInfo, SC, isInline, true /*HasPrototype*/, 8580 ConstexprKind, TrailingRequiresClause); 8581 } 8582 } 8583 8584 enum OpenCLParamType { 8585 ValidKernelParam, 8586 PtrPtrKernelParam, 8587 PtrKernelParam, 8588 InvalidAddrSpacePtrKernelParam, 8589 InvalidKernelParam, 8590 RecordKernelParam 8591 }; 8592 8593 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8594 // Size dependent types are just typedefs to normal integer types 8595 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8596 // integers other than by their names. 8597 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8598 8599 // Remove typedefs one by one until we reach a typedef 8600 // for a size dependent type. 8601 QualType DesugaredTy = Ty; 8602 do { 8603 ArrayRef<StringRef> Names(SizeTypeNames); 8604 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8605 if (Names.end() != Match) 8606 return true; 8607 8608 Ty = DesugaredTy; 8609 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8610 } while (DesugaredTy != Ty); 8611 8612 return false; 8613 } 8614 8615 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8616 if (PT->isPointerType()) { 8617 QualType PointeeType = PT->getPointeeType(); 8618 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8619 PointeeType.getAddressSpace() == LangAS::opencl_private || 8620 PointeeType.getAddressSpace() == LangAS::Default) 8621 return InvalidAddrSpacePtrKernelParam; 8622 8623 if (PointeeType->isPointerType()) { 8624 // This is a pointer to pointer parameter. 8625 // Recursively check inner type. 8626 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 8627 if (ParamKind == InvalidAddrSpacePtrKernelParam || 8628 ParamKind == InvalidKernelParam) 8629 return ParamKind; 8630 8631 return PtrPtrKernelParam; 8632 } 8633 return PtrKernelParam; 8634 } 8635 8636 // OpenCL v1.2 s6.9.k: 8637 // Arguments to kernel functions in a program cannot be declared with the 8638 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8639 // uintptr_t or a struct and/or union that contain fields declared to be one 8640 // of these built-in scalar types. 8641 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8642 return InvalidKernelParam; 8643 8644 if (PT->isImageType()) 8645 return PtrKernelParam; 8646 8647 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8648 return InvalidKernelParam; 8649 8650 // OpenCL extension spec v1.2 s9.5: 8651 // This extension adds support for half scalar and vector types as built-in 8652 // types that can be used for arithmetic operations, conversions etc. 8653 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8654 return InvalidKernelParam; 8655 8656 if (PT->isRecordType()) 8657 return RecordKernelParam; 8658 8659 // Look into an array argument to check if it has a forbidden type. 8660 if (PT->isArrayType()) { 8661 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8662 // Call ourself to check an underlying type of an array. Since the 8663 // getPointeeOrArrayElementType returns an innermost type which is not an 8664 // array, this recursive call only happens once. 8665 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8666 } 8667 8668 return ValidKernelParam; 8669 } 8670 8671 static void checkIsValidOpenCLKernelParameter( 8672 Sema &S, 8673 Declarator &D, 8674 ParmVarDecl *Param, 8675 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8676 QualType PT = Param->getType(); 8677 8678 // Cache the valid types we encounter to avoid rechecking structs that are 8679 // used again 8680 if (ValidTypes.count(PT.getTypePtr())) 8681 return; 8682 8683 switch (getOpenCLKernelParameterType(S, PT)) { 8684 case PtrPtrKernelParam: 8685 // OpenCL v3.0 s6.11.a: 8686 // A kernel function argument cannot be declared as a pointer to a pointer 8687 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 8688 if (S.getLangOpts().OpenCLVersion < 120 && 8689 !S.getLangOpts().OpenCLCPlusPlus) { 8690 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8691 D.setInvalidType(); 8692 return; 8693 } 8694 8695 ValidTypes.insert(PT.getTypePtr()); 8696 return; 8697 8698 case InvalidAddrSpacePtrKernelParam: 8699 // OpenCL v1.0 s6.5: 8700 // __kernel function arguments declared to be a pointer of a type can point 8701 // to one of the following address spaces only : __global, __local or 8702 // __constant. 8703 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8704 D.setInvalidType(); 8705 return; 8706 8707 // OpenCL v1.2 s6.9.k: 8708 // Arguments to kernel functions in a program cannot be declared with the 8709 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8710 // uintptr_t or a struct and/or union that contain fields declared to be 8711 // one of these built-in scalar types. 8712 8713 case InvalidKernelParam: 8714 // OpenCL v1.2 s6.8 n: 8715 // A kernel function argument cannot be declared 8716 // of event_t type. 8717 // Do not diagnose half type since it is diagnosed as invalid argument 8718 // type for any function elsewhere. 8719 if (!PT->isHalfType()) { 8720 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8721 8722 // Explain what typedefs are involved. 8723 const TypedefType *Typedef = nullptr; 8724 while ((Typedef = PT->getAs<TypedefType>())) { 8725 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8726 // SourceLocation may be invalid for a built-in type. 8727 if (Loc.isValid()) 8728 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8729 PT = Typedef->desugar(); 8730 } 8731 } 8732 8733 D.setInvalidType(); 8734 return; 8735 8736 case PtrKernelParam: 8737 case ValidKernelParam: 8738 ValidTypes.insert(PT.getTypePtr()); 8739 return; 8740 8741 case RecordKernelParam: 8742 break; 8743 } 8744 8745 // Track nested structs we will inspect 8746 SmallVector<const Decl *, 4> VisitStack; 8747 8748 // Track where we are in the nested structs. Items will migrate from 8749 // VisitStack to HistoryStack as we do the DFS for bad field. 8750 SmallVector<const FieldDecl *, 4> HistoryStack; 8751 HistoryStack.push_back(nullptr); 8752 8753 // At this point we already handled everything except of a RecordType or 8754 // an ArrayType of a RecordType. 8755 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8756 const RecordType *RecTy = 8757 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8758 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8759 8760 VisitStack.push_back(RecTy->getDecl()); 8761 assert(VisitStack.back() && "First decl null?"); 8762 8763 do { 8764 const Decl *Next = VisitStack.pop_back_val(); 8765 if (!Next) { 8766 assert(!HistoryStack.empty()); 8767 // Found a marker, we have gone up a level 8768 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8769 ValidTypes.insert(Hist->getType().getTypePtr()); 8770 8771 continue; 8772 } 8773 8774 // Adds everything except the original parameter declaration (which is not a 8775 // field itself) to the history stack. 8776 const RecordDecl *RD; 8777 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8778 HistoryStack.push_back(Field); 8779 8780 QualType FieldTy = Field->getType(); 8781 // Other field types (known to be valid or invalid) are handled while we 8782 // walk around RecordDecl::fields(). 8783 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8784 "Unexpected type."); 8785 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8786 8787 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8788 } else { 8789 RD = cast<RecordDecl>(Next); 8790 } 8791 8792 // Add a null marker so we know when we've gone back up a level 8793 VisitStack.push_back(nullptr); 8794 8795 for (const auto *FD : RD->fields()) { 8796 QualType QT = FD->getType(); 8797 8798 if (ValidTypes.count(QT.getTypePtr())) 8799 continue; 8800 8801 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8802 if (ParamType == ValidKernelParam) 8803 continue; 8804 8805 if (ParamType == RecordKernelParam) { 8806 VisitStack.push_back(FD); 8807 continue; 8808 } 8809 8810 // OpenCL v1.2 s6.9.p: 8811 // Arguments to kernel functions that are declared to be a struct or union 8812 // do not allow OpenCL objects to be passed as elements of the struct or 8813 // union. 8814 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8815 ParamType == InvalidAddrSpacePtrKernelParam) { 8816 S.Diag(Param->getLocation(), 8817 diag::err_record_with_pointers_kernel_param) 8818 << PT->isUnionType() 8819 << PT; 8820 } else { 8821 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8822 } 8823 8824 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8825 << OrigRecDecl->getDeclName(); 8826 8827 // We have an error, now let's go back up through history and show where 8828 // the offending field came from 8829 for (ArrayRef<const FieldDecl *>::const_iterator 8830 I = HistoryStack.begin() + 1, 8831 E = HistoryStack.end(); 8832 I != E; ++I) { 8833 const FieldDecl *OuterField = *I; 8834 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8835 << OuterField->getType(); 8836 } 8837 8838 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8839 << QT->isPointerType() 8840 << QT; 8841 D.setInvalidType(); 8842 return; 8843 } 8844 } while (!VisitStack.empty()); 8845 } 8846 8847 /// Find the DeclContext in which a tag is implicitly declared if we see an 8848 /// elaborated type specifier in the specified context, and lookup finds 8849 /// nothing. 8850 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8851 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8852 DC = DC->getParent(); 8853 return DC; 8854 } 8855 8856 /// Find the Scope in which a tag is implicitly declared if we see an 8857 /// elaborated type specifier in the specified context, and lookup finds 8858 /// nothing. 8859 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8860 while (S->isClassScope() || 8861 (LangOpts.CPlusPlus && 8862 S->isFunctionPrototypeScope()) || 8863 ((S->getFlags() & Scope::DeclScope) == 0) || 8864 (S->getEntity() && S->getEntity()->isTransparentContext())) 8865 S = S->getParent(); 8866 return S; 8867 } 8868 8869 NamedDecl* 8870 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8871 TypeSourceInfo *TInfo, LookupResult &Previous, 8872 MultiTemplateParamsArg TemplateParamListsRef, 8873 bool &AddToScope) { 8874 QualType R = TInfo->getType(); 8875 8876 assert(R->isFunctionType()); 8877 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 8878 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 8879 8880 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8881 for (TemplateParameterList *TPL : TemplateParamListsRef) 8882 TemplateParamLists.push_back(TPL); 8883 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8884 if (!TemplateParamLists.empty() && 8885 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8886 TemplateParamLists.back() = Invented; 8887 else 8888 TemplateParamLists.push_back(Invented); 8889 } 8890 8891 // TODO: consider using NameInfo for diagnostic. 8892 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8893 DeclarationName Name = NameInfo.getName(); 8894 StorageClass SC = getFunctionStorageClass(*this, D); 8895 8896 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8897 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8898 diag::err_invalid_thread) 8899 << DeclSpec::getSpecifierName(TSCS); 8900 8901 if (D.isFirstDeclarationOfMember()) 8902 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8903 D.getIdentifierLoc()); 8904 8905 bool isFriend = false; 8906 FunctionTemplateDecl *FunctionTemplate = nullptr; 8907 bool isMemberSpecialization = false; 8908 bool isFunctionTemplateSpecialization = false; 8909 8910 bool isDependentClassScopeExplicitSpecialization = false; 8911 bool HasExplicitTemplateArgs = false; 8912 TemplateArgumentListInfo TemplateArgs; 8913 8914 bool isVirtualOkay = false; 8915 8916 DeclContext *OriginalDC = DC; 8917 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8918 8919 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8920 isVirtualOkay); 8921 if (!NewFD) return nullptr; 8922 8923 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8924 NewFD->setTopLevelDeclInObjCContainer(); 8925 8926 // Set the lexical context. If this is a function-scope declaration, or has a 8927 // C++ scope specifier, or is the object of a friend declaration, the lexical 8928 // context will be different from the semantic context. 8929 NewFD->setLexicalDeclContext(CurContext); 8930 8931 if (IsLocalExternDecl) 8932 NewFD->setLocalExternDecl(); 8933 8934 if (getLangOpts().CPlusPlus) { 8935 bool isInline = D.getDeclSpec().isInlineSpecified(); 8936 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8937 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8938 isFriend = D.getDeclSpec().isFriendSpecified(); 8939 if (isFriend && !isInline && D.isFunctionDefinition()) { 8940 // C++ [class.friend]p5 8941 // A function can be defined in a friend declaration of a 8942 // class . . . . Such a function is implicitly inline. 8943 NewFD->setImplicitlyInline(); 8944 } 8945 8946 // If this is a method defined in an __interface, and is not a constructor 8947 // or an overloaded operator, then set the pure flag (isVirtual will already 8948 // return true). 8949 if (const CXXRecordDecl *Parent = 8950 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8951 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8952 NewFD->setPure(true); 8953 8954 // C++ [class.union]p2 8955 // A union can have member functions, but not virtual functions. 8956 if (isVirtual && Parent->isUnion()) 8957 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8958 } 8959 8960 SetNestedNameSpecifier(*this, NewFD, D); 8961 isMemberSpecialization = false; 8962 isFunctionTemplateSpecialization = false; 8963 if (D.isInvalidType()) 8964 NewFD->setInvalidDecl(); 8965 8966 // Match up the template parameter lists with the scope specifier, then 8967 // determine whether we have a template or a template specialization. 8968 bool Invalid = false; 8969 TemplateParameterList *TemplateParams = 8970 MatchTemplateParametersToScopeSpecifier( 8971 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8972 D.getCXXScopeSpec(), 8973 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8974 ? D.getName().TemplateId 8975 : nullptr, 8976 TemplateParamLists, isFriend, isMemberSpecialization, 8977 Invalid); 8978 if (TemplateParams) { 8979 // Check that we can declare a template here. 8980 if (CheckTemplateDeclScope(S, TemplateParams)) 8981 NewFD->setInvalidDecl(); 8982 8983 if (TemplateParams->size() > 0) { 8984 // This is a function template 8985 8986 // A destructor cannot be a template. 8987 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8988 Diag(NewFD->getLocation(), diag::err_destructor_template); 8989 NewFD->setInvalidDecl(); 8990 } 8991 8992 // If we're adding a template to a dependent context, we may need to 8993 // rebuilding some of the types used within the template parameter list, 8994 // now that we know what the current instantiation is. 8995 if (DC->isDependentContext()) { 8996 ContextRAII SavedContext(*this, DC); 8997 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8998 Invalid = true; 8999 } 9000 9001 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9002 NewFD->getLocation(), 9003 Name, TemplateParams, 9004 NewFD); 9005 FunctionTemplate->setLexicalDeclContext(CurContext); 9006 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9007 9008 // For source fidelity, store the other template param lists. 9009 if (TemplateParamLists.size() > 1) { 9010 NewFD->setTemplateParameterListsInfo(Context, 9011 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9012 .drop_back(1)); 9013 } 9014 } else { 9015 // This is a function template specialization. 9016 isFunctionTemplateSpecialization = true; 9017 // For source fidelity, store all the template param lists. 9018 if (TemplateParamLists.size() > 0) 9019 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9020 9021 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9022 if (isFriend) { 9023 // We want to remove the "template<>", found here. 9024 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9025 9026 // If we remove the template<> and the name is not a 9027 // template-id, we're actually silently creating a problem: 9028 // the friend declaration will refer to an untemplated decl, 9029 // and clearly the user wants a template specialization. So 9030 // we need to insert '<>' after the name. 9031 SourceLocation InsertLoc; 9032 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9033 InsertLoc = D.getName().getSourceRange().getEnd(); 9034 InsertLoc = getLocForEndOfToken(InsertLoc); 9035 } 9036 9037 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9038 << Name << RemoveRange 9039 << FixItHint::CreateRemoval(RemoveRange) 9040 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9041 } 9042 } 9043 } else { 9044 // Check that we can declare a template here. 9045 if (!TemplateParamLists.empty() && isMemberSpecialization && 9046 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9047 NewFD->setInvalidDecl(); 9048 9049 // All template param lists were matched against the scope specifier: 9050 // this is NOT (an explicit specialization of) a template. 9051 if (TemplateParamLists.size() > 0) 9052 // For source fidelity, store all the template param lists. 9053 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9054 } 9055 9056 if (Invalid) { 9057 NewFD->setInvalidDecl(); 9058 if (FunctionTemplate) 9059 FunctionTemplate->setInvalidDecl(); 9060 } 9061 9062 // C++ [dcl.fct.spec]p5: 9063 // The virtual specifier shall only be used in declarations of 9064 // nonstatic class member functions that appear within a 9065 // member-specification of a class declaration; see 10.3. 9066 // 9067 if (isVirtual && !NewFD->isInvalidDecl()) { 9068 if (!isVirtualOkay) { 9069 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9070 diag::err_virtual_non_function); 9071 } else if (!CurContext->isRecord()) { 9072 // 'virtual' was specified outside of the class. 9073 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9074 diag::err_virtual_out_of_class) 9075 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9076 } else if (NewFD->getDescribedFunctionTemplate()) { 9077 // C++ [temp.mem]p3: 9078 // A member function template shall not be virtual. 9079 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9080 diag::err_virtual_member_function_template) 9081 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9082 } else { 9083 // Okay: Add virtual to the method. 9084 NewFD->setVirtualAsWritten(true); 9085 } 9086 9087 if (getLangOpts().CPlusPlus14 && 9088 NewFD->getReturnType()->isUndeducedType()) 9089 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9090 } 9091 9092 if (getLangOpts().CPlusPlus14 && 9093 (NewFD->isDependentContext() || 9094 (isFriend && CurContext->isDependentContext())) && 9095 NewFD->getReturnType()->isUndeducedType()) { 9096 // If the function template is referenced directly (for instance, as a 9097 // member of the current instantiation), pretend it has a dependent type. 9098 // This is not really justified by the standard, but is the only sane 9099 // thing to do. 9100 // FIXME: For a friend function, we have not marked the function as being 9101 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9102 const FunctionProtoType *FPT = 9103 NewFD->getType()->castAs<FunctionProtoType>(); 9104 QualType Result = 9105 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9106 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9107 FPT->getExtProtoInfo())); 9108 } 9109 9110 // C++ [dcl.fct.spec]p3: 9111 // The inline specifier shall not appear on a block scope function 9112 // declaration. 9113 if (isInline && !NewFD->isInvalidDecl()) { 9114 if (CurContext->isFunctionOrMethod()) { 9115 // 'inline' is not allowed on block scope function declaration. 9116 Diag(D.getDeclSpec().getInlineSpecLoc(), 9117 diag::err_inline_declaration_block_scope) << Name 9118 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9119 } 9120 } 9121 9122 // C++ [dcl.fct.spec]p6: 9123 // The explicit specifier shall be used only in the declaration of a 9124 // constructor or conversion function within its class definition; 9125 // see 12.3.1 and 12.3.2. 9126 if (hasExplicit && !NewFD->isInvalidDecl() && 9127 !isa<CXXDeductionGuideDecl>(NewFD)) { 9128 if (!CurContext->isRecord()) { 9129 // 'explicit' was specified outside of the class. 9130 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9131 diag::err_explicit_out_of_class) 9132 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9133 } else if (!isa<CXXConstructorDecl>(NewFD) && 9134 !isa<CXXConversionDecl>(NewFD)) { 9135 // 'explicit' was specified on a function that wasn't a constructor 9136 // or conversion function. 9137 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9138 diag::err_explicit_non_ctor_or_conv_function) 9139 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9140 } 9141 } 9142 9143 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9144 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9145 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9146 // are implicitly inline. 9147 NewFD->setImplicitlyInline(); 9148 9149 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9150 // be either constructors or to return a literal type. Therefore, 9151 // destructors cannot be declared constexpr. 9152 if (isa<CXXDestructorDecl>(NewFD) && 9153 (!getLangOpts().CPlusPlus20 || 9154 ConstexprKind == ConstexprSpecKind::Consteval)) { 9155 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9156 << static_cast<int>(ConstexprKind); 9157 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9158 ? ConstexprSpecKind::Unspecified 9159 : ConstexprSpecKind::Constexpr); 9160 } 9161 // C++20 [dcl.constexpr]p2: An allocation function, or a 9162 // deallocation function shall not be declared with the consteval 9163 // specifier. 9164 if (ConstexprKind == ConstexprSpecKind::Consteval && 9165 (NewFD->getOverloadedOperator() == OO_New || 9166 NewFD->getOverloadedOperator() == OO_Array_New || 9167 NewFD->getOverloadedOperator() == OO_Delete || 9168 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9169 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9170 diag::err_invalid_consteval_decl_kind) 9171 << NewFD; 9172 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9173 } 9174 } 9175 9176 // If __module_private__ was specified, mark the function accordingly. 9177 if (D.getDeclSpec().isModulePrivateSpecified()) { 9178 if (isFunctionTemplateSpecialization) { 9179 SourceLocation ModulePrivateLoc 9180 = D.getDeclSpec().getModulePrivateSpecLoc(); 9181 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9182 << 0 9183 << FixItHint::CreateRemoval(ModulePrivateLoc); 9184 } else { 9185 NewFD->setModulePrivate(); 9186 if (FunctionTemplate) 9187 FunctionTemplate->setModulePrivate(); 9188 } 9189 } 9190 9191 if (isFriend) { 9192 if (FunctionTemplate) { 9193 FunctionTemplate->setObjectOfFriendDecl(); 9194 FunctionTemplate->setAccess(AS_public); 9195 } 9196 NewFD->setObjectOfFriendDecl(); 9197 NewFD->setAccess(AS_public); 9198 } 9199 9200 // If a function is defined as defaulted or deleted, mark it as such now. 9201 // We'll do the relevant checks on defaulted / deleted functions later. 9202 switch (D.getFunctionDefinitionKind()) { 9203 case FunctionDefinitionKind::Declaration: 9204 case FunctionDefinitionKind::Definition: 9205 break; 9206 9207 case FunctionDefinitionKind::Defaulted: 9208 NewFD->setDefaulted(); 9209 break; 9210 9211 case FunctionDefinitionKind::Deleted: 9212 NewFD->setDeletedAsWritten(); 9213 break; 9214 } 9215 9216 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9217 D.isFunctionDefinition()) { 9218 // C++ [class.mfct]p2: 9219 // A member function may be defined (8.4) in its class definition, in 9220 // which case it is an inline member function (7.1.2) 9221 NewFD->setImplicitlyInline(); 9222 } 9223 9224 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9225 !CurContext->isRecord()) { 9226 // C++ [class.static]p1: 9227 // A data or function member of a class may be declared static 9228 // in a class definition, in which case it is a static member of 9229 // the class. 9230 9231 // Complain about the 'static' specifier if it's on an out-of-line 9232 // member function definition. 9233 9234 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9235 // member function template declaration and class member template 9236 // declaration (MSVC versions before 2015), warn about this. 9237 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9238 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9239 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9240 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9241 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9242 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9243 } 9244 9245 // C++11 [except.spec]p15: 9246 // A deallocation function with no exception-specification is treated 9247 // as if it were specified with noexcept(true). 9248 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9249 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9250 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9251 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9252 NewFD->setType(Context.getFunctionType( 9253 FPT->getReturnType(), FPT->getParamTypes(), 9254 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9255 } 9256 9257 // Filter out previous declarations that don't match the scope. 9258 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9259 D.getCXXScopeSpec().isNotEmpty() || 9260 isMemberSpecialization || 9261 isFunctionTemplateSpecialization); 9262 9263 // Handle GNU asm-label extension (encoded as an attribute). 9264 if (Expr *E = (Expr*) D.getAsmLabel()) { 9265 // The parser guarantees this is a string. 9266 StringLiteral *SE = cast<StringLiteral>(E); 9267 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9268 /*IsLiteralLabel=*/true, 9269 SE->getStrTokenLoc(0))); 9270 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9271 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9272 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9273 if (I != ExtnameUndeclaredIdentifiers.end()) { 9274 if (isDeclExternC(NewFD)) { 9275 NewFD->addAttr(I->second); 9276 ExtnameUndeclaredIdentifiers.erase(I); 9277 } else 9278 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9279 << /*Variable*/0 << NewFD; 9280 } 9281 } 9282 9283 // Copy the parameter declarations from the declarator D to the function 9284 // declaration NewFD, if they are available. First scavenge them into Params. 9285 SmallVector<ParmVarDecl*, 16> Params; 9286 unsigned FTIIdx; 9287 if (D.isFunctionDeclarator(FTIIdx)) { 9288 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9289 9290 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9291 // function that takes no arguments, not a function that takes a 9292 // single void argument. 9293 // We let through "const void" here because Sema::GetTypeForDeclarator 9294 // already checks for that case. 9295 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9296 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9297 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9298 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9299 Param->setDeclContext(NewFD); 9300 Params.push_back(Param); 9301 9302 if (Param->isInvalidDecl()) 9303 NewFD->setInvalidDecl(); 9304 } 9305 } 9306 9307 if (!getLangOpts().CPlusPlus) { 9308 // In C, find all the tag declarations from the prototype and move them 9309 // into the function DeclContext. Remove them from the surrounding tag 9310 // injection context of the function, which is typically but not always 9311 // the TU. 9312 DeclContext *PrototypeTagContext = 9313 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9314 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9315 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9316 9317 // We don't want to reparent enumerators. Look at their parent enum 9318 // instead. 9319 if (!TD) { 9320 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9321 TD = cast<EnumDecl>(ECD->getDeclContext()); 9322 } 9323 if (!TD) 9324 continue; 9325 DeclContext *TagDC = TD->getLexicalDeclContext(); 9326 if (!TagDC->containsDecl(TD)) 9327 continue; 9328 TagDC->removeDecl(TD); 9329 TD->setDeclContext(NewFD); 9330 NewFD->addDecl(TD); 9331 9332 // Preserve the lexical DeclContext if it is not the surrounding tag 9333 // injection context of the FD. In this example, the semantic context of 9334 // E will be f and the lexical context will be S, while both the 9335 // semantic and lexical contexts of S will be f: 9336 // void f(struct S { enum E { a } f; } s); 9337 if (TagDC != PrototypeTagContext) 9338 TD->setLexicalDeclContext(TagDC); 9339 } 9340 } 9341 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9342 // When we're declaring a function with a typedef, typeof, etc as in the 9343 // following example, we'll need to synthesize (unnamed) 9344 // parameters for use in the declaration. 9345 // 9346 // @code 9347 // typedef void fn(int); 9348 // fn f; 9349 // @endcode 9350 9351 // Synthesize a parameter for each argument type. 9352 for (const auto &AI : FT->param_types()) { 9353 ParmVarDecl *Param = 9354 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9355 Param->setScopeInfo(0, Params.size()); 9356 Params.push_back(Param); 9357 } 9358 } else { 9359 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9360 "Should not need args for typedef of non-prototype fn"); 9361 } 9362 9363 // Finally, we know we have the right number of parameters, install them. 9364 NewFD->setParams(Params); 9365 9366 if (D.getDeclSpec().isNoreturnSpecified()) 9367 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9368 D.getDeclSpec().getNoreturnSpecLoc(), 9369 AttributeCommonInfo::AS_Keyword)); 9370 9371 // Functions returning a variably modified type violate C99 6.7.5.2p2 9372 // because all functions have linkage. 9373 if (!NewFD->isInvalidDecl() && 9374 NewFD->getReturnType()->isVariablyModifiedType()) { 9375 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9376 NewFD->setInvalidDecl(); 9377 } 9378 9379 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9380 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9381 !NewFD->hasAttr<SectionAttr>()) 9382 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9383 Context, PragmaClangTextSection.SectionName, 9384 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9385 9386 // Apply an implicit SectionAttr if #pragma code_seg is active. 9387 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9388 !NewFD->hasAttr<SectionAttr>()) { 9389 NewFD->addAttr(SectionAttr::CreateImplicit( 9390 Context, CodeSegStack.CurrentValue->getString(), 9391 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9392 SectionAttr::Declspec_allocate)); 9393 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9394 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9395 ASTContext::PSF_Read, 9396 NewFD)) 9397 NewFD->dropAttr<SectionAttr>(); 9398 } 9399 9400 // Apply an implicit CodeSegAttr from class declspec or 9401 // apply an implicit SectionAttr from #pragma code_seg if active. 9402 if (!NewFD->hasAttr<CodeSegAttr>()) { 9403 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9404 D.isFunctionDefinition())) { 9405 NewFD->addAttr(SAttr); 9406 } 9407 } 9408 9409 // Handle attributes. 9410 ProcessDeclAttributes(S, NewFD, D); 9411 9412 if (getLangOpts().OpenCL) { 9413 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9414 // type declaration will generate a compilation error. 9415 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9416 if (AddressSpace != LangAS::Default) { 9417 Diag(NewFD->getLocation(), 9418 diag::err_opencl_return_value_with_address_space); 9419 NewFD->setInvalidDecl(); 9420 } 9421 } 9422 9423 if (!getLangOpts().CPlusPlus) { 9424 // Perform semantic checking on the function declaration. 9425 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9426 CheckMain(NewFD, D.getDeclSpec()); 9427 9428 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9429 CheckMSVCRTEntryPoint(NewFD); 9430 9431 if (!NewFD->isInvalidDecl()) 9432 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9433 isMemberSpecialization)); 9434 else if (!Previous.empty()) 9435 // Recover gracefully from an invalid redeclaration. 9436 D.setRedeclaration(true); 9437 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9438 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9439 "previous declaration set still overloaded"); 9440 9441 // Diagnose no-prototype function declarations with calling conventions that 9442 // don't support variadic calls. Only do this in C and do it after merging 9443 // possibly prototyped redeclarations. 9444 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9445 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9446 CallingConv CC = FT->getExtInfo().getCC(); 9447 if (!supportsVariadicCall(CC)) { 9448 // Windows system headers sometimes accidentally use stdcall without 9449 // (void) parameters, so we relax this to a warning. 9450 int DiagID = 9451 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9452 Diag(NewFD->getLocation(), DiagID) 9453 << FunctionType::getNameForCallConv(CC); 9454 } 9455 } 9456 9457 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9458 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9459 checkNonTrivialCUnion(NewFD->getReturnType(), 9460 NewFD->getReturnTypeSourceRange().getBegin(), 9461 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9462 } else { 9463 // C++11 [replacement.functions]p3: 9464 // The program's definitions shall not be specified as inline. 9465 // 9466 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9467 // 9468 // Suppress the diagnostic if the function is __attribute__((used)), since 9469 // that forces an external definition to be emitted. 9470 if (D.getDeclSpec().isInlineSpecified() && 9471 NewFD->isReplaceableGlobalAllocationFunction() && 9472 !NewFD->hasAttr<UsedAttr>()) 9473 Diag(D.getDeclSpec().getInlineSpecLoc(), 9474 diag::ext_operator_new_delete_declared_inline) 9475 << NewFD->getDeclName(); 9476 9477 // If the declarator is a template-id, translate the parser's template 9478 // argument list into our AST format. 9479 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9480 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9481 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9482 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9483 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9484 TemplateId->NumArgs); 9485 translateTemplateArguments(TemplateArgsPtr, 9486 TemplateArgs); 9487 9488 HasExplicitTemplateArgs = true; 9489 9490 if (NewFD->isInvalidDecl()) { 9491 HasExplicitTemplateArgs = false; 9492 } else if (FunctionTemplate) { 9493 // Function template with explicit template arguments. 9494 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9495 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9496 9497 HasExplicitTemplateArgs = false; 9498 } else { 9499 assert((isFunctionTemplateSpecialization || 9500 D.getDeclSpec().isFriendSpecified()) && 9501 "should have a 'template<>' for this decl"); 9502 // "friend void foo<>(int);" is an implicit specialization decl. 9503 isFunctionTemplateSpecialization = true; 9504 } 9505 } else if (isFriend && isFunctionTemplateSpecialization) { 9506 // This combination is only possible in a recovery case; the user 9507 // wrote something like: 9508 // template <> friend void foo(int); 9509 // which we're recovering from as if the user had written: 9510 // friend void foo<>(int); 9511 // Go ahead and fake up a template id. 9512 HasExplicitTemplateArgs = true; 9513 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9514 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9515 } 9516 9517 // We do not add HD attributes to specializations here because 9518 // they may have different constexpr-ness compared to their 9519 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9520 // may end up with different effective targets. Instead, a 9521 // specialization inherits its target attributes from its template 9522 // in the CheckFunctionTemplateSpecialization() call below. 9523 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9524 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9525 9526 // If it's a friend (and only if it's a friend), it's possible 9527 // that either the specialized function type or the specialized 9528 // template is dependent, and therefore matching will fail. In 9529 // this case, don't check the specialization yet. 9530 if (isFunctionTemplateSpecialization && isFriend && 9531 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9532 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 9533 TemplateArgs.arguments()))) { 9534 assert(HasExplicitTemplateArgs && 9535 "friend function specialization without template args"); 9536 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9537 Previous)) 9538 NewFD->setInvalidDecl(); 9539 } else if (isFunctionTemplateSpecialization) { 9540 if (CurContext->isDependentContext() && CurContext->isRecord() 9541 && !isFriend) { 9542 isDependentClassScopeExplicitSpecialization = true; 9543 } else if (!NewFD->isInvalidDecl() && 9544 CheckFunctionTemplateSpecialization( 9545 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9546 Previous)) 9547 NewFD->setInvalidDecl(); 9548 9549 // C++ [dcl.stc]p1: 9550 // A storage-class-specifier shall not be specified in an explicit 9551 // specialization (14.7.3) 9552 FunctionTemplateSpecializationInfo *Info = 9553 NewFD->getTemplateSpecializationInfo(); 9554 if (Info && SC != SC_None) { 9555 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9556 Diag(NewFD->getLocation(), 9557 diag::err_explicit_specialization_inconsistent_storage_class) 9558 << SC 9559 << FixItHint::CreateRemoval( 9560 D.getDeclSpec().getStorageClassSpecLoc()); 9561 9562 else 9563 Diag(NewFD->getLocation(), 9564 diag::ext_explicit_specialization_storage_class) 9565 << FixItHint::CreateRemoval( 9566 D.getDeclSpec().getStorageClassSpecLoc()); 9567 } 9568 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9569 if (CheckMemberSpecialization(NewFD, Previous)) 9570 NewFD->setInvalidDecl(); 9571 } 9572 9573 // Perform semantic checking on the function declaration. 9574 if (!isDependentClassScopeExplicitSpecialization) { 9575 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9576 CheckMain(NewFD, D.getDeclSpec()); 9577 9578 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9579 CheckMSVCRTEntryPoint(NewFD); 9580 9581 if (!NewFD->isInvalidDecl()) 9582 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9583 isMemberSpecialization)); 9584 else if (!Previous.empty()) 9585 // Recover gracefully from an invalid redeclaration. 9586 D.setRedeclaration(true); 9587 } 9588 9589 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9590 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9591 "previous declaration set still overloaded"); 9592 9593 NamedDecl *PrincipalDecl = (FunctionTemplate 9594 ? cast<NamedDecl>(FunctionTemplate) 9595 : NewFD); 9596 9597 if (isFriend && NewFD->getPreviousDecl()) { 9598 AccessSpecifier Access = AS_public; 9599 if (!NewFD->isInvalidDecl()) 9600 Access = NewFD->getPreviousDecl()->getAccess(); 9601 9602 NewFD->setAccess(Access); 9603 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9604 } 9605 9606 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9607 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9608 PrincipalDecl->setNonMemberOperator(); 9609 9610 // If we have a function template, check the template parameter 9611 // list. This will check and merge default template arguments. 9612 if (FunctionTemplate) { 9613 FunctionTemplateDecl *PrevTemplate = 9614 FunctionTemplate->getPreviousDecl(); 9615 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9616 PrevTemplate ? PrevTemplate->getTemplateParameters() 9617 : nullptr, 9618 D.getDeclSpec().isFriendSpecified() 9619 ? (D.isFunctionDefinition() 9620 ? TPC_FriendFunctionTemplateDefinition 9621 : TPC_FriendFunctionTemplate) 9622 : (D.getCXXScopeSpec().isSet() && 9623 DC && DC->isRecord() && 9624 DC->isDependentContext()) 9625 ? TPC_ClassTemplateMember 9626 : TPC_FunctionTemplate); 9627 } 9628 9629 if (NewFD->isInvalidDecl()) { 9630 // Ignore all the rest of this. 9631 } else if (!D.isRedeclaration()) { 9632 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9633 AddToScope }; 9634 // Fake up an access specifier if it's supposed to be a class member. 9635 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9636 NewFD->setAccess(AS_public); 9637 9638 // Qualified decls generally require a previous declaration. 9639 if (D.getCXXScopeSpec().isSet()) { 9640 // ...with the major exception of templated-scope or 9641 // dependent-scope friend declarations. 9642 9643 // TODO: we currently also suppress this check in dependent 9644 // contexts because (1) the parameter depth will be off when 9645 // matching friend templates and (2) we might actually be 9646 // selecting a friend based on a dependent factor. But there 9647 // are situations where these conditions don't apply and we 9648 // can actually do this check immediately. 9649 // 9650 // Unless the scope is dependent, it's always an error if qualified 9651 // redeclaration lookup found nothing at all. Diagnose that now; 9652 // nothing will diagnose that error later. 9653 if (isFriend && 9654 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9655 (!Previous.empty() && CurContext->isDependentContext()))) { 9656 // ignore these 9657 } else { 9658 // The user tried to provide an out-of-line definition for a 9659 // function that is a member of a class or namespace, but there 9660 // was no such member function declared (C++ [class.mfct]p2, 9661 // C++ [namespace.memdef]p2). For example: 9662 // 9663 // class X { 9664 // void f() const; 9665 // }; 9666 // 9667 // void X::f() { } // ill-formed 9668 // 9669 // Complain about this problem, and attempt to suggest close 9670 // matches (e.g., those that differ only in cv-qualifiers and 9671 // whether the parameter types are references). 9672 9673 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9674 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9675 AddToScope = ExtraArgs.AddToScope; 9676 return Result; 9677 } 9678 } 9679 9680 // Unqualified local friend declarations are required to resolve 9681 // to something. 9682 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9683 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9684 *this, Previous, NewFD, ExtraArgs, true, S)) { 9685 AddToScope = ExtraArgs.AddToScope; 9686 return Result; 9687 } 9688 } 9689 } else if (!D.isFunctionDefinition() && 9690 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9691 !isFriend && !isFunctionTemplateSpecialization && 9692 !isMemberSpecialization) { 9693 // An out-of-line member function declaration must also be a 9694 // definition (C++ [class.mfct]p2). 9695 // Note that this is not the case for explicit specializations of 9696 // function templates or member functions of class templates, per 9697 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9698 // extension for compatibility with old SWIG code which likes to 9699 // generate them. 9700 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9701 << D.getCXXScopeSpec().getRange(); 9702 } 9703 } 9704 9705 // If this is the first declaration of a library builtin function, add 9706 // attributes as appropriate. 9707 if (!D.isRedeclaration() && 9708 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 9709 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 9710 if (unsigned BuiltinID = II->getBuiltinID()) { 9711 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 9712 // Validate the type matches unless this builtin is specified as 9713 // matching regardless of its declared type. 9714 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 9715 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9716 } else { 9717 ASTContext::GetBuiltinTypeError Error; 9718 LookupNecessaryTypesForBuiltin(S, BuiltinID); 9719 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 9720 9721 if (!Error && !BuiltinType.isNull() && 9722 Context.hasSameFunctionTypeIgnoringExceptionSpec( 9723 NewFD->getType(), BuiltinType)) 9724 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9725 } 9726 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 9727 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9728 // FIXME: We should consider this a builtin only in the std namespace. 9729 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9730 } 9731 } 9732 } 9733 } 9734 9735 ProcessPragmaWeak(S, NewFD); 9736 checkAttributesAfterMerging(*this, *NewFD); 9737 9738 AddKnownFunctionAttributes(NewFD); 9739 9740 if (NewFD->hasAttr<OverloadableAttr>() && 9741 !NewFD->getType()->getAs<FunctionProtoType>()) { 9742 Diag(NewFD->getLocation(), 9743 diag::err_attribute_overloadable_no_prototype) 9744 << NewFD; 9745 9746 // Turn this into a variadic function with no parameters. 9747 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9748 FunctionProtoType::ExtProtoInfo EPI( 9749 Context.getDefaultCallingConvention(true, false)); 9750 EPI.Variadic = true; 9751 EPI.ExtInfo = FT->getExtInfo(); 9752 9753 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9754 NewFD->setType(R); 9755 } 9756 9757 // If there's a #pragma GCC visibility in scope, and this isn't a class 9758 // member, set the visibility of this function. 9759 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9760 AddPushedVisibilityAttribute(NewFD); 9761 9762 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9763 // marking the function. 9764 AddCFAuditedAttribute(NewFD); 9765 9766 // If this is a function definition, check if we have to apply optnone due to 9767 // a pragma. 9768 if(D.isFunctionDefinition()) 9769 AddRangeBasedOptnone(NewFD); 9770 9771 // If this is the first declaration of an extern C variable, update 9772 // the map of such variables. 9773 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9774 isIncompleteDeclExternC(*this, NewFD)) 9775 RegisterLocallyScopedExternCDecl(NewFD, S); 9776 9777 // Set this FunctionDecl's range up to the right paren. 9778 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9779 9780 if (D.isRedeclaration() && !Previous.empty()) { 9781 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9782 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9783 isMemberSpecialization || 9784 isFunctionTemplateSpecialization, 9785 D.isFunctionDefinition()); 9786 } 9787 9788 if (getLangOpts().CUDA) { 9789 IdentifierInfo *II = NewFD->getIdentifier(); 9790 if (II && II->isStr(getCudaConfigureFuncName()) && 9791 !NewFD->isInvalidDecl() && 9792 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9793 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9794 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9795 << getCudaConfigureFuncName(); 9796 Context.setcudaConfigureCallDecl(NewFD); 9797 } 9798 9799 // Variadic functions, other than a *declaration* of printf, are not allowed 9800 // in device-side CUDA code, unless someone passed 9801 // -fcuda-allow-variadic-functions. 9802 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9803 (NewFD->hasAttr<CUDADeviceAttr>() || 9804 NewFD->hasAttr<CUDAGlobalAttr>()) && 9805 !(II && II->isStr("printf") && NewFD->isExternC() && 9806 !D.isFunctionDefinition())) { 9807 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9808 } 9809 } 9810 9811 MarkUnusedFileScopedDecl(NewFD); 9812 9813 9814 9815 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9816 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9817 if ((getLangOpts().OpenCLVersion >= 120) 9818 && (SC == SC_Static)) { 9819 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9820 D.setInvalidType(); 9821 } 9822 9823 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9824 if (!NewFD->getReturnType()->isVoidType()) { 9825 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9826 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9827 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9828 : FixItHint()); 9829 D.setInvalidType(); 9830 } 9831 9832 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9833 for (auto Param : NewFD->parameters()) 9834 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9835 9836 if (getLangOpts().OpenCLCPlusPlus) { 9837 if (DC->isRecord()) { 9838 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9839 D.setInvalidType(); 9840 } 9841 if (FunctionTemplate) { 9842 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9843 D.setInvalidType(); 9844 } 9845 } 9846 } 9847 9848 if (getLangOpts().CPlusPlus) { 9849 if (FunctionTemplate) { 9850 if (NewFD->isInvalidDecl()) 9851 FunctionTemplate->setInvalidDecl(); 9852 return FunctionTemplate; 9853 } 9854 9855 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9856 CompleteMemberSpecialization(NewFD, Previous); 9857 } 9858 9859 for (const ParmVarDecl *Param : NewFD->parameters()) { 9860 QualType PT = Param->getType(); 9861 9862 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9863 // types. 9864 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9865 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9866 QualType ElemTy = PipeTy->getElementType(); 9867 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9868 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9869 D.setInvalidType(); 9870 } 9871 } 9872 } 9873 } 9874 9875 // Here we have an function template explicit specialization at class scope. 9876 // The actual specialization will be postponed to template instatiation 9877 // time via the ClassScopeFunctionSpecializationDecl node. 9878 if (isDependentClassScopeExplicitSpecialization) { 9879 ClassScopeFunctionSpecializationDecl *NewSpec = 9880 ClassScopeFunctionSpecializationDecl::Create( 9881 Context, CurContext, NewFD->getLocation(), 9882 cast<CXXMethodDecl>(NewFD), 9883 HasExplicitTemplateArgs, TemplateArgs); 9884 CurContext->addDecl(NewSpec); 9885 AddToScope = false; 9886 } 9887 9888 // Diagnose availability attributes. Availability cannot be used on functions 9889 // that are run during load/unload. 9890 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9891 if (NewFD->hasAttr<ConstructorAttr>()) { 9892 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9893 << 1; 9894 NewFD->dropAttr<AvailabilityAttr>(); 9895 } 9896 if (NewFD->hasAttr<DestructorAttr>()) { 9897 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9898 << 2; 9899 NewFD->dropAttr<AvailabilityAttr>(); 9900 } 9901 } 9902 9903 // Diagnose no_builtin attribute on function declaration that are not a 9904 // definition. 9905 // FIXME: We should really be doing this in 9906 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9907 // the FunctionDecl and at this point of the code 9908 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9909 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9910 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9911 switch (D.getFunctionDefinitionKind()) { 9912 case FunctionDefinitionKind::Defaulted: 9913 case FunctionDefinitionKind::Deleted: 9914 Diag(NBA->getLocation(), 9915 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9916 << NBA->getSpelling(); 9917 break; 9918 case FunctionDefinitionKind::Declaration: 9919 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9920 << NBA->getSpelling(); 9921 break; 9922 case FunctionDefinitionKind::Definition: 9923 break; 9924 } 9925 9926 return NewFD; 9927 } 9928 9929 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9930 /// when __declspec(code_seg) "is applied to a class, all member functions of 9931 /// the class and nested classes -- this includes compiler-generated special 9932 /// member functions -- are put in the specified segment." 9933 /// The actual behavior is a little more complicated. The Microsoft compiler 9934 /// won't check outer classes if there is an active value from #pragma code_seg. 9935 /// The CodeSeg is always applied from the direct parent but only from outer 9936 /// classes when the #pragma code_seg stack is empty. See: 9937 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9938 /// available since MS has removed the page. 9939 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9940 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9941 if (!Method) 9942 return nullptr; 9943 const CXXRecordDecl *Parent = Method->getParent(); 9944 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9945 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9946 NewAttr->setImplicit(true); 9947 return NewAttr; 9948 } 9949 9950 // The Microsoft compiler won't check outer classes for the CodeSeg 9951 // when the #pragma code_seg stack is active. 9952 if (S.CodeSegStack.CurrentValue) 9953 return nullptr; 9954 9955 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9956 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9957 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9958 NewAttr->setImplicit(true); 9959 return NewAttr; 9960 } 9961 } 9962 return nullptr; 9963 } 9964 9965 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9966 /// containing class. Otherwise it will return implicit SectionAttr if the 9967 /// function is a definition and there is an active value on CodeSegStack 9968 /// (from the current #pragma code-seg value). 9969 /// 9970 /// \param FD Function being declared. 9971 /// \param IsDefinition Whether it is a definition or just a declarartion. 9972 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9973 /// nullptr if no attribute should be added. 9974 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9975 bool IsDefinition) { 9976 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9977 return A; 9978 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9979 CodeSegStack.CurrentValue) 9980 return SectionAttr::CreateImplicit( 9981 getASTContext(), CodeSegStack.CurrentValue->getString(), 9982 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9983 SectionAttr::Declspec_allocate); 9984 return nullptr; 9985 } 9986 9987 /// Determines if we can perform a correct type check for \p D as a 9988 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9989 /// best-effort check. 9990 /// 9991 /// \param NewD The new declaration. 9992 /// \param OldD The old declaration. 9993 /// \param NewT The portion of the type of the new declaration to check. 9994 /// \param OldT The portion of the type of the old declaration to check. 9995 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9996 QualType NewT, QualType OldT) { 9997 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9998 return true; 9999 10000 // For dependently-typed local extern declarations and friends, we can't 10001 // perform a correct type check in general until instantiation: 10002 // 10003 // int f(); 10004 // template<typename T> void g() { T f(); } 10005 // 10006 // (valid if g() is only instantiated with T = int). 10007 if (NewT->isDependentType() && 10008 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10009 return false; 10010 10011 // Similarly, if the previous declaration was a dependent local extern 10012 // declaration, we don't really know its type yet. 10013 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10014 return false; 10015 10016 return true; 10017 } 10018 10019 /// Checks if the new declaration declared in dependent context must be 10020 /// put in the same redeclaration chain as the specified declaration. 10021 /// 10022 /// \param D Declaration that is checked. 10023 /// \param PrevDecl Previous declaration found with proper lookup method for the 10024 /// same declaration name. 10025 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10026 /// belongs to. 10027 /// 10028 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10029 if (!D->getLexicalDeclContext()->isDependentContext()) 10030 return true; 10031 10032 // Don't chain dependent friend function definitions until instantiation, to 10033 // permit cases like 10034 // 10035 // void func(); 10036 // template<typename T> class C1 { friend void func() {} }; 10037 // template<typename T> class C2 { friend void func() {} }; 10038 // 10039 // ... which is valid if only one of C1 and C2 is ever instantiated. 10040 // 10041 // FIXME: This need only apply to function definitions. For now, we proxy 10042 // this by checking for a file-scope function. We do not want this to apply 10043 // to friend declarations nominating member functions, because that gets in 10044 // the way of access checks. 10045 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10046 return false; 10047 10048 auto *VD = dyn_cast<ValueDecl>(D); 10049 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10050 return !VD || !PrevVD || 10051 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10052 PrevVD->getType()); 10053 } 10054 10055 /// Check the target attribute of the function for MultiVersion 10056 /// validity. 10057 /// 10058 /// Returns true if there was an error, false otherwise. 10059 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10060 const auto *TA = FD->getAttr<TargetAttr>(); 10061 assert(TA && "MultiVersion Candidate requires a target attribute"); 10062 ParsedTargetAttr ParseInfo = TA->parse(); 10063 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10064 enum ErrType { Feature = 0, Architecture = 1 }; 10065 10066 if (!ParseInfo.Architecture.empty() && 10067 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10068 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10069 << Architecture << ParseInfo.Architecture; 10070 return true; 10071 } 10072 10073 for (const auto &Feat : ParseInfo.Features) { 10074 auto BareFeat = StringRef{Feat}.substr(1); 10075 if (Feat[0] == '-') { 10076 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10077 << Feature << ("no-" + BareFeat).str(); 10078 return true; 10079 } 10080 10081 if (!TargetInfo.validateCpuSupports(BareFeat) || 10082 !TargetInfo.isValidFeatureName(BareFeat)) { 10083 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10084 << Feature << BareFeat; 10085 return true; 10086 } 10087 } 10088 return false; 10089 } 10090 10091 // Provide a white-list of attributes that are allowed to be combined with 10092 // multiversion functions. 10093 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10094 MultiVersionKind MVType) { 10095 // Note: this list/diagnosis must match the list in 10096 // checkMultiversionAttributesAllSame. 10097 switch (Kind) { 10098 default: 10099 return false; 10100 case attr::Used: 10101 return MVType == MultiVersionKind::Target; 10102 case attr::NonNull: 10103 case attr::NoThrow: 10104 return true; 10105 } 10106 } 10107 10108 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10109 const FunctionDecl *FD, 10110 const FunctionDecl *CausedFD, 10111 MultiVersionKind MVType) { 10112 bool IsCPUSpecificCPUDispatchMVType = 10113 MVType == MultiVersionKind::CPUDispatch || 10114 MVType == MultiVersionKind::CPUSpecific; 10115 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType]( 10116 Sema &S, const Attr *A) { 10117 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10118 << IsCPUSpecificCPUDispatchMVType << A; 10119 if (CausedFD) 10120 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10121 return true; 10122 }; 10123 10124 for (const Attr *A : FD->attrs()) { 10125 switch (A->getKind()) { 10126 case attr::CPUDispatch: 10127 case attr::CPUSpecific: 10128 if (MVType != MultiVersionKind::CPUDispatch && 10129 MVType != MultiVersionKind::CPUSpecific) 10130 return Diagnose(S, A); 10131 break; 10132 case attr::Target: 10133 if (MVType != MultiVersionKind::Target) 10134 return Diagnose(S, A); 10135 break; 10136 default: 10137 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10138 return Diagnose(S, A); 10139 break; 10140 } 10141 } 10142 return false; 10143 } 10144 10145 bool Sema::areMultiversionVariantFunctionsCompatible( 10146 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10147 const PartialDiagnostic &NoProtoDiagID, 10148 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10149 const PartialDiagnosticAt &NoSupportDiagIDAt, 10150 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10151 bool ConstexprSupported, bool CLinkageMayDiffer) { 10152 enum DoesntSupport { 10153 FuncTemplates = 0, 10154 VirtFuncs = 1, 10155 DeducedReturn = 2, 10156 Constructors = 3, 10157 Destructors = 4, 10158 DeletedFuncs = 5, 10159 DefaultedFuncs = 6, 10160 ConstexprFuncs = 7, 10161 ConstevalFuncs = 8, 10162 }; 10163 enum Different { 10164 CallingConv = 0, 10165 ReturnType = 1, 10166 ConstexprSpec = 2, 10167 InlineSpec = 3, 10168 StorageClass = 4, 10169 Linkage = 5, 10170 }; 10171 10172 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10173 !OldFD->getType()->getAs<FunctionProtoType>()) { 10174 Diag(OldFD->getLocation(), NoProtoDiagID); 10175 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10176 return true; 10177 } 10178 10179 if (NoProtoDiagID.getDiagID() != 0 && 10180 !NewFD->getType()->getAs<FunctionProtoType>()) 10181 return Diag(NewFD->getLocation(), NoProtoDiagID); 10182 10183 if (!TemplatesSupported && 10184 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10185 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10186 << FuncTemplates; 10187 10188 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10189 if (NewCXXFD->isVirtual()) 10190 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10191 << VirtFuncs; 10192 10193 if (isa<CXXConstructorDecl>(NewCXXFD)) 10194 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10195 << Constructors; 10196 10197 if (isa<CXXDestructorDecl>(NewCXXFD)) 10198 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10199 << Destructors; 10200 } 10201 10202 if (NewFD->isDeleted()) 10203 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10204 << DeletedFuncs; 10205 10206 if (NewFD->isDefaulted()) 10207 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10208 << DefaultedFuncs; 10209 10210 if (!ConstexprSupported && NewFD->isConstexpr()) 10211 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10212 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10213 10214 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10215 const auto *NewType = cast<FunctionType>(NewQType); 10216 QualType NewReturnType = NewType->getReturnType(); 10217 10218 if (NewReturnType->isUndeducedType()) 10219 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10220 << DeducedReturn; 10221 10222 // Ensure the return type is identical. 10223 if (OldFD) { 10224 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10225 const auto *OldType = cast<FunctionType>(OldQType); 10226 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10227 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10228 10229 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10230 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10231 10232 QualType OldReturnType = OldType->getReturnType(); 10233 10234 if (OldReturnType != NewReturnType) 10235 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10236 10237 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10238 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10239 10240 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10241 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10242 10243 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10244 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10245 10246 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10247 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10248 10249 if (CheckEquivalentExceptionSpec( 10250 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10251 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10252 return true; 10253 } 10254 return false; 10255 } 10256 10257 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10258 const FunctionDecl *NewFD, 10259 bool CausesMV, 10260 MultiVersionKind MVType) { 10261 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10262 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10263 if (OldFD) 10264 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10265 return true; 10266 } 10267 10268 bool IsCPUSpecificCPUDispatchMVType = 10269 MVType == MultiVersionKind::CPUDispatch || 10270 MVType == MultiVersionKind::CPUSpecific; 10271 10272 if (CausesMV && OldFD && 10273 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType)) 10274 return true; 10275 10276 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType)) 10277 return true; 10278 10279 // Only allow transition to MultiVersion if it hasn't been used. 10280 if (OldFD && CausesMV && OldFD->isUsed(false)) 10281 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10282 10283 return S.areMultiversionVariantFunctionsCompatible( 10284 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10285 PartialDiagnosticAt(NewFD->getLocation(), 10286 S.PDiag(diag::note_multiversioning_caused_here)), 10287 PartialDiagnosticAt(NewFD->getLocation(), 10288 S.PDiag(diag::err_multiversion_doesnt_support) 10289 << IsCPUSpecificCPUDispatchMVType), 10290 PartialDiagnosticAt(NewFD->getLocation(), 10291 S.PDiag(diag::err_multiversion_diff)), 10292 /*TemplatesSupported=*/false, 10293 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10294 /*CLinkageMayDiffer=*/false); 10295 } 10296 10297 /// Check the validity of a multiversion function declaration that is the 10298 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10299 /// 10300 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10301 /// 10302 /// Returns true if there was an error, false otherwise. 10303 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10304 MultiVersionKind MVType, 10305 const TargetAttr *TA) { 10306 assert(MVType != MultiVersionKind::None && 10307 "Function lacks multiversion attribute"); 10308 10309 // Target only causes MV if it is default, otherwise this is a normal 10310 // function. 10311 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10312 return false; 10313 10314 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10315 FD->setInvalidDecl(); 10316 return true; 10317 } 10318 10319 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10320 FD->setInvalidDecl(); 10321 return true; 10322 } 10323 10324 FD->setIsMultiVersion(); 10325 return false; 10326 } 10327 10328 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10329 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10330 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10331 return true; 10332 } 10333 10334 return false; 10335 } 10336 10337 static bool CheckTargetCausesMultiVersioning( 10338 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10339 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10340 LookupResult &Previous) { 10341 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10342 ParsedTargetAttr NewParsed = NewTA->parse(); 10343 // Sort order doesn't matter, it just needs to be consistent. 10344 llvm::sort(NewParsed.Features); 10345 10346 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10347 // to change, this is a simple redeclaration. 10348 if (!NewTA->isDefaultVersion() && 10349 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10350 return false; 10351 10352 // Otherwise, this decl causes MultiVersioning. 10353 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10354 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10355 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10356 NewFD->setInvalidDecl(); 10357 return true; 10358 } 10359 10360 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10361 MultiVersionKind::Target)) { 10362 NewFD->setInvalidDecl(); 10363 return true; 10364 } 10365 10366 if (CheckMultiVersionValue(S, NewFD)) { 10367 NewFD->setInvalidDecl(); 10368 return true; 10369 } 10370 10371 // If this is 'default', permit the forward declaration. 10372 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10373 Redeclaration = true; 10374 OldDecl = OldFD; 10375 OldFD->setIsMultiVersion(); 10376 NewFD->setIsMultiVersion(); 10377 return false; 10378 } 10379 10380 if (CheckMultiVersionValue(S, OldFD)) { 10381 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10382 NewFD->setInvalidDecl(); 10383 return true; 10384 } 10385 10386 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10387 10388 if (OldParsed == NewParsed) { 10389 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10390 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10391 NewFD->setInvalidDecl(); 10392 return true; 10393 } 10394 10395 for (const auto *FD : OldFD->redecls()) { 10396 const auto *CurTA = FD->getAttr<TargetAttr>(); 10397 // We allow forward declarations before ANY multiversioning attributes, but 10398 // nothing after the fact. 10399 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10400 (!CurTA || CurTA->isInherited())) { 10401 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10402 << 0; 10403 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10404 NewFD->setInvalidDecl(); 10405 return true; 10406 } 10407 } 10408 10409 OldFD->setIsMultiVersion(); 10410 NewFD->setIsMultiVersion(); 10411 Redeclaration = false; 10412 MergeTypeWithPrevious = false; 10413 OldDecl = nullptr; 10414 Previous.clear(); 10415 return false; 10416 } 10417 10418 /// Check the validity of a new function declaration being added to an existing 10419 /// multiversioned declaration collection. 10420 static bool CheckMultiVersionAdditionalDecl( 10421 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10422 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10423 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10424 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10425 LookupResult &Previous) { 10426 10427 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10428 // Disallow mixing of multiversioning types. 10429 if ((OldMVType == MultiVersionKind::Target && 10430 NewMVType != MultiVersionKind::Target) || 10431 (NewMVType == MultiVersionKind::Target && 10432 OldMVType != MultiVersionKind::Target)) { 10433 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10434 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10435 NewFD->setInvalidDecl(); 10436 return true; 10437 } 10438 10439 ParsedTargetAttr NewParsed; 10440 if (NewTA) { 10441 NewParsed = NewTA->parse(); 10442 llvm::sort(NewParsed.Features); 10443 } 10444 10445 bool UseMemberUsingDeclRules = 10446 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10447 10448 // Next, check ALL non-overloads to see if this is a redeclaration of a 10449 // previous member of the MultiVersion set. 10450 for (NamedDecl *ND : Previous) { 10451 FunctionDecl *CurFD = ND->getAsFunction(); 10452 if (!CurFD) 10453 continue; 10454 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10455 continue; 10456 10457 if (NewMVType == MultiVersionKind::Target) { 10458 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10459 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10460 NewFD->setIsMultiVersion(); 10461 Redeclaration = true; 10462 OldDecl = ND; 10463 return false; 10464 } 10465 10466 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10467 if (CurParsed == NewParsed) { 10468 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10469 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10470 NewFD->setInvalidDecl(); 10471 return true; 10472 } 10473 } else { 10474 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10475 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10476 // Handle CPUDispatch/CPUSpecific versions. 10477 // Only 1 CPUDispatch function is allowed, this will make it go through 10478 // the redeclaration errors. 10479 if (NewMVType == MultiVersionKind::CPUDispatch && 10480 CurFD->hasAttr<CPUDispatchAttr>()) { 10481 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10482 std::equal( 10483 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10484 NewCPUDisp->cpus_begin(), 10485 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10486 return Cur->getName() == New->getName(); 10487 })) { 10488 NewFD->setIsMultiVersion(); 10489 Redeclaration = true; 10490 OldDecl = ND; 10491 return false; 10492 } 10493 10494 // If the declarations don't match, this is an error condition. 10495 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10496 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10497 NewFD->setInvalidDecl(); 10498 return true; 10499 } 10500 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10501 10502 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10503 std::equal( 10504 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10505 NewCPUSpec->cpus_begin(), 10506 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10507 return Cur->getName() == New->getName(); 10508 })) { 10509 NewFD->setIsMultiVersion(); 10510 Redeclaration = true; 10511 OldDecl = ND; 10512 return false; 10513 } 10514 10515 // Only 1 version of CPUSpecific is allowed for each CPU. 10516 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10517 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10518 if (CurII == NewII) { 10519 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10520 << NewII; 10521 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10522 NewFD->setInvalidDecl(); 10523 return true; 10524 } 10525 } 10526 } 10527 } 10528 // If the two decls aren't the same MVType, there is no possible error 10529 // condition. 10530 } 10531 } 10532 10533 // Else, this is simply a non-redecl case. Checking the 'value' is only 10534 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10535 // handled in the attribute adding step. 10536 if (NewMVType == MultiVersionKind::Target && 10537 CheckMultiVersionValue(S, NewFD)) { 10538 NewFD->setInvalidDecl(); 10539 return true; 10540 } 10541 10542 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10543 !OldFD->isMultiVersion(), NewMVType)) { 10544 NewFD->setInvalidDecl(); 10545 return true; 10546 } 10547 10548 // Permit forward declarations in the case where these two are compatible. 10549 if (!OldFD->isMultiVersion()) { 10550 OldFD->setIsMultiVersion(); 10551 NewFD->setIsMultiVersion(); 10552 Redeclaration = true; 10553 OldDecl = OldFD; 10554 return false; 10555 } 10556 10557 NewFD->setIsMultiVersion(); 10558 Redeclaration = false; 10559 MergeTypeWithPrevious = false; 10560 OldDecl = nullptr; 10561 Previous.clear(); 10562 return false; 10563 } 10564 10565 10566 /// Check the validity of a mulitversion function declaration. 10567 /// Also sets the multiversion'ness' of the function itself. 10568 /// 10569 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10570 /// 10571 /// Returns true if there was an error, false otherwise. 10572 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10573 bool &Redeclaration, NamedDecl *&OldDecl, 10574 bool &MergeTypeWithPrevious, 10575 LookupResult &Previous) { 10576 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10577 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10578 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10579 10580 // Mixing Multiversioning types is prohibited. 10581 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10582 (NewCPUDisp && NewCPUSpec)) { 10583 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10584 NewFD->setInvalidDecl(); 10585 return true; 10586 } 10587 10588 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10589 10590 // Main isn't allowed to become a multiversion function, however it IS 10591 // permitted to have 'main' be marked with the 'target' optimization hint. 10592 if (NewFD->isMain()) { 10593 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10594 MVType == MultiVersionKind::CPUDispatch || 10595 MVType == MultiVersionKind::CPUSpecific) { 10596 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10597 NewFD->setInvalidDecl(); 10598 return true; 10599 } 10600 return false; 10601 } 10602 10603 if (!OldDecl || !OldDecl->getAsFunction() || 10604 OldDecl->getDeclContext()->getRedeclContext() != 10605 NewFD->getDeclContext()->getRedeclContext()) { 10606 // If there's no previous declaration, AND this isn't attempting to cause 10607 // multiversioning, this isn't an error condition. 10608 if (MVType == MultiVersionKind::None) 10609 return false; 10610 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10611 } 10612 10613 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10614 10615 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10616 return false; 10617 10618 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10619 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10620 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10621 NewFD->setInvalidDecl(); 10622 return true; 10623 } 10624 10625 // Handle the target potentially causes multiversioning case. 10626 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10627 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10628 Redeclaration, OldDecl, 10629 MergeTypeWithPrevious, Previous); 10630 10631 // At this point, we have a multiversion function decl (in OldFD) AND an 10632 // appropriate attribute in the current function decl. Resolve that these are 10633 // still compatible with previous declarations. 10634 return CheckMultiVersionAdditionalDecl( 10635 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10636 OldDecl, MergeTypeWithPrevious, Previous); 10637 } 10638 10639 /// Perform semantic checking of a new function declaration. 10640 /// 10641 /// Performs semantic analysis of the new function declaration 10642 /// NewFD. This routine performs all semantic checking that does not 10643 /// require the actual declarator involved in the declaration, and is 10644 /// used both for the declaration of functions as they are parsed 10645 /// (called via ActOnDeclarator) and for the declaration of functions 10646 /// that have been instantiated via C++ template instantiation (called 10647 /// via InstantiateDecl). 10648 /// 10649 /// \param IsMemberSpecialization whether this new function declaration is 10650 /// a member specialization (that replaces any definition provided by the 10651 /// previous declaration). 10652 /// 10653 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10654 /// 10655 /// \returns true if the function declaration is a redeclaration. 10656 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10657 LookupResult &Previous, 10658 bool IsMemberSpecialization) { 10659 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10660 "Variably modified return types are not handled here"); 10661 10662 // Determine whether the type of this function should be merged with 10663 // a previous visible declaration. This never happens for functions in C++, 10664 // and always happens in C if the previous declaration was visible. 10665 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10666 !Previous.isShadowed(); 10667 10668 bool Redeclaration = false; 10669 NamedDecl *OldDecl = nullptr; 10670 bool MayNeedOverloadableChecks = false; 10671 10672 // Merge or overload the declaration with an existing declaration of 10673 // the same name, if appropriate. 10674 if (!Previous.empty()) { 10675 // Determine whether NewFD is an overload of PrevDecl or 10676 // a declaration that requires merging. If it's an overload, 10677 // there's no more work to do here; we'll just add the new 10678 // function to the scope. 10679 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10680 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10681 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10682 Redeclaration = true; 10683 OldDecl = Candidate; 10684 } 10685 } else { 10686 MayNeedOverloadableChecks = true; 10687 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10688 /*NewIsUsingDecl*/ false)) { 10689 case Ovl_Match: 10690 Redeclaration = true; 10691 break; 10692 10693 case Ovl_NonFunction: 10694 Redeclaration = true; 10695 break; 10696 10697 case Ovl_Overload: 10698 Redeclaration = false; 10699 break; 10700 } 10701 } 10702 } 10703 10704 // Check for a previous extern "C" declaration with this name. 10705 if (!Redeclaration && 10706 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10707 if (!Previous.empty()) { 10708 // This is an extern "C" declaration with the same name as a previous 10709 // declaration, and thus redeclares that entity... 10710 Redeclaration = true; 10711 OldDecl = Previous.getFoundDecl(); 10712 MergeTypeWithPrevious = false; 10713 10714 // ... except in the presence of __attribute__((overloadable)). 10715 if (OldDecl->hasAttr<OverloadableAttr>() || 10716 NewFD->hasAttr<OverloadableAttr>()) { 10717 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10718 MayNeedOverloadableChecks = true; 10719 Redeclaration = false; 10720 OldDecl = nullptr; 10721 } 10722 } 10723 } 10724 } 10725 10726 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10727 MergeTypeWithPrevious, Previous)) 10728 return Redeclaration; 10729 10730 // PPC MMA non-pointer types are not allowed as function return types. 10731 if (Context.getTargetInfo().getTriple().isPPC64() && 10732 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 10733 NewFD->setInvalidDecl(); 10734 } 10735 10736 // C++11 [dcl.constexpr]p8: 10737 // A constexpr specifier for a non-static member function that is not 10738 // a constructor declares that member function to be const. 10739 // 10740 // This needs to be delayed until we know whether this is an out-of-line 10741 // definition of a static member function. 10742 // 10743 // This rule is not present in C++1y, so we produce a backwards 10744 // compatibility warning whenever it happens in C++11. 10745 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10746 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10747 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10748 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10749 CXXMethodDecl *OldMD = nullptr; 10750 if (OldDecl) 10751 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10752 if (!OldMD || !OldMD->isStatic()) { 10753 const FunctionProtoType *FPT = 10754 MD->getType()->castAs<FunctionProtoType>(); 10755 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10756 EPI.TypeQuals.addConst(); 10757 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10758 FPT->getParamTypes(), EPI)); 10759 10760 // Warn that we did this, if we're not performing template instantiation. 10761 // In that case, we'll have warned already when the template was defined. 10762 if (!inTemplateInstantiation()) { 10763 SourceLocation AddConstLoc; 10764 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10765 .IgnoreParens().getAs<FunctionTypeLoc>()) 10766 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10767 10768 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10769 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10770 } 10771 } 10772 } 10773 10774 if (Redeclaration) { 10775 // NewFD and OldDecl represent declarations that need to be 10776 // merged. 10777 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10778 NewFD->setInvalidDecl(); 10779 return Redeclaration; 10780 } 10781 10782 Previous.clear(); 10783 Previous.addDecl(OldDecl); 10784 10785 if (FunctionTemplateDecl *OldTemplateDecl = 10786 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10787 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10788 FunctionTemplateDecl *NewTemplateDecl 10789 = NewFD->getDescribedFunctionTemplate(); 10790 assert(NewTemplateDecl && "Template/non-template mismatch"); 10791 10792 // The call to MergeFunctionDecl above may have created some state in 10793 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10794 // can add it as a redeclaration. 10795 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10796 10797 NewFD->setPreviousDeclaration(OldFD); 10798 if (NewFD->isCXXClassMember()) { 10799 NewFD->setAccess(OldTemplateDecl->getAccess()); 10800 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10801 } 10802 10803 // If this is an explicit specialization of a member that is a function 10804 // template, mark it as a member specialization. 10805 if (IsMemberSpecialization && 10806 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10807 NewTemplateDecl->setMemberSpecialization(); 10808 assert(OldTemplateDecl->isMemberSpecialization()); 10809 // Explicit specializations of a member template do not inherit deleted 10810 // status from the parent member template that they are specializing. 10811 if (OldFD->isDeleted()) { 10812 // FIXME: This assert will not hold in the presence of modules. 10813 assert(OldFD->getCanonicalDecl() == OldFD); 10814 // FIXME: We need an update record for this AST mutation. 10815 OldFD->setDeletedAsWritten(false); 10816 } 10817 } 10818 10819 } else { 10820 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10821 auto *OldFD = cast<FunctionDecl>(OldDecl); 10822 // This needs to happen first so that 'inline' propagates. 10823 NewFD->setPreviousDeclaration(OldFD); 10824 if (NewFD->isCXXClassMember()) 10825 NewFD->setAccess(OldFD->getAccess()); 10826 } 10827 } 10828 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10829 !NewFD->getAttr<OverloadableAttr>()) { 10830 assert((Previous.empty() || 10831 llvm::any_of(Previous, 10832 [](const NamedDecl *ND) { 10833 return ND->hasAttr<OverloadableAttr>(); 10834 })) && 10835 "Non-redecls shouldn't happen without overloadable present"); 10836 10837 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10838 const auto *FD = dyn_cast<FunctionDecl>(ND); 10839 return FD && !FD->hasAttr<OverloadableAttr>(); 10840 }); 10841 10842 if (OtherUnmarkedIter != Previous.end()) { 10843 Diag(NewFD->getLocation(), 10844 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10845 Diag((*OtherUnmarkedIter)->getLocation(), 10846 diag::note_attribute_overloadable_prev_overload) 10847 << false; 10848 10849 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10850 } 10851 } 10852 10853 if (LangOpts.OpenMP) 10854 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 10855 10856 // Semantic checking for this function declaration (in isolation). 10857 10858 if (getLangOpts().CPlusPlus) { 10859 // C++-specific checks. 10860 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10861 CheckConstructor(Constructor); 10862 } else if (CXXDestructorDecl *Destructor = 10863 dyn_cast<CXXDestructorDecl>(NewFD)) { 10864 CXXRecordDecl *Record = Destructor->getParent(); 10865 QualType ClassType = Context.getTypeDeclType(Record); 10866 10867 // FIXME: Shouldn't we be able to perform this check even when the class 10868 // type is dependent? Both gcc and edg can handle that. 10869 if (!ClassType->isDependentType()) { 10870 DeclarationName Name 10871 = Context.DeclarationNames.getCXXDestructorName( 10872 Context.getCanonicalType(ClassType)); 10873 if (NewFD->getDeclName() != Name) { 10874 Diag(NewFD->getLocation(), diag::err_destructor_name); 10875 NewFD->setInvalidDecl(); 10876 return Redeclaration; 10877 } 10878 } 10879 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10880 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10881 CheckDeductionGuideTemplate(TD); 10882 10883 // A deduction guide is not on the list of entities that can be 10884 // explicitly specialized. 10885 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10886 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10887 << /*explicit specialization*/ 1; 10888 } 10889 10890 // Find any virtual functions that this function overrides. 10891 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10892 if (!Method->isFunctionTemplateSpecialization() && 10893 !Method->getDescribedFunctionTemplate() && 10894 Method->isCanonicalDecl()) { 10895 AddOverriddenMethods(Method->getParent(), Method); 10896 } 10897 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10898 // C++2a [class.virtual]p6 10899 // A virtual method shall not have a requires-clause. 10900 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10901 diag::err_constrained_virtual_method); 10902 10903 if (Method->isStatic()) 10904 checkThisInStaticMemberFunctionType(Method); 10905 } 10906 10907 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 10908 ActOnConversionDeclarator(Conversion); 10909 10910 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10911 if (NewFD->isOverloadedOperator() && 10912 CheckOverloadedOperatorDeclaration(NewFD)) { 10913 NewFD->setInvalidDecl(); 10914 return Redeclaration; 10915 } 10916 10917 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10918 if (NewFD->getLiteralIdentifier() && 10919 CheckLiteralOperatorDeclaration(NewFD)) { 10920 NewFD->setInvalidDecl(); 10921 return Redeclaration; 10922 } 10923 10924 // In C++, check default arguments now that we have merged decls. Unless 10925 // the lexical context is the class, because in this case this is done 10926 // during delayed parsing anyway. 10927 if (!CurContext->isRecord()) 10928 CheckCXXDefaultArguments(NewFD); 10929 10930 // If this function declares a builtin function, check the type of this 10931 // declaration against the expected type for the builtin. 10932 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10933 ASTContext::GetBuiltinTypeError Error; 10934 LookupNecessaryTypesForBuiltin(S, BuiltinID); 10935 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10936 // If the type of the builtin differs only in its exception 10937 // specification, that's OK. 10938 // FIXME: If the types do differ in this way, it would be better to 10939 // retain the 'noexcept' form of the type. 10940 if (!T.isNull() && 10941 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10942 NewFD->getType())) 10943 // The type of this function differs from the type of the builtin, 10944 // so forget about the builtin entirely. 10945 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10946 } 10947 10948 // If this function is declared as being extern "C", then check to see if 10949 // the function returns a UDT (class, struct, or union type) that is not C 10950 // compatible, and if it does, warn the user. 10951 // But, issue any diagnostic on the first declaration only. 10952 if (Previous.empty() && NewFD->isExternC()) { 10953 QualType R = NewFD->getReturnType(); 10954 if (R->isIncompleteType() && !R->isVoidType()) 10955 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10956 << NewFD << R; 10957 else if (!R.isPODType(Context) && !R->isVoidType() && 10958 !R->isObjCObjectPointerType()) 10959 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10960 } 10961 10962 // C++1z [dcl.fct]p6: 10963 // [...] whether the function has a non-throwing exception-specification 10964 // [is] part of the function type 10965 // 10966 // This results in an ABI break between C++14 and C++17 for functions whose 10967 // declared type includes an exception-specification in a parameter or 10968 // return type. (Exception specifications on the function itself are OK in 10969 // most cases, and exception specifications are not permitted in most other 10970 // contexts where they could make it into a mangling.) 10971 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10972 auto HasNoexcept = [&](QualType T) -> bool { 10973 // Strip off declarator chunks that could be between us and a function 10974 // type. We don't need to look far, exception specifications are very 10975 // restricted prior to C++17. 10976 if (auto *RT = T->getAs<ReferenceType>()) 10977 T = RT->getPointeeType(); 10978 else if (T->isAnyPointerType()) 10979 T = T->getPointeeType(); 10980 else if (auto *MPT = T->getAs<MemberPointerType>()) 10981 T = MPT->getPointeeType(); 10982 if (auto *FPT = T->getAs<FunctionProtoType>()) 10983 if (FPT->isNothrow()) 10984 return true; 10985 return false; 10986 }; 10987 10988 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10989 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10990 for (QualType T : FPT->param_types()) 10991 AnyNoexcept |= HasNoexcept(T); 10992 if (AnyNoexcept) 10993 Diag(NewFD->getLocation(), 10994 diag::warn_cxx17_compat_exception_spec_in_signature) 10995 << NewFD; 10996 } 10997 10998 if (!Redeclaration && LangOpts.CUDA) 10999 checkCUDATargetOverload(NewFD, Previous); 11000 } 11001 return Redeclaration; 11002 } 11003 11004 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11005 // C++11 [basic.start.main]p3: 11006 // A program that [...] declares main to be inline, static or 11007 // constexpr is ill-formed. 11008 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11009 // appear in a declaration of main. 11010 // static main is not an error under C99, but we should warn about it. 11011 // We accept _Noreturn main as an extension. 11012 if (FD->getStorageClass() == SC_Static) 11013 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11014 ? diag::err_static_main : diag::warn_static_main) 11015 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11016 if (FD->isInlineSpecified()) 11017 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11018 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11019 if (DS.isNoreturnSpecified()) { 11020 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11021 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11022 Diag(NoreturnLoc, diag::ext_noreturn_main); 11023 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11024 << FixItHint::CreateRemoval(NoreturnRange); 11025 } 11026 if (FD->isConstexpr()) { 11027 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11028 << FD->isConsteval() 11029 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11030 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11031 } 11032 11033 if (getLangOpts().OpenCL) { 11034 Diag(FD->getLocation(), diag::err_opencl_no_main) 11035 << FD->hasAttr<OpenCLKernelAttr>(); 11036 FD->setInvalidDecl(); 11037 return; 11038 } 11039 11040 QualType T = FD->getType(); 11041 assert(T->isFunctionType() && "function decl is not of function type"); 11042 const FunctionType* FT = T->castAs<FunctionType>(); 11043 11044 // Set default calling convention for main() 11045 if (FT->getCallConv() != CC_C) { 11046 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11047 FD->setType(QualType(FT, 0)); 11048 T = Context.getCanonicalType(FD->getType()); 11049 } 11050 11051 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11052 // In C with GNU extensions we allow main() to have non-integer return 11053 // type, but we should warn about the extension, and we disable the 11054 // implicit-return-zero rule. 11055 11056 // GCC in C mode accepts qualified 'int'. 11057 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11058 FD->setHasImplicitReturnZero(true); 11059 else { 11060 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11061 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11062 if (RTRange.isValid()) 11063 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11064 << FixItHint::CreateReplacement(RTRange, "int"); 11065 } 11066 } else { 11067 // In C and C++, main magically returns 0 if you fall off the end; 11068 // set the flag which tells us that. 11069 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11070 11071 // All the standards say that main() should return 'int'. 11072 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11073 FD->setHasImplicitReturnZero(true); 11074 else { 11075 // Otherwise, this is just a flat-out error. 11076 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11077 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11078 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11079 : FixItHint()); 11080 FD->setInvalidDecl(true); 11081 } 11082 } 11083 11084 // Treat protoless main() as nullary. 11085 if (isa<FunctionNoProtoType>(FT)) return; 11086 11087 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11088 unsigned nparams = FTP->getNumParams(); 11089 assert(FD->getNumParams() == nparams); 11090 11091 bool HasExtraParameters = (nparams > 3); 11092 11093 if (FTP->isVariadic()) { 11094 Diag(FD->getLocation(), diag::ext_variadic_main); 11095 // FIXME: if we had information about the location of the ellipsis, we 11096 // could add a FixIt hint to remove it as a parameter. 11097 } 11098 11099 // Darwin passes an undocumented fourth argument of type char**. If 11100 // other platforms start sprouting these, the logic below will start 11101 // getting shifty. 11102 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11103 HasExtraParameters = false; 11104 11105 if (HasExtraParameters) { 11106 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11107 FD->setInvalidDecl(true); 11108 nparams = 3; 11109 } 11110 11111 // FIXME: a lot of the following diagnostics would be improved 11112 // if we had some location information about types. 11113 11114 QualType CharPP = 11115 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11116 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11117 11118 for (unsigned i = 0; i < nparams; ++i) { 11119 QualType AT = FTP->getParamType(i); 11120 11121 bool mismatch = true; 11122 11123 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11124 mismatch = false; 11125 else if (Expected[i] == CharPP) { 11126 // As an extension, the following forms are okay: 11127 // char const ** 11128 // char const * const * 11129 // char * const * 11130 11131 QualifierCollector qs; 11132 const PointerType* PT; 11133 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11134 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11135 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11136 Context.CharTy)) { 11137 qs.removeConst(); 11138 mismatch = !qs.empty(); 11139 } 11140 } 11141 11142 if (mismatch) { 11143 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11144 // TODO: suggest replacing given type with expected type 11145 FD->setInvalidDecl(true); 11146 } 11147 } 11148 11149 if (nparams == 1 && !FD->isInvalidDecl()) { 11150 Diag(FD->getLocation(), diag::warn_main_one_arg); 11151 } 11152 11153 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11154 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11155 FD->setInvalidDecl(); 11156 } 11157 } 11158 11159 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11160 QualType T = FD->getType(); 11161 assert(T->isFunctionType() && "function decl is not of function type"); 11162 const FunctionType *FT = T->castAs<FunctionType>(); 11163 11164 // Set an implicit return of 'zero' if the function can return some integral, 11165 // enumeration, pointer or nullptr type. 11166 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11167 FT->getReturnType()->isAnyPointerType() || 11168 FT->getReturnType()->isNullPtrType()) 11169 // DllMain is exempt because a return value of zero means it failed. 11170 if (FD->getName() != "DllMain") 11171 FD->setHasImplicitReturnZero(true); 11172 11173 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11174 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11175 FD->setInvalidDecl(); 11176 } 11177 } 11178 11179 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11180 // FIXME: Need strict checking. In C89, we need to check for 11181 // any assignment, increment, decrement, function-calls, or 11182 // commas outside of a sizeof. In C99, it's the same list, 11183 // except that the aforementioned are allowed in unevaluated 11184 // expressions. Everything else falls under the 11185 // "may accept other forms of constant expressions" exception. 11186 // 11187 // Regular C++ code will not end up here (exceptions: language extensions, 11188 // OpenCL C++ etc), so the constant expression rules there don't matter. 11189 if (Init->isValueDependent()) { 11190 assert(Init->containsErrors() && 11191 "Dependent code should only occur in error-recovery path."); 11192 return true; 11193 } 11194 const Expr *Culprit; 11195 if (Init->isConstantInitializer(Context, false, &Culprit)) 11196 return false; 11197 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11198 << Culprit->getSourceRange(); 11199 return true; 11200 } 11201 11202 namespace { 11203 // Visits an initialization expression to see if OrigDecl is evaluated in 11204 // its own initialization and throws a warning if it does. 11205 class SelfReferenceChecker 11206 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11207 Sema &S; 11208 Decl *OrigDecl; 11209 bool isRecordType; 11210 bool isPODType; 11211 bool isReferenceType; 11212 11213 bool isInitList; 11214 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11215 11216 public: 11217 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11218 11219 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11220 S(S), OrigDecl(OrigDecl) { 11221 isPODType = false; 11222 isRecordType = false; 11223 isReferenceType = false; 11224 isInitList = false; 11225 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11226 isPODType = VD->getType().isPODType(S.Context); 11227 isRecordType = VD->getType()->isRecordType(); 11228 isReferenceType = VD->getType()->isReferenceType(); 11229 } 11230 } 11231 11232 // For most expressions, just call the visitor. For initializer lists, 11233 // track the index of the field being initialized since fields are 11234 // initialized in order allowing use of previously initialized fields. 11235 void CheckExpr(Expr *E) { 11236 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11237 if (!InitList) { 11238 Visit(E); 11239 return; 11240 } 11241 11242 // Track and increment the index here. 11243 isInitList = true; 11244 InitFieldIndex.push_back(0); 11245 for (auto Child : InitList->children()) { 11246 CheckExpr(cast<Expr>(Child)); 11247 ++InitFieldIndex.back(); 11248 } 11249 InitFieldIndex.pop_back(); 11250 } 11251 11252 // Returns true if MemberExpr is checked and no further checking is needed. 11253 // Returns false if additional checking is required. 11254 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11255 llvm::SmallVector<FieldDecl*, 4> Fields; 11256 Expr *Base = E; 11257 bool ReferenceField = false; 11258 11259 // Get the field members used. 11260 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11261 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11262 if (!FD) 11263 return false; 11264 Fields.push_back(FD); 11265 if (FD->getType()->isReferenceType()) 11266 ReferenceField = true; 11267 Base = ME->getBase()->IgnoreParenImpCasts(); 11268 } 11269 11270 // Keep checking only if the base Decl is the same. 11271 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11272 if (!DRE || DRE->getDecl() != OrigDecl) 11273 return false; 11274 11275 // A reference field can be bound to an unininitialized field. 11276 if (CheckReference && !ReferenceField) 11277 return true; 11278 11279 // Convert FieldDecls to their index number. 11280 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11281 for (const FieldDecl *I : llvm::reverse(Fields)) 11282 UsedFieldIndex.push_back(I->getFieldIndex()); 11283 11284 // See if a warning is needed by checking the first difference in index 11285 // numbers. If field being used has index less than the field being 11286 // initialized, then the use is safe. 11287 for (auto UsedIter = UsedFieldIndex.begin(), 11288 UsedEnd = UsedFieldIndex.end(), 11289 OrigIter = InitFieldIndex.begin(), 11290 OrigEnd = InitFieldIndex.end(); 11291 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11292 if (*UsedIter < *OrigIter) 11293 return true; 11294 if (*UsedIter > *OrigIter) 11295 break; 11296 } 11297 11298 // TODO: Add a different warning which will print the field names. 11299 HandleDeclRefExpr(DRE); 11300 return true; 11301 } 11302 11303 // For most expressions, the cast is directly above the DeclRefExpr. 11304 // For conditional operators, the cast can be outside the conditional 11305 // operator if both expressions are DeclRefExpr's. 11306 void HandleValue(Expr *E) { 11307 E = E->IgnoreParens(); 11308 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11309 HandleDeclRefExpr(DRE); 11310 return; 11311 } 11312 11313 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11314 Visit(CO->getCond()); 11315 HandleValue(CO->getTrueExpr()); 11316 HandleValue(CO->getFalseExpr()); 11317 return; 11318 } 11319 11320 if (BinaryConditionalOperator *BCO = 11321 dyn_cast<BinaryConditionalOperator>(E)) { 11322 Visit(BCO->getCond()); 11323 HandleValue(BCO->getFalseExpr()); 11324 return; 11325 } 11326 11327 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11328 HandleValue(OVE->getSourceExpr()); 11329 return; 11330 } 11331 11332 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11333 if (BO->getOpcode() == BO_Comma) { 11334 Visit(BO->getLHS()); 11335 HandleValue(BO->getRHS()); 11336 return; 11337 } 11338 } 11339 11340 if (isa<MemberExpr>(E)) { 11341 if (isInitList) { 11342 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11343 false /*CheckReference*/)) 11344 return; 11345 } 11346 11347 Expr *Base = E->IgnoreParenImpCasts(); 11348 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11349 // Check for static member variables and don't warn on them. 11350 if (!isa<FieldDecl>(ME->getMemberDecl())) 11351 return; 11352 Base = ME->getBase()->IgnoreParenImpCasts(); 11353 } 11354 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11355 HandleDeclRefExpr(DRE); 11356 return; 11357 } 11358 11359 Visit(E); 11360 } 11361 11362 // Reference types not handled in HandleValue are handled here since all 11363 // uses of references are bad, not just r-value uses. 11364 void VisitDeclRefExpr(DeclRefExpr *E) { 11365 if (isReferenceType) 11366 HandleDeclRefExpr(E); 11367 } 11368 11369 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11370 if (E->getCastKind() == CK_LValueToRValue) { 11371 HandleValue(E->getSubExpr()); 11372 return; 11373 } 11374 11375 Inherited::VisitImplicitCastExpr(E); 11376 } 11377 11378 void VisitMemberExpr(MemberExpr *E) { 11379 if (isInitList) { 11380 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11381 return; 11382 } 11383 11384 // Don't warn on arrays since they can be treated as pointers. 11385 if (E->getType()->canDecayToPointerType()) return; 11386 11387 // Warn when a non-static method call is followed by non-static member 11388 // field accesses, which is followed by a DeclRefExpr. 11389 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11390 bool Warn = (MD && !MD->isStatic()); 11391 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11392 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11393 if (!isa<FieldDecl>(ME->getMemberDecl())) 11394 Warn = false; 11395 Base = ME->getBase()->IgnoreParenImpCasts(); 11396 } 11397 11398 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11399 if (Warn) 11400 HandleDeclRefExpr(DRE); 11401 return; 11402 } 11403 11404 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11405 // Visit that expression. 11406 Visit(Base); 11407 } 11408 11409 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11410 Expr *Callee = E->getCallee(); 11411 11412 if (isa<UnresolvedLookupExpr>(Callee)) 11413 return Inherited::VisitCXXOperatorCallExpr(E); 11414 11415 Visit(Callee); 11416 for (auto Arg: E->arguments()) 11417 HandleValue(Arg->IgnoreParenImpCasts()); 11418 } 11419 11420 void VisitUnaryOperator(UnaryOperator *E) { 11421 // For POD record types, addresses of its own members are well-defined. 11422 if (E->getOpcode() == UO_AddrOf && isRecordType && 11423 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11424 if (!isPODType) 11425 HandleValue(E->getSubExpr()); 11426 return; 11427 } 11428 11429 if (E->isIncrementDecrementOp()) { 11430 HandleValue(E->getSubExpr()); 11431 return; 11432 } 11433 11434 Inherited::VisitUnaryOperator(E); 11435 } 11436 11437 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11438 11439 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11440 if (E->getConstructor()->isCopyConstructor()) { 11441 Expr *ArgExpr = E->getArg(0); 11442 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11443 if (ILE->getNumInits() == 1) 11444 ArgExpr = ILE->getInit(0); 11445 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11446 if (ICE->getCastKind() == CK_NoOp) 11447 ArgExpr = ICE->getSubExpr(); 11448 HandleValue(ArgExpr); 11449 return; 11450 } 11451 Inherited::VisitCXXConstructExpr(E); 11452 } 11453 11454 void VisitCallExpr(CallExpr *E) { 11455 // Treat std::move as a use. 11456 if (E->isCallToStdMove()) { 11457 HandleValue(E->getArg(0)); 11458 return; 11459 } 11460 11461 Inherited::VisitCallExpr(E); 11462 } 11463 11464 void VisitBinaryOperator(BinaryOperator *E) { 11465 if (E->isCompoundAssignmentOp()) { 11466 HandleValue(E->getLHS()); 11467 Visit(E->getRHS()); 11468 return; 11469 } 11470 11471 Inherited::VisitBinaryOperator(E); 11472 } 11473 11474 // A custom visitor for BinaryConditionalOperator is needed because the 11475 // regular visitor would check the condition and true expression separately 11476 // but both point to the same place giving duplicate diagnostics. 11477 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11478 Visit(E->getCond()); 11479 Visit(E->getFalseExpr()); 11480 } 11481 11482 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11483 Decl* ReferenceDecl = DRE->getDecl(); 11484 if (OrigDecl != ReferenceDecl) return; 11485 unsigned diag; 11486 if (isReferenceType) { 11487 diag = diag::warn_uninit_self_reference_in_reference_init; 11488 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11489 diag = diag::warn_static_self_reference_in_init; 11490 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11491 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11492 DRE->getDecl()->getType()->isRecordType()) { 11493 diag = diag::warn_uninit_self_reference_in_init; 11494 } else { 11495 // Local variables will be handled by the CFG analysis. 11496 return; 11497 } 11498 11499 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11500 S.PDiag(diag) 11501 << DRE->getDecl() << OrigDecl->getLocation() 11502 << DRE->getSourceRange()); 11503 } 11504 }; 11505 11506 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11507 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11508 bool DirectInit) { 11509 // Parameters arguments are occassionially constructed with itself, 11510 // for instance, in recursive functions. Skip them. 11511 if (isa<ParmVarDecl>(OrigDecl)) 11512 return; 11513 11514 E = E->IgnoreParens(); 11515 11516 // Skip checking T a = a where T is not a record or reference type. 11517 // Doing so is a way to silence uninitialized warnings. 11518 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11519 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11520 if (ICE->getCastKind() == CK_LValueToRValue) 11521 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11522 if (DRE->getDecl() == OrigDecl) 11523 return; 11524 11525 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11526 } 11527 } // end anonymous namespace 11528 11529 namespace { 11530 // Simple wrapper to add the name of a variable or (if no variable is 11531 // available) a DeclarationName into a diagnostic. 11532 struct VarDeclOrName { 11533 VarDecl *VDecl; 11534 DeclarationName Name; 11535 11536 friend const Sema::SemaDiagnosticBuilder & 11537 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11538 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11539 } 11540 }; 11541 } // end anonymous namespace 11542 11543 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11544 DeclarationName Name, QualType Type, 11545 TypeSourceInfo *TSI, 11546 SourceRange Range, bool DirectInit, 11547 Expr *Init) { 11548 bool IsInitCapture = !VDecl; 11549 assert((!VDecl || !VDecl->isInitCapture()) && 11550 "init captures are expected to be deduced prior to initialization"); 11551 11552 VarDeclOrName VN{VDecl, Name}; 11553 11554 DeducedType *Deduced = Type->getContainedDeducedType(); 11555 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11556 11557 // C++11 [dcl.spec.auto]p3 11558 if (!Init) { 11559 assert(VDecl && "no init for init capture deduction?"); 11560 11561 // Except for class argument deduction, and then for an initializing 11562 // declaration only, i.e. no static at class scope or extern. 11563 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11564 VDecl->hasExternalStorage() || 11565 VDecl->isStaticDataMember()) { 11566 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11567 << VDecl->getDeclName() << Type; 11568 return QualType(); 11569 } 11570 } 11571 11572 ArrayRef<Expr*> DeduceInits; 11573 if (Init) 11574 DeduceInits = Init; 11575 11576 if (DirectInit) { 11577 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11578 DeduceInits = PL->exprs(); 11579 } 11580 11581 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11582 assert(VDecl && "non-auto type for init capture deduction?"); 11583 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11584 InitializationKind Kind = InitializationKind::CreateForInit( 11585 VDecl->getLocation(), DirectInit, Init); 11586 // FIXME: Initialization should not be taking a mutable list of inits. 11587 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11588 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11589 InitsCopy); 11590 } 11591 11592 if (DirectInit) { 11593 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11594 DeduceInits = IL->inits(); 11595 } 11596 11597 // Deduction only works if we have exactly one source expression. 11598 if (DeduceInits.empty()) { 11599 // It isn't possible to write this directly, but it is possible to 11600 // end up in this situation with "auto x(some_pack...);" 11601 Diag(Init->getBeginLoc(), IsInitCapture 11602 ? diag::err_init_capture_no_expression 11603 : diag::err_auto_var_init_no_expression) 11604 << VN << Type << Range; 11605 return QualType(); 11606 } 11607 11608 if (DeduceInits.size() > 1) { 11609 Diag(DeduceInits[1]->getBeginLoc(), 11610 IsInitCapture ? diag::err_init_capture_multiple_expressions 11611 : diag::err_auto_var_init_multiple_expressions) 11612 << VN << Type << Range; 11613 return QualType(); 11614 } 11615 11616 Expr *DeduceInit = DeduceInits[0]; 11617 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11618 Diag(Init->getBeginLoc(), IsInitCapture 11619 ? diag::err_init_capture_paren_braces 11620 : diag::err_auto_var_init_paren_braces) 11621 << isa<InitListExpr>(Init) << VN << Type << Range; 11622 return QualType(); 11623 } 11624 11625 // Expressions default to 'id' when we're in a debugger. 11626 bool DefaultedAnyToId = false; 11627 if (getLangOpts().DebuggerCastResultToId && 11628 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11629 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11630 if (Result.isInvalid()) { 11631 return QualType(); 11632 } 11633 Init = Result.get(); 11634 DefaultedAnyToId = true; 11635 } 11636 11637 // C++ [dcl.decomp]p1: 11638 // If the assignment-expression [...] has array type A and no ref-qualifier 11639 // is present, e has type cv A 11640 if (VDecl && isa<DecompositionDecl>(VDecl) && 11641 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11642 DeduceInit->getType()->isConstantArrayType()) 11643 return Context.getQualifiedType(DeduceInit->getType(), 11644 Type.getQualifiers()); 11645 11646 QualType DeducedType; 11647 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11648 if (!IsInitCapture) 11649 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11650 else if (isa<InitListExpr>(Init)) 11651 Diag(Range.getBegin(), 11652 diag::err_init_capture_deduction_failure_from_init_list) 11653 << VN 11654 << (DeduceInit->getType().isNull() ? TSI->getType() 11655 : DeduceInit->getType()) 11656 << DeduceInit->getSourceRange(); 11657 else 11658 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11659 << VN << TSI->getType() 11660 << (DeduceInit->getType().isNull() ? TSI->getType() 11661 : DeduceInit->getType()) 11662 << DeduceInit->getSourceRange(); 11663 } 11664 11665 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11666 // 'id' instead of a specific object type prevents most of our usual 11667 // checks. 11668 // We only want to warn outside of template instantiations, though: 11669 // inside a template, the 'id' could have come from a parameter. 11670 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11671 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11672 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11673 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11674 } 11675 11676 return DeducedType; 11677 } 11678 11679 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11680 Expr *Init) { 11681 assert(!Init || !Init->containsErrors()); 11682 QualType DeducedType = deduceVarTypeFromInitializer( 11683 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11684 VDecl->getSourceRange(), DirectInit, Init); 11685 if (DeducedType.isNull()) { 11686 VDecl->setInvalidDecl(); 11687 return true; 11688 } 11689 11690 VDecl->setType(DeducedType); 11691 assert(VDecl->isLinkageValid()); 11692 11693 // In ARC, infer lifetime. 11694 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11695 VDecl->setInvalidDecl(); 11696 11697 if (getLangOpts().OpenCL) 11698 deduceOpenCLAddressSpace(VDecl); 11699 11700 // If this is a redeclaration, check that the type we just deduced matches 11701 // the previously declared type. 11702 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11703 // We never need to merge the type, because we cannot form an incomplete 11704 // array of auto, nor deduce such a type. 11705 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11706 } 11707 11708 // Check the deduced type is valid for a variable declaration. 11709 CheckVariableDeclarationType(VDecl); 11710 return VDecl->isInvalidDecl(); 11711 } 11712 11713 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11714 SourceLocation Loc) { 11715 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11716 Init = EWC->getSubExpr(); 11717 11718 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11719 Init = CE->getSubExpr(); 11720 11721 QualType InitType = Init->getType(); 11722 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11723 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11724 "shouldn't be called if type doesn't have a non-trivial C struct"); 11725 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11726 for (auto I : ILE->inits()) { 11727 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11728 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11729 continue; 11730 SourceLocation SL = I->getExprLoc(); 11731 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11732 } 11733 return; 11734 } 11735 11736 if (isa<ImplicitValueInitExpr>(Init)) { 11737 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11738 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11739 NTCUK_Init); 11740 } else { 11741 // Assume all other explicit initializers involving copying some existing 11742 // object. 11743 // TODO: ignore any explicit initializers where we can guarantee 11744 // copy-elision. 11745 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11746 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11747 } 11748 } 11749 11750 namespace { 11751 11752 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11753 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11754 // in the source code or implicitly by the compiler if it is in a union 11755 // defined in a system header and has non-trivial ObjC ownership 11756 // qualifications. We don't want those fields to participate in determining 11757 // whether the containing union is non-trivial. 11758 return FD->hasAttr<UnavailableAttr>(); 11759 } 11760 11761 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11762 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11763 void> { 11764 using Super = 11765 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11766 void>; 11767 11768 DiagNonTrivalCUnionDefaultInitializeVisitor( 11769 QualType OrigTy, SourceLocation OrigLoc, 11770 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11771 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11772 11773 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11774 const FieldDecl *FD, bool InNonTrivialUnion) { 11775 if (const auto *AT = S.Context.getAsArrayType(QT)) 11776 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11777 InNonTrivialUnion); 11778 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11779 } 11780 11781 void visitARCStrong(QualType QT, const FieldDecl *FD, 11782 bool InNonTrivialUnion) { 11783 if (InNonTrivialUnion) 11784 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11785 << 1 << 0 << QT << FD->getName(); 11786 } 11787 11788 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11789 if (InNonTrivialUnion) 11790 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11791 << 1 << 0 << QT << FD->getName(); 11792 } 11793 11794 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11795 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11796 if (RD->isUnion()) { 11797 if (OrigLoc.isValid()) { 11798 bool IsUnion = false; 11799 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11800 IsUnion = OrigRD->isUnion(); 11801 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11802 << 0 << OrigTy << IsUnion << UseContext; 11803 // Reset OrigLoc so that this diagnostic is emitted only once. 11804 OrigLoc = SourceLocation(); 11805 } 11806 InNonTrivialUnion = true; 11807 } 11808 11809 if (InNonTrivialUnion) 11810 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11811 << 0 << 0 << QT.getUnqualifiedType() << ""; 11812 11813 for (const FieldDecl *FD : RD->fields()) 11814 if (!shouldIgnoreForRecordTriviality(FD)) 11815 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11816 } 11817 11818 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11819 11820 // The non-trivial C union type or the struct/union type that contains a 11821 // non-trivial C union. 11822 QualType OrigTy; 11823 SourceLocation OrigLoc; 11824 Sema::NonTrivialCUnionContext UseContext; 11825 Sema &S; 11826 }; 11827 11828 struct DiagNonTrivalCUnionDestructedTypeVisitor 11829 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11830 using Super = 11831 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11832 11833 DiagNonTrivalCUnionDestructedTypeVisitor( 11834 QualType OrigTy, SourceLocation OrigLoc, 11835 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11836 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11837 11838 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11839 const FieldDecl *FD, bool InNonTrivialUnion) { 11840 if (const auto *AT = S.Context.getAsArrayType(QT)) 11841 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11842 InNonTrivialUnion); 11843 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11844 } 11845 11846 void visitARCStrong(QualType QT, const FieldDecl *FD, 11847 bool InNonTrivialUnion) { 11848 if (InNonTrivialUnion) 11849 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11850 << 1 << 1 << QT << FD->getName(); 11851 } 11852 11853 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11854 if (InNonTrivialUnion) 11855 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11856 << 1 << 1 << QT << FD->getName(); 11857 } 11858 11859 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11860 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11861 if (RD->isUnion()) { 11862 if (OrigLoc.isValid()) { 11863 bool IsUnion = false; 11864 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11865 IsUnion = OrigRD->isUnion(); 11866 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11867 << 1 << OrigTy << IsUnion << UseContext; 11868 // Reset OrigLoc so that this diagnostic is emitted only once. 11869 OrigLoc = SourceLocation(); 11870 } 11871 InNonTrivialUnion = true; 11872 } 11873 11874 if (InNonTrivialUnion) 11875 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11876 << 0 << 1 << QT.getUnqualifiedType() << ""; 11877 11878 for (const FieldDecl *FD : RD->fields()) 11879 if (!shouldIgnoreForRecordTriviality(FD)) 11880 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11881 } 11882 11883 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11884 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11885 bool InNonTrivialUnion) {} 11886 11887 // The non-trivial C union type or the struct/union type that contains a 11888 // non-trivial C union. 11889 QualType OrigTy; 11890 SourceLocation OrigLoc; 11891 Sema::NonTrivialCUnionContext UseContext; 11892 Sema &S; 11893 }; 11894 11895 struct DiagNonTrivalCUnionCopyVisitor 11896 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11897 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11898 11899 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11900 Sema::NonTrivialCUnionContext UseContext, 11901 Sema &S) 11902 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11903 11904 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11905 const FieldDecl *FD, bool InNonTrivialUnion) { 11906 if (const auto *AT = S.Context.getAsArrayType(QT)) 11907 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11908 InNonTrivialUnion); 11909 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11910 } 11911 11912 void visitARCStrong(QualType QT, const FieldDecl *FD, 11913 bool InNonTrivialUnion) { 11914 if (InNonTrivialUnion) 11915 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11916 << 1 << 2 << QT << FD->getName(); 11917 } 11918 11919 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11920 if (InNonTrivialUnion) 11921 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11922 << 1 << 2 << QT << FD->getName(); 11923 } 11924 11925 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11926 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11927 if (RD->isUnion()) { 11928 if (OrigLoc.isValid()) { 11929 bool IsUnion = false; 11930 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11931 IsUnion = OrigRD->isUnion(); 11932 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11933 << 2 << OrigTy << IsUnion << UseContext; 11934 // Reset OrigLoc so that this diagnostic is emitted only once. 11935 OrigLoc = SourceLocation(); 11936 } 11937 InNonTrivialUnion = true; 11938 } 11939 11940 if (InNonTrivialUnion) 11941 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11942 << 0 << 2 << QT.getUnqualifiedType() << ""; 11943 11944 for (const FieldDecl *FD : RD->fields()) 11945 if (!shouldIgnoreForRecordTriviality(FD)) 11946 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11947 } 11948 11949 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 11950 const FieldDecl *FD, bool InNonTrivialUnion) {} 11951 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11952 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 11953 bool InNonTrivialUnion) {} 11954 11955 // The non-trivial C union type or the struct/union type that contains a 11956 // non-trivial C union. 11957 QualType OrigTy; 11958 SourceLocation OrigLoc; 11959 Sema::NonTrivialCUnionContext UseContext; 11960 Sema &S; 11961 }; 11962 11963 } // namespace 11964 11965 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 11966 NonTrivialCUnionContext UseContext, 11967 unsigned NonTrivialKind) { 11968 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11969 QT.hasNonTrivialToPrimitiveDestructCUnion() || 11970 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 11971 "shouldn't be called if type doesn't have a non-trivial C union"); 11972 11973 if ((NonTrivialKind & NTCUK_Init) && 11974 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11975 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 11976 .visit(QT, nullptr, false); 11977 if ((NonTrivialKind & NTCUK_Destruct) && 11978 QT.hasNonTrivialToPrimitiveDestructCUnion()) 11979 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 11980 .visit(QT, nullptr, false); 11981 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 11982 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 11983 .visit(QT, nullptr, false); 11984 } 11985 11986 /// AddInitializerToDecl - Adds the initializer Init to the 11987 /// declaration dcl. If DirectInit is true, this is C++ direct 11988 /// initialization rather than copy initialization. 11989 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11990 // If there is no declaration, there was an error parsing it. Just ignore 11991 // the initializer. 11992 if (!RealDecl || RealDecl->isInvalidDecl()) { 11993 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11994 return; 11995 } 11996 11997 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11998 // Pure-specifiers are handled in ActOnPureSpecifier. 11999 Diag(Method->getLocation(), diag::err_member_function_initialization) 12000 << Method->getDeclName() << Init->getSourceRange(); 12001 Method->setInvalidDecl(); 12002 return; 12003 } 12004 12005 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12006 if (!VDecl) { 12007 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 12008 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12009 RealDecl->setInvalidDecl(); 12010 return; 12011 } 12012 12013 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12014 if (VDecl->getType()->isUndeducedType()) { 12015 // Attempt typo correction early so that the type of the init expression can 12016 // be deduced based on the chosen correction if the original init contains a 12017 // TypoExpr. 12018 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12019 if (!Res.isUsable()) { 12020 // There are unresolved typos in Init, just drop them. 12021 // FIXME: improve the recovery strategy to preserve the Init. 12022 RealDecl->setInvalidDecl(); 12023 return; 12024 } 12025 if (Res.get()->containsErrors()) { 12026 // Invalidate the decl as we don't know the type for recovery-expr yet. 12027 RealDecl->setInvalidDecl(); 12028 VDecl->setInit(Res.get()); 12029 return; 12030 } 12031 Init = Res.get(); 12032 12033 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12034 return; 12035 } 12036 12037 // dllimport cannot be used on variable definitions. 12038 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12039 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12040 VDecl->setInvalidDecl(); 12041 return; 12042 } 12043 12044 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12045 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12046 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12047 VDecl->setInvalidDecl(); 12048 return; 12049 } 12050 12051 if (!VDecl->getType()->isDependentType()) { 12052 // A definition must end up with a complete type, which means it must be 12053 // complete with the restriction that an array type might be completed by 12054 // the initializer; note that later code assumes this restriction. 12055 QualType BaseDeclType = VDecl->getType(); 12056 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12057 BaseDeclType = Array->getElementType(); 12058 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12059 diag::err_typecheck_decl_incomplete_type)) { 12060 RealDecl->setInvalidDecl(); 12061 return; 12062 } 12063 12064 // The variable can not have an abstract class type. 12065 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12066 diag::err_abstract_type_in_decl, 12067 AbstractVariableType)) 12068 VDecl->setInvalidDecl(); 12069 } 12070 12071 // If adding the initializer will turn this declaration into a definition, 12072 // and we already have a definition for this variable, diagnose or otherwise 12073 // handle the situation. 12074 VarDecl *Def; 12075 if ((Def = VDecl->getDefinition()) && Def != VDecl && 12076 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12077 !VDecl->isThisDeclarationADemotedDefinition() && 12078 checkVarDeclRedefinition(Def, VDecl)) 12079 return; 12080 12081 if (getLangOpts().CPlusPlus) { 12082 // C++ [class.static.data]p4 12083 // If a static data member is of const integral or const 12084 // enumeration type, its declaration in the class definition can 12085 // specify a constant-initializer which shall be an integral 12086 // constant expression (5.19). In that case, the member can appear 12087 // in integral constant expressions. The member shall still be 12088 // defined in a namespace scope if it is used in the program and the 12089 // namespace scope definition shall not contain an initializer. 12090 // 12091 // We already performed a redefinition check above, but for static 12092 // data members we also need to check whether there was an in-class 12093 // declaration with an initializer. 12094 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12095 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12096 << VDecl->getDeclName(); 12097 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12098 diag::note_previous_initializer) 12099 << 0; 12100 return; 12101 } 12102 12103 if (VDecl->hasLocalStorage()) 12104 setFunctionHasBranchProtectedScope(); 12105 12106 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12107 VDecl->setInvalidDecl(); 12108 return; 12109 } 12110 } 12111 12112 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12113 // a kernel function cannot be initialized." 12114 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12115 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12116 VDecl->setInvalidDecl(); 12117 return; 12118 } 12119 12120 // The LoaderUninitialized attribute acts as a definition (of undef). 12121 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12122 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12123 VDecl->setInvalidDecl(); 12124 return; 12125 } 12126 12127 // Get the decls type and save a reference for later, since 12128 // CheckInitializerTypes may change it. 12129 QualType DclT = VDecl->getType(), SavT = DclT; 12130 12131 // Expressions default to 'id' when we're in a debugger 12132 // and we are assigning it to a variable of Objective-C pointer type. 12133 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12134 Init->getType() == Context.UnknownAnyTy) { 12135 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12136 if (Result.isInvalid()) { 12137 VDecl->setInvalidDecl(); 12138 return; 12139 } 12140 Init = Result.get(); 12141 } 12142 12143 // Perform the initialization. 12144 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12145 if (!VDecl->isInvalidDecl()) { 12146 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12147 InitializationKind Kind = InitializationKind::CreateForInit( 12148 VDecl->getLocation(), DirectInit, Init); 12149 12150 MultiExprArg Args = Init; 12151 if (CXXDirectInit) 12152 Args = MultiExprArg(CXXDirectInit->getExprs(), 12153 CXXDirectInit->getNumExprs()); 12154 12155 // Try to correct any TypoExprs in the initialization arguments. 12156 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12157 ExprResult Res = CorrectDelayedTyposInExpr( 12158 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12159 [this, Entity, Kind](Expr *E) { 12160 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12161 return Init.Failed() ? ExprError() : E; 12162 }); 12163 if (Res.isInvalid()) { 12164 VDecl->setInvalidDecl(); 12165 } else if (Res.get() != Args[Idx]) { 12166 Args[Idx] = Res.get(); 12167 } 12168 } 12169 if (VDecl->isInvalidDecl()) 12170 return; 12171 12172 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12173 /*TopLevelOfInitList=*/false, 12174 /*TreatUnavailableAsInvalid=*/false); 12175 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12176 if (Result.isInvalid()) { 12177 // If the provied initializer fails to initialize the var decl, 12178 // we attach a recovery expr for better recovery. 12179 auto RecoveryExpr = 12180 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12181 if (RecoveryExpr.get()) 12182 VDecl->setInit(RecoveryExpr.get()); 12183 return; 12184 } 12185 12186 Init = Result.getAs<Expr>(); 12187 } 12188 12189 // Check for self-references within variable initializers. 12190 // Variables declared within a function/method body (except for references) 12191 // are handled by a dataflow analysis. 12192 // This is undefined behavior in C++, but valid in C. 12193 if (getLangOpts().CPlusPlus) { 12194 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12195 VDecl->getType()->isReferenceType()) { 12196 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12197 } 12198 } 12199 12200 // If the type changed, it means we had an incomplete type that was 12201 // completed by the initializer. For example: 12202 // int ary[] = { 1, 3, 5 }; 12203 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12204 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12205 VDecl->setType(DclT); 12206 12207 if (!VDecl->isInvalidDecl()) { 12208 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12209 12210 if (VDecl->hasAttr<BlocksAttr>()) 12211 checkRetainCycles(VDecl, Init); 12212 12213 // It is safe to assign a weak reference into a strong variable. 12214 // Although this code can still have problems: 12215 // id x = self.weakProp; 12216 // id y = self.weakProp; 12217 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12218 // paths through the function. This should be revisited if 12219 // -Wrepeated-use-of-weak is made flow-sensitive. 12220 if (FunctionScopeInfo *FSI = getCurFunction()) 12221 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12222 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12223 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12224 Init->getBeginLoc())) 12225 FSI->markSafeWeakUse(Init); 12226 } 12227 12228 // The initialization is usually a full-expression. 12229 // 12230 // FIXME: If this is a braced initialization of an aggregate, it is not 12231 // an expression, and each individual field initializer is a separate 12232 // full-expression. For instance, in: 12233 // 12234 // struct Temp { ~Temp(); }; 12235 // struct S { S(Temp); }; 12236 // struct T { S a, b; } t = { Temp(), Temp() } 12237 // 12238 // we should destroy the first Temp before constructing the second. 12239 ExprResult Result = 12240 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12241 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12242 if (Result.isInvalid()) { 12243 VDecl->setInvalidDecl(); 12244 return; 12245 } 12246 Init = Result.get(); 12247 12248 // Attach the initializer to the decl. 12249 VDecl->setInit(Init); 12250 12251 if (VDecl->isLocalVarDecl()) { 12252 // Don't check the initializer if the declaration is malformed. 12253 if (VDecl->isInvalidDecl()) { 12254 // do nothing 12255 12256 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12257 // This is true even in C++ for OpenCL. 12258 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12259 CheckForConstantInitializer(Init, DclT); 12260 12261 // Otherwise, C++ does not restrict the initializer. 12262 } else if (getLangOpts().CPlusPlus) { 12263 // do nothing 12264 12265 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12266 // static storage duration shall be constant expressions or string literals. 12267 } else if (VDecl->getStorageClass() == SC_Static) { 12268 CheckForConstantInitializer(Init, DclT); 12269 12270 // C89 is stricter than C99 for aggregate initializers. 12271 // C89 6.5.7p3: All the expressions [...] in an initializer list 12272 // for an object that has aggregate or union type shall be 12273 // constant expressions. 12274 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12275 isa<InitListExpr>(Init)) { 12276 const Expr *Culprit; 12277 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12278 Diag(Culprit->getExprLoc(), 12279 diag::ext_aggregate_init_not_constant) 12280 << Culprit->getSourceRange(); 12281 } 12282 } 12283 12284 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12285 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12286 if (VDecl->hasLocalStorage()) 12287 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12288 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12289 VDecl->getLexicalDeclContext()->isRecord()) { 12290 // This is an in-class initialization for a static data member, e.g., 12291 // 12292 // struct S { 12293 // static const int value = 17; 12294 // }; 12295 12296 // C++ [class.mem]p4: 12297 // A member-declarator can contain a constant-initializer only 12298 // if it declares a static member (9.4) of const integral or 12299 // const enumeration type, see 9.4.2. 12300 // 12301 // C++11 [class.static.data]p3: 12302 // If a non-volatile non-inline const static data member is of integral 12303 // or enumeration type, its declaration in the class definition can 12304 // specify a brace-or-equal-initializer in which every initializer-clause 12305 // that is an assignment-expression is a constant expression. A static 12306 // data member of literal type can be declared in the class definition 12307 // with the constexpr specifier; if so, its declaration shall specify a 12308 // brace-or-equal-initializer in which every initializer-clause that is 12309 // an assignment-expression is a constant expression. 12310 12311 // Do nothing on dependent types. 12312 if (DclT->isDependentType()) { 12313 12314 // Allow any 'static constexpr' members, whether or not they are of literal 12315 // type. We separately check that every constexpr variable is of literal 12316 // type. 12317 } else if (VDecl->isConstexpr()) { 12318 12319 // Require constness. 12320 } else if (!DclT.isConstQualified()) { 12321 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12322 << Init->getSourceRange(); 12323 VDecl->setInvalidDecl(); 12324 12325 // We allow integer constant expressions in all cases. 12326 } else if (DclT->isIntegralOrEnumerationType()) { 12327 // Check whether the expression is a constant expression. 12328 SourceLocation Loc; 12329 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12330 // In C++11, a non-constexpr const static data member with an 12331 // in-class initializer cannot be volatile. 12332 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12333 else if (Init->isValueDependent()) 12334 ; // Nothing to check. 12335 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12336 ; // Ok, it's an ICE! 12337 else if (Init->getType()->isScopedEnumeralType() && 12338 Init->isCXX11ConstantExpr(Context)) 12339 ; // Ok, it is a scoped-enum constant expression. 12340 else if (Init->isEvaluatable(Context)) { 12341 // If we can constant fold the initializer through heroics, accept it, 12342 // but report this as a use of an extension for -pedantic. 12343 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12344 << Init->getSourceRange(); 12345 } else { 12346 // Otherwise, this is some crazy unknown case. Report the issue at the 12347 // location provided by the isIntegerConstantExpr failed check. 12348 Diag(Loc, diag::err_in_class_initializer_non_constant) 12349 << Init->getSourceRange(); 12350 VDecl->setInvalidDecl(); 12351 } 12352 12353 // We allow foldable floating-point constants as an extension. 12354 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12355 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12356 // it anyway and provide a fixit to add the 'constexpr'. 12357 if (getLangOpts().CPlusPlus11) { 12358 Diag(VDecl->getLocation(), 12359 diag::ext_in_class_initializer_float_type_cxx11) 12360 << DclT << Init->getSourceRange(); 12361 Diag(VDecl->getBeginLoc(), 12362 diag::note_in_class_initializer_float_type_cxx11) 12363 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12364 } else { 12365 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12366 << DclT << Init->getSourceRange(); 12367 12368 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12369 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12370 << Init->getSourceRange(); 12371 VDecl->setInvalidDecl(); 12372 } 12373 } 12374 12375 // Suggest adding 'constexpr' in C++11 for literal types. 12376 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12377 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12378 << DclT << Init->getSourceRange() 12379 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12380 VDecl->setConstexpr(true); 12381 12382 } else { 12383 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12384 << DclT << Init->getSourceRange(); 12385 VDecl->setInvalidDecl(); 12386 } 12387 } else if (VDecl->isFileVarDecl()) { 12388 // In C, extern is typically used to avoid tentative definitions when 12389 // declaring variables in headers, but adding an intializer makes it a 12390 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12391 // In C++, extern is often used to give implictly static const variables 12392 // external linkage, so don't warn in that case. If selectany is present, 12393 // this might be header code intended for C and C++ inclusion, so apply the 12394 // C++ rules. 12395 if (VDecl->getStorageClass() == SC_Extern && 12396 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12397 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12398 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12399 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12400 Diag(VDecl->getLocation(), diag::warn_extern_init); 12401 12402 // In Microsoft C++ mode, a const variable defined in namespace scope has 12403 // external linkage by default if the variable is declared with 12404 // __declspec(dllexport). 12405 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12406 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12407 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12408 VDecl->setStorageClass(SC_Extern); 12409 12410 // C99 6.7.8p4. All file scoped initializers need to be constant. 12411 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12412 CheckForConstantInitializer(Init, DclT); 12413 } 12414 12415 QualType InitType = Init->getType(); 12416 if (!InitType.isNull() && 12417 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12418 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12419 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12420 12421 // We will represent direct-initialization similarly to copy-initialization: 12422 // int x(1); -as-> int x = 1; 12423 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12424 // 12425 // Clients that want to distinguish between the two forms, can check for 12426 // direct initializer using VarDecl::getInitStyle(). 12427 // A major benefit is that clients that don't particularly care about which 12428 // exactly form was it (like the CodeGen) can handle both cases without 12429 // special case code. 12430 12431 // C++ 8.5p11: 12432 // The form of initialization (using parentheses or '=') is generally 12433 // insignificant, but does matter when the entity being initialized has a 12434 // class type. 12435 if (CXXDirectInit) { 12436 assert(DirectInit && "Call-style initializer must be direct init."); 12437 VDecl->setInitStyle(VarDecl::CallInit); 12438 } else if (DirectInit) { 12439 // This must be list-initialization. No other way is direct-initialization. 12440 VDecl->setInitStyle(VarDecl::ListInit); 12441 } 12442 12443 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12444 DeclsToCheckForDeferredDiags.push_back(VDecl); 12445 CheckCompleteVariableDeclaration(VDecl); 12446 } 12447 12448 /// ActOnInitializerError - Given that there was an error parsing an 12449 /// initializer for the given declaration, try to return to some form 12450 /// of sanity. 12451 void Sema::ActOnInitializerError(Decl *D) { 12452 // Our main concern here is re-establishing invariants like "a 12453 // variable's type is either dependent or complete". 12454 if (!D || D->isInvalidDecl()) return; 12455 12456 VarDecl *VD = dyn_cast<VarDecl>(D); 12457 if (!VD) return; 12458 12459 // Bindings are not usable if we can't make sense of the initializer. 12460 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12461 for (auto *BD : DD->bindings()) 12462 BD->setInvalidDecl(); 12463 12464 // Auto types are meaningless if we can't make sense of the initializer. 12465 if (VD->getType()->isUndeducedType()) { 12466 D->setInvalidDecl(); 12467 return; 12468 } 12469 12470 QualType Ty = VD->getType(); 12471 if (Ty->isDependentType()) return; 12472 12473 // Require a complete type. 12474 if (RequireCompleteType(VD->getLocation(), 12475 Context.getBaseElementType(Ty), 12476 diag::err_typecheck_decl_incomplete_type)) { 12477 VD->setInvalidDecl(); 12478 return; 12479 } 12480 12481 // Require a non-abstract type. 12482 if (RequireNonAbstractType(VD->getLocation(), Ty, 12483 diag::err_abstract_type_in_decl, 12484 AbstractVariableType)) { 12485 VD->setInvalidDecl(); 12486 return; 12487 } 12488 12489 // Don't bother complaining about constructors or destructors, 12490 // though. 12491 } 12492 12493 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12494 // If there is no declaration, there was an error parsing it. Just ignore it. 12495 if (!RealDecl) 12496 return; 12497 12498 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12499 QualType Type = Var->getType(); 12500 12501 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12502 if (isa<DecompositionDecl>(RealDecl)) { 12503 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12504 Var->setInvalidDecl(); 12505 return; 12506 } 12507 12508 if (Type->isUndeducedType() && 12509 DeduceVariableDeclarationType(Var, false, nullptr)) 12510 return; 12511 12512 // C++11 [class.static.data]p3: A static data member can be declared with 12513 // the constexpr specifier; if so, its declaration shall specify 12514 // a brace-or-equal-initializer. 12515 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12516 // the definition of a variable [...] or the declaration of a static data 12517 // member. 12518 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12519 !Var->isThisDeclarationADemotedDefinition()) { 12520 if (Var->isStaticDataMember()) { 12521 // C++1z removes the relevant rule; the in-class declaration is always 12522 // a definition there. 12523 if (!getLangOpts().CPlusPlus17 && 12524 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12525 Diag(Var->getLocation(), 12526 diag::err_constexpr_static_mem_var_requires_init) 12527 << Var; 12528 Var->setInvalidDecl(); 12529 return; 12530 } 12531 } else { 12532 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12533 Var->setInvalidDecl(); 12534 return; 12535 } 12536 } 12537 12538 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12539 // be initialized. 12540 if (!Var->isInvalidDecl() && 12541 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12542 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12543 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12544 Var->setInvalidDecl(); 12545 return; 12546 } 12547 12548 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12549 if (Var->getStorageClass() == SC_Extern) { 12550 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12551 << Var; 12552 Var->setInvalidDecl(); 12553 return; 12554 } 12555 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12556 diag::err_typecheck_decl_incomplete_type)) { 12557 Var->setInvalidDecl(); 12558 return; 12559 } 12560 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12561 if (!RD->hasTrivialDefaultConstructor()) { 12562 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12563 Var->setInvalidDecl(); 12564 return; 12565 } 12566 } 12567 } 12568 12569 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12570 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12571 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12572 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12573 NTCUC_DefaultInitializedObject, NTCUK_Init); 12574 12575 12576 switch (DefKind) { 12577 case VarDecl::Definition: 12578 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12579 break; 12580 12581 // We have an out-of-line definition of a static data member 12582 // that has an in-class initializer, so we type-check this like 12583 // a declaration. 12584 // 12585 LLVM_FALLTHROUGH; 12586 12587 case VarDecl::DeclarationOnly: 12588 // It's only a declaration. 12589 12590 // Block scope. C99 6.7p7: If an identifier for an object is 12591 // declared with no linkage (C99 6.2.2p6), the type for the 12592 // object shall be complete. 12593 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12594 !Var->hasLinkage() && !Var->isInvalidDecl() && 12595 RequireCompleteType(Var->getLocation(), Type, 12596 diag::err_typecheck_decl_incomplete_type)) 12597 Var->setInvalidDecl(); 12598 12599 // Make sure that the type is not abstract. 12600 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12601 RequireNonAbstractType(Var->getLocation(), Type, 12602 diag::err_abstract_type_in_decl, 12603 AbstractVariableType)) 12604 Var->setInvalidDecl(); 12605 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12606 Var->getStorageClass() == SC_PrivateExtern) { 12607 Diag(Var->getLocation(), diag::warn_private_extern); 12608 Diag(Var->getLocation(), diag::note_private_extern); 12609 } 12610 12611 if (Context.getTargetInfo().allowDebugInfoForExternalVar() && 12612 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12613 ExternalDeclarations.push_back(Var); 12614 12615 return; 12616 12617 case VarDecl::TentativeDefinition: 12618 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12619 // object that has file scope without an initializer, and without a 12620 // storage-class specifier or with the storage-class specifier "static", 12621 // constitutes a tentative definition. Note: A tentative definition with 12622 // external linkage is valid (C99 6.2.2p5). 12623 if (!Var->isInvalidDecl()) { 12624 if (const IncompleteArrayType *ArrayT 12625 = Context.getAsIncompleteArrayType(Type)) { 12626 if (RequireCompleteSizedType( 12627 Var->getLocation(), ArrayT->getElementType(), 12628 diag::err_array_incomplete_or_sizeless_type)) 12629 Var->setInvalidDecl(); 12630 } else if (Var->getStorageClass() == SC_Static) { 12631 // C99 6.9.2p3: If the declaration of an identifier for an object is 12632 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12633 // declared type shall not be an incomplete type. 12634 // NOTE: code such as the following 12635 // static struct s; 12636 // struct s { int a; }; 12637 // is accepted by gcc. Hence here we issue a warning instead of 12638 // an error and we do not invalidate the static declaration. 12639 // NOTE: to avoid multiple warnings, only check the first declaration. 12640 if (Var->isFirstDecl()) 12641 RequireCompleteType(Var->getLocation(), Type, 12642 diag::ext_typecheck_decl_incomplete_type); 12643 } 12644 } 12645 12646 // Record the tentative definition; we're done. 12647 if (!Var->isInvalidDecl()) 12648 TentativeDefinitions.push_back(Var); 12649 return; 12650 } 12651 12652 // Provide a specific diagnostic for uninitialized variable 12653 // definitions with incomplete array type. 12654 if (Type->isIncompleteArrayType()) { 12655 Diag(Var->getLocation(), 12656 diag::err_typecheck_incomplete_array_needs_initializer); 12657 Var->setInvalidDecl(); 12658 return; 12659 } 12660 12661 // Provide a specific diagnostic for uninitialized variable 12662 // definitions with reference type. 12663 if (Type->isReferenceType()) { 12664 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12665 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 12666 Var->setInvalidDecl(); 12667 return; 12668 } 12669 12670 // Do not attempt to type-check the default initializer for a 12671 // variable with dependent type. 12672 if (Type->isDependentType()) 12673 return; 12674 12675 if (Var->isInvalidDecl()) 12676 return; 12677 12678 if (!Var->hasAttr<AliasAttr>()) { 12679 if (RequireCompleteType(Var->getLocation(), 12680 Context.getBaseElementType(Type), 12681 diag::err_typecheck_decl_incomplete_type)) { 12682 Var->setInvalidDecl(); 12683 return; 12684 } 12685 } else { 12686 return; 12687 } 12688 12689 // The variable can not have an abstract class type. 12690 if (RequireNonAbstractType(Var->getLocation(), Type, 12691 diag::err_abstract_type_in_decl, 12692 AbstractVariableType)) { 12693 Var->setInvalidDecl(); 12694 return; 12695 } 12696 12697 // Check for jumps past the implicit initializer. C++0x 12698 // clarifies that this applies to a "variable with automatic 12699 // storage duration", not a "local variable". 12700 // C++11 [stmt.dcl]p3 12701 // A program that jumps from a point where a variable with automatic 12702 // storage duration is not in scope to a point where it is in scope is 12703 // ill-formed unless the variable has scalar type, class type with a 12704 // trivial default constructor and a trivial destructor, a cv-qualified 12705 // version of one of these types, or an array of one of the preceding 12706 // types and is declared without an initializer. 12707 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12708 if (const RecordType *Record 12709 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12710 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12711 // Mark the function (if we're in one) for further checking even if the 12712 // looser rules of C++11 do not require such checks, so that we can 12713 // diagnose incompatibilities with C++98. 12714 if (!CXXRecord->isPOD()) 12715 setFunctionHasBranchProtectedScope(); 12716 } 12717 } 12718 // In OpenCL, we can't initialize objects in the __local address space, 12719 // even implicitly, so don't synthesize an implicit initializer. 12720 if (getLangOpts().OpenCL && 12721 Var->getType().getAddressSpace() == LangAS::opencl_local) 12722 return; 12723 // C++03 [dcl.init]p9: 12724 // If no initializer is specified for an object, and the 12725 // object is of (possibly cv-qualified) non-POD class type (or 12726 // array thereof), the object shall be default-initialized; if 12727 // the object is of const-qualified type, the underlying class 12728 // type shall have a user-declared default 12729 // constructor. Otherwise, if no initializer is specified for 12730 // a non- static object, the object and its subobjects, if 12731 // any, have an indeterminate initial value); if the object 12732 // or any of its subobjects are of const-qualified type, the 12733 // program is ill-formed. 12734 // C++0x [dcl.init]p11: 12735 // If no initializer is specified for an object, the object is 12736 // default-initialized; [...]. 12737 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12738 InitializationKind Kind 12739 = InitializationKind::CreateDefault(Var->getLocation()); 12740 12741 InitializationSequence InitSeq(*this, Entity, Kind, None); 12742 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12743 12744 if (Init.get()) { 12745 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12746 // This is important for template substitution. 12747 Var->setInitStyle(VarDecl::CallInit); 12748 } else if (Init.isInvalid()) { 12749 // If default-init fails, attach a recovery-expr initializer to track 12750 // that initialization was attempted and failed. 12751 auto RecoveryExpr = 12752 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12753 if (RecoveryExpr.get()) 12754 Var->setInit(RecoveryExpr.get()); 12755 } 12756 12757 CheckCompleteVariableDeclaration(Var); 12758 } 12759 } 12760 12761 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12762 // If there is no declaration, there was an error parsing it. Ignore it. 12763 if (!D) 12764 return; 12765 12766 VarDecl *VD = dyn_cast<VarDecl>(D); 12767 if (!VD) { 12768 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12769 D->setInvalidDecl(); 12770 return; 12771 } 12772 12773 VD->setCXXForRangeDecl(true); 12774 12775 // for-range-declaration cannot be given a storage class specifier. 12776 int Error = -1; 12777 switch (VD->getStorageClass()) { 12778 case SC_None: 12779 break; 12780 case SC_Extern: 12781 Error = 0; 12782 break; 12783 case SC_Static: 12784 Error = 1; 12785 break; 12786 case SC_PrivateExtern: 12787 Error = 2; 12788 break; 12789 case SC_Auto: 12790 Error = 3; 12791 break; 12792 case SC_Register: 12793 Error = 4; 12794 break; 12795 } 12796 12797 // for-range-declaration cannot be given a storage class specifier con't. 12798 switch (VD->getTSCSpec()) { 12799 case TSCS_thread_local: 12800 Error = 6; 12801 break; 12802 case TSCS___thread: 12803 case TSCS__Thread_local: 12804 case TSCS_unspecified: 12805 break; 12806 } 12807 12808 if (Error != -1) { 12809 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12810 << VD << Error; 12811 D->setInvalidDecl(); 12812 } 12813 } 12814 12815 StmtResult 12816 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12817 IdentifierInfo *Ident, 12818 ParsedAttributes &Attrs, 12819 SourceLocation AttrEnd) { 12820 // C++1y [stmt.iter]p1: 12821 // A range-based for statement of the form 12822 // for ( for-range-identifier : for-range-initializer ) statement 12823 // is equivalent to 12824 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12825 DeclSpec DS(Attrs.getPool().getFactory()); 12826 12827 const char *PrevSpec; 12828 unsigned DiagID; 12829 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12830 getPrintingPolicy()); 12831 12832 Declarator D(DS, DeclaratorContext::ForInit); 12833 D.SetIdentifier(Ident, IdentLoc); 12834 D.takeAttributes(Attrs, AttrEnd); 12835 12836 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12837 IdentLoc); 12838 Decl *Var = ActOnDeclarator(S, D); 12839 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12840 FinalizeDeclaration(Var); 12841 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12842 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12843 } 12844 12845 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12846 if (var->isInvalidDecl()) return; 12847 12848 if (getLangOpts().OpenCL) { 12849 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12850 // initialiser 12851 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12852 !var->hasInit()) { 12853 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12854 << 1 /*Init*/; 12855 var->setInvalidDecl(); 12856 return; 12857 } 12858 } 12859 12860 // In Objective-C, don't allow jumps past the implicit initialization of a 12861 // local retaining variable. 12862 if (getLangOpts().ObjC && 12863 var->hasLocalStorage()) { 12864 switch (var->getType().getObjCLifetime()) { 12865 case Qualifiers::OCL_None: 12866 case Qualifiers::OCL_ExplicitNone: 12867 case Qualifiers::OCL_Autoreleasing: 12868 break; 12869 12870 case Qualifiers::OCL_Weak: 12871 case Qualifiers::OCL_Strong: 12872 setFunctionHasBranchProtectedScope(); 12873 break; 12874 } 12875 } 12876 12877 if (var->hasLocalStorage() && 12878 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12879 setFunctionHasBranchProtectedScope(); 12880 12881 // Warn about externally-visible variables being defined without a 12882 // prior declaration. We only want to do this for global 12883 // declarations, but we also specifically need to avoid doing it for 12884 // class members because the linkage of an anonymous class can 12885 // change if it's later given a typedef name. 12886 if (var->isThisDeclarationADefinition() && 12887 var->getDeclContext()->getRedeclContext()->isFileContext() && 12888 var->isExternallyVisible() && var->hasLinkage() && 12889 !var->isInline() && !var->getDescribedVarTemplate() && 12890 !isa<VarTemplatePartialSpecializationDecl>(var) && 12891 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12892 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12893 var->getLocation())) { 12894 // Find a previous declaration that's not a definition. 12895 VarDecl *prev = var->getPreviousDecl(); 12896 while (prev && prev->isThisDeclarationADefinition()) 12897 prev = prev->getPreviousDecl(); 12898 12899 if (!prev) { 12900 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12901 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12902 << /* variable */ 0; 12903 } 12904 } 12905 12906 // Cache the result of checking for constant initialization. 12907 Optional<bool> CacheHasConstInit; 12908 const Expr *CacheCulprit = nullptr; 12909 auto checkConstInit = [&]() mutable { 12910 if (!CacheHasConstInit) 12911 CacheHasConstInit = var->getInit()->isConstantInitializer( 12912 Context, var->getType()->isReferenceType(), &CacheCulprit); 12913 return *CacheHasConstInit; 12914 }; 12915 12916 if (var->getTLSKind() == VarDecl::TLS_Static) { 12917 if (var->getType().isDestructedType()) { 12918 // GNU C++98 edits for __thread, [basic.start.term]p3: 12919 // The type of an object with thread storage duration shall not 12920 // have a non-trivial destructor. 12921 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12922 if (getLangOpts().CPlusPlus11) 12923 Diag(var->getLocation(), diag::note_use_thread_local); 12924 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12925 if (!checkConstInit()) { 12926 // GNU C++98 edits for __thread, [basic.start.init]p4: 12927 // An object of thread storage duration shall not require dynamic 12928 // initialization. 12929 // FIXME: Need strict checking here. 12930 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12931 << CacheCulprit->getSourceRange(); 12932 if (getLangOpts().CPlusPlus11) 12933 Diag(var->getLocation(), diag::note_use_thread_local); 12934 } 12935 } 12936 } 12937 12938 // Apply section attributes and pragmas to global variables. 12939 bool GlobalStorage = var->hasGlobalStorage(); 12940 if (GlobalStorage && var->isThisDeclarationADefinition() && 12941 !inTemplateInstantiation()) { 12942 PragmaStack<StringLiteral *> *Stack = nullptr; 12943 int SectionFlags = ASTContext::PSF_Read; 12944 if (var->getType().isConstQualified()) 12945 Stack = &ConstSegStack; 12946 else if (!var->getInit()) { 12947 Stack = &BSSSegStack; 12948 SectionFlags |= ASTContext::PSF_Write; 12949 } else { 12950 Stack = &DataSegStack; 12951 SectionFlags |= ASTContext::PSF_Write; 12952 } 12953 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 12954 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 12955 SectionFlags |= ASTContext::PSF_Implicit; 12956 UnifySection(SA->getName(), SectionFlags, var); 12957 } else if (Stack->CurrentValue) { 12958 SectionFlags |= ASTContext::PSF_Implicit; 12959 auto SectionName = Stack->CurrentValue->getString(); 12960 var->addAttr(SectionAttr::CreateImplicit( 12961 Context, SectionName, Stack->CurrentPragmaLocation, 12962 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 12963 if (UnifySection(SectionName, SectionFlags, var)) 12964 var->dropAttr<SectionAttr>(); 12965 } 12966 12967 // Apply the init_seg attribute if this has an initializer. If the 12968 // initializer turns out to not be dynamic, we'll end up ignoring this 12969 // attribute. 12970 if (CurInitSeg && var->getInit()) 12971 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 12972 CurInitSegLoc, 12973 AttributeCommonInfo::AS_Pragma)); 12974 } 12975 12976 if (!var->getType()->isStructureType() && var->hasInit() && 12977 isa<InitListExpr>(var->getInit())) { 12978 const auto *ILE = cast<InitListExpr>(var->getInit()); 12979 unsigned NumInits = ILE->getNumInits(); 12980 if (NumInits > 2) 12981 for (unsigned I = 0; I < NumInits; ++I) { 12982 const auto *Init = ILE->getInit(I); 12983 if (!Init) 12984 break; 12985 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 12986 if (!SL) 12987 break; 12988 12989 unsigned NumConcat = SL->getNumConcatenated(); 12990 // Diagnose missing comma in string array initialization. 12991 // Do not warn when all the elements in the initializer are concatenated 12992 // together. Do not warn for macros too. 12993 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 12994 bool OnlyOneMissingComma = true; 12995 for (unsigned J = I + 1; J < NumInits; ++J) { 12996 const auto *Init = ILE->getInit(J); 12997 if (!Init) 12998 break; 12999 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13000 if (!SLJ || SLJ->getNumConcatenated() > 1) { 13001 OnlyOneMissingComma = false; 13002 break; 13003 } 13004 } 13005 13006 if (OnlyOneMissingComma) { 13007 SmallVector<FixItHint, 1> Hints; 13008 for (unsigned i = 0; i < NumConcat - 1; ++i) 13009 Hints.push_back(FixItHint::CreateInsertion( 13010 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13011 13012 Diag(SL->getStrTokenLoc(1), 13013 diag::warn_concatenated_literal_array_init) 13014 << Hints; 13015 Diag(SL->getBeginLoc(), 13016 diag::note_concatenated_string_literal_silence); 13017 } 13018 // In any case, stop now. 13019 break; 13020 } 13021 } 13022 } 13023 13024 // All the following checks are C++ only. 13025 if (!getLangOpts().CPlusPlus) { 13026 // If this variable must be emitted, add it as an initializer for the 13027 // current module. 13028 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13029 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13030 return; 13031 } 13032 13033 QualType type = var->getType(); 13034 13035 if (var->hasAttr<BlocksAttr>()) 13036 getCurFunction()->addByrefBlockVar(var); 13037 13038 Expr *Init = var->getInit(); 13039 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13040 QualType baseType = Context.getBaseElementType(type); 13041 13042 // Check whether the initializer is sufficiently constant. 13043 if (!type->isDependentType() && Init && !Init->isValueDependent() && 13044 (GlobalStorage || var->isConstexpr() || 13045 var->mightBeUsableInConstantExpressions(Context))) { 13046 // If this variable might have a constant initializer or might be usable in 13047 // constant expressions, check whether or not it actually is now. We can't 13048 // do this lazily, because the result might depend on things that change 13049 // later, such as which constexpr functions happen to be defined. 13050 SmallVector<PartialDiagnosticAt, 8> Notes; 13051 bool HasConstInit; 13052 if (!getLangOpts().CPlusPlus11) { 13053 // Prior to C++11, in contexts where a constant initializer is required, 13054 // the set of valid constant initializers is described by syntactic rules 13055 // in [expr.const]p2-6. 13056 // FIXME: Stricter checking for these rules would be useful for constinit / 13057 // -Wglobal-constructors. 13058 HasConstInit = checkConstInit(); 13059 13060 // Compute and cache the constant value, and remember that we have a 13061 // constant initializer. 13062 if (HasConstInit) { 13063 (void)var->checkForConstantInitialization(Notes); 13064 Notes.clear(); 13065 } else if (CacheCulprit) { 13066 Notes.emplace_back(CacheCulprit->getExprLoc(), 13067 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13068 Notes.back().second << CacheCulprit->getSourceRange(); 13069 } 13070 } else { 13071 // Evaluate the initializer to see if it's a constant initializer. 13072 HasConstInit = var->checkForConstantInitialization(Notes); 13073 } 13074 13075 if (HasConstInit) { 13076 // FIXME: Consider replacing the initializer with a ConstantExpr. 13077 } else if (var->isConstexpr()) { 13078 SourceLocation DiagLoc = var->getLocation(); 13079 // If the note doesn't add any useful information other than a source 13080 // location, fold it into the primary diagnostic. 13081 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13082 diag::note_invalid_subexpr_in_const_expr) { 13083 DiagLoc = Notes[0].first; 13084 Notes.clear(); 13085 } 13086 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13087 << var << Init->getSourceRange(); 13088 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13089 Diag(Notes[I].first, Notes[I].second); 13090 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13091 auto *Attr = var->getAttr<ConstInitAttr>(); 13092 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13093 << Init->getSourceRange(); 13094 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13095 << Attr->getRange() << Attr->isConstinit(); 13096 for (auto &it : Notes) 13097 Diag(it.first, it.second); 13098 } else if (IsGlobal && 13099 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13100 var->getLocation())) { 13101 // Warn about globals which don't have a constant initializer. Don't 13102 // warn about globals with a non-trivial destructor because we already 13103 // warned about them. 13104 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13105 if (!(RD && !RD->hasTrivialDestructor())) { 13106 // checkConstInit() here permits trivial default initialization even in 13107 // C++11 onwards, where such an initializer is not a constant initializer 13108 // but nonetheless doesn't require a global constructor. 13109 if (!checkConstInit()) 13110 Diag(var->getLocation(), diag::warn_global_constructor) 13111 << Init->getSourceRange(); 13112 } 13113 } 13114 } 13115 13116 // Require the destructor. 13117 if (!type->isDependentType()) 13118 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13119 FinalizeVarWithDestructor(var, recordType); 13120 13121 // If this variable must be emitted, add it as an initializer for the current 13122 // module. 13123 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13124 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13125 13126 // Build the bindings if this is a structured binding declaration. 13127 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13128 CheckCompleteDecompositionDeclaration(DD); 13129 } 13130 13131 /// Determines if a variable's alignment is dependent. 13132 static bool hasDependentAlignment(VarDecl *VD) { 13133 if (VD->getType()->isDependentType()) 13134 return true; 13135 for (auto *I : VD->specific_attrs<AlignedAttr>()) 13136 if (I->isAlignmentDependent()) 13137 return true; 13138 return false; 13139 } 13140 13141 /// Check if VD needs to be dllexport/dllimport due to being in a 13142 /// dllexport/import function. 13143 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13144 assert(VD->isStaticLocal()); 13145 13146 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13147 13148 // Find outermost function when VD is in lambda function. 13149 while (FD && !getDLLAttr(FD) && 13150 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13151 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13152 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13153 } 13154 13155 if (!FD) 13156 return; 13157 13158 // Static locals inherit dll attributes from their function. 13159 if (Attr *A = getDLLAttr(FD)) { 13160 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13161 NewAttr->setInherited(true); 13162 VD->addAttr(NewAttr); 13163 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13164 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13165 NewAttr->setInherited(true); 13166 VD->addAttr(NewAttr); 13167 13168 // Export this function to enforce exporting this static variable even 13169 // if it is not used in this compilation unit. 13170 if (!FD->hasAttr<DLLExportAttr>()) 13171 FD->addAttr(NewAttr); 13172 13173 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13174 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13175 NewAttr->setInherited(true); 13176 VD->addAttr(NewAttr); 13177 } 13178 } 13179 13180 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13181 /// any semantic actions necessary after any initializer has been attached. 13182 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13183 // Note that we are no longer parsing the initializer for this declaration. 13184 ParsingInitForAutoVars.erase(ThisDecl); 13185 13186 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13187 if (!VD) 13188 return; 13189 13190 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13191 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13192 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13193 if (PragmaClangBSSSection.Valid) 13194 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13195 Context, PragmaClangBSSSection.SectionName, 13196 PragmaClangBSSSection.PragmaLocation, 13197 AttributeCommonInfo::AS_Pragma)); 13198 if (PragmaClangDataSection.Valid) 13199 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13200 Context, PragmaClangDataSection.SectionName, 13201 PragmaClangDataSection.PragmaLocation, 13202 AttributeCommonInfo::AS_Pragma)); 13203 if (PragmaClangRodataSection.Valid) 13204 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13205 Context, PragmaClangRodataSection.SectionName, 13206 PragmaClangRodataSection.PragmaLocation, 13207 AttributeCommonInfo::AS_Pragma)); 13208 if (PragmaClangRelroSection.Valid) 13209 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13210 Context, PragmaClangRelroSection.SectionName, 13211 PragmaClangRelroSection.PragmaLocation, 13212 AttributeCommonInfo::AS_Pragma)); 13213 } 13214 13215 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13216 for (auto *BD : DD->bindings()) { 13217 FinalizeDeclaration(BD); 13218 } 13219 } 13220 13221 checkAttributesAfterMerging(*this, *VD); 13222 13223 // Perform TLS alignment check here after attributes attached to the variable 13224 // which may affect the alignment have been processed. Only perform the check 13225 // if the target has a maximum TLS alignment (zero means no constraints). 13226 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13227 // Protect the check so that it's not performed on dependent types and 13228 // dependent alignments (we can't determine the alignment in that case). 13229 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 13230 !VD->isInvalidDecl()) { 13231 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13232 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13233 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13234 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13235 << (unsigned)MaxAlignChars.getQuantity(); 13236 } 13237 } 13238 } 13239 13240 if (VD->isStaticLocal()) 13241 CheckStaticLocalForDllExport(VD); 13242 13243 // Perform check for initializers of device-side global variables. 13244 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13245 // 7.5). We must also apply the same checks to all __shared__ 13246 // variables whether they are local or not. CUDA also allows 13247 // constant initializers for __constant__ and __device__ variables. 13248 if (getLangOpts().CUDA) 13249 checkAllowedCUDAInitializer(VD); 13250 13251 // Grab the dllimport or dllexport attribute off of the VarDecl. 13252 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13253 13254 // Imported static data members cannot be defined out-of-line. 13255 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13256 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13257 VD->isThisDeclarationADefinition()) { 13258 // We allow definitions of dllimport class template static data members 13259 // with a warning. 13260 CXXRecordDecl *Context = 13261 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13262 bool IsClassTemplateMember = 13263 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13264 Context->getDescribedClassTemplate(); 13265 13266 Diag(VD->getLocation(), 13267 IsClassTemplateMember 13268 ? diag::warn_attribute_dllimport_static_field_definition 13269 : diag::err_attribute_dllimport_static_field_definition); 13270 Diag(IA->getLocation(), diag::note_attribute); 13271 if (!IsClassTemplateMember) 13272 VD->setInvalidDecl(); 13273 } 13274 } 13275 13276 // dllimport/dllexport variables cannot be thread local, their TLS index 13277 // isn't exported with the variable. 13278 if (DLLAttr && VD->getTLSKind()) { 13279 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13280 if (F && getDLLAttr(F)) { 13281 assert(VD->isStaticLocal()); 13282 // But if this is a static local in a dlimport/dllexport function, the 13283 // function will never be inlined, which means the var would never be 13284 // imported, so having it marked import/export is safe. 13285 } else { 13286 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13287 << DLLAttr; 13288 VD->setInvalidDecl(); 13289 } 13290 } 13291 13292 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13293 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13294 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 13295 VD->dropAttr<UsedAttr>(); 13296 } 13297 } 13298 13299 const DeclContext *DC = VD->getDeclContext(); 13300 // If there's a #pragma GCC visibility in scope, and this isn't a class 13301 // member, set the visibility of this variable. 13302 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13303 AddPushedVisibilityAttribute(VD); 13304 13305 // FIXME: Warn on unused var template partial specializations. 13306 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13307 MarkUnusedFileScopedDecl(VD); 13308 13309 // Now we have parsed the initializer and can update the table of magic 13310 // tag values. 13311 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13312 !VD->getType()->isIntegralOrEnumerationType()) 13313 return; 13314 13315 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13316 const Expr *MagicValueExpr = VD->getInit(); 13317 if (!MagicValueExpr) { 13318 continue; 13319 } 13320 Optional<llvm::APSInt> MagicValueInt; 13321 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13322 Diag(I->getRange().getBegin(), 13323 diag::err_type_tag_for_datatype_not_ice) 13324 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13325 continue; 13326 } 13327 if (MagicValueInt->getActiveBits() > 64) { 13328 Diag(I->getRange().getBegin(), 13329 diag::err_type_tag_for_datatype_too_large) 13330 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13331 continue; 13332 } 13333 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13334 RegisterTypeTagForDatatype(I->getArgumentKind(), 13335 MagicValue, 13336 I->getMatchingCType(), 13337 I->getLayoutCompatible(), 13338 I->getMustBeNull()); 13339 } 13340 } 13341 13342 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13343 auto *VD = dyn_cast<VarDecl>(DD); 13344 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13345 } 13346 13347 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13348 ArrayRef<Decl *> Group) { 13349 SmallVector<Decl*, 8> Decls; 13350 13351 if (DS.isTypeSpecOwned()) 13352 Decls.push_back(DS.getRepAsDecl()); 13353 13354 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13355 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13356 bool DiagnosedMultipleDecomps = false; 13357 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13358 bool DiagnosedNonDeducedAuto = false; 13359 13360 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13361 if (Decl *D = Group[i]) { 13362 // For declarators, there are some additional syntactic-ish checks we need 13363 // to perform. 13364 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13365 if (!FirstDeclaratorInGroup) 13366 FirstDeclaratorInGroup = DD; 13367 if (!FirstDecompDeclaratorInGroup) 13368 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13369 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13370 !hasDeducedAuto(DD)) 13371 FirstNonDeducedAutoInGroup = DD; 13372 13373 if (FirstDeclaratorInGroup != DD) { 13374 // A decomposition declaration cannot be combined with any other 13375 // declaration in the same group. 13376 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13377 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13378 diag::err_decomp_decl_not_alone) 13379 << FirstDeclaratorInGroup->getSourceRange() 13380 << DD->getSourceRange(); 13381 DiagnosedMultipleDecomps = true; 13382 } 13383 13384 // A declarator that uses 'auto' in any way other than to declare a 13385 // variable with a deduced type cannot be combined with any other 13386 // declarator in the same group. 13387 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13388 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13389 diag::err_auto_non_deduced_not_alone) 13390 << FirstNonDeducedAutoInGroup->getType() 13391 ->hasAutoForTrailingReturnType() 13392 << FirstDeclaratorInGroup->getSourceRange() 13393 << DD->getSourceRange(); 13394 DiagnosedNonDeducedAuto = true; 13395 } 13396 } 13397 } 13398 13399 Decls.push_back(D); 13400 } 13401 } 13402 13403 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13404 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13405 handleTagNumbering(Tag, S); 13406 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13407 getLangOpts().CPlusPlus) 13408 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13409 } 13410 } 13411 13412 return BuildDeclaratorGroup(Decls); 13413 } 13414 13415 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13416 /// group, performing any necessary semantic checking. 13417 Sema::DeclGroupPtrTy 13418 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13419 // C++14 [dcl.spec.auto]p7: (DR1347) 13420 // If the type that replaces the placeholder type is not the same in each 13421 // deduction, the program is ill-formed. 13422 if (Group.size() > 1) { 13423 QualType Deduced; 13424 VarDecl *DeducedDecl = nullptr; 13425 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13426 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13427 if (!D || D->isInvalidDecl()) 13428 break; 13429 DeducedType *DT = D->getType()->getContainedDeducedType(); 13430 if (!DT || DT->getDeducedType().isNull()) 13431 continue; 13432 if (Deduced.isNull()) { 13433 Deduced = DT->getDeducedType(); 13434 DeducedDecl = D; 13435 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13436 auto *AT = dyn_cast<AutoType>(DT); 13437 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13438 diag::err_auto_different_deductions) 13439 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13440 << DeducedDecl->getDeclName() << DT->getDeducedType() 13441 << D->getDeclName(); 13442 if (DeducedDecl->hasInit()) 13443 Dia << DeducedDecl->getInit()->getSourceRange(); 13444 if (D->getInit()) 13445 Dia << D->getInit()->getSourceRange(); 13446 D->setInvalidDecl(); 13447 break; 13448 } 13449 } 13450 } 13451 13452 ActOnDocumentableDecls(Group); 13453 13454 return DeclGroupPtrTy::make( 13455 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13456 } 13457 13458 void Sema::ActOnDocumentableDecl(Decl *D) { 13459 ActOnDocumentableDecls(D); 13460 } 13461 13462 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13463 // Don't parse the comment if Doxygen diagnostics are ignored. 13464 if (Group.empty() || !Group[0]) 13465 return; 13466 13467 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13468 Group[0]->getLocation()) && 13469 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13470 Group[0]->getLocation())) 13471 return; 13472 13473 if (Group.size() >= 2) { 13474 // This is a decl group. Normally it will contain only declarations 13475 // produced from declarator list. But in case we have any definitions or 13476 // additional declaration references: 13477 // 'typedef struct S {} S;' 13478 // 'typedef struct S *S;' 13479 // 'struct S *pS;' 13480 // FinalizeDeclaratorGroup adds these as separate declarations. 13481 Decl *MaybeTagDecl = Group[0]; 13482 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13483 Group = Group.slice(1); 13484 } 13485 } 13486 13487 // FIMXE: We assume every Decl in the group is in the same file. 13488 // This is false when preprocessor constructs the group from decls in 13489 // different files (e. g. macros or #include). 13490 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13491 } 13492 13493 /// Common checks for a parameter-declaration that should apply to both function 13494 /// parameters and non-type template parameters. 13495 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13496 // Check that there are no default arguments inside the type of this 13497 // parameter. 13498 if (getLangOpts().CPlusPlus) 13499 CheckExtraCXXDefaultArguments(D); 13500 13501 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13502 if (D.getCXXScopeSpec().isSet()) { 13503 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13504 << D.getCXXScopeSpec().getRange(); 13505 } 13506 13507 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13508 // simple identifier except [...irrelevant cases...]. 13509 switch (D.getName().getKind()) { 13510 case UnqualifiedIdKind::IK_Identifier: 13511 break; 13512 13513 case UnqualifiedIdKind::IK_OperatorFunctionId: 13514 case UnqualifiedIdKind::IK_ConversionFunctionId: 13515 case UnqualifiedIdKind::IK_LiteralOperatorId: 13516 case UnqualifiedIdKind::IK_ConstructorName: 13517 case UnqualifiedIdKind::IK_DestructorName: 13518 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13519 case UnqualifiedIdKind::IK_DeductionGuideName: 13520 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13521 << GetNameForDeclarator(D).getName(); 13522 break; 13523 13524 case UnqualifiedIdKind::IK_TemplateId: 13525 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13526 // GetNameForDeclarator would not produce a useful name in this case. 13527 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13528 break; 13529 } 13530 } 13531 13532 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13533 /// to introduce parameters into function prototype scope. 13534 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13535 const DeclSpec &DS = D.getDeclSpec(); 13536 13537 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13538 13539 // C++03 [dcl.stc]p2 also permits 'auto'. 13540 StorageClass SC = SC_None; 13541 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13542 SC = SC_Register; 13543 // In C++11, the 'register' storage class specifier is deprecated. 13544 // In C++17, it is not allowed, but we tolerate it as an extension. 13545 if (getLangOpts().CPlusPlus11) { 13546 Diag(DS.getStorageClassSpecLoc(), 13547 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13548 : diag::warn_deprecated_register) 13549 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13550 } 13551 } else if (getLangOpts().CPlusPlus && 13552 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13553 SC = SC_Auto; 13554 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13555 Diag(DS.getStorageClassSpecLoc(), 13556 diag::err_invalid_storage_class_in_func_decl); 13557 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13558 } 13559 13560 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13561 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13562 << DeclSpec::getSpecifierName(TSCS); 13563 if (DS.isInlineSpecified()) 13564 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13565 << getLangOpts().CPlusPlus17; 13566 if (DS.hasConstexprSpecifier()) 13567 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13568 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 13569 13570 DiagnoseFunctionSpecifiers(DS); 13571 13572 CheckFunctionOrTemplateParamDeclarator(S, D); 13573 13574 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13575 QualType parmDeclType = TInfo->getType(); 13576 13577 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13578 IdentifierInfo *II = D.getIdentifier(); 13579 if (II) { 13580 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13581 ForVisibleRedeclaration); 13582 LookupName(R, S); 13583 if (R.isSingleResult()) { 13584 NamedDecl *PrevDecl = R.getFoundDecl(); 13585 if (PrevDecl->isTemplateParameter()) { 13586 // Maybe we will complain about the shadowed template parameter. 13587 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13588 // Just pretend that we didn't see the previous declaration. 13589 PrevDecl = nullptr; 13590 } else if (S->isDeclScope(PrevDecl)) { 13591 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13592 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13593 13594 // Recover by removing the name 13595 II = nullptr; 13596 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13597 D.setInvalidType(true); 13598 } 13599 } 13600 } 13601 13602 // Temporarily put parameter variables in the translation unit, not 13603 // the enclosing context. This prevents them from accidentally 13604 // looking like class members in C++. 13605 ParmVarDecl *New = 13606 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13607 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13608 13609 if (D.isInvalidType()) 13610 New->setInvalidDecl(); 13611 13612 assert(S->isFunctionPrototypeScope()); 13613 assert(S->getFunctionPrototypeDepth() >= 1); 13614 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13615 S->getNextFunctionPrototypeIndex()); 13616 13617 // Add the parameter declaration into this scope. 13618 S->AddDecl(New); 13619 if (II) 13620 IdResolver.AddDecl(New); 13621 13622 ProcessDeclAttributes(S, New, D); 13623 13624 if (D.getDeclSpec().isModulePrivateSpecified()) 13625 Diag(New->getLocation(), diag::err_module_private_local) 13626 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13627 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13628 13629 if (New->hasAttr<BlocksAttr>()) { 13630 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13631 } 13632 13633 if (getLangOpts().OpenCL) 13634 deduceOpenCLAddressSpace(New); 13635 13636 return New; 13637 } 13638 13639 /// Synthesizes a variable for a parameter arising from a 13640 /// typedef. 13641 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13642 SourceLocation Loc, 13643 QualType T) { 13644 /* FIXME: setting StartLoc == Loc. 13645 Would it be worth to modify callers so as to provide proper source 13646 location for the unnamed parameters, embedding the parameter's type? */ 13647 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13648 T, Context.getTrivialTypeSourceInfo(T, Loc), 13649 SC_None, nullptr); 13650 Param->setImplicit(); 13651 return Param; 13652 } 13653 13654 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13655 // Don't diagnose unused-parameter errors in template instantiations; we 13656 // will already have done so in the template itself. 13657 if (inTemplateInstantiation()) 13658 return; 13659 13660 for (const ParmVarDecl *Parameter : Parameters) { 13661 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13662 !Parameter->hasAttr<UnusedAttr>()) { 13663 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13664 << Parameter->getDeclName(); 13665 } 13666 } 13667 } 13668 13669 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13670 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13671 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13672 return; 13673 13674 // Warn if the return value is pass-by-value and larger than the specified 13675 // threshold. 13676 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13677 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13678 if (Size > LangOpts.NumLargeByValueCopy) 13679 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 13680 } 13681 13682 // Warn if any parameter is pass-by-value and larger than the specified 13683 // threshold. 13684 for (const ParmVarDecl *Parameter : Parameters) { 13685 QualType T = Parameter->getType(); 13686 if (T->isDependentType() || !T.isPODType(Context)) 13687 continue; 13688 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13689 if (Size > LangOpts.NumLargeByValueCopy) 13690 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13691 << Parameter << Size; 13692 } 13693 } 13694 13695 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13696 SourceLocation NameLoc, IdentifierInfo *Name, 13697 QualType T, TypeSourceInfo *TSInfo, 13698 StorageClass SC) { 13699 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13700 if (getLangOpts().ObjCAutoRefCount && 13701 T.getObjCLifetime() == Qualifiers::OCL_None && 13702 T->isObjCLifetimeType()) { 13703 13704 Qualifiers::ObjCLifetime lifetime; 13705 13706 // Special cases for arrays: 13707 // - if it's const, use __unsafe_unretained 13708 // - otherwise, it's an error 13709 if (T->isArrayType()) { 13710 if (!T.isConstQualified()) { 13711 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13712 DelayedDiagnostics.add( 13713 sema::DelayedDiagnostic::makeForbiddenType( 13714 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13715 else 13716 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13717 << TSInfo->getTypeLoc().getSourceRange(); 13718 } 13719 lifetime = Qualifiers::OCL_ExplicitNone; 13720 } else { 13721 lifetime = T->getObjCARCImplicitLifetime(); 13722 } 13723 T = Context.getLifetimeQualifiedType(T, lifetime); 13724 } 13725 13726 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13727 Context.getAdjustedParameterType(T), 13728 TSInfo, SC, nullptr); 13729 13730 // Make a note if we created a new pack in the scope of a lambda, so that 13731 // we know that references to that pack must also be expanded within the 13732 // lambda scope. 13733 if (New->isParameterPack()) 13734 if (auto *LSI = getEnclosingLambda()) 13735 LSI->LocalPacks.push_back(New); 13736 13737 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13738 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13739 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13740 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13741 13742 // Parameters can not be abstract class types. 13743 // For record types, this is done by the AbstractClassUsageDiagnoser once 13744 // the class has been completely parsed. 13745 if (!CurContext->isRecord() && 13746 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13747 AbstractParamType)) 13748 New->setInvalidDecl(); 13749 13750 // Parameter declarators cannot be interface types. All ObjC objects are 13751 // passed by reference. 13752 if (T->isObjCObjectType()) { 13753 SourceLocation TypeEndLoc = 13754 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13755 Diag(NameLoc, 13756 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13757 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13758 T = Context.getObjCObjectPointerType(T); 13759 New->setType(T); 13760 } 13761 13762 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13763 // duration shall not be qualified by an address-space qualifier." 13764 // Since all parameters have automatic store duration, they can not have 13765 // an address space. 13766 if (T.getAddressSpace() != LangAS::Default && 13767 // OpenCL allows function arguments declared to be an array of a type 13768 // to be qualified with an address space. 13769 !(getLangOpts().OpenCL && 13770 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13771 Diag(NameLoc, diag::err_arg_with_address_space); 13772 New->setInvalidDecl(); 13773 } 13774 13775 // PPC MMA non-pointer types are not allowed as function argument types. 13776 if (Context.getTargetInfo().getTriple().isPPC64() && 13777 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 13778 New->setInvalidDecl(); 13779 } 13780 13781 return New; 13782 } 13783 13784 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13785 SourceLocation LocAfterDecls) { 13786 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13787 13788 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13789 // for a K&R function. 13790 if (!FTI.hasPrototype) { 13791 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13792 --i; 13793 if (FTI.Params[i].Param == nullptr) { 13794 SmallString<256> Code; 13795 llvm::raw_svector_ostream(Code) 13796 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13797 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13798 << FTI.Params[i].Ident 13799 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13800 13801 // Implicitly declare the argument as type 'int' for lack of a better 13802 // type. 13803 AttributeFactory attrs; 13804 DeclSpec DS(attrs); 13805 const char* PrevSpec; // unused 13806 unsigned DiagID; // unused 13807 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13808 DiagID, Context.getPrintingPolicy()); 13809 // Use the identifier location for the type source range. 13810 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13811 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13812 Declarator ParamD(DS, DeclaratorContext::KNRTypeList); 13813 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13814 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13815 } 13816 } 13817 } 13818 } 13819 13820 Decl * 13821 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13822 MultiTemplateParamsArg TemplateParameterLists, 13823 SkipBodyInfo *SkipBody) { 13824 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13825 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13826 Scope *ParentScope = FnBodyScope->getParent(); 13827 13828 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 13829 // we define a non-templated function definition, we will create a declaration 13830 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 13831 // The base function declaration will have the equivalent of an `omp declare 13832 // variant` annotation which specifies the mangled definition as a 13833 // specialization function under the OpenMP context defined as part of the 13834 // `omp begin declare variant`. 13835 SmallVector<FunctionDecl *, 4> Bases; 13836 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 13837 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 13838 ParentScope, D, TemplateParameterLists, Bases); 13839 13840 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 13841 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13842 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13843 13844 if (!Bases.empty()) 13845 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 13846 13847 return Dcl; 13848 } 13849 13850 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13851 Consumer.HandleInlineFunctionDefinition(D); 13852 } 13853 13854 static bool 13855 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13856 const FunctionDecl *&PossiblePrototype) { 13857 // Don't warn about invalid declarations. 13858 if (FD->isInvalidDecl()) 13859 return false; 13860 13861 // Or declarations that aren't global. 13862 if (!FD->isGlobal()) 13863 return false; 13864 13865 // Don't warn about C++ member functions. 13866 if (isa<CXXMethodDecl>(FD)) 13867 return false; 13868 13869 // Don't warn about 'main'. 13870 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13871 if (IdentifierInfo *II = FD->getIdentifier()) 13872 if (II->isStr("main")) 13873 return false; 13874 13875 // Don't warn about inline functions. 13876 if (FD->isInlined()) 13877 return false; 13878 13879 // Don't warn about function templates. 13880 if (FD->getDescribedFunctionTemplate()) 13881 return false; 13882 13883 // Don't warn about function template specializations. 13884 if (FD->isFunctionTemplateSpecialization()) 13885 return false; 13886 13887 // Don't warn for OpenCL kernels. 13888 if (FD->hasAttr<OpenCLKernelAttr>()) 13889 return false; 13890 13891 // Don't warn on explicitly deleted functions. 13892 if (FD->isDeleted()) 13893 return false; 13894 13895 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13896 Prev; Prev = Prev->getPreviousDecl()) { 13897 // Ignore any declarations that occur in function or method 13898 // scope, because they aren't visible from the header. 13899 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13900 continue; 13901 13902 PossiblePrototype = Prev; 13903 return Prev->getType()->isFunctionNoProtoType(); 13904 } 13905 13906 return true; 13907 } 13908 13909 void 13910 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13911 const FunctionDecl *EffectiveDefinition, 13912 SkipBodyInfo *SkipBody) { 13913 const FunctionDecl *Definition = EffectiveDefinition; 13914 if (!Definition && 13915 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 13916 return; 13917 13918 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 13919 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 13920 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13921 // A merged copy of the same function, instantiated as a member of 13922 // the same class, is OK. 13923 if (declaresSameEntity(OrigFD, OrigDef) && 13924 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 13925 cast<Decl>(FD->getLexicalDeclContext()))) 13926 return; 13927 } 13928 } 13929 } 13930 13931 if (canRedefineFunction(Definition, getLangOpts())) 13932 return; 13933 13934 // Don't emit an error when this is redefinition of a typo-corrected 13935 // definition. 13936 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13937 return; 13938 13939 // If we don't have a visible definition of the function, and it's inline or 13940 // a template, skip the new definition. 13941 if (SkipBody && !hasVisibleDefinition(Definition) && 13942 (Definition->getFormalLinkage() == InternalLinkage || 13943 Definition->isInlined() || 13944 Definition->getDescribedFunctionTemplate() || 13945 Definition->getNumTemplateParameterLists())) { 13946 SkipBody->ShouldSkip = true; 13947 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 13948 if (auto *TD = Definition->getDescribedFunctionTemplate()) 13949 makeMergedDefinitionVisible(TD); 13950 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 13951 return; 13952 } 13953 13954 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 13955 Definition->getStorageClass() == SC_Extern) 13956 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 13957 << FD << getLangOpts().CPlusPlus; 13958 else 13959 Diag(FD->getLocation(), diag::err_redefinition) << FD; 13960 13961 Diag(Definition->getLocation(), diag::note_previous_definition); 13962 FD->setInvalidDecl(); 13963 } 13964 13965 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 13966 Sema &S) { 13967 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 13968 13969 LambdaScopeInfo *LSI = S.PushLambdaScope(); 13970 LSI->CallOperator = CallOperator; 13971 LSI->Lambda = LambdaClass; 13972 LSI->ReturnType = CallOperator->getReturnType(); 13973 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 13974 13975 if (LCD == LCD_None) 13976 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 13977 else if (LCD == LCD_ByCopy) 13978 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 13979 else if (LCD == LCD_ByRef) 13980 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 13981 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 13982 13983 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 13984 LSI->Mutable = !CallOperator->isConst(); 13985 13986 // Add the captures to the LSI so they can be noted as already 13987 // captured within tryCaptureVar. 13988 auto I = LambdaClass->field_begin(); 13989 for (const auto &C : LambdaClass->captures()) { 13990 if (C.capturesVariable()) { 13991 VarDecl *VD = C.getCapturedVar(); 13992 if (VD->isInitCapture()) 13993 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 13994 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 13995 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 13996 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 13997 /*EllipsisLoc*/C.isPackExpansion() 13998 ? C.getEllipsisLoc() : SourceLocation(), 13999 I->getType(), /*Invalid*/false); 14000 14001 } else if (C.capturesThis()) { 14002 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 14003 C.getCaptureKind() == LCK_StarThis); 14004 } else { 14005 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14006 I->getType()); 14007 } 14008 ++I; 14009 } 14010 } 14011 14012 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14013 SkipBodyInfo *SkipBody) { 14014 if (!D) { 14015 // Parsing the function declaration failed in some way. Push on a fake scope 14016 // anyway so we can try to parse the function body. 14017 PushFunctionScope(); 14018 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14019 return D; 14020 } 14021 14022 FunctionDecl *FD = nullptr; 14023 14024 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14025 FD = FunTmpl->getTemplatedDecl(); 14026 else 14027 FD = cast<FunctionDecl>(D); 14028 14029 // Do not push if it is a lambda because one is already pushed when building 14030 // the lambda in ActOnStartOfLambdaDefinition(). 14031 if (!isLambdaCallOperator(FD)) 14032 PushExpressionEvaluationContext( 14033 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14034 : ExprEvalContexts.back().Context); 14035 14036 // Check for defining attributes before the check for redefinition. 14037 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14038 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14039 FD->dropAttr<AliasAttr>(); 14040 FD->setInvalidDecl(); 14041 } 14042 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14043 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14044 FD->dropAttr<IFuncAttr>(); 14045 FD->setInvalidDecl(); 14046 } 14047 14048 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14049 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14050 Ctor->isDefaultConstructor() && 14051 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14052 // If this is an MS ABI dllexport default constructor, instantiate any 14053 // default arguments. 14054 InstantiateDefaultCtorDefaultArgs(Ctor); 14055 } 14056 } 14057 14058 // See if this is a redefinition. If 'will have body' (or similar) is already 14059 // set, then these checks were already performed when it was set. 14060 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14061 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14062 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14063 14064 // If we're skipping the body, we're done. Don't enter the scope. 14065 if (SkipBody && SkipBody->ShouldSkip) 14066 return D; 14067 } 14068 14069 // Mark this function as "will have a body eventually". This lets users to 14070 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14071 // this function. 14072 FD->setWillHaveBody(); 14073 14074 // If we are instantiating a generic lambda call operator, push 14075 // a LambdaScopeInfo onto the function stack. But use the information 14076 // that's already been calculated (ActOnLambdaExpr) to prime the current 14077 // LambdaScopeInfo. 14078 // When the template operator is being specialized, the LambdaScopeInfo, 14079 // has to be properly restored so that tryCaptureVariable doesn't try 14080 // and capture any new variables. In addition when calculating potential 14081 // captures during transformation of nested lambdas, it is necessary to 14082 // have the LSI properly restored. 14083 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14084 assert(inTemplateInstantiation() && 14085 "There should be an active template instantiation on the stack " 14086 "when instantiating a generic lambda!"); 14087 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14088 } else { 14089 // Enter a new function scope 14090 PushFunctionScope(); 14091 } 14092 14093 // Builtin functions cannot be defined. 14094 if (unsigned BuiltinID = FD->getBuiltinID()) { 14095 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14096 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14097 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14098 FD->setInvalidDecl(); 14099 } 14100 } 14101 14102 // The return type of a function definition must be complete 14103 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14104 QualType ResultType = FD->getReturnType(); 14105 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14106 !FD->isInvalidDecl() && 14107 RequireCompleteType(FD->getLocation(), ResultType, 14108 diag::err_func_def_incomplete_result)) 14109 FD->setInvalidDecl(); 14110 14111 if (FnBodyScope) 14112 PushDeclContext(FnBodyScope, FD); 14113 14114 // Check the validity of our function parameters 14115 CheckParmsForFunctionDef(FD->parameters(), 14116 /*CheckParameterNames=*/true); 14117 14118 // Add non-parameter declarations already in the function to the current 14119 // scope. 14120 if (FnBodyScope) { 14121 for (Decl *NPD : FD->decls()) { 14122 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14123 if (!NonParmDecl) 14124 continue; 14125 assert(!isa<ParmVarDecl>(NonParmDecl) && 14126 "parameters should not be in newly created FD yet"); 14127 14128 // If the decl has a name, make it accessible in the current scope. 14129 if (NonParmDecl->getDeclName()) 14130 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14131 14132 // Similarly, dive into enums and fish their constants out, making them 14133 // accessible in this scope. 14134 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14135 for (auto *EI : ED->enumerators()) 14136 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14137 } 14138 } 14139 } 14140 14141 // Introduce our parameters into the function scope 14142 for (auto Param : FD->parameters()) { 14143 Param->setOwningFunction(FD); 14144 14145 // If this has an identifier, add it to the scope stack. 14146 if (Param->getIdentifier() && FnBodyScope) { 14147 CheckShadow(FnBodyScope, Param); 14148 14149 PushOnScopeChains(Param, FnBodyScope); 14150 } 14151 } 14152 14153 // Ensure that the function's exception specification is instantiated. 14154 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14155 ResolveExceptionSpec(D->getLocation(), FPT); 14156 14157 // dllimport cannot be applied to non-inline function definitions. 14158 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14159 !FD->isTemplateInstantiation()) { 14160 assert(!FD->hasAttr<DLLExportAttr>()); 14161 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14162 FD->setInvalidDecl(); 14163 return D; 14164 } 14165 // We want to attach documentation to original Decl (which might be 14166 // a function template). 14167 ActOnDocumentableDecl(D); 14168 if (getCurLexicalContext()->isObjCContainer() && 14169 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14170 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14171 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14172 14173 return D; 14174 } 14175 14176 /// Given the set of return statements within a function body, 14177 /// compute the variables that are subject to the named return value 14178 /// optimization. 14179 /// 14180 /// Each of the variables that is subject to the named return value 14181 /// optimization will be marked as NRVO variables in the AST, and any 14182 /// return statement that has a marked NRVO variable as its NRVO candidate can 14183 /// use the named return value optimization. 14184 /// 14185 /// This function applies a very simplistic algorithm for NRVO: if every return 14186 /// statement in the scope of a variable has the same NRVO candidate, that 14187 /// candidate is an NRVO variable. 14188 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14189 ReturnStmt **Returns = Scope->Returns.data(); 14190 14191 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14192 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14193 if (!NRVOCandidate->isNRVOVariable()) 14194 Returns[I]->setNRVOCandidate(nullptr); 14195 } 14196 } 14197 } 14198 14199 bool Sema::canDelayFunctionBody(const Declarator &D) { 14200 // We can't delay parsing the body of a constexpr function template (yet). 14201 if (D.getDeclSpec().hasConstexprSpecifier()) 14202 return false; 14203 14204 // We can't delay parsing the body of a function template with a deduced 14205 // return type (yet). 14206 if (D.getDeclSpec().hasAutoTypeSpec()) { 14207 // If the placeholder introduces a non-deduced trailing return type, 14208 // we can still delay parsing it. 14209 if (D.getNumTypeObjects()) { 14210 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14211 if (Outer.Kind == DeclaratorChunk::Function && 14212 Outer.Fun.hasTrailingReturnType()) { 14213 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14214 return Ty.isNull() || !Ty->isUndeducedType(); 14215 } 14216 } 14217 return false; 14218 } 14219 14220 return true; 14221 } 14222 14223 bool Sema::canSkipFunctionBody(Decl *D) { 14224 // We cannot skip the body of a function (or function template) which is 14225 // constexpr, since we may need to evaluate its body in order to parse the 14226 // rest of the file. 14227 // We cannot skip the body of a function with an undeduced return type, 14228 // because any callers of that function need to know the type. 14229 if (const FunctionDecl *FD = D->getAsFunction()) { 14230 if (FD->isConstexpr()) 14231 return false; 14232 // We can't simply call Type::isUndeducedType here, because inside template 14233 // auto can be deduced to a dependent type, which is not considered 14234 // "undeduced". 14235 if (FD->getReturnType()->getContainedDeducedType()) 14236 return false; 14237 } 14238 return Consumer.shouldSkipFunctionBody(D); 14239 } 14240 14241 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14242 if (!Decl) 14243 return nullptr; 14244 if (FunctionDecl *FD = Decl->getAsFunction()) 14245 FD->setHasSkippedBody(); 14246 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14247 MD->setHasSkippedBody(); 14248 return Decl; 14249 } 14250 14251 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14252 return ActOnFinishFunctionBody(D, BodyArg, false); 14253 } 14254 14255 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14256 /// body. 14257 class ExitFunctionBodyRAII { 14258 public: 14259 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14260 ~ExitFunctionBodyRAII() { 14261 if (!IsLambda) 14262 S.PopExpressionEvaluationContext(); 14263 } 14264 14265 private: 14266 Sema &S; 14267 bool IsLambda = false; 14268 }; 14269 14270 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14271 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14272 14273 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14274 if (EscapeInfo.count(BD)) 14275 return EscapeInfo[BD]; 14276 14277 bool R = false; 14278 const BlockDecl *CurBD = BD; 14279 14280 do { 14281 R = !CurBD->doesNotEscape(); 14282 if (R) 14283 break; 14284 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14285 } while (CurBD); 14286 14287 return EscapeInfo[BD] = R; 14288 }; 14289 14290 // If the location where 'self' is implicitly retained is inside a escaping 14291 // block, emit a diagnostic. 14292 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14293 S.ImplicitlyRetainedSelfLocs) 14294 if (IsOrNestedInEscapingBlock(P.second)) 14295 S.Diag(P.first, diag::warn_implicitly_retains_self) 14296 << FixItHint::CreateInsertion(P.first, "self->"); 14297 } 14298 14299 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14300 bool IsInstantiation) { 14301 FunctionScopeInfo *FSI = getCurFunction(); 14302 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14303 14304 if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>()) 14305 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14306 14307 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14308 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14309 14310 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14311 CheckCompletedCoroutineBody(FD, Body); 14312 14313 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14314 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14315 // meant to pop the context added in ActOnStartOfFunctionDef(). 14316 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14317 14318 if (FD) { 14319 FD->setBody(Body); 14320 FD->setWillHaveBody(false); 14321 14322 if (getLangOpts().CPlusPlus14) { 14323 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14324 FD->getReturnType()->isUndeducedType()) { 14325 // If the function has a deduced result type but contains no 'return' 14326 // statements, the result type as written must be exactly 'auto', and 14327 // the deduced result type is 'void'. 14328 if (!FD->getReturnType()->getAs<AutoType>()) { 14329 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14330 << FD->getReturnType(); 14331 FD->setInvalidDecl(); 14332 } else { 14333 // Substitute 'void' for the 'auto' in the type. 14334 TypeLoc ResultType = getReturnTypeLoc(FD); 14335 Context.adjustDeducedFunctionResultType( 14336 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14337 } 14338 } 14339 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14340 // In C++11, we don't use 'auto' deduction rules for lambda call 14341 // operators because we don't support return type deduction. 14342 auto *LSI = getCurLambda(); 14343 if (LSI->HasImplicitReturnType) { 14344 deduceClosureReturnType(*LSI); 14345 14346 // C++11 [expr.prim.lambda]p4: 14347 // [...] if there are no return statements in the compound-statement 14348 // [the deduced type is] the type void 14349 QualType RetType = 14350 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14351 14352 // Update the return type to the deduced type. 14353 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14354 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14355 Proto->getExtProtoInfo())); 14356 } 14357 } 14358 14359 // If the function implicitly returns zero (like 'main') or is naked, 14360 // don't complain about missing return statements. 14361 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14362 WP.disableCheckFallThrough(); 14363 14364 // MSVC permits the use of pure specifier (=0) on function definition, 14365 // defined at class scope, warn about this non-standard construct. 14366 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14367 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14368 14369 if (!FD->isInvalidDecl()) { 14370 // Don't diagnose unused parameters of defaulted or deleted functions. 14371 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14372 DiagnoseUnusedParameters(FD->parameters()); 14373 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14374 FD->getReturnType(), FD); 14375 14376 // If this is a structor, we need a vtable. 14377 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14378 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14379 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14380 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14381 14382 // Try to apply the named return value optimization. We have to check 14383 // if we can do this here because lambdas keep return statements around 14384 // to deduce an implicit return type. 14385 if (FD->getReturnType()->isRecordType() && 14386 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14387 computeNRVO(Body, FSI); 14388 } 14389 14390 // GNU warning -Wmissing-prototypes: 14391 // Warn if a global function is defined without a previous 14392 // prototype declaration. This warning is issued even if the 14393 // definition itself provides a prototype. The aim is to detect 14394 // global functions that fail to be declared in header files. 14395 const FunctionDecl *PossiblePrototype = nullptr; 14396 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14397 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14398 14399 if (PossiblePrototype) { 14400 // We found a declaration that is not a prototype, 14401 // but that could be a zero-parameter prototype 14402 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14403 TypeLoc TL = TI->getTypeLoc(); 14404 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14405 Diag(PossiblePrototype->getLocation(), 14406 diag::note_declaration_not_a_prototype) 14407 << (FD->getNumParams() != 0) 14408 << (FD->getNumParams() == 0 14409 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14410 : FixItHint{}); 14411 } 14412 } else { 14413 // Returns true if the token beginning at this Loc is `const`. 14414 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14415 const LangOptions &LangOpts) { 14416 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14417 if (LocInfo.first.isInvalid()) 14418 return false; 14419 14420 bool Invalid = false; 14421 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14422 if (Invalid) 14423 return false; 14424 14425 if (LocInfo.second > Buffer.size()) 14426 return false; 14427 14428 const char *LexStart = Buffer.data() + LocInfo.second; 14429 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14430 14431 return StartTok.consume_front("const") && 14432 (StartTok.empty() || isWhitespace(StartTok[0]) || 14433 StartTok.startswith("/*") || StartTok.startswith("//")); 14434 }; 14435 14436 auto findBeginLoc = [&]() { 14437 // If the return type has `const` qualifier, we want to insert 14438 // `static` before `const` (and not before the typename). 14439 if ((FD->getReturnType()->isAnyPointerType() && 14440 FD->getReturnType()->getPointeeType().isConstQualified()) || 14441 FD->getReturnType().isConstQualified()) { 14442 // But only do this if we can determine where the `const` is. 14443 14444 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14445 getLangOpts())) 14446 14447 return FD->getBeginLoc(); 14448 } 14449 return FD->getTypeSpecStartLoc(); 14450 }; 14451 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14452 << /* function */ 1 14453 << (FD->getStorageClass() == SC_None 14454 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14455 : FixItHint{}); 14456 } 14457 14458 // GNU warning -Wstrict-prototypes 14459 // Warn if K&R function is defined without a previous declaration. 14460 // This warning is issued only if the definition itself does not provide 14461 // a prototype. Only K&R definitions do not provide a prototype. 14462 if (!FD->hasWrittenPrototype()) { 14463 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14464 TypeLoc TL = TI->getTypeLoc(); 14465 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14466 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14467 } 14468 } 14469 14470 // Warn on CPUDispatch with an actual body. 14471 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14472 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14473 if (!CmpndBody->body_empty()) 14474 Diag(CmpndBody->body_front()->getBeginLoc(), 14475 diag::warn_dispatch_body_ignored); 14476 14477 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14478 const CXXMethodDecl *KeyFunction; 14479 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14480 MD->isVirtual() && 14481 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14482 MD == KeyFunction->getCanonicalDecl()) { 14483 // Update the key-function state if necessary for this ABI. 14484 if (FD->isInlined() && 14485 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14486 Context.setNonKeyFunction(MD); 14487 14488 // If the newly-chosen key function is already defined, then we 14489 // need to mark the vtable as used retroactively. 14490 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14491 const FunctionDecl *Definition; 14492 if (KeyFunction && KeyFunction->isDefined(Definition)) 14493 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14494 } else { 14495 // We just defined they key function; mark the vtable as used. 14496 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14497 } 14498 } 14499 } 14500 14501 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14502 "Function parsing confused"); 14503 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14504 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14505 MD->setBody(Body); 14506 if (!MD->isInvalidDecl()) { 14507 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14508 MD->getReturnType(), MD); 14509 14510 if (Body) 14511 computeNRVO(Body, FSI); 14512 } 14513 if (FSI->ObjCShouldCallSuper) { 14514 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14515 << MD->getSelector().getAsString(); 14516 FSI->ObjCShouldCallSuper = false; 14517 } 14518 if (FSI->ObjCWarnForNoDesignatedInitChain) { 14519 const ObjCMethodDecl *InitMethod = nullptr; 14520 bool isDesignated = 14521 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14522 assert(isDesignated && InitMethod); 14523 (void)isDesignated; 14524 14525 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14526 auto IFace = MD->getClassInterface(); 14527 if (!IFace) 14528 return false; 14529 auto SuperD = IFace->getSuperClass(); 14530 if (!SuperD) 14531 return false; 14532 return SuperD->getIdentifier() == 14533 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14534 }; 14535 // Don't issue this warning for unavailable inits or direct subclasses 14536 // of NSObject. 14537 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14538 Diag(MD->getLocation(), 14539 diag::warn_objc_designated_init_missing_super_call); 14540 Diag(InitMethod->getLocation(), 14541 diag::note_objc_designated_init_marked_here); 14542 } 14543 FSI->ObjCWarnForNoDesignatedInitChain = false; 14544 } 14545 if (FSI->ObjCWarnForNoInitDelegation) { 14546 // Don't issue this warning for unavaialable inits. 14547 if (!MD->isUnavailable()) 14548 Diag(MD->getLocation(), 14549 diag::warn_objc_secondary_init_missing_init_call); 14550 FSI->ObjCWarnForNoInitDelegation = false; 14551 } 14552 14553 diagnoseImplicitlyRetainedSelf(*this); 14554 } else { 14555 // Parsing the function declaration failed in some way. Pop the fake scope 14556 // we pushed on. 14557 PopFunctionScopeInfo(ActivePolicy, dcl); 14558 return nullptr; 14559 } 14560 14561 if (Body && FSI->HasPotentialAvailabilityViolations) 14562 DiagnoseUnguardedAvailabilityViolations(dcl); 14563 14564 assert(!FSI->ObjCShouldCallSuper && 14565 "This should only be set for ObjC methods, which should have been " 14566 "handled in the block above."); 14567 14568 // Verify and clean out per-function state. 14569 if (Body && (!FD || !FD->isDefaulted())) { 14570 // C++ constructors that have function-try-blocks can't have return 14571 // statements in the handlers of that block. (C++ [except.handle]p14) 14572 // Verify this. 14573 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14574 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14575 14576 // Verify that gotos and switch cases don't jump into scopes illegally. 14577 if (FSI->NeedsScopeChecking() && 14578 !PP.isCodeCompletionEnabled()) 14579 DiagnoseInvalidJumps(Body); 14580 14581 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14582 if (!Destructor->getParent()->isDependentType()) 14583 CheckDestructor(Destructor); 14584 14585 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14586 Destructor->getParent()); 14587 } 14588 14589 // If any errors have occurred, clear out any temporaries that may have 14590 // been leftover. This ensures that these temporaries won't be picked up for 14591 // deletion in some later function. 14592 if (hasUncompilableErrorOccurred() || 14593 getDiagnostics().getSuppressAllDiagnostics()) { 14594 DiscardCleanupsInEvaluationContext(); 14595 } 14596 if (!hasUncompilableErrorOccurred() && 14597 !isa<FunctionTemplateDecl>(dcl)) { 14598 // Since the body is valid, issue any analysis-based warnings that are 14599 // enabled. 14600 ActivePolicy = &WP; 14601 } 14602 14603 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14604 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14605 FD->setInvalidDecl(); 14606 14607 if (FD && FD->hasAttr<NakedAttr>()) { 14608 for (const Stmt *S : Body->children()) { 14609 // Allow local register variables without initializer as they don't 14610 // require prologue. 14611 bool RegisterVariables = false; 14612 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14613 for (const auto *Decl : DS->decls()) { 14614 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14615 RegisterVariables = 14616 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14617 if (!RegisterVariables) 14618 break; 14619 } 14620 } 14621 } 14622 if (RegisterVariables) 14623 continue; 14624 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14625 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14626 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14627 FD->setInvalidDecl(); 14628 break; 14629 } 14630 } 14631 } 14632 14633 assert(ExprCleanupObjects.size() == 14634 ExprEvalContexts.back().NumCleanupObjects && 14635 "Leftover temporaries in function"); 14636 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14637 assert(MaybeODRUseExprs.empty() && 14638 "Leftover expressions for odr-use checking"); 14639 } 14640 14641 if (!IsInstantiation) 14642 PopDeclContext(); 14643 14644 PopFunctionScopeInfo(ActivePolicy, dcl); 14645 // If any errors have occurred, clear out any temporaries that may have 14646 // been leftover. This ensures that these temporaries won't be picked up for 14647 // deletion in some later function. 14648 if (hasUncompilableErrorOccurred()) { 14649 DiscardCleanupsInEvaluationContext(); 14650 } 14651 14652 if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 14653 auto ES = getEmissionStatus(FD); 14654 if (ES == Sema::FunctionEmissionStatus::Emitted || 14655 ES == Sema::FunctionEmissionStatus::Unknown) 14656 DeclsToCheckForDeferredDiags.push_back(FD); 14657 } 14658 14659 return dcl; 14660 } 14661 14662 /// When we finish delayed parsing of an attribute, we must attach it to the 14663 /// relevant Decl. 14664 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14665 ParsedAttributes &Attrs) { 14666 // Always attach attributes to the underlying decl. 14667 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14668 D = TD->getTemplatedDecl(); 14669 ProcessDeclAttributeList(S, D, Attrs); 14670 14671 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14672 if (Method->isStatic()) 14673 checkThisInStaticMemberFunctionAttributes(Method); 14674 } 14675 14676 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14677 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14678 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14679 IdentifierInfo &II, Scope *S) { 14680 // Find the scope in which the identifier is injected and the corresponding 14681 // DeclContext. 14682 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14683 // In that case, we inject the declaration into the translation unit scope 14684 // instead. 14685 Scope *BlockScope = S; 14686 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14687 BlockScope = BlockScope->getParent(); 14688 14689 Scope *ContextScope = BlockScope; 14690 while (!ContextScope->getEntity()) 14691 ContextScope = ContextScope->getParent(); 14692 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14693 14694 // Before we produce a declaration for an implicitly defined 14695 // function, see whether there was a locally-scoped declaration of 14696 // this name as a function or variable. If so, use that 14697 // (non-visible) declaration, and complain about it. 14698 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14699 if (ExternCPrev) { 14700 // We still need to inject the function into the enclosing block scope so 14701 // that later (non-call) uses can see it. 14702 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14703 14704 // C89 footnote 38: 14705 // If in fact it is not defined as having type "function returning int", 14706 // the behavior is undefined. 14707 if (!isa<FunctionDecl>(ExternCPrev) || 14708 !Context.typesAreCompatible( 14709 cast<FunctionDecl>(ExternCPrev)->getType(), 14710 Context.getFunctionNoProtoType(Context.IntTy))) { 14711 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14712 << ExternCPrev << !getLangOpts().C99; 14713 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14714 return ExternCPrev; 14715 } 14716 } 14717 14718 // Extension in C99. Legal in C90, but warn about it. 14719 unsigned diag_id; 14720 if (II.getName().startswith("__builtin_")) 14721 diag_id = diag::warn_builtin_unknown; 14722 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14723 else if (getLangOpts().OpenCL) 14724 diag_id = diag::err_opencl_implicit_function_decl; 14725 else if (getLangOpts().C99) 14726 diag_id = diag::ext_implicit_function_decl; 14727 else 14728 diag_id = diag::warn_implicit_function_decl; 14729 Diag(Loc, diag_id) << &II; 14730 14731 // If we found a prior declaration of this function, don't bother building 14732 // another one. We've already pushed that one into scope, so there's nothing 14733 // more to do. 14734 if (ExternCPrev) 14735 return ExternCPrev; 14736 14737 // Because typo correction is expensive, only do it if the implicit 14738 // function declaration is going to be treated as an error. 14739 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14740 TypoCorrection Corrected; 14741 DeclFilterCCC<FunctionDecl> CCC{}; 14742 if (S && (Corrected = 14743 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14744 S, nullptr, CCC, CTK_NonError))) 14745 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14746 /*ErrorRecovery*/false); 14747 } 14748 14749 // Set a Declarator for the implicit definition: int foo(); 14750 const char *Dummy; 14751 AttributeFactory attrFactory; 14752 DeclSpec DS(attrFactory); 14753 unsigned DiagID; 14754 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14755 Context.getPrintingPolicy()); 14756 (void)Error; // Silence warning. 14757 assert(!Error && "Error setting up implicit decl!"); 14758 SourceLocation NoLoc; 14759 Declarator D(DS, DeclaratorContext::Block); 14760 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14761 /*IsAmbiguous=*/false, 14762 /*LParenLoc=*/NoLoc, 14763 /*Params=*/nullptr, 14764 /*NumParams=*/0, 14765 /*EllipsisLoc=*/NoLoc, 14766 /*RParenLoc=*/NoLoc, 14767 /*RefQualifierIsLvalueRef=*/true, 14768 /*RefQualifierLoc=*/NoLoc, 14769 /*MutableLoc=*/NoLoc, EST_None, 14770 /*ESpecRange=*/SourceRange(), 14771 /*Exceptions=*/nullptr, 14772 /*ExceptionRanges=*/nullptr, 14773 /*NumExceptions=*/0, 14774 /*NoexceptExpr=*/nullptr, 14775 /*ExceptionSpecTokens=*/nullptr, 14776 /*DeclsInPrototype=*/None, Loc, 14777 Loc, D), 14778 std::move(DS.getAttributes()), SourceLocation()); 14779 D.SetIdentifier(&II, Loc); 14780 14781 // Insert this function into the enclosing block scope. 14782 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14783 FD->setImplicit(); 14784 14785 AddKnownFunctionAttributes(FD); 14786 14787 return FD; 14788 } 14789 14790 /// If this function is a C++ replaceable global allocation function 14791 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14792 /// adds any function attributes that we know a priori based on the standard. 14793 /// 14794 /// We need to check for duplicate attributes both here and where user-written 14795 /// attributes are applied to declarations. 14796 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14797 FunctionDecl *FD) { 14798 if (FD->isInvalidDecl()) 14799 return; 14800 14801 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14802 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14803 return; 14804 14805 Optional<unsigned> AlignmentParam; 14806 bool IsNothrow = false; 14807 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14808 return; 14809 14810 // C++2a [basic.stc.dynamic.allocation]p4: 14811 // An allocation function that has a non-throwing exception specification 14812 // indicates failure by returning a null pointer value. Any other allocation 14813 // function never returns a null pointer value and indicates failure only by 14814 // throwing an exception [...] 14815 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14816 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14817 14818 // C++2a [basic.stc.dynamic.allocation]p2: 14819 // An allocation function attempts to allocate the requested amount of 14820 // storage. [...] If the request succeeds, the value returned by a 14821 // replaceable allocation function is a [...] pointer value p0 different 14822 // from any previously returned value p1 [...] 14823 // 14824 // However, this particular information is being added in codegen, 14825 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14826 14827 // C++2a [basic.stc.dynamic.allocation]p2: 14828 // An allocation function attempts to allocate the requested amount of 14829 // storage. If it is successful, it returns the address of the start of a 14830 // block of storage whose length in bytes is at least as large as the 14831 // requested size. 14832 if (!FD->hasAttr<AllocSizeAttr>()) { 14833 FD->addAttr(AllocSizeAttr::CreateImplicit( 14834 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14835 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14836 } 14837 14838 // C++2a [basic.stc.dynamic.allocation]p3: 14839 // For an allocation function [...], the pointer returned on a successful 14840 // call shall represent the address of storage that is aligned as follows: 14841 // (3.1) If the allocation function takes an argument of type 14842 // std::align_val_t, the storage will have the alignment 14843 // specified by the value of this argument. 14844 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14845 FD->addAttr(AllocAlignAttr::CreateImplicit( 14846 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14847 } 14848 14849 // FIXME: 14850 // C++2a [basic.stc.dynamic.allocation]p3: 14851 // For an allocation function [...], the pointer returned on a successful 14852 // call shall represent the address of storage that is aligned as follows: 14853 // (3.2) Otherwise, if the allocation function is named operator new[], 14854 // the storage is aligned for any object that does not have 14855 // new-extended alignment ([basic.align]) and is no larger than the 14856 // requested size. 14857 // (3.3) Otherwise, the storage is aligned for any object that does not 14858 // have new-extended alignment and is of the requested size. 14859 } 14860 14861 /// Adds any function attributes that we know a priori based on 14862 /// the declaration of this function. 14863 /// 14864 /// These attributes can apply both to implicitly-declared builtins 14865 /// (like __builtin___printf_chk) or to library-declared functions 14866 /// like NSLog or printf. 14867 /// 14868 /// We need to check for duplicate attributes both here and where user-written 14869 /// attributes are applied to declarations. 14870 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14871 if (FD->isInvalidDecl()) 14872 return; 14873 14874 // If this is a built-in function, map its builtin attributes to 14875 // actual attributes. 14876 if (unsigned BuiltinID = FD->getBuiltinID()) { 14877 // Handle printf-formatting attributes. 14878 unsigned FormatIdx; 14879 bool HasVAListArg; 14880 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14881 if (!FD->hasAttr<FormatAttr>()) { 14882 const char *fmt = "printf"; 14883 unsigned int NumParams = FD->getNumParams(); 14884 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14885 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14886 fmt = "NSString"; 14887 FD->addAttr(FormatAttr::CreateImplicit(Context, 14888 &Context.Idents.get(fmt), 14889 FormatIdx+1, 14890 HasVAListArg ? 0 : FormatIdx+2, 14891 FD->getLocation())); 14892 } 14893 } 14894 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14895 HasVAListArg)) { 14896 if (!FD->hasAttr<FormatAttr>()) 14897 FD->addAttr(FormatAttr::CreateImplicit(Context, 14898 &Context.Idents.get("scanf"), 14899 FormatIdx+1, 14900 HasVAListArg ? 0 : FormatIdx+2, 14901 FD->getLocation())); 14902 } 14903 14904 // Handle automatically recognized callbacks. 14905 SmallVector<int, 4> Encoding; 14906 if (!FD->hasAttr<CallbackAttr>() && 14907 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14908 FD->addAttr(CallbackAttr::CreateImplicit( 14909 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14910 14911 // Mark const if we don't care about errno and that is the only thing 14912 // preventing the function from being const. This allows IRgen to use LLVM 14913 // intrinsics for such functions. 14914 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14915 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14916 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14917 14918 // We make "fma" on some platforms const because we know it does not set 14919 // errno in those environments even though it could set errno based on the 14920 // C standard. 14921 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14922 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14923 !FD->hasAttr<ConstAttr>()) { 14924 switch (BuiltinID) { 14925 case Builtin::BI__builtin_fma: 14926 case Builtin::BI__builtin_fmaf: 14927 case Builtin::BI__builtin_fmal: 14928 case Builtin::BIfma: 14929 case Builtin::BIfmaf: 14930 case Builtin::BIfmal: 14931 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14932 break; 14933 default: 14934 break; 14935 } 14936 } 14937 14938 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14939 !FD->hasAttr<ReturnsTwiceAttr>()) 14940 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 14941 FD->getLocation())); 14942 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 14943 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14944 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 14945 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 14946 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 14947 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14948 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 14949 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 14950 // Add the appropriate attribute, depending on the CUDA compilation mode 14951 // and which target the builtin belongs to. For example, during host 14952 // compilation, aux builtins are __device__, while the rest are __host__. 14953 if (getLangOpts().CUDAIsDevice != 14954 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 14955 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 14956 else 14957 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 14958 } 14959 } 14960 14961 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 14962 14963 // If C++ exceptions are enabled but we are told extern "C" functions cannot 14964 // throw, add an implicit nothrow attribute to any extern "C" function we come 14965 // across. 14966 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 14967 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 14968 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 14969 if (!FPT || FPT->getExceptionSpecType() == EST_None) 14970 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14971 } 14972 14973 IdentifierInfo *Name = FD->getIdentifier(); 14974 if (!Name) 14975 return; 14976 if ((!getLangOpts().CPlusPlus && 14977 FD->getDeclContext()->isTranslationUnit()) || 14978 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 14979 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 14980 LinkageSpecDecl::lang_c)) { 14981 // Okay: this could be a libc/libm/Objective-C function we know 14982 // about. 14983 } else 14984 return; 14985 14986 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 14987 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 14988 // target-specific builtins, perhaps? 14989 if (!FD->hasAttr<FormatAttr>()) 14990 FD->addAttr(FormatAttr::CreateImplicit(Context, 14991 &Context.Idents.get("printf"), 2, 14992 Name->isStr("vasprintf") ? 0 : 3, 14993 FD->getLocation())); 14994 } 14995 14996 if (Name->isStr("__CFStringMakeConstantString")) { 14997 // We already have a __builtin___CFStringMakeConstantString, 14998 // but builds that use -fno-constant-cfstrings don't go through that. 14999 if (!FD->hasAttr<FormatArgAttr>()) 15000 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 15001 FD->getLocation())); 15002 } 15003 } 15004 15005 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15006 TypeSourceInfo *TInfo) { 15007 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 15008 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15009 15010 if (!TInfo) { 15011 assert(D.isInvalidType() && "no declarator info for valid type"); 15012 TInfo = Context.getTrivialTypeSourceInfo(T); 15013 } 15014 15015 // Scope manipulation handled by caller. 15016 TypedefDecl *NewTD = 15017 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15018 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15019 15020 // Bail out immediately if we have an invalid declaration. 15021 if (D.isInvalidType()) { 15022 NewTD->setInvalidDecl(); 15023 return NewTD; 15024 } 15025 15026 if (D.getDeclSpec().isModulePrivateSpecified()) { 15027 if (CurContext->isFunctionOrMethod()) 15028 Diag(NewTD->getLocation(), diag::err_module_private_local) 15029 << 2 << NewTD 15030 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15031 << FixItHint::CreateRemoval( 15032 D.getDeclSpec().getModulePrivateSpecLoc()); 15033 else 15034 NewTD->setModulePrivate(); 15035 } 15036 15037 // C++ [dcl.typedef]p8: 15038 // If the typedef declaration defines an unnamed class (or 15039 // enum), the first typedef-name declared by the declaration 15040 // to be that class type (or enum type) is used to denote the 15041 // class type (or enum type) for linkage purposes only. 15042 // We need to check whether the type was declared in the declaration. 15043 switch (D.getDeclSpec().getTypeSpecType()) { 15044 case TST_enum: 15045 case TST_struct: 15046 case TST_interface: 15047 case TST_union: 15048 case TST_class: { 15049 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15050 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15051 break; 15052 } 15053 15054 default: 15055 break; 15056 } 15057 15058 return NewTD; 15059 } 15060 15061 /// Check that this is a valid underlying type for an enum declaration. 15062 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15063 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15064 QualType T = TI->getType(); 15065 15066 if (T->isDependentType()) 15067 return false; 15068 15069 // This doesn't use 'isIntegralType' despite the error message mentioning 15070 // integral type because isIntegralType would also allow enum types in C. 15071 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15072 if (BT->isInteger()) 15073 return false; 15074 15075 if (T->isExtIntType()) 15076 return false; 15077 15078 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15079 } 15080 15081 /// Check whether this is a valid redeclaration of a previous enumeration. 15082 /// \return true if the redeclaration was invalid. 15083 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15084 QualType EnumUnderlyingTy, bool IsFixed, 15085 const EnumDecl *Prev) { 15086 if (IsScoped != Prev->isScoped()) { 15087 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15088 << Prev->isScoped(); 15089 Diag(Prev->getLocation(), diag::note_previous_declaration); 15090 return true; 15091 } 15092 15093 if (IsFixed && Prev->isFixed()) { 15094 if (!EnumUnderlyingTy->isDependentType() && 15095 !Prev->getIntegerType()->isDependentType() && 15096 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15097 Prev->getIntegerType())) { 15098 // TODO: Highlight the underlying type of the redeclaration. 15099 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15100 << EnumUnderlyingTy << Prev->getIntegerType(); 15101 Diag(Prev->getLocation(), diag::note_previous_declaration) 15102 << Prev->getIntegerTypeRange(); 15103 return true; 15104 } 15105 } else if (IsFixed != Prev->isFixed()) { 15106 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15107 << Prev->isFixed(); 15108 Diag(Prev->getLocation(), diag::note_previous_declaration); 15109 return true; 15110 } 15111 15112 return false; 15113 } 15114 15115 /// Get diagnostic %select index for tag kind for 15116 /// redeclaration diagnostic message. 15117 /// WARNING: Indexes apply to particular diagnostics only! 15118 /// 15119 /// \returns diagnostic %select index. 15120 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15121 switch (Tag) { 15122 case TTK_Struct: return 0; 15123 case TTK_Interface: return 1; 15124 case TTK_Class: return 2; 15125 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15126 } 15127 } 15128 15129 /// Determine if tag kind is a class-key compatible with 15130 /// class for redeclaration (class, struct, or __interface). 15131 /// 15132 /// \returns true iff the tag kind is compatible. 15133 static bool isClassCompatTagKind(TagTypeKind Tag) 15134 { 15135 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15136 } 15137 15138 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15139 TagTypeKind TTK) { 15140 if (isa<TypedefDecl>(PrevDecl)) 15141 return NTK_Typedef; 15142 else if (isa<TypeAliasDecl>(PrevDecl)) 15143 return NTK_TypeAlias; 15144 else if (isa<ClassTemplateDecl>(PrevDecl)) 15145 return NTK_Template; 15146 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15147 return NTK_TypeAliasTemplate; 15148 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15149 return NTK_TemplateTemplateArgument; 15150 switch (TTK) { 15151 case TTK_Struct: 15152 case TTK_Interface: 15153 case TTK_Class: 15154 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15155 case TTK_Union: 15156 return NTK_NonUnion; 15157 case TTK_Enum: 15158 return NTK_NonEnum; 15159 } 15160 llvm_unreachable("invalid TTK"); 15161 } 15162 15163 /// Determine whether a tag with a given kind is acceptable 15164 /// as a redeclaration of the given tag declaration. 15165 /// 15166 /// \returns true if the new tag kind is acceptable, false otherwise. 15167 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15168 TagTypeKind NewTag, bool isDefinition, 15169 SourceLocation NewTagLoc, 15170 const IdentifierInfo *Name) { 15171 // C++ [dcl.type.elab]p3: 15172 // The class-key or enum keyword present in the 15173 // elaborated-type-specifier shall agree in kind with the 15174 // declaration to which the name in the elaborated-type-specifier 15175 // refers. This rule also applies to the form of 15176 // elaborated-type-specifier that declares a class-name or 15177 // friend class since it can be construed as referring to the 15178 // definition of the class. Thus, in any 15179 // elaborated-type-specifier, the enum keyword shall be used to 15180 // refer to an enumeration (7.2), the union class-key shall be 15181 // used to refer to a union (clause 9), and either the class or 15182 // struct class-key shall be used to refer to a class (clause 9) 15183 // declared using the class or struct class-key. 15184 TagTypeKind OldTag = Previous->getTagKind(); 15185 if (OldTag != NewTag && 15186 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15187 return false; 15188 15189 // Tags are compatible, but we might still want to warn on mismatched tags. 15190 // Non-class tags can't be mismatched at this point. 15191 if (!isClassCompatTagKind(NewTag)) 15192 return true; 15193 15194 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15195 // by our warning analysis. We don't want to warn about mismatches with (eg) 15196 // declarations in system headers that are designed to be specialized, but if 15197 // a user asks us to warn, we should warn if their code contains mismatched 15198 // declarations. 15199 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15200 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15201 Loc); 15202 }; 15203 if (IsIgnoredLoc(NewTagLoc)) 15204 return true; 15205 15206 auto IsIgnored = [&](const TagDecl *Tag) { 15207 return IsIgnoredLoc(Tag->getLocation()); 15208 }; 15209 while (IsIgnored(Previous)) { 15210 Previous = Previous->getPreviousDecl(); 15211 if (!Previous) 15212 return true; 15213 OldTag = Previous->getTagKind(); 15214 } 15215 15216 bool isTemplate = false; 15217 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15218 isTemplate = Record->getDescribedClassTemplate(); 15219 15220 if (inTemplateInstantiation()) { 15221 if (OldTag != NewTag) { 15222 // In a template instantiation, do not offer fix-its for tag mismatches 15223 // since they usually mess up the template instead of fixing the problem. 15224 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15225 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15226 << getRedeclDiagFromTagKind(OldTag); 15227 // FIXME: Note previous location? 15228 } 15229 return true; 15230 } 15231 15232 if (isDefinition) { 15233 // On definitions, check all previous tags and issue a fix-it for each 15234 // one that doesn't match the current tag. 15235 if (Previous->getDefinition()) { 15236 // Don't suggest fix-its for redefinitions. 15237 return true; 15238 } 15239 15240 bool previousMismatch = false; 15241 for (const TagDecl *I : Previous->redecls()) { 15242 if (I->getTagKind() != NewTag) { 15243 // Ignore previous declarations for which the warning was disabled. 15244 if (IsIgnored(I)) 15245 continue; 15246 15247 if (!previousMismatch) { 15248 previousMismatch = true; 15249 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15250 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15251 << getRedeclDiagFromTagKind(I->getTagKind()); 15252 } 15253 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15254 << getRedeclDiagFromTagKind(NewTag) 15255 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15256 TypeWithKeyword::getTagTypeKindName(NewTag)); 15257 } 15258 } 15259 return true; 15260 } 15261 15262 // Identify the prevailing tag kind: this is the kind of the definition (if 15263 // there is a non-ignored definition), or otherwise the kind of the prior 15264 // (non-ignored) declaration. 15265 const TagDecl *PrevDef = Previous->getDefinition(); 15266 if (PrevDef && IsIgnored(PrevDef)) 15267 PrevDef = nullptr; 15268 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15269 if (Redecl->getTagKind() != NewTag) { 15270 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15271 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15272 << getRedeclDiagFromTagKind(OldTag); 15273 Diag(Redecl->getLocation(), diag::note_previous_use); 15274 15275 // If there is a previous definition, suggest a fix-it. 15276 if (PrevDef) { 15277 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15278 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15279 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15280 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15281 } 15282 } 15283 15284 return true; 15285 } 15286 15287 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15288 /// from an outer enclosing namespace or file scope inside a friend declaration. 15289 /// This should provide the commented out code in the following snippet: 15290 /// namespace N { 15291 /// struct X; 15292 /// namespace M { 15293 /// struct Y { friend struct /*N::*/ X; }; 15294 /// } 15295 /// } 15296 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15297 SourceLocation NameLoc) { 15298 // While the decl is in a namespace, do repeated lookup of that name and see 15299 // if we get the same namespace back. If we do not, continue until 15300 // translation unit scope, at which point we have a fully qualified NNS. 15301 SmallVector<IdentifierInfo *, 4> Namespaces; 15302 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15303 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15304 // This tag should be declared in a namespace, which can only be enclosed by 15305 // other namespaces. Bail if there's an anonymous namespace in the chain. 15306 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15307 if (!Namespace || Namespace->isAnonymousNamespace()) 15308 return FixItHint(); 15309 IdentifierInfo *II = Namespace->getIdentifier(); 15310 Namespaces.push_back(II); 15311 NamedDecl *Lookup = SemaRef.LookupSingleName( 15312 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15313 if (Lookup == Namespace) 15314 break; 15315 } 15316 15317 // Once we have all the namespaces, reverse them to go outermost first, and 15318 // build an NNS. 15319 SmallString<64> Insertion; 15320 llvm::raw_svector_ostream OS(Insertion); 15321 if (DC->isTranslationUnit()) 15322 OS << "::"; 15323 std::reverse(Namespaces.begin(), Namespaces.end()); 15324 for (auto *II : Namespaces) 15325 OS << II->getName() << "::"; 15326 return FixItHint::CreateInsertion(NameLoc, Insertion); 15327 } 15328 15329 /// Determine whether a tag originally declared in context \p OldDC can 15330 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15331 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15332 /// using-declaration). 15333 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15334 DeclContext *NewDC) { 15335 OldDC = OldDC->getRedeclContext(); 15336 NewDC = NewDC->getRedeclContext(); 15337 15338 if (OldDC->Equals(NewDC)) 15339 return true; 15340 15341 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15342 // encloses the other). 15343 if (S.getLangOpts().MSVCCompat && 15344 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15345 return true; 15346 15347 return false; 15348 } 15349 15350 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15351 /// former case, Name will be non-null. In the later case, Name will be null. 15352 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15353 /// reference/declaration/definition of a tag. 15354 /// 15355 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15356 /// trailing-type-specifier) other than one in an alias-declaration. 15357 /// 15358 /// \param SkipBody If non-null, will be set to indicate if the caller should 15359 /// skip the definition of this tag and treat it as if it were a declaration. 15360 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15361 SourceLocation KWLoc, CXXScopeSpec &SS, 15362 IdentifierInfo *Name, SourceLocation NameLoc, 15363 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15364 SourceLocation ModulePrivateLoc, 15365 MultiTemplateParamsArg TemplateParameterLists, 15366 bool &OwnedDecl, bool &IsDependent, 15367 SourceLocation ScopedEnumKWLoc, 15368 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15369 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15370 SkipBodyInfo *SkipBody) { 15371 // If this is not a definition, it must have a name. 15372 IdentifierInfo *OrigName = Name; 15373 assert((Name != nullptr || TUK == TUK_Definition) && 15374 "Nameless record must be a definition!"); 15375 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15376 15377 OwnedDecl = false; 15378 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15379 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15380 15381 // FIXME: Check member specializations more carefully. 15382 bool isMemberSpecialization = false; 15383 bool Invalid = false; 15384 15385 // We only need to do this matching if we have template parameters 15386 // or a scope specifier, which also conveniently avoids this work 15387 // for non-C++ cases. 15388 if (TemplateParameterLists.size() > 0 || 15389 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15390 if (TemplateParameterList *TemplateParams = 15391 MatchTemplateParametersToScopeSpecifier( 15392 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15393 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15394 if (Kind == TTK_Enum) { 15395 Diag(KWLoc, diag::err_enum_template); 15396 return nullptr; 15397 } 15398 15399 if (TemplateParams->size() > 0) { 15400 // This is a declaration or definition of a class template (which may 15401 // be a member of another template). 15402 15403 if (Invalid) 15404 return nullptr; 15405 15406 OwnedDecl = false; 15407 DeclResult Result = CheckClassTemplate( 15408 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15409 AS, ModulePrivateLoc, 15410 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15411 TemplateParameterLists.data(), SkipBody); 15412 return Result.get(); 15413 } else { 15414 // The "template<>" header is extraneous. 15415 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15416 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15417 isMemberSpecialization = true; 15418 } 15419 } 15420 15421 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15422 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15423 return nullptr; 15424 } 15425 15426 // Figure out the underlying type if this a enum declaration. We need to do 15427 // this early, because it's needed to detect if this is an incompatible 15428 // redeclaration. 15429 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15430 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15431 15432 if (Kind == TTK_Enum) { 15433 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15434 // No underlying type explicitly specified, or we failed to parse the 15435 // type, default to int. 15436 EnumUnderlying = Context.IntTy.getTypePtr(); 15437 } else if (UnderlyingType.get()) { 15438 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15439 // integral type; any cv-qualification is ignored. 15440 TypeSourceInfo *TI = nullptr; 15441 GetTypeFromParser(UnderlyingType.get(), &TI); 15442 EnumUnderlying = TI; 15443 15444 if (CheckEnumUnderlyingType(TI)) 15445 // Recover by falling back to int. 15446 EnumUnderlying = Context.IntTy.getTypePtr(); 15447 15448 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15449 UPPC_FixedUnderlyingType)) 15450 EnumUnderlying = Context.IntTy.getTypePtr(); 15451 15452 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15453 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15454 // of 'int'. However, if this is an unfixed forward declaration, don't set 15455 // the underlying type unless the user enables -fms-compatibility. This 15456 // makes unfixed forward declared enums incomplete and is more conforming. 15457 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15458 EnumUnderlying = Context.IntTy.getTypePtr(); 15459 } 15460 } 15461 15462 DeclContext *SearchDC = CurContext; 15463 DeclContext *DC = CurContext; 15464 bool isStdBadAlloc = false; 15465 bool isStdAlignValT = false; 15466 15467 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15468 if (TUK == TUK_Friend || TUK == TUK_Reference) 15469 Redecl = NotForRedeclaration; 15470 15471 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15472 /// implemented asks for structural equivalence checking, the returned decl 15473 /// here is passed back to the parser, allowing the tag body to be parsed. 15474 auto createTagFromNewDecl = [&]() -> TagDecl * { 15475 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15476 // If there is an identifier, use the location of the identifier as the 15477 // location of the decl, otherwise use the location of the struct/union 15478 // keyword. 15479 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15480 TagDecl *New = nullptr; 15481 15482 if (Kind == TTK_Enum) { 15483 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15484 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15485 // If this is an undefined enum, bail. 15486 if (TUK != TUK_Definition && !Invalid) 15487 return nullptr; 15488 if (EnumUnderlying) { 15489 EnumDecl *ED = cast<EnumDecl>(New); 15490 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15491 ED->setIntegerTypeSourceInfo(TI); 15492 else 15493 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15494 ED->setPromotionType(ED->getIntegerType()); 15495 } 15496 } else { // struct/union 15497 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15498 nullptr); 15499 } 15500 15501 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15502 // Add alignment attributes if necessary; these attributes are checked 15503 // when the ASTContext lays out the structure. 15504 // 15505 // It is important for implementing the correct semantics that this 15506 // happen here (in ActOnTag). The #pragma pack stack is 15507 // maintained as a result of parser callbacks which can occur at 15508 // many points during the parsing of a struct declaration (because 15509 // the #pragma tokens are effectively skipped over during the 15510 // parsing of the struct). 15511 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15512 AddAlignmentAttributesForRecord(RD); 15513 AddMsStructLayoutForRecord(RD); 15514 } 15515 } 15516 New->setLexicalDeclContext(CurContext); 15517 return New; 15518 }; 15519 15520 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15521 if (Name && SS.isNotEmpty()) { 15522 // We have a nested-name tag ('struct foo::bar'). 15523 15524 // Check for invalid 'foo::'. 15525 if (SS.isInvalid()) { 15526 Name = nullptr; 15527 goto CreateNewDecl; 15528 } 15529 15530 // If this is a friend or a reference to a class in a dependent 15531 // context, don't try to make a decl for it. 15532 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15533 DC = computeDeclContext(SS, false); 15534 if (!DC) { 15535 IsDependent = true; 15536 return nullptr; 15537 } 15538 } else { 15539 DC = computeDeclContext(SS, true); 15540 if (!DC) { 15541 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15542 << SS.getRange(); 15543 return nullptr; 15544 } 15545 } 15546 15547 if (RequireCompleteDeclContext(SS, DC)) 15548 return nullptr; 15549 15550 SearchDC = DC; 15551 // Look-up name inside 'foo::'. 15552 LookupQualifiedName(Previous, DC); 15553 15554 if (Previous.isAmbiguous()) 15555 return nullptr; 15556 15557 if (Previous.empty()) { 15558 // Name lookup did not find anything. However, if the 15559 // nested-name-specifier refers to the current instantiation, 15560 // and that current instantiation has any dependent base 15561 // classes, we might find something at instantiation time: treat 15562 // this as a dependent elaborated-type-specifier. 15563 // But this only makes any sense for reference-like lookups. 15564 if (Previous.wasNotFoundInCurrentInstantiation() && 15565 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15566 IsDependent = true; 15567 return nullptr; 15568 } 15569 15570 // A tag 'foo::bar' must already exist. 15571 Diag(NameLoc, diag::err_not_tag_in_scope) 15572 << Kind << Name << DC << SS.getRange(); 15573 Name = nullptr; 15574 Invalid = true; 15575 goto CreateNewDecl; 15576 } 15577 } else if (Name) { 15578 // C++14 [class.mem]p14: 15579 // If T is the name of a class, then each of the following shall have a 15580 // name different from T: 15581 // -- every member of class T that is itself a type 15582 if (TUK != TUK_Reference && TUK != TUK_Friend && 15583 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15584 return nullptr; 15585 15586 // If this is a named struct, check to see if there was a previous forward 15587 // declaration or definition. 15588 // FIXME: We're looking into outer scopes here, even when we 15589 // shouldn't be. Doing so can result in ambiguities that we 15590 // shouldn't be diagnosing. 15591 LookupName(Previous, S); 15592 15593 // When declaring or defining a tag, ignore ambiguities introduced 15594 // by types using'ed into this scope. 15595 if (Previous.isAmbiguous() && 15596 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15597 LookupResult::Filter F = Previous.makeFilter(); 15598 while (F.hasNext()) { 15599 NamedDecl *ND = F.next(); 15600 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15601 SearchDC->getRedeclContext())) 15602 F.erase(); 15603 } 15604 F.done(); 15605 } 15606 15607 // C++11 [namespace.memdef]p3: 15608 // If the name in a friend declaration is neither qualified nor 15609 // a template-id and the declaration is a function or an 15610 // elaborated-type-specifier, the lookup to determine whether 15611 // the entity has been previously declared shall not consider 15612 // any scopes outside the innermost enclosing namespace. 15613 // 15614 // MSVC doesn't implement the above rule for types, so a friend tag 15615 // declaration may be a redeclaration of a type declared in an enclosing 15616 // scope. They do implement this rule for friend functions. 15617 // 15618 // Does it matter that this should be by scope instead of by 15619 // semantic context? 15620 if (!Previous.empty() && TUK == TUK_Friend) { 15621 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15622 LookupResult::Filter F = Previous.makeFilter(); 15623 bool FriendSawTagOutsideEnclosingNamespace = false; 15624 while (F.hasNext()) { 15625 NamedDecl *ND = F.next(); 15626 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15627 if (DC->isFileContext() && 15628 !EnclosingNS->Encloses(ND->getDeclContext())) { 15629 if (getLangOpts().MSVCCompat) 15630 FriendSawTagOutsideEnclosingNamespace = true; 15631 else 15632 F.erase(); 15633 } 15634 } 15635 F.done(); 15636 15637 // Diagnose this MSVC extension in the easy case where lookup would have 15638 // unambiguously found something outside the enclosing namespace. 15639 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15640 NamedDecl *ND = Previous.getFoundDecl(); 15641 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15642 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15643 } 15644 } 15645 15646 // Note: there used to be some attempt at recovery here. 15647 if (Previous.isAmbiguous()) 15648 return nullptr; 15649 15650 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15651 // FIXME: This makes sure that we ignore the contexts associated 15652 // with C structs, unions, and enums when looking for a matching 15653 // tag declaration or definition. See the similar lookup tweak 15654 // in Sema::LookupName; is there a better way to deal with this? 15655 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15656 SearchDC = SearchDC->getParent(); 15657 } 15658 } 15659 15660 if (Previous.isSingleResult() && 15661 Previous.getFoundDecl()->isTemplateParameter()) { 15662 // Maybe we will complain about the shadowed template parameter. 15663 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15664 // Just pretend that we didn't see the previous declaration. 15665 Previous.clear(); 15666 } 15667 15668 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15669 DC->Equals(getStdNamespace())) { 15670 if (Name->isStr("bad_alloc")) { 15671 // This is a declaration of or a reference to "std::bad_alloc". 15672 isStdBadAlloc = true; 15673 15674 // If std::bad_alloc has been implicitly declared (but made invisible to 15675 // name lookup), fill in this implicit declaration as the previous 15676 // declaration, so that the declarations get chained appropriately. 15677 if (Previous.empty() && StdBadAlloc) 15678 Previous.addDecl(getStdBadAlloc()); 15679 } else if (Name->isStr("align_val_t")) { 15680 isStdAlignValT = true; 15681 if (Previous.empty() && StdAlignValT) 15682 Previous.addDecl(getStdAlignValT()); 15683 } 15684 } 15685 15686 // If we didn't find a previous declaration, and this is a reference 15687 // (or friend reference), move to the correct scope. In C++, we 15688 // also need to do a redeclaration lookup there, just in case 15689 // there's a shadow friend decl. 15690 if (Name && Previous.empty() && 15691 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15692 if (Invalid) goto CreateNewDecl; 15693 assert(SS.isEmpty()); 15694 15695 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15696 // C++ [basic.scope.pdecl]p5: 15697 // -- for an elaborated-type-specifier of the form 15698 // 15699 // class-key identifier 15700 // 15701 // if the elaborated-type-specifier is used in the 15702 // decl-specifier-seq or parameter-declaration-clause of a 15703 // function defined in namespace scope, the identifier is 15704 // declared as a class-name in the namespace that contains 15705 // the declaration; otherwise, except as a friend 15706 // declaration, the identifier is declared in the smallest 15707 // non-class, non-function-prototype scope that contains the 15708 // declaration. 15709 // 15710 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15711 // C structs and unions. 15712 // 15713 // It is an error in C++ to declare (rather than define) an enum 15714 // type, including via an elaborated type specifier. We'll 15715 // diagnose that later; for now, declare the enum in the same 15716 // scope as we would have picked for any other tag type. 15717 // 15718 // GNU C also supports this behavior as part of its incomplete 15719 // enum types extension, while GNU C++ does not. 15720 // 15721 // Find the context where we'll be declaring the tag. 15722 // FIXME: We would like to maintain the current DeclContext as the 15723 // lexical context, 15724 SearchDC = getTagInjectionContext(SearchDC); 15725 15726 // Find the scope where we'll be declaring the tag. 15727 S = getTagInjectionScope(S, getLangOpts()); 15728 } else { 15729 assert(TUK == TUK_Friend); 15730 // C++ [namespace.memdef]p3: 15731 // If a friend declaration in a non-local class first declares a 15732 // class or function, the friend class or function is a member of 15733 // the innermost enclosing namespace. 15734 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15735 } 15736 15737 // In C++, we need to do a redeclaration lookup to properly 15738 // diagnose some problems. 15739 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15740 // hidden declaration so that we don't get ambiguity errors when using a 15741 // type declared by an elaborated-type-specifier. In C that is not correct 15742 // and we should instead merge compatible types found by lookup. 15743 if (getLangOpts().CPlusPlus) { 15744 // FIXME: This can perform qualified lookups into function contexts, 15745 // which are meaningless. 15746 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15747 LookupQualifiedName(Previous, SearchDC); 15748 } else { 15749 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15750 LookupName(Previous, S); 15751 } 15752 } 15753 15754 // If we have a known previous declaration to use, then use it. 15755 if (Previous.empty() && SkipBody && SkipBody->Previous) 15756 Previous.addDecl(SkipBody->Previous); 15757 15758 if (!Previous.empty()) { 15759 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15760 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15761 15762 // It's okay to have a tag decl in the same scope as a typedef 15763 // which hides a tag decl in the same scope. Finding this 15764 // insanity with a redeclaration lookup can only actually happen 15765 // in C++. 15766 // 15767 // This is also okay for elaborated-type-specifiers, which is 15768 // technically forbidden by the current standard but which is 15769 // okay according to the likely resolution of an open issue; 15770 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15771 if (getLangOpts().CPlusPlus) { 15772 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15773 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15774 TagDecl *Tag = TT->getDecl(); 15775 if (Tag->getDeclName() == Name && 15776 Tag->getDeclContext()->getRedeclContext() 15777 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15778 PrevDecl = Tag; 15779 Previous.clear(); 15780 Previous.addDecl(Tag); 15781 Previous.resolveKind(); 15782 } 15783 } 15784 } 15785 } 15786 15787 // If this is a redeclaration of a using shadow declaration, it must 15788 // declare a tag in the same context. In MSVC mode, we allow a 15789 // redefinition if either context is within the other. 15790 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15791 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15792 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15793 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15794 !(OldTag && isAcceptableTagRedeclContext( 15795 *this, OldTag->getDeclContext(), SearchDC))) { 15796 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15797 Diag(Shadow->getTargetDecl()->getLocation(), 15798 diag::note_using_decl_target); 15799 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15800 << 0; 15801 // Recover by ignoring the old declaration. 15802 Previous.clear(); 15803 goto CreateNewDecl; 15804 } 15805 } 15806 15807 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15808 // If this is a use of a previous tag, or if the tag is already declared 15809 // in the same scope (so that the definition/declaration completes or 15810 // rementions the tag), reuse the decl. 15811 if (TUK == TUK_Reference || TUK == TUK_Friend || 15812 isDeclInScope(DirectPrevDecl, SearchDC, S, 15813 SS.isNotEmpty() || isMemberSpecialization)) { 15814 // Make sure that this wasn't declared as an enum and now used as a 15815 // struct or something similar. 15816 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15817 TUK == TUK_Definition, KWLoc, 15818 Name)) { 15819 bool SafeToContinue 15820 = (PrevTagDecl->getTagKind() != TTK_Enum && 15821 Kind != TTK_Enum); 15822 if (SafeToContinue) 15823 Diag(KWLoc, diag::err_use_with_wrong_tag) 15824 << Name 15825 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15826 PrevTagDecl->getKindName()); 15827 else 15828 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15829 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15830 15831 if (SafeToContinue) 15832 Kind = PrevTagDecl->getTagKind(); 15833 else { 15834 // Recover by making this an anonymous redefinition. 15835 Name = nullptr; 15836 Previous.clear(); 15837 Invalid = true; 15838 } 15839 } 15840 15841 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15842 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15843 if (TUK == TUK_Reference || TUK == TUK_Friend) 15844 return PrevTagDecl; 15845 15846 QualType EnumUnderlyingTy; 15847 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15848 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15849 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15850 EnumUnderlyingTy = QualType(T, 0); 15851 15852 // All conflicts with previous declarations are recovered by 15853 // returning the previous declaration, unless this is a definition, 15854 // in which case we want the caller to bail out. 15855 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15856 ScopedEnum, EnumUnderlyingTy, 15857 IsFixed, PrevEnum)) 15858 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15859 } 15860 15861 // C++11 [class.mem]p1: 15862 // A member shall not be declared twice in the member-specification, 15863 // except that a nested class or member class template can be declared 15864 // and then later defined. 15865 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15866 S->isDeclScope(PrevDecl)) { 15867 Diag(NameLoc, diag::ext_member_redeclared); 15868 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15869 } 15870 15871 if (!Invalid) { 15872 // If this is a use, just return the declaration we found, unless 15873 // we have attributes. 15874 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15875 if (!Attrs.empty()) { 15876 // FIXME: Diagnose these attributes. For now, we create a new 15877 // declaration to hold them. 15878 } else if (TUK == TUK_Reference && 15879 (PrevTagDecl->getFriendObjectKind() == 15880 Decl::FOK_Undeclared || 15881 PrevDecl->getOwningModule() != getCurrentModule()) && 15882 SS.isEmpty()) { 15883 // This declaration is a reference to an existing entity, but 15884 // has different visibility from that entity: it either makes 15885 // a friend visible or it makes a type visible in a new module. 15886 // In either case, create a new declaration. We only do this if 15887 // the declaration would have meant the same thing if no prior 15888 // declaration were found, that is, if it was found in the same 15889 // scope where we would have injected a declaration. 15890 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15891 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15892 return PrevTagDecl; 15893 // This is in the injected scope, create a new declaration in 15894 // that scope. 15895 S = getTagInjectionScope(S, getLangOpts()); 15896 } else { 15897 return PrevTagDecl; 15898 } 15899 } 15900 15901 // Diagnose attempts to redefine a tag. 15902 if (TUK == TUK_Definition) { 15903 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15904 // If we're defining a specialization and the previous definition 15905 // is from an implicit instantiation, don't emit an error 15906 // here; we'll catch this in the general case below. 15907 bool IsExplicitSpecializationAfterInstantiation = false; 15908 if (isMemberSpecialization) { 15909 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15910 IsExplicitSpecializationAfterInstantiation = 15911 RD->getTemplateSpecializationKind() != 15912 TSK_ExplicitSpecialization; 15913 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15914 IsExplicitSpecializationAfterInstantiation = 15915 ED->getTemplateSpecializationKind() != 15916 TSK_ExplicitSpecialization; 15917 } 15918 15919 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15920 // not keep more that one definition around (merge them). However, 15921 // ensure the decl passes the structural compatibility check in 15922 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15923 NamedDecl *Hidden = nullptr; 15924 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15925 // There is a definition of this tag, but it is not visible. We 15926 // explicitly make use of C++'s one definition rule here, and 15927 // assume that this definition is identical to the hidden one 15928 // we already have. Make the existing definition visible and 15929 // use it in place of this one. 15930 if (!getLangOpts().CPlusPlus) { 15931 // Postpone making the old definition visible until after we 15932 // complete parsing the new one and do the structural 15933 // comparison. 15934 SkipBody->CheckSameAsPrevious = true; 15935 SkipBody->New = createTagFromNewDecl(); 15936 SkipBody->Previous = Def; 15937 return Def; 15938 } else { 15939 SkipBody->ShouldSkip = true; 15940 SkipBody->Previous = Def; 15941 makeMergedDefinitionVisible(Hidden); 15942 // Carry on and handle it like a normal definition. We'll 15943 // skip starting the definitiion later. 15944 } 15945 } else if (!IsExplicitSpecializationAfterInstantiation) { 15946 // A redeclaration in function prototype scope in C isn't 15947 // visible elsewhere, so merely issue a warning. 15948 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 15949 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 15950 else 15951 Diag(NameLoc, diag::err_redefinition) << Name; 15952 notePreviousDefinition(Def, 15953 NameLoc.isValid() ? NameLoc : KWLoc); 15954 // If this is a redefinition, recover by making this 15955 // struct be anonymous, which will make any later 15956 // references get the previous definition. 15957 Name = nullptr; 15958 Previous.clear(); 15959 Invalid = true; 15960 } 15961 } else { 15962 // If the type is currently being defined, complain 15963 // about a nested redefinition. 15964 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 15965 if (TD->isBeingDefined()) { 15966 Diag(NameLoc, diag::err_nested_redefinition) << Name; 15967 Diag(PrevTagDecl->getLocation(), 15968 diag::note_previous_definition); 15969 Name = nullptr; 15970 Previous.clear(); 15971 Invalid = true; 15972 } 15973 } 15974 15975 // Okay, this is definition of a previously declared or referenced 15976 // tag. We're going to create a new Decl for it. 15977 } 15978 15979 // Okay, we're going to make a redeclaration. If this is some kind 15980 // of reference, make sure we build the redeclaration in the same DC 15981 // as the original, and ignore the current access specifier. 15982 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15983 SearchDC = PrevTagDecl->getDeclContext(); 15984 AS = AS_none; 15985 } 15986 } 15987 // If we get here we have (another) forward declaration or we 15988 // have a definition. Just create a new decl. 15989 15990 } else { 15991 // If we get here, this is a definition of a new tag type in a nested 15992 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 15993 // new decl/type. We set PrevDecl to NULL so that the entities 15994 // have distinct types. 15995 Previous.clear(); 15996 } 15997 // If we get here, we're going to create a new Decl. If PrevDecl 15998 // is non-NULL, it's a definition of the tag declared by 15999 // PrevDecl. If it's NULL, we have a new definition. 16000 16001 // Otherwise, PrevDecl is not a tag, but was found with tag 16002 // lookup. This is only actually possible in C++, where a few 16003 // things like templates still live in the tag namespace. 16004 } else { 16005 // Use a better diagnostic if an elaborated-type-specifier 16006 // found the wrong kind of type on the first 16007 // (non-redeclaration) lookup. 16008 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16009 !Previous.isForRedeclaration()) { 16010 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16011 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16012 << Kind; 16013 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16014 Invalid = true; 16015 16016 // Otherwise, only diagnose if the declaration is in scope. 16017 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16018 SS.isNotEmpty() || isMemberSpecialization)) { 16019 // do nothing 16020 16021 // Diagnose implicit declarations introduced by elaborated types. 16022 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16023 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16024 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16025 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16026 Invalid = true; 16027 16028 // Otherwise it's a declaration. Call out a particularly common 16029 // case here. 16030 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16031 unsigned Kind = 0; 16032 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16033 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16034 << Name << Kind << TND->getUnderlyingType(); 16035 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16036 Invalid = true; 16037 16038 // Otherwise, diagnose. 16039 } else { 16040 // The tag name clashes with something else in the target scope, 16041 // issue an error and recover by making this tag be anonymous. 16042 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16043 notePreviousDefinition(PrevDecl, NameLoc); 16044 Name = nullptr; 16045 Invalid = true; 16046 } 16047 16048 // The existing declaration isn't relevant to us; we're in a 16049 // new scope, so clear out the previous declaration. 16050 Previous.clear(); 16051 } 16052 } 16053 16054 CreateNewDecl: 16055 16056 TagDecl *PrevDecl = nullptr; 16057 if (Previous.isSingleResult()) 16058 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16059 16060 // If there is an identifier, use the location of the identifier as the 16061 // location of the decl, otherwise use the location of the struct/union 16062 // keyword. 16063 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16064 16065 // Otherwise, create a new declaration. If there is a previous 16066 // declaration of the same entity, the two will be linked via 16067 // PrevDecl. 16068 TagDecl *New; 16069 16070 if (Kind == TTK_Enum) { 16071 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16072 // enum X { A, B, C } D; D should chain to X. 16073 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16074 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16075 ScopedEnumUsesClassTag, IsFixed); 16076 16077 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16078 StdAlignValT = cast<EnumDecl>(New); 16079 16080 // If this is an undefined enum, warn. 16081 if (TUK != TUK_Definition && !Invalid) { 16082 TagDecl *Def; 16083 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16084 // C++0x: 7.2p2: opaque-enum-declaration. 16085 // Conflicts are diagnosed above. Do nothing. 16086 } 16087 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16088 Diag(Loc, diag::ext_forward_ref_enum_def) 16089 << New; 16090 Diag(Def->getLocation(), diag::note_previous_definition); 16091 } else { 16092 unsigned DiagID = diag::ext_forward_ref_enum; 16093 if (getLangOpts().MSVCCompat) 16094 DiagID = diag::ext_ms_forward_ref_enum; 16095 else if (getLangOpts().CPlusPlus) 16096 DiagID = diag::err_forward_ref_enum; 16097 Diag(Loc, DiagID); 16098 } 16099 } 16100 16101 if (EnumUnderlying) { 16102 EnumDecl *ED = cast<EnumDecl>(New); 16103 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16104 ED->setIntegerTypeSourceInfo(TI); 16105 else 16106 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16107 ED->setPromotionType(ED->getIntegerType()); 16108 assert(ED->isComplete() && "enum with type should be complete"); 16109 } 16110 } else { 16111 // struct/union/class 16112 16113 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16114 // struct X { int A; } D; D should chain to X. 16115 if (getLangOpts().CPlusPlus) { 16116 // FIXME: Look for a way to use RecordDecl for simple structs. 16117 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16118 cast_or_null<CXXRecordDecl>(PrevDecl)); 16119 16120 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16121 StdBadAlloc = cast<CXXRecordDecl>(New); 16122 } else 16123 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16124 cast_or_null<RecordDecl>(PrevDecl)); 16125 } 16126 16127 // C++11 [dcl.type]p3: 16128 // A type-specifier-seq shall not define a class or enumeration [...]. 16129 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16130 TUK == TUK_Definition) { 16131 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16132 << Context.getTagDeclType(New); 16133 Invalid = true; 16134 } 16135 16136 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16137 DC->getDeclKind() == Decl::Enum) { 16138 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16139 << Context.getTagDeclType(New); 16140 Invalid = true; 16141 } 16142 16143 // Maybe add qualifier info. 16144 if (SS.isNotEmpty()) { 16145 if (SS.isSet()) { 16146 // If this is either a declaration or a definition, check the 16147 // nested-name-specifier against the current context. 16148 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16149 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16150 isMemberSpecialization)) 16151 Invalid = true; 16152 16153 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16154 if (TemplateParameterLists.size() > 0) { 16155 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16156 } 16157 } 16158 else 16159 Invalid = true; 16160 } 16161 16162 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16163 // Add alignment attributes if necessary; these attributes are checked when 16164 // the ASTContext lays out the structure. 16165 // 16166 // It is important for implementing the correct semantics that this 16167 // happen here (in ActOnTag). The #pragma pack stack is 16168 // maintained as a result of parser callbacks which can occur at 16169 // many points during the parsing of a struct declaration (because 16170 // the #pragma tokens are effectively skipped over during the 16171 // parsing of the struct). 16172 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16173 AddAlignmentAttributesForRecord(RD); 16174 AddMsStructLayoutForRecord(RD); 16175 } 16176 } 16177 16178 if (ModulePrivateLoc.isValid()) { 16179 if (isMemberSpecialization) 16180 Diag(New->getLocation(), diag::err_module_private_specialization) 16181 << 2 16182 << FixItHint::CreateRemoval(ModulePrivateLoc); 16183 // __module_private__ does not apply to local classes. However, we only 16184 // diagnose this as an error when the declaration specifiers are 16185 // freestanding. Here, we just ignore the __module_private__. 16186 else if (!SearchDC->isFunctionOrMethod()) 16187 New->setModulePrivate(); 16188 } 16189 16190 // If this is a specialization of a member class (of a class template), 16191 // check the specialization. 16192 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16193 Invalid = true; 16194 16195 // If we're declaring or defining a tag in function prototype scope in C, 16196 // note that this type can only be used within the function and add it to 16197 // the list of decls to inject into the function definition scope. 16198 if ((Name || Kind == TTK_Enum) && 16199 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16200 if (getLangOpts().CPlusPlus) { 16201 // C++ [dcl.fct]p6: 16202 // Types shall not be defined in return or parameter types. 16203 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16204 Diag(Loc, diag::err_type_defined_in_param_type) 16205 << Name; 16206 Invalid = true; 16207 } 16208 } else if (!PrevDecl) { 16209 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16210 } 16211 } 16212 16213 if (Invalid) 16214 New->setInvalidDecl(); 16215 16216 // Set the lexical context. If the tag has a C++ scope specifier, the 16217 // lexical context will be different from the semantic context. 16218 New->setLexicalDeclContext(CurContext); 16219 16220 // Mark this as a friend decl if applicable. 16221 // In Microsoft mode, a friend declaration also acts as a forward 16222 // declaration so we always pass true to setObjectOfFriendDecl to make 16223 // the tag name visible. 16224 if (TUK == TUK_Friend) 16225 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16226 16227 // Set the access specifier. 16228 if (!Invalid && SearchDC->isRecord()) 16229 SetMemberAccessSpecifier(New, PrevDecl, AS); 16230 16231 if (PrevDecl) 16232 CheckRedeclarationModuleOwnership(New, PrevDecl); 16233 16234 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16235 New->startDefinition(); 16236 16237 ProcessDeclAttributeList(S, New, Attrs); 16238 AddPragmaAttributes(S, New); 16239 16240 // If this has an identifier, add it to the scope stack. 16241 if (TUK == TUK_Friend) { 16242 // We might be replacing an existing declaration in the lookup tables; 16243 // if so, borrow its access specifier. 16244 if (PrevDecl) 16245 New->setAccess(PrevDecl->getAccess()); 16246 16247 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16248 DC->makeDeclVisibleInContext(New); 16249 if (Name) // can be null along some error paths 16250 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16251 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16252 } else if (Name) { 16253 S = getNonFieldDeclScope(S); 16254 PushOnScopeChains(New, S, true); 16255 } else { 16256 CurContext->addDecl(New); 16257 } 16258 16259 // If this is the C FILE type, notify the AST context. 16260 if (IdentifierInfo *II = New->getIdentifier()) 16261 if (!New->isInvalidDecl() && 16262 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16263 II->isStr("FILE")) 16264 Context.setFILEDecl(New); 16265 16266 if (PrevDecl) 16267 mergeDeclAttributes(New, PrevDecl); 16268 16269 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16270 inferGslOwnerPointerAttribute(CXXRD); 16271 16272 // If there's a #pragma GCC visibility in scope, set the visibility of this 16273 // record. 16274 AddPushedVisibilityAttribute(New); 16275 16276 if (isMemberSpecialization && !New->isInvalidDecl()) 16277 CompleteMemberSpecialization(New, Previous); 16278 16279 OwnedDecl = true; 16280 // In C++, don't return an invalid declaration. We can't recover well from 16281 // the cases where we make the type anonymous. 16282 if (Invalid && getLangOpts().CPlusPlus) { 16283 if (New->isBeingDefined()) 16284 if (auto RD = dyn_cast<RecordDecl>(New)) 16285 RD->completeDefinition(); 16286 return nullptr; 16287 } else if (SkipBody && SkipBody->ShouldSkip) { 16288 return SkipBody->Previous; 16289 } else { 16290 return New; 16291 } 16292 } 16293 16294 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16295 AdjustDeclIfTemplate(TagD); 16296 TagDecl *Tag = cast<TagDecl>(TagD); 16297 16298 // Enter the tag context. 16299 PushDeclContext(S, Tag); 16300 16301 ActOnDocumentableDecl(TagD); 16302 16303 // If there's a #pragma GCC visibility in scope, set the visibility of this 16304 // record. 16305 AddPushedVisibilityAttribute(Tag); 16306 } 16307 16308 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16309 SkipBodyInfo &SkipBody) { 16310 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16311 return false; 16312 16313 // Make the previous decl visible. 16314 makeMergedDefinitionVisible(SkipBody.Previous); 16315 return true; 16316 } 16317 16318 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16319 assert(isa<ObjCContainerDecl>(IDecl) && 16320 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16321 DeclContext *OCD = cast<DeclContext>(IDecl); 16322 assert(OCD->getLexicalParent() == CurContext && 16323 "The next DeclContext should be lexically contained in the current one."); 16324 CurContext = OCD; 16325 return IDecl; 16326 } 16327 16328 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16329 SourceLocation FinalLoc, 16330 bool IsFinalSpelledSealed, 16331 SourceLocation LBraceLoc) { 16332 AdjustDeclIfTemplate(TagD); 16333 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16334 16335 FieldCollector->StartClass(); 16336 16337 if (!Record->getIdentifier()) 16338 return; 16339 16340 if (FinalLoc.isValid()) 16341 Record->addAttr(FinalAttr::Create( 16342 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16343 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16344 16345 // C++ [class]p2: 16346 // [...] The class-name is also inserted into the scope of the 16347 // class itself; this is known as the injected-class-name. For 16348 // purposes of access checking, the injected-class-name is treated 16349 // as if it were a public member name. 16350 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16351 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16352 Record->getLocation(), Record->getIdentifier(), 16353 /*PrevDecl=*/nullptr, 16354 /*DelayTypeCreation=*/true); 16355 Context.getTypeDeclType(InjectedClassName, Record); 16356 InjectedClassName->setImplicit(); 16357 InjectedClassName->setAccess(AS_public); 16358 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16359 InjectedClassName->setDescribedClassTemplate(Template); 16360 PushOnScopeChains(InjectedClassName, S); 16361 assert(InjectedClassName->isInjectedClassName() && 16362 "Broken injected-class-name"); 16363 } 16364 16365 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16366 SourceRange BraceRange) { 16367 AdjustDeclIfTemplate(TagD); 16368 TagDecl *Tag = cast<TagDecl>(TagD); 16369 Tag->setBraceRange(BraceRange); 16370 16371 // Make sure we "complete" the definition even it is invalid. 16372 if (Tag->isBeingDefined()) { 16373 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16374 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16375 RD->completeDefinition(); 16376 } 16377 16378 if (isa<CXXRecordDecl>(Tag)) { 16379 FieldCollector->FinishClass(); 16380 } 16381 16382 // Exit this scope of this tag's definition. 16383 PopDeclContext(); 16384 16385 if (getCurLexicalContext()->isObjCContainer() && 16386 Tag->getDeclContext()->isFileContext()) 16387 Tag->setTopLevelDeclInObjCContainer(); 16388 16389 // Notify the consumer that we've defined a tag. 16390 if (!Tag->isInvalidDecl()) 16391 Consumer.HandleTagDeclDefinition(Tag); 16392 } 16393 16394 void Sema::ActOnObjCContainerFinishDefinition() { 16395 // Exit this scope of this interface definition. 16396 PopDeclContext(); 16397 } 16398 16399 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16400 assert(DC == CurContext && "Mismatch of container contexts"); 16401 OriginalLexicalContext = DC; 16402 ActOnObjCContainerFinishDefinition(); 16403 } 16404 16405 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16406 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16407 OriginalLexicalContext = nullptr; 16408 } 16409 16410 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16411 AdjustDeclIfTemplate(TagD); 16412 TagDecl *Tag = cast<TagDecl>(TagD); 16413 Tag->setInvalidDecl(); 16414 16415 // Make sure we "complete" the definition even it is invalid. 16416 if (Tag->isBeingDefined()) { 16417 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16418 RD->completeDefinition(); 16419 } 16420 16421 // We're undoing ActOnTagStartDefinition here, not 16422 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16423 // the FieldCollector. 16424 16425 PopDeclContext(); 16426 } 16427 16428 // Note that FieldName may be null for anonymous bitfields. 16429 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16430 IdentifierInfo *FieldName, 16431 QualType FieldTy, bool IsMsStruct, 16432 Expr *BitWidth, bool *ZeroWidth) { 16433 assert(BitWidth); 16434 if (BitWidth->containsErrors()) 16435 return ExprError(); 16436 16437 // Default to true; that shouldn't confuse checks for emptiness 16438 if (ZeroWidth) 16439 *ZeroWidth = true; 16440 16441 // C99 6.7.2.1p4 - verify the field type. 16442 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16443 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16444 // Handle incomplete and sizeless types with a specific error. 16445 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16446 diag::err_field_incomplete_or_sizeless)) 16447 return ExprError(); 16448 if (FieldName) 16449 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16450 << FieldName << FieldTy << BitWidth->getSourceRange(); 16451 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16452 << FieldTy << BitWidth->getSourceRange(); 16453 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16454 UPPC_BitFieldWidth)) 16455 return ExprError(); 16456 16457 // If the bit-width is type- or value-dependent, don't try to check 16458 // it now. 16459 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16460 return BitWidth; 16461 16462 llvm::APSInt Value; 16463 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 16464 if (ICE.isInvalid()) 16465 return ICE; 16466 BitWidth = ICE.get(); 16467 16468 if (Value != 0 && ZeroWidth) 16469 *ZeroWidth = false; 16470 16471 // Zero-width bitfield is ok for anonymous field. 16472 if (Value == 0 && FieldName) 16473 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16474 16475 if (Value.isSigned() && Value.isNegative()) { 16476 if (FieldName) 16477 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16478 << FieldName << Value.toString(10); 16479 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16480 << Value.toString(10); 16481 } 16482 16483 // The size of the bit-field must not exceed our maximum permitted object 16484 // size. 16485 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 16486 return Diag(FieldLoc, diag::err_bitfield_too_wide) 16487 << !FieldName << FieldName << Value.toString(10); 16488 } 16489 16490 if (!FieldTy->isDependentType()) { 16491 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16492 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16493 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16494 16495 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16496 // ABI. 16497 bool CStdConstraintViolation = 16498 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16499 bool MSBitfieldViolation = 16500 Value.ugt(TypeStorageSize) && 16501 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16502 if (CStdConstraintViolation || MSBitfieldViolation) { 16503 unsigned DiagWidth = 16504 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16505 if (FieldName) 16506 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16507 << FieldName << Value.toString(10) 16508 << !CStdConstraintViolation << DiagWidth; 16509 16510 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16511 << Value.toString(10) << !CStdConstraintViolation 16512 << DiagWidth; 16513 } 16514 16515 // Warn on types where the user might conceivably expect to get all 16516 // specified bits as value bits: that's all integral types other than 16517 // 'bool'. 16518 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 16519 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16520 << FieldName << Value.toString(10) 16521 << (unsigned)TypeWidth; 16522 } 16523 } 16524 16525 return BitWidth; 16526 } 16527 16528 /// ActOnField - Each field of a C struct/union is passed into this in order 16529 /// to create a FieldDecl object for it. 16530 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16531 Declarator &D, Expr *BitfieldWidth) { 16532 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16533 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16534 /*InitStyle=*/ICIS_NoInit, AS_public); 16535 return Res; 16536 } 16537 16538 /// HandleField - Analyze a field of a C struct or a C++ data member. 16539 /// 16540 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16541 SourceLocation DeclStart, 16542 Declarator &D, Expr *BitWidth, 16543 InClassInitStyle InitStyle, 16544 AccessSpecifier AS) { 16545 if (D.isDecompositionDeclarator()) { 16546 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16547 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16548 << Decomp.getSourceRange(); 16549 return nullptr; 16550 } 16551 16552 IdentifierInfo *II = D.getIdentifier(); 16553 SourceLocation Loc = DeclStart; 16554 if (II) Loc = D.getIdentifierLoc(); 16555 16556 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16557 QualType T = TInfo->getType(); 16558 if (getLangOpts().CPlusPlus) { 16559 CheckExtraCXXDefaultArguments(D); 16560 16561 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16562 UPPC_DataMemberType)) { 16563 D.setInvalidType(); 16564 T = Context.IntTy; 16565 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16566 } 16567 } 16568 16569 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16570 16571 if (D.getDeclSpec().isInlineSpecified()) 16572 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16573 << getLangOpts().CPlusPlus17; 16574 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16575 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16576 diag::err_invalid_thread) 16577 << DeclSpec::getSpecifierName(TSCS); 16578 16579 // Check to see if this name was declared as a member previously 16580 NamedDecl *PrevDecl = nullptr; 16581 LookupResult Previous(*this, II, Loc, LookupMemberName, 16582 ForVisibleRedeclaration); 16583 LookupName(Previous, S); 16584 switch (Previous.getResultKind()) { 16585 case LookupResult::Found: 16586 case LookupResult::FoundUnresolvedValue: 16587 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16588 break; 16589 16590 case LookupResult::FoundOverloaded: 16591 PrevDecl = Previous.getRepresentativeDecl(); 16592 break; 16593 16594 case LookupResult::NotFound: 16595 case LookupResult::NotFoundInCurrentInstantiation: 16596 case LookupResult::Ambiguous: 16597 break; 16598 } 16599 Previous.suppressDiagnostics(); 16600 16601 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16602 // Maybe we will complain about the shadowed template parameter. 16603 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16604 // Just pretend that we didn't see the previous declaration. 16605 PrevDecl = nullptr; 16606 } 16607 16608 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16609 PrevDecl = nullptr; 16610 16611 bool Mutable 16612 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16613 SourceLocation TSSL = D.getBeginLoc(); 16614 FieldDecl *NewFD 16615 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16616 TSSL, AS, PrevDecl, &D); 16617 16618 if (NewFD->isInvalidDecl()) 16619 Record->setInvalidDecl(); 16620 16621 if (D.getDeclSpec().isModulePrivateSpecified()) 16622 NewFD->setModulePrivate(); 16623 16624 if (NewFD->isInvalidDecl() && PrevDecl) { 16625 // Don't introduce NewFD into scope; there's already something 16626 // with the same name in the same scope. 16627 } else if (II) { 16628 PushOnScopeChains(NewFD, S); 16629 } else 16630 Record->addDecl(NewFD); 16631 16632 return NewFD; 16633 } 16634 16635 /// Build a new FieldDecl and check its well-formedness. 16636 /// 16637 /// This routine builds a new FieldDecl given the fields name, type, 16638 /// record, etc. \p PrevDecl should refer to any previous declaration 16639 /// with the same name and in the same scope as the field to be 16640 /// created. 16641 /// 16642 /// \returns a new FieldDecl. 16643 /// 16644 /// \todo The Declarator argument is a hack. It will be removed once 16645 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16646 TypeSourceInfo *TInfo, 16647 RecordDecl *Record, SourceLocation Loc, 16648 bool Mutable, Expr *BitWidth, 16649 InClassInitStyle InitStyle, 16650 SourceLocation TSSL, 16651 AccessSpecifier AS, NamedDecl *PrevDecl, 16652 Declarator *D) { 16653 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16654 bool InvalidDecl = false; 16655 if (D) InvalidDecl = D->isInvalidType(); 16656 16657 // If we receive a broken type, recover by assuming 'int' and 16658 // marking this declaration as invalid. 16659 if (T.isNull() || T->containsErrors()) { 16660 InvalidDecl = true; 16661 T = Context.IntTy; 16662 } 16663 16664 QualType EltTy = Context.getBaseElementType(T); 16665 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16666 if (RequireCompleteSizedType(Loc, EltTy, 16667 diag::err_field_incomplete_or_sizeless)) { 16668 // Fields of incomplete type force their record to be invalid. 16669 Record->setInvalidDecl(); 16670 InvalidDecl = true; 16671 } else { 16672 NamedDecl *Def; 16673 EltTy->isIncompleteType(&Def); 16674 if (Def && Def->isInvalidDecl()) { 16675 Record->setInvalidDecl(); 16676 InvalidDecl = true; 16677 } 16678 } 16679 } 16680 16681 // TR 18037 does not allow fields to be declared with address space 16682 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16683 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16684 Diag(Loc, diag::err_field_with_address_space); 16685 Record->setInvalidDecl(); 16686 InvalidDecl = true; 16687 } 16688 16689 if (LangOpts.OpenCL) { 16690 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16691 // used as structure or union field: image, sampler, event or block types. 16692 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16693 T->isBlockPointerType()) { 16694 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16695 Record->setInvalidDecl(); 16696 InvalidDecl = true; 16697 } 16698 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16699 if (BitWidth) { 16700 Diag(Loc, diag::err_opencl_bitfields); 16701 InvalidDecl = true; 16702 } 16703 } 16704 16705 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16706 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16707 T.hasQualifiers()) { 16708 InvalidDecl = true; 16709 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16710 } 16711 16712 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16713 // than a variably modified type. 16714 if (!InvalidDecl && T->isVariablyModifiedType()) { 16715 if (!tryToFixVariablyModifiedVarType( 16716 *this, TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 16717 InvalidDecl = true; 16718 } 16719 16720 // Fields can not have abstract class types 16721 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16722 diag::err_abstract_type_in_decl, 16723 AbstractFieldType)) 16724 InvalidDecl = true; 16725 16726 bool ZeroWidth = false; 16727 if (InvalidDecl) 16728 BitWidth = nullptr; 16729 // If this is declared as a bit-field, check the bit-field. 16730 if (BitWidth) { 16731 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16732 &ZeroWidth).get(); 16733 if (!BitWidth) { 16734 InvalidDecl = true; 16735 BitWidth = nullptr; 16736 ZeroWidth = false; 16737 } 16738 } 16739 16740 // Check that 'mutable' is consistent with the type of the declaration. 16741 if (!InvalidDecl && Mutable) { 16742 unsigned DiagID = 0; 16743 if (T->isReferenceType()) 16744 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16745 : diag::err_mutable_reference; 16746 else if (T.isConstQualified()) 16747 DiagID = diag::err_mutable_const; 16748 16749 if (DiagID) { 16750 SourceLocation ErrLoc = Loc; 16751 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16752 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16753 Diag(ErrLoc, DiagID); 16754 if (DiagID != diag::ext_mutable_reference) { 16755 Mutable = false; 16756 InvalidDecl = true; 16757 } 16758 } 16759 } 16760 16761 // C++11 [class.union]p8 (DR1460): 16762 // At most one variant member of a union may have a 16763 // brace-or-equal-initializer. 16764 if (InitStyle != ICIS_NoInit) 16765 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16766 16767 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16768 BitWidth, Mutable, InitStyle); 16769 if (InvalidDecl) 16770 NewFD->setInvalidDecl(); 16771 16772 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16773 Diag(Loc, diag::err_duplicate_member) << II; 16774 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16775 NewFD->setInvalidDecl(); 16776 } 16777 16778 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16779 if (Record->isUnion()) { 16780 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16781 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16782 if (RDecl->getDefinition()) { 16783 // C++ [class.union]p1: An object of a class with a non-trivial 16784 // constructor, a non-trivial copy constructor, a non-trivial 16785 // destructor, or a non-trivial copy assignment operator 16786 // cannot be a member of a union, nor can an array of such 16787 // objects. 16788 if (CheckNontrivialField(NewFD)) 16789 NewFD->setInvalidDecl(); 16790 } 16791 } 16792 16793 // C++ [class.union]p1: If a union contains a member of reference type, 16794 // the program is ill-formed, except when compiling with MSVC extensions 16795 // enabled. 16796 if (EltTy->isReferenceType()) { 16797 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16798 diag::ext_union_member_of_reference_type : 16799 diag::err_union_member_of_reference_type) 16800 << NewFD->getDeclName() << EltTy; 16801 if (!getLangOpts().MicrosoftExt) 16802 NewFD->setInvalidDecl(); 16803 } 16804 } 16805 } 16806 16807 // FIXME: We need to pass in the attributes given an AST 16808 // representation, not a parser representation. 16809 if (D) { 16810 // FIXME: The current scope is almost... but not entirely... correct here. 16811 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16812 16813 if (NewFD->hasAttrs()) 16814 CheckAlignasUnderalignment(NewFD); 16815 } 16816 16817 // In auto-retain/release, infer strong retension for fields of 16818 // retainable type. 16819 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16820 NewFD->setInvalidDecl(); 16821 16822 if (T.isObjCGCWeak()) 16823 Diag(Loc, diag::warn_attribute_weak_on_field); 16824 16825 // PPC MMA non-pointer types are not allowed as field types. 16826 if (Context.getTargetInfo().getTriple().isPPC64() && 16827 CheckPPCMMAType(T, NewFD->getLocation())) 16828 NewFD->setInvalidDecl(); 16829 16830 NewFD->setAccess(AS); 16831 return NewFD; 16832 } 16833 16834 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16835 assert(FD); 16836 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16837 16838 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16839 return false; 16840 16841 QualType EltTy = Context.getBaseElementType(FD->getType()); 16842 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16843 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16844 if (RDecl->getDefinition()) { 16845 // We check for copy constructors before constructors 16846 // because otherwise we'll never get complaints about 16847 // copy constructors. 16848 16849 CXXSpecialMember member = CXXInvalid; 16850 // We're required to check for any non-trivial constructors. Since the 16851 // implicit default constructor is suppressed if there are any 16852 // user-declared constructors, we just need to check that there is a 16853 // trivial default constructor and a trivial copy constructor. (We don't 16854 // worry about move constructors here, since this is a C++98 check.) 16855 if (RDecl->hasNonTrivialCopyConstructor()) 16856 member = CXXCopyConstructor; 16857 else if (!RDecl->hasTrivialDefaultConstructor()) 16858 member = CXXDefaultConstructor; 16859 else if (RDecl->hasNonTrivialCopyAssignment()) 16860 member = CXXCopyAssignment; 16861 else if (RDecl->hasNonTrivialDestructor()) 16862 member = CXXDestructor; 16863 16864 if (member != CXXInvalid) { 16865 if (!getLangOpts().CPlusPlus11 && 16866 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16867 // Objective-C++ ARC: it is an error to have a non-trivial field of 16868 // a union. However, system headers in Objective-C programs 16869 // occasionally have Objective-C lifetime objects within unions, 16870 // and rather than cause the program to fail, we make those 16871 // members unavailable. 16872 SourceLocation Loc = FD->getLocation(); 16873 if (getSourceManager().isInSystemHeader(Loc)) { 16874 if (!FD->hasAttr<UnavailableAttr>()) 16875 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16876 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16877 return false; 16878 } 16879 } 16880 16881 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16882 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16883 diag::err_illegal_union_or_anon_struct_member) 16884 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16885 DiagnoseNontrivial(RDecl, member); 16886 return !getLangOpts().CPlusPlus11; 16887 } 16888 } 16889 } 16890 16891 return false; 16892 } 16893 16894 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16895 /// AST enum value. 16896 static ObjCIvarDecl::AccessControl 16897 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16898 switch (ivarVisibility) { 16899 default: llvm_unreachable("Unknown visitibility kind"); 16900 case tok::objc_private: return ObjCIvarDecl::Private; 16901 case tok::objc_public: return ObjCIvarDecl::Public; 16902 case tok::objc_protected: return ObjCIvarDecl::Protected; 16903 case tok::objc_package: return ObjCIvarDecl::Package; 16904 } 16905 } 16906 16907 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16908 /// in order to create an IvarDecl object for it. 16909 Decl *Sema::ActOnIvar(Scope *S, 16910 SourceLocation DeclStart, 16911 Declarator &D, Expr *BitfieldWidth, 16912 tok::ObjCKeywordKind Visibility) { 16913 16914 IdentifierInfo *II = D.getIdentifier(); 16915 Expr *BitWidth = (Expr*)BitfieldWidth; 16916 SourceLocation Loc = DeclStart; 16917 if (II) Loc = D.getIdentifierLoc(); 16918 16919 // FIXME: Unnamed fields can be handled in various different ways, for 16920 // example, unnamed unions inject all members into the struct namespace! 16921 16922 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16923 QualType T = TInfo->getType(); 16924 16925 if (BitWidth) { 16926 // 6.7.2.1p3, 6.7.2.1p4 16927 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16928 if (!BitWidth) 16929 D.setInvalidType(); 16930 } else { 16931 // Not a bitfield. 16932 16933 // validate II. 16934 16935 } 16936 if (T->isReferenceType()) { 16937 Diag(Loc, diag::err_ivar_reference_type); 16938 D.setInvalidType(); 16939 } 16940 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16941 // than a variably modified type. 16942 else if (T->isVariablyModifiedType()) { 16943 if (!tryToFixVariablyModifiedVarType( 16944 *this, TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 16945 D.setInvalidType(); 16946 } 16947 16948 // Get the visibility (access control) for this ivar. 16949 ObjCIvarDecl::AccessControl ac = 16950 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 16951 : ObjCIvarDecl::None; 16952 // Must set ivar's DeclContext to its enclosing interface. 16953 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 16954 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 16955 return nullptr; 16956 ObjCContainerDecl *EnclosingContext; 16957 if (ObjCImplementationDecl *IMPDecl = 16958 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16959 if (LangOpts.ObjCRuntime.isFragile()) { 16960 // Case of ivar declared in an implementation. Context is that of its class. 16961 EnclosingContext = IMPDecl->getClassInterface(); 16962 assert(EnclosingContext && "Implementation has no class interface!"); 16963 } 16964 else 16965 EnclosingContext = EnclosingDecl; 16966 } else { 16967 if (ObjCCategoryDecl *CDecl = 16968 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16969 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 16970 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 16971 return nullptr; 16972 } 16973 } 16974 EnclosingContext = EnclosingDecl; 16975 } 16976 16977 // Construct the decl. 16978 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 16979 DeclStart, Loc, II, T, 16980 TInfo, ac, (Expr *)BitfieldWidth); 16981 16982 if (II) { 16983 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 16984 ForVisibleRedeclaration); 16985 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 16986 && !isa<TagDecl>(PrevDecl)) { 16987 Diag(Loc, diag::err_duplicate_member) << II; 16988 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16989 NewID->setInvalidDecl(); 16990 } 16991 } 16992 16993 // Process attributes attached to the ivar. 16994 ProcessDeclAttributes(S, NewID, D); 16995 16996 if (D.isInvalidType()) 16997 NewID->setInvalidDecl(); 16998 16999 // In ARC, infer 'retaining' for ivars of retainable type. 17000 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 17001 NewID->setInvalidDecl(); 17002 17003 if (D.getDeclSpec().isModulePrivateSpecified()) 17004 NewID->setModulePrivate(); 17005 17006 if (II) { 17007 // FIXME: When interfaces are DeclContexts, we'll need to add 17008 // these to the interface. 17009 S->AddDecl(NewID); 17010 IdResolver.AddDecl(NewID); 17011 } 17012 17013 if (LangOpts.ObjCRuntime.isNonFragile() && 17014 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17015 Diag(Loc, diag::warn_ivars_in_interface); 17016 17017 return NewID; 17018 } 17019 17020 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17021 /// class and class extensions. For every class \@interface and class 17022 /// extension \@interface, if the last ivar is a bitfield of any type, 17023 /// then add an implicit `char :0` ivar to the end of that interface. 17024 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17025 SmallVectorImpl<Decl *> &AllIvarDecls) { 17026 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17027 return; 17028 17029 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17030 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17031 17032 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17033 return; 17034 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17035 if (!ID) { 17036 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17037 if (!CD->IsClassExtension()) 17038 return; 17039 } 17040 // No need to add this to end of @implementation. 17041 else 17042 return; 17043 } 17044 // All conditions are met. Add a new bitfield to the tail end of ivars. 17045 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17046 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17047 17048 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17049 DeclLoc, DeclLoc, nullptr, 17050 Context.CharTy, 17051 Context.getTrivialTypeSourceInfo(Context.CharTy, 17052 DeclLoc), 17053 ObjCIvarDecl::Private, BW, 17054 true); 17055 AllIvarDecls.push_back(Ivar); 17056 } 17057 17058 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17059 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17060 SourceLocation RBrac, 17061 const ParsedAttributesView &Attrs) { 17062 assert(EnclosingDecl && "missing record or interface decl"); 17063 17064 // If this is an Objective-C @implementation or category and we have 17065 // new fields here we should reset the layout of the interface since 17066 // it will now change. 17067 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17068 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17069 switch (DC->getKind()) { 17070 default: break; 17071 case Decl::ObjCCategory: 17072 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17073 break; 17074 case Decl::ObjCImplementation: 17075 Context. 17076 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17077 break; 17078 } 17079 } 17080 17081 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17082 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17083 17084 // Start counting up the number of named members; make sure to include 17085 // members of anonymous structs and unions in the total. 17086 unsigned NumNamedMembers = 0; 17087 if (Record) { 17088 for (const auto *I : Record->decls()) { 17089 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17090 if (IFD->getDeclName()) 17091 ++NumNamedMembers; 17092 } 17093 } 17094 17095 // Verify that all the fields are okay. 17096 SmallVector<FieldDecl*, 32> RecFields; 17097 17098 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17099 i != end; ++i) { 17100 FieldDecl *FD = cast<FieldDecl>(*i); 17101 17102 // Get the type for the field. 17103 const Type *FDTy = FD->getType().getTypePtr(); 17104 17105 if (!FD->isAnonymousStructOrUnion()) { 17106 // Remember all fields written by the user. 17107 RecFields.push_back(FD); 17108 } 17109 17110 // If the field is already invalid for some reason, don't emit more 17111 // diagnostics about it. 17112 if (FD->isInvalidDecl()) { 17113 EnclosingDecl->setInvalidDecl(); 17114 continue; 17115 } 17116 17117 // C99 6.7.2.1p2: 17118 // A structure or union shall not contain a member with 17119 // incomplete or function type (hence, a structure shall not 17120 // contain an instance of itself, but may contain a pointer to 17121 // an instance of itself), except that the last member of a 17122 // structure with more than one named member may have incomplete 17123 // array type; such a structure (and any union containing, 17124 // possibly recursively, a member that is such a structure) 17125 // shall not be a member of a structure or an element of an 17126 // array. 17127 bool IsLastField = (i + 1 == Fields.end()); 17128 if (FDTy->isFunctionType()) { 17129 // Field declared as a function. 17130 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17131 << FD->getDeclName(); 17132 FD->setInvalidDecl(); 17133 EnclosingDecl->setInvalidDecl(); 17134 continue; 17135 } else if (FDTy->isIncompleteArrayType() && 17136 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17137 if (Record) { 17138 // Flexible array member. 17139 // Microsoft and g++ is more permissive regarding flexible array. 17140 // It will accept flexible array in union and also 17141 // as the sole element of a struct/class. 17142 unsigned DiagID = 0; 17143 if (!Record->isUnion() && !IsLastField) { 17144 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17145 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17146 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17147 FD->setInvalidDecl(); 17148 EnclosingDecl->setInvalidDecl(); 17149 continue; 17150 } else if (Record->isUnion()) 17151 DiagID = getLangOpts().MicrosoftExt 17152 ? diag::ext_flexible_array_union_ms 17153 : getLangOpts().CPlusPlus 17154 ? diag::ext_flexible_array_union_gnu 17155 : diag::err_flexible_array_union; 17156 else if (NumNamedMembers < 1) 17157 DiagID = getLangOpts().MicrosoftExt 17158 ? diag::ext_flexible_array_empty_aggregate_ms 17159 : getLangOpts().CPlusPlus 17160 ? diag::ext_flexible_array_empty_aggregate_gnu 17161 : diag::err_flexible_array_empty_aggregate; 17162 17163 if (DiagID) 17164 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17165 << Record->getTagKind(); 17166 // While the layout of types that contain virtual bases is not specified 17167 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17168 // virtual bases after the derived members. This would make a flexible 17169 // array member declared at the end of an object not adjacent to the end 17170 // of the type. 17171 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17172 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17173 << FD->getDeclName() << Record->getTagKind(); 17174 if (!getLangOpts().C99) 17175 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17176 << FD->getDeclName() << Record->getTagKind(); 17177 17178 // If the element type has a non-trivial destructor, we would not 17179 // implicitly destroy the elements, so disallow it for now. 17180 // 17181 // FIXME: GCC allows this. We should probably either implicitly delete 17182 // the destructor of the containing class, or just allow this. 17183 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17184 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17185 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17186 << FD->getDeclName() << FD->getType(); 17187 FD->setInvalidDecl(); 17188 EnclosingDecl->setInvalidDecl(); 17189 continue; 17190 } 17191 // Okay, we have a legal flexible array member at the end of the struct. 17192 Record->setHasFlexibleArrayMember(true); 17193 } else { 17194 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17195 // unless they are followed by another ivar. That check is done 17196 // elsewhere, after synthesized ivars are known. 17197 } 17198 } else if (!FDTy->isDependentType() && 17199 RequireCompleteSizedType( 17200 FD->getLocation(), FD->getType(), 17201 diag::err_field_incomplete_or_sizeless)) { 17202 // Incomplete type 17203 FD->setInvalidDecl(); 17204 EnclosingDecl->setInvalidDecl(); 17205 continue; 17206 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17207 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17208 // A type which contains a flexible array member is considered to be a 17209 // flexible array member. 17210 Record->setHasFlexibleArrayMember(true); 17211 if (!Record->isUnion()) { 17212 // If this is a struct/class and this is not the last element, reject 17213 // it. Note that GCC supports variable sized arrays in the middle of 17214 // structures. 17215 if (!IsLastField) 17216 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17217 << FD->getDeclName() << FD->getType(); 17218 else { 17219 // We support flexible arrays at the end of structs in 17220 // other structs as an extension. 17221 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17222 << FD->getDeclName(); 17223 } 17224 } 17225 } 17226 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17227 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17228 diag::err_abstract_type_in_decl, 17229 AbstractIvarType)) { 17230 // Ivars can not have abstract class types 17231 FD->setInvalidDecl(); 17232 } 17233 if (Record && FDTTy->getDecl()->hasObjectMember()) 17234 Record->setHasObjectMember(true); 17235 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17236 Record->setHasVolatileMember(true); 17237 } else if (FDTy->isObjCObjectType()) { 17238 /// A field cannot be an Objective-c object 17239 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17240 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17241 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17242 FD->setType(T); 17243 } else if (Record && Record->isUnion() && 17244 FD->getType().hasNonTrivialObjCLifetime() && 17245 getSourceManager().isInSystemHeader(FD->getLocation()) && 17246 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17247 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17248 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17249 // For backward compatibility, fields of C unions declared in system 17250 // headers that have non-trivial ObjC ownership qualifications are marked 17251 // as unavailable unless the qualifier is explicit and __strong. This can 17252 // break ABI compatibility between programs compiled with ARC and MRR, but 17253 // is a better option than rejecting programs using those unions under 17254 // ARC. 17255 FD->addAttr(UnavailableAttr::CreateImplicit( 17256 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17257 FD->getLocation())); 17258 } else if (getLangOpts().ObjC && 17259 getLangOpts().getGC() != LangOptions::NonGC && Record && 17260 !Record->hasObjectMember()) { 17261 if (FD->getType()->isObjCObjectPointerType() || 17262 FD->getType().isObjCGCStrong()) 17263 Record->setHasObjectMember(true); 17264 else if (Context.getAsArrayType(FD->getType())) { 17265 QualType BaseType = Context.getBaseElementType(FD->getType()); 17266 if (BaseType->isRecordType() && 17267 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17268 Record->setHasObjectMember(true); 17269 else if (BaseType->isObjCObjectPointerType() || 17270 BaseType.isObjCGCStrong()) 17271 Record->setHasObjectMember(true); 17272 } 17273 } 17274 17275 if (Record && !getLangOpts().CPlusPlus && 17276 !shouldIgnoreForRecordTriviality(FD)) { 17277 QualType FT = FD->getType(); 17278 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17279 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17280 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17281 Record->isUnion()) 17282 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17283 } 17284 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17285 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17286 Record->setNonTrivialToPrimitiveCopy(true); 17287 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17288 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17289 } 17290 if (FT.isDestructedType()) { 17291 Record->setNonTrivialToPrimitiveDestroy(true); 17292 Record->setParamDestroyedInCallee(true); 17293 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17294 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17295 } 17296 17297 if (const auto *RT = FT->getAs<RecordType>()) { 17298 if (RT->getDecl()->getArgPassingRestrictions() == 17299 RecordDecl::APK_CanNeverPassInRegs) 17300 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17301 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17302 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17303 } 17304 17305 if (Record && FD->getType().isVolatileQualified()) 17306 Record->setHasVolatileMember(true); 17307 // Keep track of the number of named members. 17308 if (FD->getIdentifier()) 17309 ++NumNamedMembers; 17310 } 17311 17312 // Okay, we successfully defined 'Record'. 17313 if (Record) { 17314 bool Completed = false; 17315 if (CXXRecord) { 17316 if (!CXXRecord->isInvalidDecl()) { 17317 // Set access bits correctly on the directly-declared conversions. 17318 for (CXXRecordDecl::conversion_iterator 17319 I = CXXRecord->conversion_begin(), 17320 E = CXXRecord->conversion_end(); I != E; ++I) 17321 I.setAccess((*I)->getAccess()); 17322 } 17323 17324 // Add any implicitly-declared members to this class. 17325 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17326 17327 if (!CXXRecord->isDependentType()) { 17328 if (!CXXRecord->isInvalidDecl()) { 17329 // If we have virtual base classes, we may end up finding multiple 17330 // final overriders for a given virtual function. Check for this 17331 // problem now. 17332 if (CXXRecord->getNumVBases()) { 17333 CXXFinalOverriderMap FinalOverriders; 17334 CXXRecord->getFinalOverriders(FinalOverriders); 17335 17336 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17337 MEnd = FinalOverriders.end(); 17338 M != MEnd; ++M) { 17339 for (OverridingMethods::iterator SO = M->second.begin(), 17340 SOEnd = M->second.end(); 17341 SO != SOEnd; ++SO) { 17342 assert(SO->second.size() > 0 && 17343 "Virtual function without overriding functions?"); 17344 if (SO->second.size() == 1) 17345 continue; 17346 17347 // C++ [class.virtual]p2: 17348 // In a derived class, if a virtual member function of a base 17349 // class subobject has more than one final overrider the 17350 // program is ill-formed. 17351 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17352 << (const NamedDecl *)M->first << Record; 17353 Diag(M->first->getLocation(), 17354 diag::note_overridden_virtual_function); 17355 for (OverridingMethods::overriding_iterator 17356 OM = SO->second.begin(), 17357 OMEnd = SO->second.end(); 17358 OM != OMEnd; ++OM) 17359 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17360 << (const NamedDecl *)M->first << OM->Method->getParent(); 17361 17362 Record->setInvalidDecl(); 17363 } 17364 } 17365 CXXRecord->completeDefinition(&FinalOverriders); 17366 Completed = true; 17367 } 17368 } 17369 } 17370 } 17371 17372 if (!Completed) 17373 Record->completeDefinition(); 17374 17375 // Handle attributes before checking the layout. 17376 ProcessDeclAttributeList(S, Record, Attrs); 17377 17378 // We may have deferred checking for a deleted destructor. Check now. 17379 if (CXXRecord) { 17380 auto *Dtor = CXXRecord->getDestructor(); 17381 if (Dtor && Dtor->isImplicit() && 17382 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17383 CXXRecord->setImplicitDestructorIsDeleted(); 17384 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17385 } 17386 } 17387 17388 if (Record->hasAttrs()) { 17389 CheckAlignasUnderalignment(Record); 17390 17391 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17392 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17393 IA->getRange(), IA->getBestCase(), 17394 IA->getInheritanceModel()); 17395 } 17396 17397 // Check if the structure/union declaration is a type that can have zero 17398 // size in C. For C this is a language extension, for C++ it may cause 17399 // compatibility problems. 17400 bool CheckForZeroSize; 17401 if (!getLangOpts().CPlusPlus) { 17402 CheckForZeroSize = true; 17403 } else { 17404 // For C++ filter out types that cannot be referenced in C code. 17405 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17406 CheckForZeroSize = 17407 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17408 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 17409 CXXRecord->isCLike(); 17410 } 17411 if (CheckForZeroSize) { 17412 bool ZeroSize = true; 17413 bool IsEmpty = true; 17414 unsigned NonBitFields = 0; 17415 for (RecordDecl::field_iterator I = Record->field_begin(), 17416 E = Record->field_end(); 17417 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17418 IsEmpty = false; 17419 if (I->isUnnamedBitfield()) { 17420 if (!I->isZeroLengthBitField(Context)) 17421 ZeroSize = false; 17422 } else { 17423 ++NonBitFields; 17424 QualType FieldType = I->getType(); 17425 if (FieldType->isIncompleteType() || 17426 !Context.getTypeSizeInChars(FieldType).isZero()) 17427 ZeroSize = false; 17428 } 17429 } 17430 17431 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17432 // allowed in C++, but warn if its declaration is inside 17433 // extern "C" block. 17434 if (ZeroSize) { 17435 Diag(RecLoc, getLangOpts().CPlusPlus ? 17436 diag::warn_zero_size_struct_union_in_extern_c : 17437 diag::warn_zero_size_struct_union_compat) 17438 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17439 } 17440 17441 // Structs without named members are extension in C (C99 6.7.2.1p7), 17442 // but are accepted by GCC. 17443 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17444 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17445 diag::ext_no_named_members_in_struct_union) 17446 << Record->isUnion(); 17447 } 17448 } 17449 } else { 17450 ObjCIvarDecl **ClsFields = 17451 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17452 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17453 ID->setEndOfDefinitionLoc(RBrac); 17454 // Add ivar's to class's DeclContext. 17455 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17456 ClsFields[i]->setLexicalDeclContext(ID); 17457 ID->addDecl(ClsFields[i]); 17458 } 17459 // Must enforce the rule that ivars in the base classes may not be 17460 // duplicates. 17461 if (ID->getSuperClass()) 17462 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17463 } else if (ObjCImplementationDecl *IMPDecl = 17464 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17465 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17466 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17467 // Ivar declared in @implementation never belongs to the implementation. 17468 // Only it is in implementation's lexical context. 17469 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17470 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17471 IMPDecl->setIvarLBraceLoc(LBrac); 17472 IMPDecl->setIvarRBraceLoc(RBrac); 17473 } else if (ObjCCategoryDecl *CDecl = 17474 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17475 // case of ivars in class extension; all other cases have been 17476 // reported as errors elsewhere. 17477 // FIXME. Class extension does not have a LocEnd field. 17478 // CDecl->setLocEnd(RBrac); 17479 // Add ivar's to class extension's DeclContext. 17480 // Diagnose redeclaration of private ivars. 17481 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17482 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17483 if (IDecl) { 17484 if (const ObjCIvarDecl *ClsIvar = 17485 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17486 Diag(ClsFields[i]->getLocation(), 17487 diag::err_duplicate_ivar_declaration); 17488 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17489 continue; 17490 } 17491 for (const auto *Ext : IDecl->known_extensions()) { 17492 if (const ObjCIvarDecl *ClsExtIvar 17493 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17494 Diag(ClsFields[i]->getLocation(), 17495 diag::err_duplicate_ivar_declaration); 17496 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17497 continue; 17498 } 17499 } 17500 } 17501 ClsFields[i]->setLexicalDeclContext(CDecl); 17502 CDecl->addDecl(ClsFields[i]); 17503 } 17504 CDecl->setIvarLBraceLoc(LBrac); 17505 CDecl->setIvarRBraceLoc(RBrac); 17506 } 17507 } 17508 } 17509 17510 /// Determine whether the given integral value is representable within 17511 /// the given type T. 17512 static bool isRepresentableIntegerValue(ASTContext &Context, 17513 llvm::APSInt &Value, 17514 QualType T) { 17515 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17516 "Integral type required!"); 17517 unsigned BitWidth = Context.getIntWidth(T); 17518 17519 if (Value.isUnsigned() || Value.isNonNegative()) { 17520 if (T->isSignedIntegerOrEnumerationType()) 17521 --BitWidth; 17522 return Value.getActiveBits() <= BitWidth; 17523 } 17524 return Value.getMinSignedBits() <= BitWidth; 17525 } 17526 17527 // Given an integral type, return the next larger integral type 17528 // (or a NULL type of no such type exists). 17529 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17530 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17531 // enum checking below. 17532 assert((T->isIntegralType(Context) || 17533 T->isEnumeralType()) && "Integral type required!"); 17534 const unsigned NumTypes = 4; 17535 QualType SignedIntegralTypes[NumTypes] = { 17536 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17537 }; 17538 QualType UnsignedIntegralTypes[NumTypes] = { 17539 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17540 Context.UnsignedLongLongTy 17541 }; 17542 17543 unsigned BitWidth = Context.getTypeSize(T); 17544 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17545 : UnsignedIntegralTypes; 17546 for (unsigned I = 0; I != NumTypes; ++I) 17547 if (Context.getTypeSize(Types[I]) > BitWidth) 17548 return Types[I]; 17549 17550 return QualType(); 17551 } 17552 17553 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17554 EnumConstantDecl *LastEnumConst, 17555 SourceLocation IdLoc, 17556 IdentifierInfo *Id, 17557 Expr *Val) { 17558 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17559 llvm::APSInt EnumVal(IntWidth); 17560 QualType EltTy; 17561 17562 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17563 Val = nullptr; 17564 17565 if (Val) 17566 Val = DefaultLvalueConversion(Val).get(); 17567 17568 if (Val) { 17569 if (Enum->isDependentType() || Val->isTypeDependent()) 17570 EltTy = Context.DependentTy; 17571 else { 17572 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 17573 // underlying type, but do allow it in all other contexts. 17574 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17575 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17576 // constant-expression in the enumerator-definition shall be a converted 17577 // constant expression of the underlying type. 17578 EltTy = Enum->getIntegerType(); 17579 ExprResult Converted = 17580 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17581 CCEK_Enumerator); 17582 if (Converted.isInvalid()) 17583 Val = nullptr; 17584 else 17585 Val = Converted.get(); 17586 } else if (!Val->isValueDependent() && 17587 !(Val = 17588 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 17589 .get())) { 17590 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17591 } else { 17592 if (Enum->isComplete()) { 17593 EltTy = Enum->getIntegerType(); 17594 17595 // In Obj-C and Microsoft mode, require the enumeration value to be 17596 // representable in the underlying type of the enumeration. In C++11, 17597 // we perform a non-narrowing conversion as part of converted constant 17598 // expression checking. 17599 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17600 if (Context.getTargetInfo() 17601 .getTriple() 17602 .isWindowsMSVCEnvironment()) { 17603 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17604 } else { 17605 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17606 } 17607 } 17608 17609 // Cast to the underlying type. 17610 Val = ImpCastExprToType(Val, EltTy, 17611 EltTy->isBooleanType() ? CK_IntegralToBoolean 17612 : CK_IntegralCast) 17613 .get(); 17614 } else if (getLangOpts().CPlusPlus) { 17615 // C++11 [dcl.enum]p5: 17616 // If the underlying type is not fixed, the type of each enumerator 17617 // is the type of its initializing value: 17618 // - If an initializer is specified for an enumerator, the 17619 // initializing value has the same type as the expression. 17620 EltTy = Val->getType(); 17621 } else { 17622 // C99 6.7.2.2p2: 17623 // The expression that defines the value of an enumeration constant 17624 // shall be an integer constant expression that has a value 17625 // representable as an int. 17626 17627 // Complain if the value is not representable in an int. 17628 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17629 Diag(IdLoc, diag::ext_enum_value_not_int) 17630 << EnumVal.toString(10) << Val->getSourceRange() 17631 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17632 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17633 // Force the type of the expression to 'int'. 17634 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17635 } 17636 EltTy = Val->getType(); 17637 } 17638 } 17639 } 17640 } 17641 17642 if (!Val) { 17643 if (Enum->isDependentType()) 17644 EltTy = Context.DependentTy; 17645 else if (!LastEnumConst) { 17646 // C++0x [dcl.enum]p5: 17647 // If the underlying type is not fixed, the type of each enumerator 17648 // is the type of its initializing value: 17649 // - If no initializer is specified for the first enumerator, the 17650 // initializing value has an unspecified integral type. 17651 // 17652 // GCC uses 'int' for its unspecified integral type, as does 17653 // C99 6.7.2.2p3. 17654 if (Enum->isFixed()) { 17655 EltTy = Enum->getIntegerType(); 17656 } 17657 else { 17658 EltTy = Context.IntTy; 17659 } 17660 } else { 17661 // Assign the last value + 1. 17662 EnumVal = LastEnumConst->getInitVal(); 17663 ++EnumVal; 17664 EltTy = LastEnumConst->getType(); 17665 17666 // Check for overflow on increment. 17667 if (EnumVal < LastEnumConst->getInitVal()) { 17668 // C++0x [dcl.enum]p5: 17669 // If the underlying type is not fixed, the type of each enumerator 17670 // is the type of its initializing value: 17671 // 17672 // - Otherwise the type of the initializing value is the same as 17673 // the type of the initializing value of the preceding enumerator 17674 // unless the incremented value is not representable in that type, 17675 // in which case the type is an unspecified integral type 17676 // sufficient to contain the incremented value. If no such type 17677 // exists, the program is ill-formed. 17678 QualType T = getNextLargerIntegralType(Context, EltTy); 17679 if (T.isNull() || Enum->isFixed()) { 17680 // There is no integral type larger enough to represent this 17681 // value. Complain, then allow the value to wrap around. 17682 EnumVal = LastEnumConst->getInitVal(); 17683 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17684 ++EnumVal; 17685 if (Enum->isFixed()) 17686 // When the underlying type is fixed, this is ill-formed. 17687 Diag(IdLoc, diag::err_enumerator_wrapped) 17688 << EnumVal.toString(10) 17689 << EltTy; 17690 else 17691 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17692 << EnumVal.toString(10); 17693 } else { 17694 EltTy = T; 17695 } 17696 17697 // Retrieve the last enumerator's value, extent that type to the 17698 // type that is supposed to be large enough to represent the incremented 17699 // value, then increment. 17700 EnumVal = LastEnumConst->getInitVal(); 17701 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17702 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17703 ++EnumVal; 17704 17705 // If we're not in C++, diagnose the overflow of enumerator values, 17706 // which in C99 means that the enumerator value is not representable in 17707 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17708 // permits enumerator values that are representable in some larger 17709 // integral type. 17710 if (!getLangOpts().CPlusPlus && !T.isNull()) 17711 Diag(IdLoc, diag::warn_enum_value_overflow); 17712 } else if (!getLangOpts().CPlusPlus && 17713 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17714 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17715 Diag(IdLoc, diag::ext_enum_value_not_int) 17716 << EnumVal.toString(10) << 1; 17717 } 17718 } 17719 } 17720 17721 if (!EltTy->isDependentType()) { 17722 // Make the enumerator value match the signedness and size of the 17723 // enumerator's type. 17724 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17725 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17726 } 17727 17728 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17729 Val, EnumVal); 17730 } 17731 17732 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17733 SourceLocation IILoc) { 17734 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17735 !getLangOpts().CPlusPlus) 17736 return SkipBodyInfo(); 17737 17738 // We have an anonymous enum definition. Look up the first enumerator to 17739 // determine if we should merge the definition with an existing one and 17740 // skip the body. 17741 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17742 forRedeclarationInCurContext()); 17743 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17744 if (!PrevECD) 17745 return SkipBodyInfo(); 17746 17747 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17748 NamedDecl *Hidden; 17749 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17750 SkipBodyInfo Skip; 17751 Skip.Previous = Hidden; 17752 return Skip; 17753 } 17754 17755 return SkipBodyInfo(); 17756 } 17757 17758 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17759 SourceLocation IdLoc, IdentifierInfo *Id, 17760 const ParsedAttributesView &Attrs, 17761 SourceLocation EqualLoc, Expr *Val) { 17762 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17763 EnumConstantDecl *LastEnumConst = 17764 cast_or_null<EnumConstantDecl>(lastEnumConst); 17765 17766 // The scope passed in may not be a decl scope. Zip up the scope tree until 17767 // we find one that is. 17768 S = getNonFieldDeclScope(S); 17769 17770 // Verify that there isn't already something declared with this name in this 17771 // scope. 17772 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17773 LookupName(R, S); 17774 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17775 17776 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17777 // Maybe we will complain about the shadowed template parameter. 17778 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17779 // Just pretend that we didn't see the previous declaration. 17780 PrevDecl = nullptr; 17781 } 17782 17783 // C++ [class.mem]p15: 17784 // If T is the name of a class, then each of the following shall have a name 17785 // different from T: 17786 // - every enumerator of every member of class T that is an unscoped 17787 // enumerated type 17788 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17789 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17790 DeclarationNameInfo(Id, IdLoc)); 17791 17792 EnumConstantDecl *New = 17793 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17794 if (!New) 17795 return nullptr; 17796 17797 if (PrevDecl) { 17798 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17799 // Check for other kinds of shadowing not already handled. 17800 CheckShadow(New, PrevDecl, R); 17801 } 17802 17803 // When in C++, we may get a TagDecl with the same name; in this case the 17804 // enum constant will 'hide' the tag. 17805 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17806 "Received TagDecl when not in C++!"); 17807 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17808 if (isa<EnumConstantDecl>(PrevDecl)) 17809 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17810 else 17811 Diag(IdLoc, diag::err_redefinition) << Id; 17812 notePreviousDefinition(PrevDecl, IdLoc); 17813 return nullptr; 17814 } 17815 } 17816 17817 // Process attributes. 17818 ProcessDeclAttributeList(S, New, Attrs); 17819 AddPragmaAttributes(S, New); 17820 17821 // Register this decl in the current scope stack. 17822 New->setAccess(TheEnumDecl->getAccess()); 17823 PushOnScopeChains(New, S); 17824 17825 ActOnDocumentableDecl(New); 17826 17827 return New; 17828 } 17829 17830 // Returns true when the enum initial expression does not trigger the 17831 // duplicate enum warning. A few common cases are exempted as follows: 17832 // Element2 = Element1 17833 // Element2 = Element1 + 1 17834 // Element2 = Element1 - 1 17835 // Where Element2 and Element1 are from the same enum. 17836 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17837 Expr *InitExpr = ECD->getInitExpr(); 17838 if (!InitExpr) 17839 return true; 17840 InitExpr = InitExpr->IgnoreImpCasts(); 17841 17842 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17843 if (!BO->isAdditiveOp()) 17844 return true; 17845 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17846 if (!IL) 17847 return true; 17848 if (IL->getValue() != 1) 17849 return true; 17850 17851 InitExpr = BO->getLHS(); 17852 } 17853 17854 // This checks if the elements are from the same enum. 17855 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17856 if (!DRE) 17857 return true; 17858 17859 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17860 if (!EnumConstant) 17861 return true; 17862 17863 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17864 Enum) 17865 return true; 17866 17867 return false; 17868 } 17869 17870 // Emits a warning when an element is implicitly set a value that 17871 // a previous element has already been set to. 17872 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17873 EnumDecl *Enum, QualType EnumType) { 17874 // Avoid anonymous enums 17875 if (!Enum->getIdentifier()) 17876 return; 17877 17878 // Only check for small enums. 17879 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17880 return; 17881 17882 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17883 return; 17884 17885 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17886 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17887 17888 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17889 17890 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 17891 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17892 17893 // Use int64_t as a key to avoid needing special handling for map keys. 17894 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17895 llvm::APSInt Val = D->getInitVal(); 17896 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17897 }; 17898 17899 DuplicatesVector DupVector; 17900 ValueToVectorMap EnumMap; 17901 17902 // Populate the EnumMap with all values represented by enum constants without 17903 // an initializer. 17904 for (auto *Element : Elements) { 17905 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17906 17907 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17908 // this constant. Skip this enum since it may be ill-formed. 17909 if (!ECD) { 17910 return; 17911 } 17912 17913 // Constants with initalizers are handled in the next loop. 17914 if (ECD->getInitExpr()) 17915 continue; 17916 17917 // Duplicate values are handled in the next loop. 17918 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17919 } 17920 17921 if (EnumMap.size() == 0) 17922 return; 17923 17924 // Create vectors for any values that has duplicates. 17925 for (auto *Element : Elements) { 17926 // The last loop returned if any constant was null. 17927 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17928 if (!ValidDuplicateEnum(ECD, Enum)) 17929 continue; 17930 17931 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17932 if (Iter == EnumMap.end()) 17933 continue; 17934 17935 DeclOrVector& Entry = Iter->second; 17936 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17937 // Ensure constants are different. 17938 if (D == ECD) 17939 continue; 17940 17941 // Create new vector and push values onto it. 17942 auto Vec = std::make_unique<ECDVector>(); 17943 Vec->push_back(D); 17944 Vec->push_back(ECD); 17945 17946 // Update entry to point to the duplicates vector. 17947 Entry = Vec.get(); 17948 17949 // Store the vector somewhere we can consult later for quick emission of 17950 // diagnostics. 17951 DupVector.emplace_back(std::move(Vec)); 17952 continue; 17953 } 17954 17955 ECDVector *Vec = Entry.get<ECDVector*>(); 17956 // Make sure constants are not added more than once. 17957 if (*Vec->begin() == ECD) 17958 continue; 17959 17960 Vec->push_back(ECD); 17961 } 17962 17963 // Emit diagnostics. 17964 for (const auto &Vec : DupVector) { 17965 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 17966 17967 // Emit warning for one enum constant. 17968 auto *FirstECD = Vec->front(); 17969 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 17970 << FirstECD << FirstECD->getInitVal().toString(10) 17971 << FirstECD->getSourceRange(); 17972 17973 // Emit one note for each of the remaining enum constants with 17974 // the same value. 17975 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 17976 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 17977 << ECD << ECD->getInitVal().toString(10) 17978 << ECD->getSourceRange(); 17979 } 17980 } 17981 17982 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 17983 bool AllowMask) const { 17984 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 17985 assert(ED->isCompleteDefinition() && "expected enum definition"); 17986 17987 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 17988 llvm::APInt &FlagBits = R.first->second; 17989 17990 if (R.second) { 17991 for (auto *E : ED->enumerators()) { 17992 const auto &EVal = E->getInitVal(); 17993 // Only single-bit enumerators introduce new flag values. 17994 if (EVal.isPowerOf2()) 17995 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 17996 } 17997 } 17998 17999 // A value is in a flag enum if either its bits are a subset of the enum's 18000 // flag bits (the first condition) or we are allowing masks and the same is 18001 // true of its complement (the second condition). When masks are allowed, we 18002 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 18003 // 18004 // While it's true that any value could be used as a mask, the assumption is 18005 // that a mask will have all of the insignificant bits set. Anything else is 18006 // likely a logic error. 18007 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18008 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18009 } 18010 18011 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18012 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18013 const ParsedAttributesView &Attrs) { 18014 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18015 QualType EnumType = Context.getTypeDeclType(Enum); 18016 18017 ProcessDeclAttributeList(S, Enum, Attrs); 18018 18019 if (Enum->isDependentType()) { 18020 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18021 EnumConstantDecl *ECD = 18022 cast_or_null<EnumConstantDecl>(Elements[i]); 18023 if (!ECD) continue; 18024 18025 ECD->setType(EnumType); 18026 } 18027 18028 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18029 return; 18030 } 18031 18032 // TODO: If the result value doesn't fit in an int, it must be a long or long 18033 // long value. ISO C does not support this, but GCC does as an extension, 18034 // emit a warning. 18035 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18036 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18037 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18038 18039 // Verify that all the values are okay, compute the size of the values, and 18040 // reverse the list. 18041 unsigned NumNegativeBits = 0; 18042 unsigned NumPositiveBits = 0; 18043 18044 // Keep track of whether all elements have type int. 18045 bool AllElementsInt = true; 18046 18047 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18048 EnumConstantDecl *ECD = 18049 cast_or_null<EnumConstantDecl>(Elements[i]); 18050 if (!ECD) continue; // Already issued a diagnostic. 18051 18052 const llvm::APSInt &InitVal = ECD->getInitVal(); 18053 18054 // Keep track of the size of positive and negative values. 18055 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18056 NumPositiveBits = std::max(NumPositiveBits, 18057 (unsigned)InitVal.getActiveBits()); 18058 else 18059 NumNegativeBits = std::max(NumNegativeBits, 18060 (unsigned)InitVal.getMinSignedBits()); 18061 18062 // Keep track of whether every enum element has type int (very common). 18063 if (AllElementsInt) 18064 AllElementsInt = ECD->getType() == Context.IntTy; 18065 } 18066 18067 // Figure out the type that should be used for this enum. 18068 QualType BestType; 18069 unsigned BestWidth; 18070 18071 // C++0x N3000 [conv.prom]p3: 18072 // An rvalue of an unscoped enumeration type whose underlying 18073 // type is not fixed can be converted to an rvalue of the first 18074 // of the following types that can represent all the values of 18075 // the enumeration: int, unsigned int, long int, unsigned long 18076 // int, long long int, or unsigned long long int. 18077 // C99 6.4.4.3p2: 18078 // An identifier declared as an enumeration constant has type int. 18079 // The C99 rule is modified by a gcc extension 18080 QualType BestPromotionType; 18081 18082 bool Packed = Enum->hasAttr<PackedAttr>(); 18083 // -fshort-enums is the equivalent to specifying the packed attribute on all 18084 // enum definitions. 18085 if (LangOpts.ShortEnums) 18086 Packed = true; 18087 18088 // If the enum already has a type because it is fixed or dictated by the 18089 // target, promote that type instead of analyzing the enumerators. 18090 if (Enum->isComplete()) { 18091 BestType = Enum->getIntegerType(); 18092 if (BestType->isPromotableIntegerType()) 18093 BestPromotionType = Context.getPromotedIntegerType(BestType); 18094 else 18095 BestPromotionType = BestType; 18096 18097 BestWidth = Context.getIntWidth(BestType); 18098 } 18099 else if (NumNegativeBits) { 18100 // If there is a negative value, figure out the smallest integer type (of 18101 // int/long/longlong) that fits. 18102 // If it's packed, check also if it fits a char or a short. 18103 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18104 BestType = Context.SignedCharTy; 18105 BestWidth = CharWidth; 18106 } else if (Packed && NumNegativeBits <= ShortWidth && 18107 NumPositiveBits < ShortWidth) { 18108 BestType = Context.ShortTy; 18109 BestWidth = ShortWidth; 18110 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18111 BestType = Context.IntTy; 18112 BestWidth = IntWidth; 18113 } else { 18114 BestWidth = Context.getTargetInfo().getLongWidth(); 18115 18116 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18117 BestType = Context.LongTy; 18118 } else { 18119 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18120 18121 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18122 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18123 BestType = Context.LongLongTy; 18124 } 18125 } 18126 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18127 } else { 18128 // If there is no negative value, figure out the smallest type that fits 18129 // all of the enumerator values. 18130 // If it's packed, check also if it fits a char or a short. 18131 if (Packed && NumPositiveBits <= CharWidth) { 18132 BestType = Context.UnsignedCharTy; 18133 BestPromotionType = Context.IntTy; 18134 BestWidth = CharWidth; 18135 } else if (Packed && NumPositiveBits <= ShortWidth) { 18136 BestType = Context.UnsignedShortTy; 18137 BestPromotionType = Context.IntTy; 18138 BestWidth = ShortWidth; 18139 } else if (NumPositiveBits <= IntWidth) { 18140 BestType = Context.UnsignedIntTy; 18141 BestWidth = IntWidth; 18142 BestPromotionType 18143 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18144 ? Context.UnsignedIntTy : Context.IntTy; 18145 } else if (NumPositiveBits <= 18146 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18147 BestType = Context.UnsignedLongTy; 18148 BestPromotionType 18149 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18150 ? Context.UnsignedLongTy : Context.LongTy; 18151 } else { 18152 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18153 assert(NumPositiveBits <= BestWidth && 18154 "How could an initializer get larger than ULL?"); 18155 BestType = Context.UnsignedLongLongTy; 18156 BestPromotionType 18157 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18158 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18159 } 18160 } 18161 18162 // Loop over all of the enumerator constants, changing their types to match 18163 // the type of the enum if needed. 18164 for (auto *D : Elements) { 18165 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18166 if (!ECD) continue; // Already issued a diagnostic. 18167 18168 // Standard C says the enumerators have int type, but we allow, as an 18169 // extension, the enumerators to be larger than int size. If each 18170 // enumerator value fits in an int, type it as an int, otherwise type it the 18171 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18172 // that X has type 'int', not 'unsigned'. 18173 18174 // Determine whether the value fits into an int. 18175 llvm::APSInt InitVal = ECD->getInitVal(); 18176 18177 // If it fits into an integer type, force it. Otherwise force it to match 18178 // the enum decl type. 18179 QualType NewTy; 18180 unsigned NewWidth; 18181 bool NewSign; 18182 if (!getLangOpts().CPlusPlus && 18183 !Enum->isFixed() && 18184 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18185 NewTy = Context.IntTy; 18186 NewWidth = IntWidth; 18187 NewSign = true; 18188 } else if (ECD->getType() == BestType) { 18189 // Already the right type! 18190 if (getLangOpts().CPlusPlus) 18191 // C++ [dcl.enum]p4: Following the closing brace of an 18192 // enum-specifier, each enumerator has the type of its 18193 // enumeration. 18194 ECD->setType(EnumType); 18195 continue; 18196 } else { 18197 NewTy = BestType; 18198 NewWidth = BestWidth; 18199 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18200 } 18201 18202 // Adjust the APSInt value. 18203 InitVal = InitVal.extOrTrunc(NewWidth); 18204 InitVal.setIsSigned(NewSign); 18205 ECD->setInitVal(InitVal); 18206 18207 // Adjust the Expr initializer and type. 18208 if (ECD->getInitExpr() && 18209 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18210 ECD->setInitExpr(ImplicitCastExpr::Create( 18211 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18212 /*base paths*/ nullptr, VK_RValue, FPOptionsOverride())); 18213 if (getLangOpts().CPlusPlus) 18214 // C++ [dcl.enum]p4: Following the closing brace of an 18215 // enum-specifier, each enumerator has the type of its 18216 // enumeration. 18217 ECD->setType(EnumType); 18218 else 18219 ECD->setType(NewTy); 18220 } 18221 18222 Enum->completeDefinition(BestType, BestPromotionType, 18223 NumPositiveBits, NumNegativeBits); 18224 18225 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18226 18227 if (Enum->isClosedFlag()) { 18228 for (Decl *D : Elements) { 18229 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18230 if (!ECD) continue; // Already issued a diagnostic. 18231 18232 llvm::APSInt InitVal = ECD->getInitVal(); 18233 if (InitVal != 0 && !InitVal.isPowerOf2() && 18234 !IsValueInFlagEnum(Enum, InitVal, true)) 18235 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18236 << ECD << Enum; 18237 } 18238 } 18239 18240 // Now that the enum type is defined, ensure it's not been underaligned. 18241 if (Enum->hasAttrs()) 18242 CheckAlignasUnderalignment(Enum); 18243 } 18244 18245 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18246 SourceLocation StartLoc, 18247 SourceLocation EndLoc) { 18248 StringLiteral *AsmString = cast<StringLiteral>(expr); 18249 18250 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18251 AsmString, StartLoc, 18252 EndLoc); 18253 CurContext->addDecl(New); 18254 return New; 18255 } 18256 18257 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18258 IdentifierInfo* AliasName, 18259 SourceLocation PragmaLoc, 18260 SourceLocation NameLoc, 18261 SourceLocation AliasNameLoc) { 18262 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18263 LookupOrdinaryName); 18264 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18265 AttributeCommonInfo::AS_Pragma); 18266 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18267 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18268 18269 // If a declaration that: 18270 // 1) declares a function or a variable 18271 // 2) has external linkage 18272 // already exists, add a label attribute to it. 18273 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18274 if (isDeclExternC(PrevDecl)) 18275 PrevDecl->addAttr(Attr); 18276 else 18277 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18278 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18279 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18280 } else 18281 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18282 } 18283 18284 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18285 SourceLocation PragmaLoc, 18286 SourceLocation NameLoc) { 18287 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18288 18289 if (PrevDecl) { 18290 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18291 } else { 18292 (void)WeakUndeclaredIdentifiers.insert( 18293 std::pair<IdentifierInfo*,WeakInfo> 18294 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18295 } 18296 } 18297 18298 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18299 IdentifierInfo* AliasName, 18300 SourceLocation PragmaLoc, 18301 SourceLocation NameLoc, 18302 SourceLocation AliasNameLoc) { 18303 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18304 LookupOrdinaryName); 18305 WeakInfo W = WeakInfo(Name, NameLoc); 18306 18307 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18308 if (!PrevDecl->hasAttr<AliasAttr>()) 18309 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18310 DeclApplyPragmaWeak(TUScope, ND, W); 18311 } else { 18312 (void)WeakUndeclaredIdentifiers.insert( 18313 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18314 } 18315 } 18316 18317 Decl *Sema::getObjCDeclContext() const { 18318 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18319 } 18320 18321 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18322 bool Final) { 18323 // SYCL functions can be template, so we check if they have appropriate 18324 // attribute prior to checking if it is a template. 18325 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18326 return FunctionEmissionStatus::Emitted; 18327 18328 // Templates are emitted when they're instantiated. 18329 if (FD->isDependentContext()) 18330 return FunctionEmissionStatus::TemplateDiscarded; 18331 18332 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; 18333 if (LangOpts.OpenMPIsDevice) { 18334 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18335 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18336 if (DevTy.hasValue()) { 18337 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18338 OMPES = FunctionEmissionStatus::OMPDiscarded; 18339 else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost || 18340 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) { 18341 OMPES = FunctionEmissionStatus::Emitted; 18342 } 18343 } 18344 } else if (LangOpts.OpenMP) { 18345 // In OpenMP 4.5 all the functions are host functions. 18346 if (LangOpts.OpenMP <= 45) { 18347 OMPES = FunctionEmissionStatus::Emitted; 18348 } else { 18349 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18350 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18351 // In OpenMP 5.0 or above, DevTy may be changed later by 18352 // #pragma omp declare target to(*) device_type(*). Therefore DevTy 18353 // having no value does not imply host. The emission status will be 18354 // checked again at the end of compilation unit. 18355 if (DevTy.hasValue()) { 18356 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 18357 OMPES = FunctionEmissionStatus::OMPDiscarded; 18358 } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host || 18359 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) 18360 OMPES = FunctionEmissionStatus::Emitted; 18361 } else if (Final) 18362 OMPES = FunctionEmissionStatus::Emitted; 18363 } 18364 } 18365 if (OMPES == FunctionEmissionStatus::OMPDiscarded || 18366 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) 18367 return OMPES; 18368 18369 if (LangOpts.CUDA) { 18370 // When compiling for device, host functions are never emitted. Similarly, 18371 // when compiling for host, device and global functions are never emitted. 18372 // (Technically, we do emit a host-side stub for global functions, but this 18373 // doesn't count for our purposes here.) 18374 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18375 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18376 return FunctionEmissionStatus::CUDADiscarded; 18377 if (!LangOpts.CUDAIsDevice && 18378 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18379 return FunctionEmissionStatus::CUDADiscarded; 18380 18381 // Check whether this function is externally visible -- if so, it's 18382 // known-emitted. 18383 // 18384 // We have to check the GVA linkage of the function's *definition* -- if we 18385 // only have a declaration, we don't know whether or not the function will 18386 // be emitted, because (say) the definition could include "inline". 18387 FunctionDecl *Def = FD->getDefinition(); 18388 18389 if (Def && 18390 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) 18391 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) 18392 return FunctionEmissionStatus::Emitted; 18393 } 18394 18395 // Otherwise, the function is known-emitted if it's in our set of 18396 // known-emitted functions. 18397 return FunctionEmissionStatus::Unknown; 18398 } 18399 18400 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18401 // Host-side references to a __global__ function refer to the stub, so the 18402 // function itself is never emitted and therefore should not be marked. 18403 // If we have host fn calls kernel fn calls host+device, the HD function 18404 // does not get instantiated on the host. We model this by omitting at the 18405 // call to the kernel from the callgraph. This ensures that, when compiling 18406 // for host, only HD functions actually called from the host get marked as 18407 // known-emitted. 18408 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18409 IdentifyCUDATarget(Callee) == CFT_Global; 18410 } 18411