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 is invalid, just give up here. 3242 if (Old->isInvalidDecl()) 3243 return true; 3244 3245 // Disallow redeclaration of some builtins. 3246 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3247 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3248 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3249 << Old << Old->getType(); 3250 return true; 3251 } 3252 3253 diag::kind PrevDiag; 3254 SourceLocation OldLocation; 3255 std::tie(PrevDiag, OldLocation) = 3256 getNoteDiagForInvalidRedeclaration(Old, New); 3257 3258 // Don't complain about this if we're in GNU89 mode and the old function 3259 // is an extern inline function. 3260 // Don't complain about specializations. They are not supposed to have 3261 // storage classes. 3262 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3263 New->getStorageClass() == SC_Static && 3264 Old->hasExternalFormalLinkage() && 3265 !New->getTemplateSpecializationInfo() && 3266 !canRedefineFunction(Old, getLangOpts())) { 3267 if (getLangOpts().MicrosoftExt) { 3268 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3269 Diag(OldLocation, PrevDiag); 3270 } else { 3271 Diag(New->getLocation(), diag::err_static_non_static) << New; 3272 Diag(OldLocation, PrevDiag); 3273 return true; 3274 } 3275 } 3276 3277 if (New->hasAttr<InternalLinkageAttr>() && 3278 !Old->hasAttr<InternalLinkageAttr>()) { 3279 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3280 << New->getDeclName(); 3281 notePreviousDefinition(Old, New->getLocation()); 3282 New->dropAttr<InternalLinkageAttr>(); 3283 } 3284 3285 if (CheckRedeclarationModuleOwnership(New, Old)) 3286 return true; 3287 3288 if (!getLangOpts().CPlusPlus) { 3289 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3290 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3291 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3292 << New << OldOvl; 3293 3294 // Try our best to find a decl that actually has the overloadable 3295 // attribute for the note. In most cases (e.g. programs with only one 3296 // broken declaration/definition), this won't matter. 3297 // 3298 // FIXME: We could do this if we juggled some extra state in 3299 // OverloadableAttr, rather than just removing it. 3300 const Decl *DiagOld = Old; 3301 if (OldOvl) { 3302 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3303 const auto *A = D->getAttr<OverloadableAttr>(); 3304 return A && !A->isImplicit(); 3305 }); 3306 // If we've implicitly added *all* of the overloadable attrs to this 3307 // chain, emitting a "previous redecl" note is pointless. 3308 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3309 } 3310 3311 if (DiagOld) 3312 Diag(DiagOld->getLocation(), 3313 diag::note_attribute_overloadable_prev_overload) 3314 << OldOvl; 3315 3316 if (OldOvl) 3317 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3318 else 3319 New->dropAttr<OverloadableAttr>(); 3320 } 3321 } 3322 3323 // If a function is first declared with a calling convention, but is later 3324 // declared or defined without one, all following decls assume the calling 3325 // convention of the first. 3326 // 3327 // It's OK if a function is first declared without a calling convention, 3328 // but is later declared or defined with the default calling convention. 3329 // 3330 // To test if either decl has an explicit calling convention, we look for 3331 // AttributedType sugar nodes on the type as written. If they are missing or 3332 // were canonicalized away, we assume the calling convention was implicit. 3333 // 3334 // Note also that we DO NOT return at this point, because we still have 3335 // other tests to run. 3336 QualType OldQType = Context.getCanonicalType(Old->getType()); 3337 QualType NewQType = Context.getCanonicalType(New->getType()); 3338 const FunctionType *OldType = cast<FunctionType>(OldQType); 3339 const FunctionType *NewType = cast<FunctionType>(NewQType); 3340 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3341 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3342 bool RequiresAdjustment = false; 3343 3344 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3345 FunctionDecl *First = Old->getFirstDecl(); 3346 const FunctionType *FT = 3347 First->getType().getCanonicalType()->castAs<FunctionType>(); 3348 FunctionType::ExtInfo FI = FT->getExtInfo(); 3349 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3350 if (!NewCCExplicit) { 3351 // Inherit the CC from the previous declaration if it was specified 3352 // there but not here. 3353 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3354 RequiresAdjustment = true; 3355 } else if (Old->getBuiltinID()) { 3356 // Builtin attribute isn't propagated to the new one yet at this point, 3357 // so we check if the old one is a builtin. 3358 3359 // Calling Conventions on a Builtin aren't really useful and setting a 3360 // default calling convention and cdecl'ing some builtin redeclarations is 3361 // common, so warn and ignore the calling convention on the redeclaration. 3362 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3363 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3364 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3365 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3366 RequiresAdjustment = true; 3367 } else { 3368 // Calling conventions aren't compatible, so complain. 3369 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3370 Diag(New->getLocation(), diag::err_cconv_change) 3371 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3372 << !FirstCCExplicit 3373 << (!FirstCCExplicit ? "" : 3374 FunctionType::getNameForCallConv(FI.getCC())); 3375 3376 // Put the note on the first decl, since it is the one that matters. 3377 Diag(First->getLocation(), diag::note_previous_declaration); 3378 return true; 3379 } 3380 } 3381 3382 // FIXME: diagnose the other way around? 3383 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3384 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3385 RequiresAdjustment = true; 3386 } 3387 3388 // Merge regparm attribute. 3389 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3390 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3391 if (NewTypeInfo.getHasRegParm()) { 3392 Diag(New->getLocation(), diag::err_regparm_mismatch) 3393 << NewType->getRegParmType() 3394 << OldType->getRegParmType(); 3395 Diag(OldLocation, diag::note_previous_declaration); 3396 return true; 3397 } 3398 3399 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3400 RequiresAdjustment = true; 3401 } 3402 3403 // Merge ns_returns_retained attribute. 3404 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3405 if (NewTypeInfo.getProducesResult()) { 3406 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3407 << "'ns_returns_retained'"; 3408 Diag(OldLocation, diag::note_previous_declaration); 3409 return true; 3410 } 3411 3412 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3413 RequiresAdjustment = true; 3414 } 3415 3416 if (OldTypeInfo.getNoCallerSavedRegs() != 3417 NewTypeInfo.getNoCallerSavedRegs()) { 3418 if (NewTypeInfo.getNoCallerSavedRegs()) { 3419 AnyX86NoCallerSavedRegistersAttr *Attr = 3420 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3421 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3422 Diag(OldLocation, diag::note_previous_declaration); 3423 return true; 3424 } 3425 3426 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3427 RequiresAdjustment = true; 3428 } 3429 3430 if (RequiresAdjustment) { 3431 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3432 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3433 New->setType(QualType(AdjustedType, 0)); 3434 NewQType = Context.getCanonicalType(New->getType()); 3435 } 3436 3437 // If this redeclaration makes the function inline, we may need to add it to 3438 // UndefinedButUsed. 3439 if (!Old->isInlined() && New->isInlined() && 3440 !New->hasAttr<GNUInlineAttr>() && 3441 !getLangOpts().GNUInline && 3442 Old->isUsed(false) && 3443 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3444 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3445 SourceLocation())); 3446 3447 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3448 // about it. 3449 if (New->hasAttr<GNUInlineAttr>() && 3450 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3451 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3452 } 3453 3454 // If pass_object_size params don't match up perfectly, this isn't a valid 3455 // redeclaration. 3456 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3457 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3458 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3459 << New->getDeclName(); 3460 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3461 return true; 3462 } 3463 3464 if (getLangOpts().CPlusPlus) { 3465 // C++1z [over.load]p2 3466 // Certain function declarations cannot be overloaded: 3467 // -- Function declarations that differ only in the return type, 3468 // the exception specification, or both cannot be overloaded. 3469 3470 // Check the exception specifications match. This may recompute the type of 3471 // both Old and New if it resolved exception specifications, so grab the 3472 // types again after this. Because this updates the type, we do this before 3473 // any of the other checks below, which may update the "de facto" NewQType 3474 // but do not necessarily update the type of New. 3475 if (CheckEquivalentExceptionSpec(Old, New)) 3476 return true; 3477 OldQType = Context.getCanonicalType(Old->getType()); 3478 NewQType = Context.getCanonicalType(New->getType()); 3479 3480 // Go back to the type source info to compare the declared return types, 3481 // per C++1y [dcl.type.auto]p13: 3482 // Redeclarations or specializations of a function or function template 3483 // with a declared return type that uses a placeholder type shall also 3484 // use that placeholder, not a deduced type. 3485 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3486 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3487 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3488 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3489 OldDeclaredReturnType)) { 3490 QualType ResQT; 3491 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3492 OldDeclaredReturnType->isObjCObjectPointerType()) 3493 // FIXME: This does the wrong thing for a deduced return type. 3494 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3495 if (ResQT.isNull()) { 3496 if (New->isCXXClassMember() && New->isOutOfLine()) 3497 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3498 << New << New->getReturnTypeSourceRange(); 3499 else 3500 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3501 << New->getReturnTypeSourceRange(); 3502 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3503 << Old->getReturnTypeSourceRange(); 3504 return true; 3505 } 3506 else 3507 NewQType = ResQT; 3508 } 3509 3510 QualType OldReturnType = OldType->getReturnType(); 3511 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3512 if (OldReturnType != NewReturnType) { 3513 // If this function has a deduced return type and has already been 3514 // defined, copy the deduced value from the old declaration. 3515 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3516 if (OldAT && OldAT->isDeduced()) { 3517 New->setType( 3518 SubstAutoType(New->getType(), 3519 OldAT->isDependentType() ? Context.DependentTy 3520 : OldAT->getDeducedType())); 3521 NewQType = Context.getCanonicalType( 3522 SubstAutoType(NewQType, 3523 OldAT->isDependentType() ? Context.DependentTy 3524 : OldAT->getDeducedType())); 3525 } 3526 } 3527 3528 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3529 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3530 if (OldMethod && NewMethod) { 3531 // Preserve triviality. 3532 NewMethod->setTrivial(OldMethod->isTrivial()); 3533 3534 // MSVC allows explicit template specialization at class scope: 3535 // 2 CXXMethodDecls referring to the same function will be injected. 3536 // We don't want a redeclaration error. 3537 bool IsClassScopeExplicitSpecialization = 3538 OldMethod->isFunctionTemplateSpecialization() && 3539 NewMethod->isFunctionTemplateSpecialization(); 3540 bool isFriend = NewMethod->getFriendObjectKind(); 3541 3542 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3543 !IsClassScopeExplicitSpecialization) { 3544 // -- Member function declarations with the same name and the 3545 // same parameter types cannot be overloaded if any of them 3546 // is a static member function declaration. 3547 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3548 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3549 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3550 return true; 3551 } 3552 3553 // C++ [class.mem]p1: 3554 // [...] A member shall not be declared twice in the 3555 // member-specification, except that a nested class or member 3556 // class template can be declared and then later defined. 3557 if (!inTemplateInstantiation()) { 3558 unsigned NewDiag; 3559 if (isa<CXXConstructorDecl>(OldMethod)) 3560 NewDiag = diag::err_constructor_redeclared; 3561 else if (isa<CXXDestructorDecl>(NewMethod)) 3562 NewDiag = diag::err_destructor_redeclared; 3563 else if (isa<CXXConversionDecl>(NewMethod)) 3564 NewDiag = diag::err_conv_function_redeclared; 3565 else 3566 NewDiag = diag::err_member_redeclared; 3567 3568 Diag(New->getLocation(), NewDiag); 3569 } else { 3570 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3571 << New << New->getType(); 3572 } 3573 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3574 return true; 3575 3576 // Complain if this is an explicit declaration of a special 3577 // member that was initially declared implicitly. 3578 // 3579 // As an exception, it's okay to befriend such methods in order 3580 // to permit the implicit constructor/destructor/operator calls. 3581 } else if (OldMethod->isImplicit()) { 3582 if (isFriend) { 3583 NewMethod->setImplicit(); 3584 } else { 3585 Diag(NewMethod->getLocation(), 3586 diag::err_definition_of_implicitly_declared_member) 3587 << New << getSpecialMember(OldMethod); 3588 return true; 3589 } 3590 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3591 Diag(NewMethod->getLocation(), 3592 diag::err_definition_of_explicitly_defaulted_member) 3593 << getSpecialMember(OldMethod); 3594 return true; 3595 } 3596 } 3597 3598 // C++11 [dcl.attr.noreturn]p1: 3599 // The first declaration of a function shall specify the noreturn 3600 // attribute if any declaration of that function specifies the noreturn 3601 // attribute. 3602 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3603 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3604 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3605 Diag(Old->getFirstDecl()->getLocation(), 3606 diag::note_noreturn_missing_first_decl); 3607 } 3608 3609 // C++11 [dcl.attr.depend]p2: 3610 // The first declaration of a function shall specify the 3611 // carries_dependency attribute for its declarator-id if any declaration 3612 // of the function specifies the carries_dependency attribute. 3613 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3614 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3615 Diag(CDA->getLocation(), 3616 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3617 Diag(Old->getFirstDecl()->getLocation(), 3618 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3619 } 3620 3621 // (C++98 8.3.5p3): 3622 // All declarations for a function shall agree exactly in both the 3623 // return type and the parameter-type-list. 3624 // We also want to respect all the extended bits except noreturn. 3625 3626 // noreturn should now match unless the old type info didn't have it. 3627 QualType OldQTypeForComparison = OldQType; 3628 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3629 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3630 const FunctionType *OldTypeForComparison 3631 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3632 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3633 assert(OldQTypeForComparison.isCanonical()); 3634 } 3635 3636 if (haveIncompatibleLanguageLinkages(Old, New)) { 3637 // As a special case, retain the language linkage from previous 3638 // declarations of a friend function as an extension. 3639 // 3640 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3641 // and is useful because there's otherwise no way to specify language 3642 // linkage within class scope. 3643 // 3644 // Check cautiously as the friend object kind isn't yet complete. 3645 if (New->getFriendObjectKind() != Decl::FOK_None) { 3646 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3647 Diag(OldLocation, PrevDiag); 3648 } else { 3649 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3650 Diag(OldLocation, PrevDiag); 3651 return true; 3652 } 3653 } 3654 3655 // If the function types are compatible, merge the declarations. Ignore the 3656 // exception specifier because it was already checked above in 3657 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3658 // about incompatible types under -fms-compatibility. 3659 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3660 NewQType)) 3661 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3662 3663 // If the types are imprecise (due to dependent constructs in friends or 3664 // local extern declarations), it's OK if they differ. We'll check again 3665 // during instantiation. 3666 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3667 return false; 3668 3669 // Fall through for conflicting redeclarations and redefinitions. 3670 } 3671 3672 // C: Function types need to be compatible, not identical. This handles 3673 // duplicate function decls like "void f(int); void f(enum X);" properly. 3674 if (!getLangOpts().CPlusPlus && 3675 Context.typesAreCompatible(OldQType, NewQType)) { 3676 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3677 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3678 const FunctionProtoType *OldProto = nullptr; 3679 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3680 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3681 // The old declaration provided a function prototype, but the 3682 // new declaration does not. Merge in the prototype. 3683 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3684 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3685 NewQType = 3686 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3687 OldProto->getExtProtoInfo()); 3688 New->setType(NewQType); 3689 New->setHasInheritedPrototype(); 3690 3691 // Synthesize parameters with the same types. 3692 SmallVector<ParmVarDecl*, 16> Params; 3693 for (const auto &ParamType : OldProto->param_types()) { 3694 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3695 SourceLocation(), nullptr, 3696 ParamType, /*TInfo=*/nullptr, 3697 SC_None, nullptr); 3698 Param->setScopeInfo(0, Params.size()); 3699 Param->setImplicit(); 3700 Params.push_back(Param); 3701 } 3702 3703 New->setParams(Params); 3704 } 3705 3706 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3707 } 3708 3709 // Check if the function types are compatible when pointer size address 3710 // spaces are ignored. 3711 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3712 return false; 3713 3714 // GNU C permits a K&R definition to follow a prototype declaration 3715 // if the declared types of the parameters in the K&R definition 3716 // match the types in the prototype declaration, even when the 3717 // promoted types of the parameters from the K&R definition differ 3718 // from the types in the prototype. GCC then keeps the types from 3719 // the prototype. 3720 // 3721 // If a variadic prototype is followed by a non-variadic K&R definition, 3722 // the K&R definition becomes variadic. This is sort of an edge case, but 3723 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3724 // C99 6.9.1p8. 3725 if (!getLangOpts().CPlusPlus && 3726 Old->hasPrototype() && !New->hasPrototype() && 3727 New->getType()->getAs<FunctionProtoType>() && 3728 Old->getNumParams() == New->getNumParams()) { 3729 SmallVector<QualType, 16> ArgTypes; 3730 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3731 const FunctionProtoType *OldProto 3732 = Old->getType()->getAs<FunctionProtoType>(); 3733 const FunctionProtoType *NewProto 3734 = New->getType()->getAs<FunctionProtoType>(); 3735 3736 // Determine whether this is the GNU C extension. 3737 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3738 NewProto->getReturnType()); 3739 bool LooseCompatible = !MergedReturn.isNull(); 3740 for (unsigned Idx = 0, End = Old->getNumParams(); 3741 LooseCompatible && Idx != End; ++Idx) { 3742 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3743 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3744 if (Context.typesAreCompatible(OldParm->getType(), 3745 NewProto->getParamType(Idx))) { 3746 ArgTypes.push_back(NewParm->getType()); 3747 } else if (Context.typesAreCompatible(OldParm->getType(), 3748 NewParm->getType(), 3749 /*CompareUnqualified=*/true)) { 3750 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3751 NewProto->getParamType(Idx) }; 3752 Warnings.push_back(Warn); 3753 ArgTypes.push_back(NewParm->getType()); 3754 } else 3755 LooseCompatible = false; 3756 } 3757 3758 if (LooseCompatible) { 3759 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3760 Diag(Warnings[Warn].NewParm->getLocation(), 3761 diag::ext_param_promoted_not_compatible_with_prototype) 3762 << Warnings[Warn].PromotedType 3763 << Warnings[Warn].OldParm->getType(); 3764 if (Warnings[Warn].OldParm->getLocation().isValid()) 3765 Diag(Warnings[Warn].OldParm->getLocation(), 3766 diag::note_previous_declaration); 3767 } 3768 3769 if (MergeTypeWithOld) 3770 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3771 OldProto->getExtProtoInfo())); 3772 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3773 } 3774 3775 // Fall through to diagnose conflicting types. 3776 } 3777 3778 // A function that has already been declared has been redeclared or 3779 // defined with a different type; show an appropriate diagnostic. 3780 3781 // If the previous declaration was an implicitly-generated builtin 3782 // declaration, then at the very least we should use a specialized note. 3783 unsigned BuiltinID; 3784 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3785 // If it's actually a library-defined builtin function like 'malloc' 3786 // or 'printf', just warn about the incompatible redeclaration. 3787 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3788 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3789 Diag(OldLocation, diag::note_previous_builtin_declaration) 3790 << Old << Old->getType(); 3791 return false; 3792 } 3793 3794 PrevDiag = diag::note_previous_builtin_declaration; 3795 } 3796 3797 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3798 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3799 return true; 3800 } 3801 3802 /// Completes the merge of two function declarations that are 3803 /// known to be compatible. 3804 /// 3805 /// This routine handles the merging of attributes and other 3806 /// properties of function declarations from the old declaration to 3807 /// the new declaration, once we know that New is in fact a 3808 /// redeclaration of Old. 3809 /// 3810 /// \returns false 3811 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3812 Scope *S, bool MergeTypeWithOld) { 3813 // Merge the attributes 3814 mergeDeclAttributes(New, Old); 3815 3816 // Merge "pure" flag. 3817 if (Old->isPure()) 3818 New->setPure(); 3819 3820 // Merge "used" flag. 3821 if (Old->getMostRecentDecl()->isUsed(false)) 3822 New->setIsUsed(); 3823 3824 // Merge attributes from the parameters. These can mismatch with K&R 3825 // declarations. 3826 if (New->getNumParams() == Old->getNumParams()) 3827 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3828 ParmVarDecl *NewParam = New->getParamDecl(i); 3829 ParmVarDecl *OldParam = Old->getParamDecl(i); 3830 mergeParamDeclAttributes(NewParam, OldParam, *this); 3831 mergeParamDeclTypes(NewParam, OldParam, *this); 3832 } 3833 3834 if (getLangOpts().CPlusPlus) 3835 return MergeCXXFunctionDecl(New, Old, S); 3836 3837 // Merge the function types so the we get the composite types for the return 3838 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3839 // was visible. 3840 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3841 if (!Merged.isNull() && MergeTypeWithOld) 3842 New->setType(Merged); 3843 3844 return false; 3845 } 3846 3847 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3848 ObjCMethodDecl *oldMethod) { 3849 // Merge the attributes, including deprecated/unavailable 3850 AvailabilityMergeKind MergeKind = 3851 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3852 ? AMK_ProtocolImplementation 3853 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3854 : AMK_Override; 3855 3856 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3857 3858 // Merge attributes from the parameters. 3859 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3860 oe = oldMethod->param_end(); 3861 for (ObjCMethodDecl::param_iterator 3862 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3863 ni != ne && oi != oe; ++ni, ++oi) 3864 mergeParamDeclAttributes(*ni, *oi, *this); 3865 3866 CheckObjCMethodOverride(newMethod, oldMethod); 3867 } 3868 3869 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3870 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3871 3872 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3873 ? diag::err_redefinition_different_type 3874 : diag::err_redeclaration_different_type) 3875 << New->getDeclName() << New->getType() << Old->getType(); 3876 3877 diag::kind PrevDiag; 3878 SourceLocation OldLocation; 3879 std::tie(PrevDiag, OldLocation) 3880 = getNoteDiagForInvalidRedeclaration(Old, New); 3881 S.Diag(OldLocation, PrevDiag); 3882 New->setInvalidDecl(); 3883 } 3884 3885 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3886 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3887 /// emitting diagnostics as appropriate. 3888 /// 3889 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3890 /// to here in AddInitializerToDecl. We can't check them before the initializer 3891 /// is attached. 3892 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3893 bool MergeTypeWithOld) { 3894 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3895 return; 3896 3897 QualType MergedT; 3898 if (getLangOpts().CPlusPlus) { 3899 if (New->getType()->isUndeducedType()) { 3900 // We don't know what the new type is until the initializer is attached. 3901 return; 3902 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3903 // These could still be something that needs exception specs checked. 3904 return MergeVarDeclExceptionSpecs(New, Old); 3905 } 3906 // C++ [basic.link]p10: 3907 // [...] the types specified by all declarations referring to a given 3908 // object or function shall be identical, except that declarations for an 3909 // array object can specify array types that differ by the presence or 3910 // absence of a major array bound (8.3.4). 3911 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3912 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3913 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3914 3915 // We are merging a variable declaration New into Old. If it has an array 3916 // bound, and that bound differs from Old's bound, we should diagnose the 3917 // mismatch. 3918 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3919 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3920 PrevVD = PrevVD->getPreviousDecl()) { 3921 QualType PrevVDTy = PrevVD->getType(); 3922 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3923 continue; 3924 3925 if (!Context.hasSameType(New->getType(), PrevVDTy)) 3926 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3927 } 3928 } 3929 3930 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3931 if (Context.hasSameType(OldArray->getElementType(), 3932 NewArray->getElementType())) 3933 MergedT = New->getType(); 3934 } 3935 // FIXME: Check visibility. New is hidden but has a complete type. If New 3936 // has no array bound, it should not inherit one from Old, if Old is not 3937 // visible. 3938 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3939 if (Context.hasSameType(OldArray->getElementType(), 3940 NewArray->getElementType())) 3941 MergedT = Old->getType(); 3942 } 3943 } 3944 else if (New->getType()->isObjCObjectPointerType() && 3945 Old->getType()->isObjCObjectPointerType()) { 3946 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3947 Old->getType()); 3948 } 3949 } else { 3950 // C 6.2.7p2: 3951 // All declarations that refer to the same object or function shall have 3952 // compatible type. 3953 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3954 } 3955 if (MergedT.isNull()) { 3956 // It's OK if we couldn't merge types if either type is dependent, for a 3957 // block-scope variable. In other cases (static data members of class 3958 // templates, variable templates, ...), we require the types to be 3959 // equivalent. 3960 // FIXME: The C++ standard doesn't say anything about this. 3961 if ((New->getType()->isDependentType() || 3962 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3963 // If the old type was dependent, we can't merge with it, so the new type 3964 // becomes dependent for now. We'll reproduce the original type when we 3965 // instantiate the TypeSourceInfo for the variable. 3966 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3967 New->setType(Context.DependentTy); 3968 return; 3969 } 3970 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3971 } 3972 3973 // Don't actually update the type on the new declaration if the old 3974 // declaration was an extern declaration in a different scope. 3975 if (MergeTypeWithOld) 3976 New->setType(MergedT); 3977 } 3978 3979 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3980 LookupResult &Previous) { 3981 // C11 6.2.7p4: 3982 // For an identifier with internal or external linkage declared 3983 // in a scope in which a prior declaration of that identifier is 3984 // visible, if the prior declaration specifies internal or 3985 // external linkage, the type of the identifier at the later 3986 // declaration becomes the composite type. 3987 // 3988 // If the variable isn't visible, we do not merge with its type. 3989 if (Previous.isShadowed()) 3990 return false; 3991 3992 if (S.getLangOpts().CPlusPlus) { 3993 // C++11 [dcl.array]p3: 3994 // If there is a preceding declaration of the entity in the same 3995 // scope in which the bound was specified, an omitted array bound 3996 // is taken to be the same as in that earlier declaration. 3997 return NewVD->isPreviousDeclInSameBlockScope() || 3998 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3999 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4000 } else { 4001 // If the old declaration was function-local, don't merge with its 4002 // type unless we're in the same function. 4003 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4004 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4005 } 4006 } 4007 4008 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4009 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4010 /// situation, merging decls or emitting diagnostics as appropriate. 4011 /// 4012 /// Tentative definition rules (C99 6.9.2p2) are checked by 4013 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4014 /// definitions here, since the initializer hasn't been attached. 4015 /// 4016 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4017 // If the new decl is already invalid, don't do any other checking. 4018 if (New->isInvalidDecl()) 4019 return; 4020 4021 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4022 return; 4023 4024 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4025 4026 // Verify the old decl was also a variable or variable template. 4027 VarDecl *Old = nullptr; 4028 VarTemplateDecl *OldTemplate = nullptr; 4029 if (Previous.isSingleResult()) { 4030 if (NewTemplate) { 4031 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4032 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4033 4034 if (auto *Shadow = 4035 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4036 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4037 return New->setInvalidDecl(); 4038 } else { 4039 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4040 4041 if (auto *Shadow = 4042 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4043 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4044 return New->setInvalidDecl(); 4045 } 4046 } 4047 if (!Old) { 4048 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4049 << New->getDeclName(); 4050 notePreviousDefinition(Previous.getRepresentativeDecl(), 4051 New->getLocation()); 4052 return New->setInvalidDecl(); 4053 } 4054 4055 // Ensure the template parameters are compatible. 4056 if (NewTemplate && 4057 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4058 OldTemplate->getTemplateParameters(), 4059 /*Complain=*/true, TPL_TemplateMatch)) 4060 return New->setInvalidDecl(); 4061 4062 // C++ [class.mem]p1: 4063 // A member shall not be declared twice in the member-specification [...] 4064 // 4065 // Here, we need only consider static data members. 4066 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4067 Diag(New->getLocation(), diag::err_duplicate_member) 4068 << New->getIdentifier(); 4069 Diag(Old->getLocation(), diag::note_previous_declaration); 4070 New->setInvalidDecl(); 4071 } 4072 4073 mergeDeclAttributes(New, Old); 4074 // Warn if an already-declared variable is made a weak_import in a subsequent 4075 // declaration 4076 if (New->hasAttr<WeakImportAttr>() && 4077 Old->getStorageClass() == SC_None && 4078 !Old->hasAttr<WeakImportAttr>()) { 4079 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4080 notePreviousDefinition(Old, New->getLocation()); 4081 // Remove weak_import attribute on new declaration. 4082 New->dropAttr<WeakImportAttr>(); 4083 } 4084 4085 if (New->hasAttr<InternalLinkageAttr>() && 4086 !Old->hasAttr<InternalLinkageAttr>()) { 4087 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4088 << New->getDeclName(); 4089 notePreviousDefinition(Old, New->getLocation()); 4090 New->dropAttr<InternalLinkageAttr>(); 4091 } 4092 4093 // Merge the types. 4094 VarDecl *MostRecent = Old->getMostRecentDecl(); 4095 if (MostRecent != Old) { 4096 MergeVarDeclTypes(New, MostRecent, 4097 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4098 if (New->isInvalidDecl()) 4099 return; 4100 } 4101 4102 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4103 if (New->isInvalidDecl()) 4104 return; 4105 4106 diag::kind PrevDiag; 4107 SourceLocation OldLocation; 4108 std::tie(PrevDiag, OldLocation) = 4109 getNoteDiagForInvalidRedeclaration(Old, New); 4110 4111 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4112 if (New->getStorageClass() == SC_Static && 4113 !New->isStaticDataMember() && 4114 Old->hasExternalFormalLinkage()) { 4115 if (getLangOpts().MicrosoftExt) { 4116 Diag(New->getLocation(), diag::ext_static_non_static) 4117 << New->getDeclName(); 4118 Diag(OldLocation, PrevDiag); 4119 } else { 4120 Diag(New->getLocation(), diag::err_static_non_static) 4121 << New->getDeclName(); 4122 Diag(OldLocation, PrevDiag); 4123 return New->setInvalidDecl(); 4124 } 4125 } 4126 // C99 6.2.2p4: 4127 // For an identifier declared with the storage-class specifier 4128 // extern in a scope in which a prior declaration of that 4129 // identifier is visible,23) if the prior declaration specifies 4130 // internal or external linkage, the linkage of the identifier at 4131 // the later declaration is the same as the linkage specified at 4132 // the prior declaration. If no prior declaration is visible, or 4133 // if the prior declaration specifies no linkage, then the 4134 // identifier has external linkage. 4135 if (New->hasExternalStorage() && Old->hasLinkage()) 4136 /* Okay */; 4137 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4138 !New->isStaticDataMember() && 4139 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4140 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4141 Diag(OldLocation, PrevDiag); 4142 return New->setInvalidDecl(); 4143 } 4144 4145 // Check if extern is followed by non-extern and vice-versa. 4146 if (New->hasExternalStorage() && 4147 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4148 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4149 Diag(OldLocation, PrevDiag); 4150 return New->setInvalidDecl(); 4151 } 4152 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4153 !New->hasExternalStorage()) { 4154 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4155 Diag(OldLocation, PrevDiag); 4156 return New->setInvalidDecl(); 4157 } 4158 4159 if (CheckRedeclarationModuleOwnership(New, Old)) 4160 return; 4161 4162 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4163 4164 // FIXME: The test for external storage here seems wrong? We still 4165 // need to check for mismatches. 4166 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4167 // Don't complain about out-of-line definitions of static members. 4168 !(Old->getLexicalDeclContext()->isRecord() && 4169 !New->getLexicalDeclContext()->isRecord())) { 4170 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4171 Diag(OldLocation, PrevDiag); 4172 return New->setInvalidDecl(); 4173 } 4174 4175 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4176 if (VarDecl *Def = Old->getDefinition()) { 4177 // C++1z [dcl.fcn.spec]p4: 4178 // If the definition of a variable appears in a translation unit before 4179 // its first declaration as inline, the program is ill-formed. 4180 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4181 Diag(Def->getLocation(), diag::note_previous_definition); 4182 } 4183 } 4184 4185 // If this redeclaration makes the variable inline, we may need to add it to 4186 // UndefinedButUsed. 4187 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4188 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4189 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4190 SourceLocation())); 4191 4192 if (New->getTLSKind() != Old->getTLSKind()) { 4193 if (!Old->getTLSKind()) { 4194 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4195 Diag(OldLocation, PrevDiag); 4196 } else if (!New->getTLSKind()) { 4197 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4198 Diag(OldLocation, PrevDiag); 4199 } else { 4200 // Do not allow redeclaration to change the variable between requiring 4201 // static and dynamic initialization. 4202 // FIXME: GCC allows this, but uses the TLS keyword on the first 4203 // declaration to determine the kind. Do we need to be compatible here? 4204 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4205 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4206 Diag(OldLocation, PrevDiag); 4207 } 4208 } 4209 4210 // C++ doesn't have tentative definitions, so go right ahead and check here. 4211 if (getLangOpts().CPlusPlus && 4212 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4213 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4214 Old->getCanonicalDecl()->isConstexpr()) { 4215 // This definition won't be a definition any more once it's been merged. 4216 Diag(New->getLocation(), 4217 diag::warn_deprecated_redundant_constexpr_static_def); 4218 } else if (VarDecl *Def = Old->getDefinition()) { 4219 if (checkVarDeclRedefinition(Def, New)) 4220 return; 4221 } 4222 } 4223 4224 if (haveIncompatibleLanguageLinkages(Old, New)) { 4225 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4226 Diag(OldLocation, PrevDiag); 4227 New->setInvalidDecl(); 4228 return; 4229 } 4230 4231 // Merge "used" flag. 4232 if (Old->getMostRecentDecl()->isUsed(false)) 4233 New->setIsUsed(); 4234 4235 // Keep a chain of previous declarations. 4236 New->setPreviousDecl(Old); 4237 if (NewTemplate) 4238 NewTemplate->setPreviousDecl(OldTemplate); 4239 adjustDeclContextForDeclaratorDecl(New, Old); 4240 4241 // Inherit access appropriately. 4242 New->setAccess(Old->getAccess()); 4243 if (NewTemplate) 4244 NewTemplate->setAccess(New->getAccess()); 4245 4246 if (Old->isInline()) 4247 New->setImplicitlyInline(); 4248 } 4249 4250 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4251 SourceManager &SrcMgr = getSourceManager(); 4252 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4253 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4254 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4255 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4256 auto &HSI = PP.getHeaderSearchInfo(); 4257 StringRef HdrFilename = 4258 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4259 4260 auto noteFromModuleOrInclude = [&](Module *Mod, 4261 SourceLocation IncLoc) -> bool { 4262 // Redefinition errors with modules are common with non modular mapped 4263 // headers, example: a non-modular header H in module A that also gets 4264 // included directly in a TU. Pointing twice to the same header/definition 4265 // is confusing, try to get better diagnostics when modules is on. 4266 if (IncLoc.isValid()) { 4267 if (Mod) { 4268 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4269 << HdrFilename.str() << Mod->getFullModuleName(); 4270 if (!Mod->DefinitionLoc.isInvalid()) 4271 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4272 << Mod->getFullModuleName(); 4273 } else { 4274 Diag(IncLoc, diag::note_redefinition_include_same_file) 4275 << HdrFilename.str(); 4276 } 4277 return true; 4278 } 4279 4280 return false; 4281 }; 4282 4283 // Is it the same file and same offset? Provide more information on why 4284 // this leads to a redefinition error. 4285 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4286 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4287 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4288 bool EmittedDiag = 4289 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4290 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4291 4292 // If the header has no guards, emit a note suggesting one. 4293 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4294 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4295 4296 if (EmittedDiag) 4297 return; 4298 } 4299 4300 // Redefinition coming from different files or couldn't do better above. 4301 if (Old->getLocation().isValid()) 4302 Diag(Old->getLocation(), diag::note_previous_definition); 4303 } 4304 4305 /// We've just determined that \p Old and \p New both appear to be definitions 4306 /// of the same variable. Either diagnose or fix the problem. 4307 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4308 if (!hasVisibleDefinition(Old) && 4309 (New->getFormalLinkage() == InternalLinkage || 4310 New->isInline() || 4311 New->getDescribedVarTemplate() || 4312 New->getNumTemplateParameterLists() || 4313 New->getDeclContext()->isDependentContext())) { 4314 // The previous definition is hidden, and multiple definitions are 4315 // permitted (in separate TUs). Demote this to a declaration. 4316 New->demoteThisDefinitionToDeclaration(); 4317 4318 // Make the canonical definition visible. 4319 if (auto *OldTD = Old->getDescribedVarTemplate()) 4320 makeMergedDefinitionVisible(OldTD); 4321 makeMergedDefinitionVisible(Old); 4322 return false; 4323 } else { 4324 Diag(New->getLocation(), diag::err_redefinition) << New; 4325 notePreviousDefinition(Old, New->getLocation()); 4326 New->setInvalidDecl(); 4327 return true; 4328 } 4329 } 4330 4331 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4332 /// no declarator (e.g. "struct foo;") is parsed. 4333 Decl * 4334 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4335 RecordDecl *&AnonRecord) { 4336 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4337 AnonRecord); 4338 } 4339 4340 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4341 // disambiguate entities defined in different scopes. 4342 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4343 // compatibility. 4344 // We will pick our mangling number depending on which version of MSVC is being 4345 // targeted. 4346 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4347 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4348 ? S->getMSCurManglingNumber() 4349 : S->getMSLastManglingNumber(); 4350 } 4351 4352 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4353 if (!Context.getLangOpts().CPlusPlus) 4354 return; 4355 4356 if (isa<CXXRecordDecl>(Tag->getParent())) { 4357 // If this tag is the direct child of a class, number it if 4358 // it is anonymous. 4359 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4360 return; 4361 MangleNumberingContext &MCtx = 4362 Context.getManglingNumberContext(Tag->getParent()); 4363 Context.setManglingNumber( 4364 Tag, MCtx.getManglingNumber( 4365 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4366 return; 4367 } 4368 4369 // If this tag isn't a direct child of a class, number it if it is local. 4370 MangleNumberingContext *MCtx; 4371 Decl *ManglingContextDecl; 4372 std::tie(MCtx, ManglingContextDecl) = 4373 getCurrentMangleNumberContext(Tag->getDeclContext()); 4374 if (MCtx) { 4375 Context.setManglingNumber( 4376 Tag, MCtx->getManglingNumber( 4377 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4378 } 4379 } 4380 4381 namespace { 4382 struct NonCLikeKind { 4383 enum { 4384 None, 4385 BaseClass, 4386 DefaultMemberInit, 4387 Lambda, 4388 Friend, 4389 OtherMember, 4390 Invalid, 4391 } Kind = None; 4392 SourceRange Range; 4393 4394 explicit operator bool() { return Kind != None; } 4395 }; 4396 } 4397 4398 /// Determine whether a class is C-like, according to the rules of C++ 4399 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4400 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4401 if (RD->isInvalidDecl()) 4402 return {NonCLikeKind::Invalid, {}}; 4403 4404 // C++ [dcl.typedef]p9: [P1766R1] 4405 // An unnamed class with a typedef name for linkage purposes shall not 4406 // 4407 // -- have any base classes 4408 if (RD->getNumBases()) 4409 return {NonCLikeKind::BaseClass, 4410 SourceRange(RD->bases_begin()->getBeginLoc(), 4411 RD->bases_end()[-1].getEndLoc())}; 4412 bool Invalid = false; 4413 for (Decl *D : RD->decls()) { 4414 // Don't complain about things we already diagnosed. 4415 if (D->isInvalidDecl()) { 4416 Invalid = true; 4417 continue; 4418 } 4419 4420 // -- have any [...] default member initializers 4421 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4422 if (FD->hasInClassInitializer()) { 4423 auto *Init = FD->getInClassInitializer(); 4424 return {NonCLikeKind::DefaultMemberInit, 4425 Init ? Init->getSourceRange() : D->getSourceRange()}; 4426 } 4427 continue; 4428 } 4429 4430 // FIXME: We don't allow friend declarations. This violates the wording of 4431 // P1766, but not the intent. 4432 if (isa<FriendDecl>(D)) 4433 return {NonCLikeKind::Friend, D->getSourceRange()}; 4434 4435 // -- declare any members other than non-static data members, member 4436 // enumerations, or member classes, 4437 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4438 isa<EnumDecl>(D)) 4439 continue; 4440 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4441 if (!MemberRD) { 4442 if (D->isImplicit()) 4443 continue; 4444 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4445 } 4446 4447 // -- contain a lambda-expression, 4448 if (MemberRD->isLambda()) 4449 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4450 4451 // and all member classes shall also satisfy these requirements 4452 // (recursively). 4453 if (MemberRD->isThisDeclarationADefinition()) { 4454 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4455 return Kind; 4456 } 4457 } 4458 4459 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4460 } 4461 4462 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4463 TypedefNameDecl *NewTD) { 4464 if (TagFromDeclSpec->isInvalidDecl()) 4465 return; 4466 4467 // Do nothing if the tag already has a name for linkage purposes. 4468 if (TagFromDeclSpec->hasNameForLinkage()) 4469 return; 4470 4471 // A well-formed anonymous tag must always be a TUK_Definition. 4472 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4473 4474 // The type must match the tag exactly; no qualifiers allowed. 4475 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4476 Context.getTagDeclType(TagFromDeclSpec))) { 4477 if (getLangOpts().CPlusPlus) 4478 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4479 return; 4480 } 4481 4482 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4483 // An unnamed class with a typedef name for linkage purposes shall [be 4484 // C-like]. 4485 // 4486 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4487 // shouldn't happen, but there are constructs that the language rule doesn't 4488 // disallow for which we can't reasonably avoid computing linkage early. 4489 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4490 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4491 : NonCLikeKind(); 4492 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4493 if (NonCLike || ChangesLinkage) { 4494 if (NonCLike.Kind == NonCLikeKind::Invalid) 4495 return; 4496 4497 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4498 if (ChangesLinkage) { 4499 // If the linkage changes, we can't accept this as an extension. 4500 if (NonCLike.Kind == NonCLikeKind::None) 4501 DiagID = diag::err_typedef_changes_linkage; 4502 else 4503 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4504 } 4505 4506 SourceLocation FixitLoc = 4507 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4508 llvm::SmallString<40> TextToInsert; 4509 TextToInsert += ' '; 4510 TextToInsert += NewTD->getIdentifier()->getName(); 4511 4512 Diag(FixitLoc, DiagID) 4513 << isa<TypeAliasDecl>(NewTD) 4514 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4515 if (NonCLike.Kind != NonCLikeKind::None) { 4516 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4517 << NonCLike.Kind - 1 << NonCLike.Range; 4518 } 4519 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4520 << NewTD << isa<TypeAliasDecl>(NewTD); 4521 4522 if (ChangesLinkage) 4523 return; 4524 } 4525 4526 // Otherwise, set this as the anon-decl typedef for the tag. 4527 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4528 } 4529 4530 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4531 switch (T) { 4532 case DeclSpec::TST_class: 4533 return 0; 4534 case DeclSpec::TST_struct: 4535 return 1; 4536 case DeclSpec::TST_interface: 4537 return 2; 4538 case DeclSpec::TST_union: 4539 return 3; 4540 case DeclSpec::TST_enum: 4541 return 4; 4542 default: 4543 llvm_unreachable("unexpected type specifier"); 4544 } 4545 } 4546 4547 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4548 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4549 /// parameters to cope with template friend declarations. 4550 Decl * 4551 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4552 MultiTemplateParamsArg TemplateParams, 4553 bool IsExplicitInstantiation, 4554 RecordDecl *&AnonRecord) { 4555 Decl *TagD = nullptr; 4556 TagDecl *Tag = nullptr; 4557 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4558 DS.getTypeSpecType() == DeclSpec::TST_struct || 4559 DS.getTypeSpecType() == DeclSpec::TST_interface || 4560 DS.getTypeSpecType() == DeclSpec::TST_union || 4561 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4562 TagD = DS.getRepAsDecl(); 4563 4564 if (!TagD) // We probably had an error 4565 return nullptr; 4566 4567 // Note that the above type specs guarantee that the 4568 // type rep is a Decl, whereas in many of the others 4569 // it's a Type. 4570 if (isa<TagDecl>(TagD)) 4571 Tag = cast<TagDecl>(TagD); 4572 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4573 Tag = CTD->getTemplatedDecl(); 4574 } 4575 4576 if (Tag) { 4577 handleTagNumbering(Tag, S); 4578 Tag->setFreeStanding(); 4579 if (Tag->isInvalidDecl()) 4580 return Tag; 4581 } 4582 4583 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4584 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4585 // or incomplete types shall not be restrict-qualified." 4586 if (TypeQuals & DeclSpec::TQ_restrict) 4587 Diag(DS.getRestrictSpecLoc(), 4588 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4589 << DS.getSourceRange(); 4590 } 4591 4592 if (DS.isInlineSpecified()) 4593 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4594 << getLangOpts().CPlusPlus17; 4595 4596 if (DS.hasConstexprSpecifier()) { 4597 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4598 // and definitions of functions and variables. 4599 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4600 // the declaration of a function or function template 4601 if (Tag) 4602 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4603 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4604 << static_cast<int>(DS.getConstexprSpecifier()); 4605 else 4606 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4607 << static_cast<int>(DS.getConstexprSpecifier()); 4608 // Don't emit warnings after this error. 4609 return TagD; 4610 } 4611 4612 DiagnoseFunctionSpecifiers(DS); 4613 4614 if (DS.isFriendSpecified()) { 4615 // If we're dealing with a decl but not a TagDecl, assume that 4616 // whatever routines created it handled the friendship aspect. 4617 if (TagD && !Tag) 4618 return nullptr; 4619 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4620 } 4621 4622 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4623 bool IsExplicitSpecialization = 4624 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4625 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4626 !IsExplicitInstantiation && !IsExplicitSpecialization && 4627 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4628 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4629 // nested-name-specifier unless it is an explicit instantiation 4630 // or an explicit specialization. 4631 // 4632 // FIXME: We allow class template partial specializations here too, per the 4633 // obvious intent of DR1819. 4634 // 4635 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4636 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4637 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4638 return nullptr; 4639 } 4640 4641 // Track whether this decl-specifier declares anything. 4642 bool DeclaresAnything = true; 4643 4644 // Handle anonymous struct definitions. 4645 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4646 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4647 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4648 if (getLangOpts().CPlusPlus || 4649 Record->getDeclContext()->isRecord()) { 4650 // If CurContext is a DeclContext that can contain statements, 4651 // RecursiveASTVisitor won't visit the decls that 4652 // BuildAnonymousStructOrUnion() will put into CurContext. 4653 // Also store them here so that they can be part of the 4654 // DeclStmt that gets created in this case. 4655 // FIXME: Also return the IndirectFieldDecls created by 4656 // BuildAnonymousStructOr union, for the same reason? 4657 if (CurContext->isFunctionOrMethod()) 4658 AnonRecord = Record; 4659 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4660 Context.getPrintingPolicy()); 4661 } 4662 4663 DeclaresAnything = false; 4664 } 4665 } 4666 4667 // C11 6.7.2.1p2: 4668 // A struct-declaration that does not declare an anonymous structure or 4669 // anonymous union shall contain a struct-declarator-list. 4670 // 4671 // This rule also existed in C89 and C99; the grammar for struct-declaration 4672 // did not permit a struct-declaration without a struct-declarator-list. 4673 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4674 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4675 // Check for Microsoft C extension: anonymous struct/union member. 4676 // Handle 2 kinds of anonymous struct/union: 4677 // struct STRUCT; 4678 // union UNION; 4679 // and 4680 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4681 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4682 if ((Tag && Tag->getDeclName()) || 4683 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4684 RecordDecl *Record = nullptr; 4685 if (Tag) 4686 Record = dyn_cast<RecordDecl>(Tag); 4687 else if (const RecordType *RT = 4688 DS.getRepAsType().get()->getAsStructureType()) 4689 Record = RT->getDecl(); 4690 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4691 Record = UT->getDecl(); 4692 4693 if (Record && getLangOpts().MicrosoftExt) { 4694 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4695 << Record->isUnion() << DS.getSourceRange(); 4696 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4697 } 4698 4699 DeclaresAnything = false; 4700 } 4701 } 4702 4703 // Skip all the checks below if we have a type error. 4704 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4705 (TagD && TagD->isInvalidDecl())) 4706 return TagD; 4707 4708 if (getLangOpts().CPlusPlus && 4709 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4710 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4711 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4712 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4713 DeclaresAnything = false; 4714 4715 if (!DS.isMissingDeclaratorOk()) { 4716 // Customize diagnostic for a typedef missing a name. 4717 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4718 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4719 << DS.getSourceRange(); 4720 else 4721 DeclaresAnything = false; 4722 } 4723 4724 if (DS.isModulePrivateSpecified() && 4725 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4726 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4727 << Tag->getTagKind() 4728 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4729 4730 ActOnDocumentableDecl(TagD); 4731 4732 // C 6.7/2: 4733 // A declaration [...] shall declare at least a declarator [...], a tag, 4734 // or the members of an enumeration. 4735 // C++ [dcl.dcl]p3: 4736 // [If there are no declarators], and except for the declaration of an 4737 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4738 // names into the program, or shall redeclare a name introduced by a 4739 // previous declaration. 4740 if (!DeclaresAnything) { 4741 // In C, we allow this as a (popular) extension / bug. Don't bother 4742 // producing further diagnostics for redundant qualifiers after this. 4743 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 4744 ? diag::err_no_declarators 4745 : diag::ext_no_declarators) 4746 << DS.getSourceRange(); 4747 return TagD; 4748 } 4749 4750 // C++ [dcl.stc]p1: 4751 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4752 // init-declarator-list of the declaration shall not be empty. 4753 // C++ [dcl.fct.spec]p1: 4754 // If a cv-qualifier appears in a decl-specifier-seq, the 4755 // init-declarator-list of the declaration shall not be empty. 4756 // 4757 // Spurious qualifiers here appear to be valid in C. 4758 unsigned DiagID = diag::warn_standalone_specifier; 4759 if (getLangOpts().CPlusPlus) 4760 DiagID = diag::ext_standalone_specifier; 4761 4762 // Note that a linkage-specification sets a storage class, but 4763 // 'extern "C" struct foo;' is actually valid and not theoretically 4764 // useless. 4765 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4766 if (SCS == DeclSpec::SCS_mutable) 4767 // Since mutable is not a viable storage class specifier in C, there is 4768 // no reason to treat it as an extension. Instead, diagnose as an error. 4769 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4770 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4771 Diag(DS.getStorageClassSpecLoc(), DiagID) 4772 << DeclSpec::getSpecifierName(SCS); 4773 } 4774 4775 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4776 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4777 << DeclSpec::getSpecifierName(TSCS); 4778 if (DS.getTypeQualifiers()) { 4779 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4780 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4781 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4782 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4783 // Restrict is covered above. 4784 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4785 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4786 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4787 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4788 } 4789 4790 // Warn about ignored type attributes, for example: 4791 // __attribute__((aligned)) struct A; 4792 // Attributes should be placed after tag to apply to type declaration. 4793 if (!DS.getAttributes().empty()) { 4794 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4795 if (TypeSpecType == DeclSpec::TST_class || 4796 TypeSpecType == DeclSpec::TST_struct || 4797 TypeSpecType == DeclSpec::TST_interface || 4798 TypeSpecType == DeclSpec::TST_union || 4799 TypeSpecType == DeclSpec::TST_enum) { 4800 for (const ParsedAttr &AL : DS.getAttributes()) 4801 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4802 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4803 } 4804 } 4805 4806 return TagD; 4807 } 4808 4809 /// We are trying to inject an anonymous member into the given scope; 4810 /// check if there's an existing declaration that can't be overloaded. 4811 /// 4812 /// \return true if this is a forbidden redeclaration 4813 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4814 Scope *S, 4815 DeclContext *Owner, 4816 DeclarationName Name, 4817 SourceLocation NameLoc, 4818 bool IsUnion) { 4819 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4820 Sema::ForVisibleRedeclaration); 4821 if (!SemaRef.LookupName(R, S)) return false; 4822 4823 // Pick a representative declaration. 4824 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4825 assert(PrevDecl && "Expected a non-null Decl"); 4826 4827 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4828 return false; 4829 4830 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4831 << IsUnion << Name; 4832 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4833 4834 return true; 4835 } 4836 4837 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4838 /// anonymous struct or union AnonRecord into the owning context Owner 4839 /// and scope S. This routine will be invoked just after we realize 4840 /// that an unnamed union or struct is actually an anonymous union or 4841 /// struct, e.g., 4842 /// 4843 /// @code 4844 /// union { 4845 /// int i; 4846 /// float f; 4847 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4848 /// // f into the surrounding scope.x 4849 /// @endcode 4850 /// 4851 /// This routine is recursive, injecting the names of nested anonymous 4852 /// structs/unions into the owning context and scope as well. 4853 static bool 4854 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4855 RecordDecl *AnonRecord, AccessSpecifier AS, 4856 SmallVectorImpl<NamedDecl *> &Chaining) { 4857 bool Invalid = false; 4858 4859 // Look every FieldDecl and IndirectFieldDecl with a name. 4860 for (auto *D : AnonRecord->decls()) { 4861 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4862 cast<NamedDecl>(D)->getDeclName()) { 4863 ValueDecl *VD = cast<ValueDecl>(D); 4864 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4865 VD->getLocation(), 4866 AnonRecord->isUnion())) { 4867 // C++ [class.union]p2: 4868 // The names of the members of an anonymous union shall be 4869 // distinct from the names of any other entity in the 4870 // scope in which the anonymous union is declared. 4871 Invalid = true; 4872 } else { 4873 // C++ [class.union]p2: 4874 // For the purpose of name lookup, after the anonymous union 4875 // definition, the members of the anonymous union are 4876 // considered to have been defined in the scope in which the 4877 // anonymous union is declared. 4878 unsigned OldChainingSize = Chaining.size(); 4879 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4880 Chaining.append(IF->chain_begin(), IF->chain_end()); 4881 else 4882 Chaining.push_back(VD); 4883 4884 assert(Chaining.size() >= 2); 4885 NamedDecl **NamedChain = 4886 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4887 for (unsigned i = 0; i < Chaining.size(); i++) 4888 NamedChain[i] = Chaining[i]; 4889 4890 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4891 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4892 VD->getType(), {NamedChain, Chaining.size()}); 4893 4894 for (const auto *Attr : VD->attrs()) 4895 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4896 4897 IndirectField->setAccess(AS); 4898 IndirectField->setImplicit(); 4899 SemaRef.PushOnScopeChains(IndirectField, S); 4900 4901 // That includes picking up the appropriate access specifier. 4902 if (AS != AS_none) IndirectField->setAccess(AS); 4903 4904 Chaining.resize(OldChainingSize); 4905 } 4906 } 4907 } 4908 4909 return Invalid; 4910 } 4911 4912 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4913 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4914 /// illegal input values are mapped to SC_None. 4915 static StorageClass 4916 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4917 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4918 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4919 "Parser allowed 'typedef' as storage class VarDecl."); 4920 switch (StorageClassSpec) { 4921 case DeclSpec::SCS_unspecified: return SC_None; 4922 case DeclSpec::SCS_extern: 4923 if (DS.isExternInLinkageSpec()) 4924 return SC_None; 4925 return SC_Extern; 4926 case DeclSpec::SCS_static: return SC_Static; 4927 case DeclSpec::SCS_auto: return SC_Auto; 4928 case DeclSpec::SCS_register: return SC_Register; 4929 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4930 // Illegal SCSs map to None: error reporting is up to the caller. 4931 case DeclSpec::SCS_mutable: // Fall through. 4932 case DeclSpec::SCS_typedef: return SC_None; 4933 } 4934 llvm_unreachable("unknown storage class specifier"); 4935 } 4936 4937 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4938 assert(Record->hasInClassInitializer()); 4939 4940 for (const auto *I : Record->decls()) { 4941 const auto *FD = dyn_cast<FieldDecl>(I); 4942 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4943 FD = IFD->getAnonField(); 4944 if (FD && FD->hasInClassInitializer()) 4945 return FD->getLocation(); 4946 } 4947 4948 llvm_unreachable("couldn't find in-class initializer"); 4949 } 4950 4951 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4952 SourceLocation DefaultInitLoc) { 4953 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4954 return; 4955 4956 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4957 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4958 } 4959 4960 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4961 CXXRecordDecl *AnonUnion) { 4962 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4963 return; 4964 4965 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4966 } 4967 4968 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4969 /// anonymous structure or union. Anonymous unions are a C++ feature 4970 /// (C++ [class.union]) and a C11 feature; anonymous structures 4971 /// are a C11 feature and GNU C++ extension. 4972 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4973 AccessSpecifier AS, 4974 RecordDecl *Record, 4975 const PrintingPolicy &Policy) { 4976 DeclContext *Owner = Record->getDeclContext(); 4977 4978 // Diagnose whether this anonymous struct/union is an extension. 4979 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4980 Diag(Record->getLocation(), diag::ext_anonymous_union); 4981 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4982 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4983 else if (!Record->isUnion() && !getLangOpts().C11) 4984 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4985 4986 // C and C++ require different kinds of checks for anonymous 4987 // structs/unions. 4988 bool Invalid = false; 4989 if (getLangOpts().CPlusPlus) { 4990 const char *PrevSpec = nullptr; 4991 if (Record->isUnion()) { 4992 // C++ [class.union]p6: 4993 // C++17 [class.union.anon]p2: 4994 // Anonymous unions declared in a named namespace or in the 4995 // global namespace shall be declared static. 4996 unsigned DiagID; 4997 DeclContext *OwnerScope = Owner->getRedeclContext(); 4998 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4999 (OwnerScope->isTranslationUnit() || 5000 (OwnerScope->isNamespace() && 5001 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5002 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5003 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5004 5005 // Recover by adding 'static'. 5006 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5007 PrevSpec, DiagID, Policy); 5008 } 5009 // C++ [class.union]p6: 5010 // A storage class is not allowed in a declaration of an 5011 // anonymous union in a class scope. 5012 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5013 isa<RecordDecl>(Owner)) { 5014 Diag(DS.getStorageClassSpecLoc(), 5015 diag::err_anonymous_union_with_storage_spec) 5016 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5017 5018 // Recover by removing the storage specifier. 5019 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5020 SourceLocation(), 5021 PrevSpec, DiagID, Context.getPrintingPolicy()); 5022 } 5023 } 5024 5025 // Ignore const/volatile/restrict qualifiers. 5026 if (DS.getTypeQualifiers()) { 5027 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5028 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5029 << Record->isUnion() << "const" 5030 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5031 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5032 Diag(DS.getVolatileSpecLoc(), 5033 diag::ext_anonymous_struct_union_qualified) 5034 << Record->isUnion() << "volatile" 5035 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5036 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5037 Diag(DS.getRestrictSpecLoc(), 5038 diag::ext_anonymous_struct_union_qualified) 5039 << Record->isUnion() << "restrict" 5040 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5041 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5042 Diag(DS.getAtomicSpecLoc(), 5043 diag::ext_anonymous_struct_union_qualified) 5044 << Record->isUnion() << "_Atomic" 5045 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5046 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5047 Diag(DS.getUnalignedSpecLoc(), 5048 diag::ext_anonymous_struct_union_qualified) 5049 << Record->isUnion() << "__unaligned" 5050 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5051 5052 DS.ClearTypeQualifiers(); 5053 } 5054 5055 // C++ [class.union]p2: 5056 // The member-specification of an anonymous union shall only 5057 // define non-static data members. [Note: nested types and 5058 // functions cannot be declared within an anonymous union. ] 5059 for (auto *Mem : Record->decls()) { 5060 // Ignore invalid declarations; we already diagnosed them. 5061 if (Mem->isInvalidDecl()) 5062 continue; 5063 5064 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5065 // C++ [class.union]p3: 5066 // An anonymous union shall not have private or protected 5067 // members (clause 11). 5068 assert(FD->getAccess() != AS_none); 5069 if (FD->getAccess() != AS_public) { 5070 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5071 << Record->isUnion() << (FD->getAccess() == AS_protected); 5072 Invalid = true; 5073 } 5074 5075 // C++ [class.union]p1 5076 // An object of a class with a non-trivial constructor, a non-trivial 5077 // copy constructor, a non-trivial destructor, or a non-trivial copy 5078 // assignment operator cannot be a member of a union, nor can an 5079 // array of such objects. 5080 if (CheckNontrivialField(FD)) 5081 Invalid = true; 5082 } else if (Mem->isImplicit()) { 5083 // Any implicit members are fine. 5084 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5085 // This is a type that showed up in an 5086 // elaborated-type-specifier inside the anonymous struct or 5087 // union, but which actually declares a type outside of the 5088 // anonymous struct or union. It's okay. 5089 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5090 if (!MemRecord->isAnonymousStructOrUnion() && 5091 MemRecord->getDeclName()) { 5092 // Visual C++ allows type definition in anonymous struct or union. 5093 if (getLangOpts().MicrosoftExt) 5094 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5095 << Record->isUnion(); 5096 else { 5097 // This is a nested type declaration. 5098 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5099 << Record->isUnion(); 5100 Invalid = true; 5101 } 5102 } else { 5103 // This is an anonymous type definition within another anonymous type. 5104 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5105 // not part of standard C++. 5106 Diag(MemRecord->getLocation(), 5107 diag::ext_anonymous_record_with_anonymous_type) 5108 << Record->isUnion(); 5109 } 5110 } else if (isa<AccessSpecDecl>(Mem)) { 5111 // Any access specifier is fine. 5112 } else if (isa<StaticAssertDecl>(Mem)) { 5113 // In C++1z, static_assert declarations are also fine. 5114 } else { 5115 // We have something that isn't a non-static data 5116 // member. Complain about it. 5117 unsigned DK = diag::err_anonymous_record_bad_member; 5118 if (isa<TypeDecl>(Mem)) 5119 DK = diag::err_anonymous_record_with_type; 5120 else if (isa<FunctionDecl>(Mem)) 5121 DK = diag::err_anonymous_record_with_function; 5122 else if (isa<VarDecl>(Mem)) 5123 DK = diag::err_anonymous_record_with_static; 5124 5125 // Visual C++ allows type definition in anonymous struct or union. 5126 if (getLangOpts().MicrosoftExt && 5127 DK == diag::err_anonymous_record_with_type) 5128 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5129 << Record->isUnion(); 5130 else { 5131 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5132 Invalid = true; 5133 } 5134 } 5135 } 5136 5137 // C++11 [class.union]p8 (DR1460): 5138 // At most one variant member of a union may have a 5139 // brace-or-equal-initializer. 5140 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5141 Owner->isRecord()) 5142 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5143 cast<CXXRecordDecl>(Record)); 5144 } 5145 5146 if (!Record->isUnion() && !Owner->isRecord()) { 5147 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5148 << getLangOpts().CPlusPlus; 5149 Invalid = true; 5150 } 5151 5152 // C++ [dcl.dcl]p3: 5153 // [If there are no declarators], and except for the declaration of an 5154 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5155 // names into the program 5156 // C++ [class.mem]p2: 5157 // each such member-declaration shall either declare at least one member 5158 // name of the class or declare at least one unnamed bit-field 5159 // 5160 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5161 if (getLangOpts().CPlusPlus && Record->field_empty()) 5162 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5163 5164 // Mock up a declarator. 5165 Declarator Dc(DS, DeclaratorContext::Member); 5166 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5167 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5168 5169 // Create a declaration for this anonymous struct/union. 5170 NamedDecl *Anon = nullptr; 5171 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5172 Anon = FieldDecl::Create( 5173 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5174 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5175 /*BitWidth=*/nullptr, /*Mutable=*/false, 5176 /*InitStyle=*/ICIS_NoInit); 5177 Anon->setAccess(AS); 5178 ProcessDeclAttributes(S, Anon, Dc); 5179 5180 if (getLangOpts().CPlusPlus) 5181 FieldCollector->Add(cast<FieldDecl>(Anon)); 5182 } else { 5183 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5184 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5185 if (SCSpec == DeclSpec::SCS_mutable) { 5186 // mutable can only appear on non-static class members, so it's always 5187 // an error here 5188 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5189 Invalid = true; 5190 SC = SC_None; 5191 } 5192 5193 assert(DS.getAttributes().empty() && "No attribute expected"); 5194 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5195 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5196 Context.getTypeDeclType(Record), TInfo, SC); 5197 5198 // Default-initialize the implicit variable. This initialization will be 5199 // trivial in almost all cases, except if a union member has an in-class 5200 // initializer: 5201 // union { int n = 0; }; 5202 ActOnUninitializedDecl(Anon); 5203 } 5204 Anon->setImplicit(); 5205 5206 // Mark this as an anonymous struct/union type. 5207 Record->setAnonymousStructOrUnion(true); 5208 5209 // Add the anonymous struct/union object to the current 5210 // context. We'll be referencing this object when we refer to one of 5211 // its members. 5212 Owner->addDecl(Anon); 5213 5214 // Inject the members of the anonymous struct/union into the owning 5215 // context and into the identifier resolver chain for name lookup 5216 // purposes. 5217 SmallVector<NamedDecl*, 2> Chain; 5218 Chain.push_back(Anon); 5219 5220 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5221 Invalid = true; 5222 5223 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5224 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5225 MangleNumberingContext *MCtx; 5226 Decl *ManglingContextDecl; 5227 std::tie(MCtx, ManglingContextDecl) = 5228 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5229 if (MCtx) { 5230 Context.setManglingNumber( 5231 NewVD, MCtx->getManglingNumber( 5232 NewVD, getMSManglingNumber(getLangOpts(), S))); 5233 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5234 } 5235 } 5236 } 5237 5238 if (Invalid) 5239 Anon->setInvalidDecl(); 5240 5241 return Anon; 5242 } 5243 5244 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5245 /// Microsoft C anonymous structure. 5246 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5247 /// Example: 5248 /// 5249 /// struct A { int a; }; 5250 /// struct B { struct A; int b; }; 5251 /// 5252 /// void foo() { 5253 /// B var; 5254 /// var.a = 3; 5255 /// } 5256 /// 5257 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5258 RecordDecl *Record) { 5259 assert(Record && "expected a record!"); 5260 5261 // Mock up a declarator. 5262 Declarator Dc(DS, DeclaratorContext::TypeName); 5263 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5264 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5265 5266 auto *ParentDecl = cast<RecordDecl>(CurContext); 5267 QualType RecTy = Context.getTypeDeclType(Record); 5268 5269 // Create a declaration for this anonymous struct. 5270 NamedDecl *Anon = 5271 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5272 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5273 /*BitWidth=*/nullptr, /*Mutable=*/false, 5274 /*InitStyle=*/ICIS_NoInit); 5275 Anon->setImplicit(); 5276 5277 // Add the anonymous struct object to the current context. 5278 CurContext->addDecl(Anon); 5279 5280 // Inject the members of the anonymous struct into the current 5281 // context and into the identifier resolver chain for name lookup 5282 // purposes. 5283 SmallVector<NamedDecl*, 2> Chain; 5284 Chain.push_back(Anon); 5285 5286 RecordDecl *RecordDef = Record->getDefinition(); 5287 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5288 diag::err_field_incomplete_or_sizeless) || 5289 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5290 AS_none, Chain)) { 5291 Anon->setInvalidDecl(); 5292 ParentDecl->setInvalidDecl(); 5293 } 5294 5295 return Anon; 5296 } 5297 5298 /// GetNameForDeclarator - Determine the full declaration name for the 5299 /// given Declarator. 5300 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5301 return GetNameFromUnqualifiedId(D.getName()); 5302 } 5303 5304 /// Retrieves the declaration name from a parsed unqualified-id. 5305 DeclarationNameInfo 5306 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5307 DeclarationNameInfo NameInfo; 5308 NameInfo.setLoc(Name.StartLocation); 5309 5310 switch (Name.getKind()) { 5311 5312 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5313 case UnqualifiedIdKind::IK_Identifier: 5314 NameInfo.setName(Name.Identifier); 5315 return NameInfo; 5316 5317 case UnqualifiedIdKind::IK_DeductionGuideName: { 5318 // C++ [temp.deduct.guide]p3: 5319 // The simple-template-id shall name a class template specialization. 5320 // The template-name shall be the same identifier as the template-name 5321 // of the simple-template-id. 5322 // These together intend to imply that the template-name shall name a 5323 // class template. 5324 // FIXME: template<typename T> struct X {}; 5325 // template<typename T> using Y = X<T>; 5326 // Y(int) -> Y<int>; 5327 // satisfies these rules but does not name a class template. 5328 TemplateName TN = Name.TemplateName.get().get(); 5329 auto *Template = TN.getAsTemplateDecl(); 5330 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5331 Diag(Name.StartLocation, 5332 diag::err_deduction_guide_name_not_class_template) 5333 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5334 if (Template) 5335 Diag(Template->getLocation(), diag::note_template_decl_here); 5336 return DeclarationNameInfo(); 5337 } 5338 5339 NameInfo.setName( 5340 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5341 return NameInfo; 5342 } 5343 5344 case UnqualifiedIdKind::IK_OperatorFunctionId: 5345 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5346 Name.OperatorFunctionId.Operator)); 5347 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 5348 = Name.OperatorFunctionId.SymbolLocations[0]; 5349 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5350 = Name.EndLocation.getRawEncoding(); 5351 return NameInfo; 5352 5353 case UnqualifiedIdKind::IK_LiteralOperatorId: 5354 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5355 Name.Identifier)); 5356 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5357 return NameInfo; 5358 5359 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5360 TypeSourceInfo *TInfo; 5361 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5362 if (Ty.isNull()) 5363 return DeclarationNameInfo(); 5364 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5365 Context.getCanonicalType(Ty))); 5366 NameInfo.setNamedTypeInfo(TInfo); 5367 return NameInfo; 5368 } 5369 5370 case UnqualifiedIdKind::IK_ConstructorName: { 5371 TypeSourceInfo *TInfo; 5372 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5373 if (Ty.isNull()) 5374 return DeclarationNameInfo(); 5375 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5376 Context.getCanonicalType(Ty))); 5377 NameInfo.setNamedTypeInfo(TInfo); 5378 return NameInfo; 5379 } 5380 5381 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5382 // In well-formed code, we can only have a constructor 5383 // template-id that refers to the current context, so go there 5384 // to find the actual type being constructed. 5385 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5386 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5387 return DeclarationNameInfo(); 5388 5389 // Determine the type of the class being constructed. 5390 QualType CurClassType = Context.getTypeDeclType(CurClass); 5391 5392 // FIXME: Check two things: that the template-id names the same type as 5393 // CurClassType, and that the template-id does not occur when the name 5394 // was qualified. 5395 5396 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5397 Context.getCanonicalType(CurClassType))); 5398 // FIXME: should we retrieve TypeSourceInfo? 5399 NameInfo.setNamedTypeInfo(nullptr); 5400 return NameInfo; 5401 } 5402 5403 case UnqualifiedIdKind::IK_DestructorName: { 5404 TypeSourceInfo *TInfo; 5405 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5406 if (Ty.isNull()) 5407 return DeclarationNameInfo(); 5408 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5409 Context.getCanonicalType(Ty))); 5410 NameInfo.setNamedTypeInfo(TInfo); 5411 return NameInfo; 5412 } 5413 5414 case UnqualifiedIdKind::IK_TemplateId: { 5415 TemplateName TName = Name.TemplateId->Template.get(); 5416 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5417 return Context.getNameForTemplate(TName, TNameLoc); 5418 } 5419 5420 } // switch (Name.getKind()) 5421 5422 llvm_unreachable("Unknown name kind"); 5423 } 5424 5425 static QualType getCoreType(QualType Ty) { 5426 do { 5427 if (Ty->isPointerType() || Ty->isReferenceType()) 5428 Ty = Ty->getPointeeType(); 5429 else if (Ty->isArrayType()) 5430 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5431 else 5432 return Ty.withoutLocalFastQualifiers(); 5433 } while (true); 5434 } 5435 5436 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5437 /// and Definition have "nearly" matching parameters. This heuristic is 5438 /// used to improve diagnostics in the case where an out-of-line function 5439 /// definition doesn't match any declaration within the class or namespace. 5440 /// Also sets Params to the list of indices to the parameters that differ 5441 /// between the declaration and the definition. If hasSimilarParameters 5442 /// returns true and Params is empty, then all of the parameters match. 5443 static bool hasSimilarParameters(ASTContext &Context, 5444 FunctionDecl *Declaration, 5445 FunctionDecl *Definition, 5446 SmallVectorImpl<unsigned> &Params) { 5447 Params.clear(); 5448 if (Declaration->param_size() != Definition->param_size()) 5449 return false; 5450 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5451 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5452 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5453 5454 // The parameter types are identical 5455 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5456 continue; 5457 5458 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5459 QualType DefParamBaseTy = getCoreType(DefParamTy); 5460 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5461 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5462 5463 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5464 (DeclTyName && DeclTyName == DefTyName)) 5465 Params.push_back(Idx); 5466 else // The two parameters aren't even close 5467 return false; 5468 } 5469 5470 return true; 5471 } 5472 5473 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5474 /// declarator needs to be rebuilt in the current instantiation. 5475 /// Any bits of declarator which appear before the name are valid for 5476 /// consideration here. That's specifically the type in the decl spec 5477 /// and the base type in any member-pointer chunks. 5478 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5479 DeclarationName Name) { 5480 // The types we specifically need to rebuild are: 5481 // - typenames, typeofs, and decltypes 5482 // - types which will become injected class names 5483 // Of course, we also need to rebuild any type referencing such a 5484 // type. It's safest to just say "dependent", but we call out a 5485 // few cases here. 5486 5487 DeclSpec &DS = D.getMutableDeclSpec(); 5488 switch (DS.getTypeSpecType()) { 5489 case DeclSpec::TST_typename: 5490 case DeclSpec::TST_typeofType: 5491 case DeclSpec::TST_underlyingType: 5492 case DeclSpec::TST_atomic: { 5493 // Grab the type from the parser. 5494 TypeSourceInfo *TSI = nullptr; 5495 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5496 if (T.isNull() || !T->isInstantiationDependentType()) break; 5497 5498 // Make sure there's a type source info. This isn't really much 5499 // of a waste; most dependent types should have type source info 5500 // attached already. 5501 if (!TSI) 5502 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5503 5504 // Rebuild the type in the current instantiation. 5505 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5506 if (!TSI) return true; 5507 5508 // Store the new type back in the decl spec. 5509 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5510 DS.UpdateTypeRep(LocType); 5511 break; 5512 } 5513 5514 case DeclSpec::TST_decltype: 5515 case DeclSpec::TST_typeofExpr: { 5516 Expr *E = DS.getRepAsExpr(); 5517 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5518 if (Result.isInvalid()) return true; 5519 DS.UpdateExprRep(Result.get()); 5520 break; 5521 } 5522 5523 default: 5524 // Nothing to do for these decl specs. 5525 break; 5526 } 5527 5528 // It doesn't matter what order we do this in. 5529 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5530 DeclaratorChunk &Chunk = D.getTypeObject(I); 5531 5532 // The only type information in the declarator which can come 5533 // before the declaration name is the base type of a member 5534 // pointer. 5535 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5536 continue; 5537 5538 // Rebuild the scope specifier in-place. 5539 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5540 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5541 return true; 5542 } 5543 5544 return false; 5545 } 5546 5547 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5548 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 5549 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5550 5551 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5552 Dcl && Dcl->getDeclContext()->isFileContext()) 5553 Dcl->setTopLevelDeclInObjCContainer(); 5554 5555 if (getLangOpts().OpenCL) 5556 setCurrentOpenCLExtensionForDecl(Dcl); 5557 5558 return Dcl; 5559 } 5560 5561 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5562 /// If T is the name of a class, then each of the following shall have a 5563 /// name different from T: 5564 /// - every static data member of class T; 5565 /// - every member function of class T 5566 /// - every member of class T that is itself a type; 5567 /// \returns true if the declaration name violates these rules. 5568 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5569 DeclarationNameInfo NameInfo) { 5570 DeclarationName Name = NameInfo.getName(); 5571 5572 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5573 while (Record && Record->isAnonymousStructOrUnion()) 5574 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5575 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5576 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5577 return true; 5578 } 5579 5580 return false; 5581 } 5582 5583 /// Diagnose a declaration whose declarator-id has the given 5584 /// nested-name-specifier. 5585 /// 5586 /// \param SS The nested-name-specifier of the declarator-id. 5587 /// 5588 /// \param DC The declaration context to which the nested-name-specifier 5589 /// resolves. 5590 /// 5591 /// \param Name The name of the entity being declared. 5592 /// 5593 /// \param Loc The location of the name of the entity being declared. 5594 /// 5595 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5596 /// we're declaring an explicit / partial specialization / instantiation. 5597 /// 5598 /// \returns true if we cannot safely recover from this error, false otherwise. 5599 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5600 DeclarationName Name, 5601 SourceLocation Loc, bool IsTemplateId) { 5602 DeclContext *Cur = CurContext; 5603 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5604 Cur = Cur->getParent(); 5605 5606 // If the user provided a superfluous scope specifier that refers back to the 5607 // class in which the entity is already declared, diagnose and ignore it. 5608 // 5609 // class X { 5610 // void X::f(); 5611 // }; 5612 // 5613 // Note, it was once ill-formed to give redundant qualification in all 5614 // contexts, but that rule was removed by DR482. 5615 if (Cur->Equals(DC)) { 5616 if (Cur->isRecord()) { 5617 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5618 : diag::err_member_extra_qualification) 5619 << Name << FixItHint::CreateRemoval(SS.getRange()); 5620 SS.clear(); 5621 } else { 5622 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5623 } 5624 return false; 5625 } 5626 5627 // Check whether the qualifying scope encloses the scope of the original 5628 // declaration. For a template-id, we perform the checks in 5629 // CheckTemplateSpecializationScope. 5630 if (!Cur->Encloses(DC) && !IsTemplateId) { 5631 if (Cur->isRecord()) 5632 Diag(Loc, diag::err_member_qualification) 5633 << Name << SS.getRange(); 5634 else if (isa<TranslationUnitDecl>(DC)) 5635 Diag(Loc, diag::err_invalid_declarator_global_scope) 5636 << Name << SS.getRange(); 5637 else if (isa<FunctionDecl>(Cur)) 5638 Diag(Loc, diag::err_invalid_declarator_in_function) 5639 << Name << SS.getRange(); 5640 else if (isa<BlockDecl>(Cur)) 5641 Diag(Loc, diag::err_invalid_declarator_in_block) 5642 << Name << SS.getRange(); 5643 else 5644 Diag(Loc, diag::err_invalid_declarator_scope) 5645 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5646 5647 return true; 5648 } 5649 5650 if (Cur->isRecord()) { 5651 // Cannot qualify members within a class. 5652 Diag(Loc, diag::err_member_qualification) 5653 << Name << SS.getRange(); 5654 SS.clear(); 5655 5656 // C++ constructors and destructors with incorrect scopes can break 5657 // our AST invariants by having the wrong underlying types. If 5658 // that's the case, then drop this declaration entirely. 5659 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5660 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5661 !Context.hasSameType(Name.getCXXNameType(), 5662 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5663 return true; 5664 5665 return false; 5666 } 5667 5668 // C++11 [dcl.meaning]p1: 5669 // [...] "The nested-name-specifier of the qualified declarator-id shall 5670 // not begin with a decltype-specifer" 5671 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5672 while (SpecLoc.getPrefix()) 5673 SpecLoc = SpecLoc.getPrefix(); 5674 if (dyn_cast_or_null<DecltypeType>( 5675 SpecLoc.getNestedNameSpecifier()->getAsType())) 5676 Diag(Loc, diag::err_decltype_in_declarator) 5677 << SpecLoc.getTypeLoc().getSourceRange(); 5678 5679 return false; 5680 } 5681 5682 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5683 MultiTemplateParamsArg TemplateParamLists) { 5684 // TODO: consider using NameInfo for diagnostic. 5685 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5686 DeclarationName Name = NameInfo.getName(); 5687 5688 // All of these full declarators require an identifier. If it doesn't have 5689 // one, the ParsedFreeStandingDeclSpec action should be used. 5690 if (D.isDecompositionDeclarator()) { 5691 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5692 } else if (!Name) { 5693 if (!D.isInvalidType()) // Reject this if we think it is valid. 5694 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5695 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5696 return nullptr; 5697 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5698 return nullptr; 5699 5700 // The scope passed in may not be a decl scope. Zip up the scope tree until 5701 // we find one that is. 5702 while ((S->getFlags() & Scope::DeclScope) == 0 || 5703 (S->getFlags() & Scope::TemplateParamScope) != 0) 5704 S = S->getParent(); 5705 5706 DeclContext *DC = CurContext; 5707 if (D.getCXXScopeSpec().isInvalid()) 5708 D.setInvalidType(); 5709 else if (D.getCXXScopeSpec().isSet()) { 5710 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5711 UPPC_DeclarationQualifier)) 5712 return nullptr; 5713 5714 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5715 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5716 if (!DC || isa<EnumDecl>(DC)) { 5717 // If we could not compute the declaration context, it's because the 5718 // declaration context is dependent but does not refer to a class, 5719 // class template, or class template partial specialization. Complain 5720 // and return early, to avoid the coming semantic disaster. 5721 Diag(D.getIdentifierLoc(), 5722 diag::err_template_qualified_declarator_no_match) 5723 << D.getCXXScopeSpec().getScopeRep() 5724 << D.getCXXScopeSpec().getRange(); 5725 return nullptr; 5726 } 5727 bool IsDependentContext = DC->isDependentContext(); 5728 5729 if (!IsDependentContext && 5730 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5731 return nullptr; 5732 5733 // If a class is incomplete, do not parse entities inside it. 5734 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5735 Diag(D.getIdentifierLoc(), 5736 diag::err_member_def_undefined_record) 5737 << Name << DC << D.getCXXScopeSpec().getRange(); 5738 return nullptr; 5739 } 5740 if (!D.getDeclSpec().isFriendSpecified()) { 5741 if (diagnoseQualifiedDeclaration( 5742 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5743 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5744 if (DC->isRecord()) 5745 return nullptr; 5746 5747 D.setInvalidType(); 5748 } 5749 } 5750 5751 // Check whether we need to rebuild the type of the given 5752 // declaration in the current instantiation. 5753 if (EnteringContext && IsDependentContext && 5754 TemplateParamLists.size() != 0) { 5755 ContextRAII SavedContext(*this, DC); 5756 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5757 D.setInvalidType(); 5758 } 5759 } 5760 5761 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5762 QualType R = TInfo->getType(); 5763 5764 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5765 UPPC_DeclarationType)) 5766 D.setInvalidType(); 5767 5768 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5769 forRedeclarationInCurContext()); 5770 5771 // See if this is a redefinition of a variable in the same scope. 5772 if (!D.getCXXScopeSpec().isSet()) { 5773 bool IsLinkageLookup = false; 5774 bool CreateBuiltins = false; 5775 5776 // If the declaration we're planning to build will be a function 5777 // or object with linkage, then look for another declaration with 5778 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5779 // 5780 // If the declaration we're planning to build will be declared with 5781 // external linkage in the translation unit, create any builtin with 5782 // the same name. 5783 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5784 /* Do nothing*/; 5785 else if (CurContext->isFunctionOrMethod() && 5786 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5787 R->isFunctionType())) { 5788 IsLinkageLookup = true; 5789 CreateBuiltins = 5790 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5791 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5792 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5793 CreateBuiltins = true; 5794 5795 if (IsLinkageLookup) { 5796 Previous.clear(LookupRedeclarationWithLinkage); 5797 Previous.setRedeclarationKind(ForExternalRedeclaration); 5798 } 5799 5800 LookupName(Previous, S, CreateBuiltins); 5801 } else { // Something like "int foo::x;" 5802 LookupQualifiedName(Previous, DC); 5803 5804 // C++ [dcl.meaning]p1: 5805 // When the declarator-id is qualified, the declaration shall refer to a 5806 // previously declared member of the class or namespace to which the 5807 // qualifier refers (or, in the case of a namespace, of an element of the 5808 // inline namespace set of that namespace (7.3.1)) or to a specialization 5809 // thereof; [...] 5810 // 5811 // Note that we already checked the context above, and that we do not have 5812 // enough information to make sure that Previous contains the declaration 5813 // we want to match. For example, given: 5814 // 5815 // class X { 5816 // void f(); 5817 // void f(float); 5818 // }; 5819 // 5820 // void X::f(int) { } // ill-formed 5821 // 5822 // In this case, Previous will point to the overload set 5823 // containing the two f's declared in X, but neither of them 5824 // matches. 5825 5826 // C++ [dcl.meaning]p1: 5827 // [...] the member shall not merely have been introduced by a 5828 // using-declaration in the scope of the class or namespace nominated by 5829 // the nested-name-specifier of the declarator-id. 5830 RemoveUsingDecls(Previous); 5831 } 5832 5833 if (Previous.isSingleResult() && 5834 Previous.getFoundDecl()->isTemplateParameter()) { 5835 // Maybe we will complain about the shadowed template parameter. 5836 if (!D.isInvalidType()) 5837 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5838 Previous.getFoundDecl()); 5839 5840 // Just pretend that we didn't see the previous declaration. 5841 Previous.clear(); 5842 } 5843 5844 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5845 // Forget that the previous declaration is the injected-class-name. 5846 Previous.clear(); 5847 5848 // In C++, the previous declaration we find might be a tag type 5849 // (class or enum). In this case, the new declaration will hide the 5850 // tag type. Note that this applies to functions, function templates, and 5851 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5852 if (Previous.isSingleTagDecl() && 5853 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5854 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5855 Previous.clear(); 5856 5857 // Check that there are no default arguments other than in the parameters 5858 // of a function declaration (C++ only). 5859 if (getLangOpts().CPlusPlus) 5860 CheckExtraCXXDefaultArguments(D); 5861 5862 NamedDecl *New; 5863 5864 bool AddToScope = true; 5865 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5866 if (TemplateParamLists.size()) { 5867 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5868 return nullptr; 5869 } 5870 5871 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5872 } else if (R->isFunctionType()) { 5873 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5874 TemplateParamLists, 5875 AddToScope); 5876 } else { 5877 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5878 AddToScope); 5879 } 5880 5881 if (!New) 5882 return nullptr; 5883 5884 // If this has an identifier and is not a function template specialization, 5885 // add it to the scope stack. 5886 if (New->getDeclName() && AddToScope) 5887 PushOnScopeChains(New, S); 5888 5889 if (isInOpenMPDeclareTargetContext()) 5890 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5891 5892 return New; 5893 } 5894 5895 /// Helper method to turn variable array types into constant array 5896 /// types in certain situations which would otherwise be errors (for 5897 /// GCC compatibility). 5898 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5899 ASTContext &Context, 5900 bool &SizeIsNegative, 5901 llvm::APSInt &Oversized) { 5902 // This method tries to turn a variable array into a constant 5903 // array even when the size isn't an ICE. This is necessary 5904 // for compatibility with code that depends on gcc's buggy 5905 // constant expression folding, like struct {char x[(int)(char*)2];} 5906 SizeIsNegative = false; 5907 Oversized = 0; 5908 5909 if (T->isDependentType()) 5910 return QualType(); 5911 5912 QualifierCollector Qs; 5913 const Type *Ty = Qs.strip(T); 5914 5915 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5916 QualType Pointee = PTy->getPointeeType(); 5917 QualType FixedType = 5918 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5919 Oversized); 5920 if (FixedType.isNull()) return FixedType; 5921 FixedType = Context.getPointerType(FixedType); 5922 return Qs.apply(Context, FixedType); 5923 } 5924 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5925 QualType Inner = PTy->getInnerType(); 5926 QualType FixedType = 5927 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5928 Oversized); 5929 if (FixedType.isNull()) return FixedType; 5930 FixedType = Context.getParenType(FixedType); 5931 return Qs.apply(Context, FixedType); 5932 } 5933 5934 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5935 if (!VLATy) 5936 return QualType(); 5937 5938 QualType ElemTy = VLATy->getElementType(); 5939 if (ElemTy->isVariablyModifiedType()) { 5940 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 5941 SizeIsNegative, Oversized); 5942 if (ElemTy.isNull()) 5943 return QualType(); 5944 } 5945 5946 Expr::EvalResult Result; 5947 if (!VLATy->getSizeExpr() || 5948 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5949 return QualType(); 5950 5951 llvm::APSInt Res = Result.Val.getInt(); 5952 5953 // Check whether the array size is negative. 5954 if (Res.isSigned() && Res.isNegative()) { 5955 SizeIsNegative = true; 5956 return QualType(); 5957 } 5958 5959 // Check whether the array is too large to be addressed. 5960 unsigned ActiveSizeBits = 5961 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 5962 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 5963 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 5964 : Res.getActiveBits(); 5965 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5966 Oversized = Res; 5967 return QualType(); 5968 } 5969 5970 QualType FoldedArrayType = Context.getConstantArrayType( 5971 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 5972 return Qs.apply(Context, FoldedArrayType); 5973 } 5974 5975 static void 5976 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5977 SrcTL = SrcTL.getUnqualifiedLoc(); 5978 DstTL = DstTL.getUnqualifiedLoc(); 5979 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5980 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5981 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5982 DstPTL.getPointeeLoc()); 5983 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5984 return; 5985 } 5986 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5987 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5988 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5989 DstPTL.getInnerLoc()); 5990 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5991 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5992 return; 5993 } 5994 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5995 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5996 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5997 TypeLoc DstElemTL = DstATL.getElementLoc(); 5998 if (VariableArrayTypeLoc SrcElemATL = 5999 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6000 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6001 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6002 } else { 6003 DstElemTL.initializeFullCopy(SrcElemTL); 6004 } 6005 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6006 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6007 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6008 } 6009 6010 /// Helper method to turn variable array types into constant array 6011 /// types in certain situations which would otherwise be errors (for 6012 /// GCC compatibility). 6013 static TypeSourceInfo* 6014 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6015 ASTContext &Context, 6016 bool &SizeIsNegative, 6017 llvm::APSInt &Oversized) { 6018 QualType FixedTy 6019 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6020 SizeIsNegative, Oversized); 6021 if (FixedTy.isNull()) 6022 return nullptr; 6023 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6024 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6025 FixedTInfo->getTypeLoc()); 6026 return FixedTInfo; 6027 } 6028 6029 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6030 /// true if we were successful. 6031 static bool tryToFixVariablyModifiedVarType(Sema &S, TypeSourceInfo *&TInfo, 6032 QualType &T, SourceLocation Loc, 6033 unsigned FailedFoldDiagID) { 6034 bool SizeIsNegative; 6035 llvm::APSInt Oversized; 6036 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6037 TInfo, S.Context, SizeIsNegative, Oversized); 6038 if (FixedTInfo) { 6039 S.Diag(Loc, diag::ext_vla_folded_to_constant); 6040 TInfo = FixedTInfo; 6041 T = FixedTInfo->getType(); 6042 return true; 6043 } 6044 6045 if (SizeIsNegative) 6046 S.Diag(Loc, diag::err_typecheck_negative_array_size); 6047 else if (Oversized.getBoolValue()) 6048 S.Diag(Loc, diag::err_array_too_large) << Oversized.toString(10); 6049 else if (FailedFoldDiagID) 6050 S.Diag(Loc, FailedFoldDiagID); 6051 return false; 6052 } 6053 6054 /// Register the given locally-scoped extern "C" declaration so 6055 /// that it can be found later for redeclarations. We include any extern "C" 6056 /// declaration that is not visible in the translation unit here, not just 6057 /// function-scope declarations. 6058 void 6059 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6060 if (!getLangOpts().CPlusPlus && 6061 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6062 // Don't need to track declarations in the TU in C. 6063 return; 6064 6065 // Note that we have a locally-scoped external with this name. 6066 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6067 } 6068 6069 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6070 // FIXME: We can have multiple results via __attribute__((overloadable)). 6071 auto Result = Context.getExternCContextDecl()->lookup(Name); 6072 return Result.empty() ? nullptr : *Result.begin(); 6073 } 6074 6075 /// Diagnose function specifiers on a declaration of an identifier that 6076 /// does not identify a function. 6077 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6078 // FIXME: We should probably indicate the identifier in question to avoid 6079 // confusion for constructs like "virtual int a(), b;" 6080 if (DS.isVirtualSpecified()) 6081 Diag(DS.getVirtualSpecLoc(), 6082 diag::err_virtual_non_function); 6083 6084 if (DS.hasExplicitSpecifier()) 6085 Diag(DS.getExplicitSpecLoc(), 6086 diag::err_explicit_non_function); 6087 6088 if (DS.isNoreturnSpecified()) 6089 Diag(DS.getNoreturnSpecLoc(), 6090 diag::err_noreturn_non_function); 6091 } 6092 6093 NamedDecl* 6094 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6095 TypeSourceInfo *TInfo, LookupResult &Previous) { 6096 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6097 if (D.getCXXScopeSpec().isSet()) { 6098 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6099 << D.getCXXScopeSpec().getRange(); 6100 D.setInvalidType(); 6101 // Pretend we didn't see the scope specifier. 6102 DC = CurContext; 6103 Previous.clear(); 6104 } 6105 6106 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6107 6108 if (D.getDeclSpec().isInlineSpecified()) 6109 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6110 << getLangOpts().CPlusPlus17; 6111 if (D.getDeclSpec().hasConstexprSpecifier()) 6112 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6113 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6114 6115 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6116 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6117 Diag(D.getName().StartLocation, 6118 diag::err_deduction_guide_invalid_specifier) 6119 << "typedef"; 6120 else 6121 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6122 << D.getName().getSourceRange(); 6123 return nullptr; 6124 } 6125 6126 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6127 if (!NewTD) return nullptr; 6128 6129 // Handle attributes prior to checking for duplicates in MergeVarDecl 6130 ProcessDeclAttributes(S, NewTD, D); 6131 6132 CheckTypedefForVariablyModifiedType(S, NewTD); 6133 6134 bool Redeclaration = D.isRedeclaration(); 6135 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6136 D.setRedeclaration(Redeclaration); 6137 return ND; 6138 } 6139 6140 void 6141 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6142 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6143 // then it shall have block scope. 6144 // Note that variably modified types must be fixed before merging the decl so 6145 // that redeclarations will match. 6146 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6147 QualType T = TInfo->getType(); 6148 if (T->isVariablyModifiedType()) { 6149 setFunctionHasBranchProtectedScope(); 6150 6151 if (S->getFnParent() == nullptr) { 6152 bool SizeIsNegative; 6153 llvm::APSInt Oversized; 6154 TypeSourceInfo *FixedTInfo = 6155 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6156 SizeIsNegative, 6157 Oversized); 6158 if (FixedTInfo) { 6159 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6160 NewTD->setTypeSourceInfo(FixedTInfo); 6161 } else { 6162 if (SizeIsNegative) 6163 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6164 else if (T->isVariableArrayType()) 6165 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6166 else if (Oversized.getBoolValue()) 6167 Diag(NewTD->getLocation(), diag::err_array_too_large) 6168 << Oversized.toString(10); 6169 else 6170 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6171 NewTD->setInvalidDecl(); 6172 } 6173 } 6174 } 6175 } 6176 6177 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6178 /// declares a typedef-name, either using the 'typedef' type specifier or via 6179 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6180 NamedDecl* 6181 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6182 LookupResult &Previous, bool &Redeclaration) { 6183 6184 // Find the shadowed declaration before filtering for scope. 6185 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6186 6187 // Merge the decl with the existing one if appropriate. If the decl is 6188 // in an outer scope, it isn't the same thing. 6189 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6190 /*AllowInlineNamespace*/false); 6191 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6192 if (!Previous.empty()) { 6193 Redeclaration = true; 6194 MergeTypedefNameDecl(S, NewTD, Previous); 6195 } else { 6196 inferGslPointerAttribute(NewTD); 6197 } 6198 6199 if (ShadowedDecl && !Redeclaration) 6200 CheckShadow(NewTD, ShadowedDecl, Previous); 6201 6202 // If this is the C FILE type, notify the AST context. 6203 if (IdentifierInfo *II = NewTD->getIdentifier()) 6204 if (!NewTD->isInvalidDecl() && 6205 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6206 if (II->isStr("FILE")) 6207 Context.setFILEDecl(NewTD); 6208 else if (II->isStr("jmp_buf")) 6209 Context.setjmp_bufDecl(NewTD); 6210 else if (II->isStr("sigjmp_buf")) 6211 Context.setsigjmp_bufDecl(NewTD); 6212 else if (II->isStr("ucontext_t")) 6213 Context.setucontext_tDecl(NewTD); 6214 } 6215 6216 return NewTD; 6217 } 6218 6219 /// Determines whether the given declaration is an out-of-scope 6220 /// previous declaration. 6221 /// 6222 /// This routine should be invoked when name lookup has found a 6223 /// previous declaration (PrevDecl) that is not in the scope where a 6224 /// new declaration by the same name is being introduced. If the new 6225 /// declaration occurs in a local scope, previous declarations with 6226 /// linkage may still be considered previous declarations (C99 6227 /// 6.2.2p4-5, C++ [basic.link]p6). 6228 /// 6229 /// \param PrevDecl the previous declaration found by name 6230 /// lookup 6231 /// 6232 /// \param DC the context in which the new declaration is being 6233 /// declared. 6234 /// 6235 /// \returns true if PrevDecl is an out-of-scope previous declaration 6236 /// for a new delcaration with the same name. 6237 static bool 6238 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6239 ASTContext &Context) { 6240 if (!PrevDecl) 6241 return false; 6242 6243 if (!PrevDecl->hasLinkage()) 6244 return false; 6245 6246 if (Context.getLangOpts().CPlusPlus) { 6247 // C++ [basic.link]p6: 6248 // If there is a visible declaration of an entity with linkage 6249 // having the same name and type, ignoring entities declared 6250 // outside the innermost enclosing namespace scope, the block 6251 // scope declaration declares that same entity and receives the 6252 // linkage of the previous declaration. 6253 DeclContext *OuterContext = DC->getRedeclContext(); 6254 if (!OuterContext->isFunctionOrMethod()) 6255 // This rule only applies to block-scope declarations. 6256 return false; 6257 6258 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6259 if (PrevOuterContext->isRecord()) 6260 // We found a member function: ignore it. 6261 return false; 6262 6263 // Find the innermost enclosing namespace for the new and 6264 // previous declarations. 6265 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6266 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6267 6268 // The previous declaration is in a different namespace, so it 6269 // isn't the same function. 6270 if (!OuterContext->Equals(PrevOuterContext)) 6271 return false; 6272 } 6273 6274 return true; 6275 } 6276 6277 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6278 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6279 if (!SS.isSet()) return; 6280 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6281 } 6282 6283 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6284 QualType type = decl->getType(); 6285 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6286 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6287 // Various kinds of declaration aren't allowed to be __autoreleasing. 6288 unsigned kind = -1U; 6289 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6290 if (var->hasAttr<BlocksAttr>()) 6291 kind = 0; // __block 6292 else if (!var->hasLocalStorage()) 6293 kind = 1; // global 6294 } else if (isa<ObjCIvarDecl>(decl)) { 6295 kind = 3; // ivar 6296 } else if (isa<FieldDecl>(decl)) { 6297 kind = 2; // field 6298 } 6299 6300 if (kind != -1U) { 6301 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6302 << kind; 6303 } 6304 } else if (lifetime == Qualifiers::OCL_None) { 6305 // Try to infer lifetime. 6306 if (!type->isObjCLifetimeType()) 6307 return false; 6308 6309 lifetime = type->getObjCARCImplicitLifetime(); 6310 type = Context.getLifetimeQualifiedType(type, lifetime); 6311 decl->setType(type); 6312 } 6313 6314 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6315 // Thread-local variables cannot have lifetime. 6316 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6317 var->getTLSKind()) { 6318 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6319 << var->getType(); 6320 return true; 6321 } 6322 } 6323 6324 return false; 6325 } 6326 6327 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6328 if (Decl->getType().hasAddressSpace()) 6329 return; 6330 if (Decl->getType()->isDependentType()) 6331 return; 6332 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6333 QualType Type = Var->getType(); 6334 if (Type->isSamplerT() || Type->isVoidType()) 6335 return; 6336 LangAS ImplAS = LangAS::opencl_private; 6337 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6338 Var->hasGlobalStorage()) 6339 ImplAS = LangAS::opencl_global; 6340 // If the original type from a decayed type is an array type and that array 6341 // type has no address space yet, deduce it now. 6342 if (auto DT = dyn_cast<DecayedType>(Type)) { 6343 auto OrigTy = DT->getOriginalType(); 6344 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6345 // Add the address space to the original array type and then propagate 6346 // that to the element type through `getAsArrayType`. 6347 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6348 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6349 // Re-generate the decayed type. 6350 Type = Context.getDecayedType(OrigTy); 6351 } 6352 } 6353 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6354 // Apply any qualifiers (including address space) from the array type to 6355 // the element type. This implements C99 6.7.3p8: "If the specification of 6356 // an array type includes any type qualifiers, the element type is so 6357 // qualified, not the array type." 6358 if (Type->isArrayType()) 6359 Type = QualType(Context.getAsArrayType(Type), 0); 6360 Decl->setType(Type); 6361 } 6362 } 6363 6364 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6365 // Ensure that an auto decl is deduced otherwise the checks below might cache 6366 // the wrong linkage. 6367 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6368 6369 // 'weak' only applies to declarations with external linkage. 6370 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6371 if (!ND.isExternallyVisible()) { 6372 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6373 ND.dropAttr<WeakAttr>(); 6374 } 6375 } 6376 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6377 if (ND.isExternallyVisible()) { 6378 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6379 ND.dropAttr<WeakRefAttr>(); 6380 ND.dropAttr<AliasAttr>(); 6381 } 6382 } 6383 6384 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6385 if (VD->hasInit()) { 6386 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6387 assert(VD->isThisDeclarationADefinition() && 6388 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6389 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6390 VD->dropAttr<AliasAttr>(); 6391 } 6392 } 6393 } 6394 6395 // 'selectany' only applies to externally visible variable declarations. 6396 // It does not apply to functions. 6397 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6398 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6399 S.Diag(Attr->getLocation(), 6400 diag::err_attribute_selectany_non_extern_data); 6401 ND.dropAttr<SelectAnyAttr>(); 6402 } 6403 } 6404 6405 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6406 auto *VD = dyn_cast<VarDecl>(&ND); 6407 bool IsAnonymousNS = false; 6408 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6409 if (VD) { 6410 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6411 while (NS && !IsAnonymousNS) { 6412 IsAnonymousNS = NS->isAnonymousNamespace(); 6413 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6414 } 6415 } 6416 // dll attributes require external linkage. Static locals may have external 6417 // linkage but still cannot be explicitly imported or exported. 6418 // In Microsoft mode, a variable defined in anonymous namespace must have 6419 // external linkage in order to be exported. 6420 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6421 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6422 (!AnonNSInMicrosoftMode && 6423 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6424 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6425 << &ND << Attr; 6426 ND.setInvalidDecl(); 6427 } 6428 } 6429 6430 // Virtual functions cannot be marked as 'notail'. 6431 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6432 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6433 if (MD->isVirtual()) { 6434 S.Diag(ND.getLocation(), 6435 diag::err_invalid_attribute_on_virtual_function) 6436 << Attr; 6437 ND.dropAttr<NotTailCalledAttr>(); 6438 } 6439 6440 // Check the attributes on the function type, if any. 6441 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6442 // Don't declare this variable in the second operand of the for-statement; 6443 // GCC miscompiles that by ending its lifetime before evaluating the 6444 // third operand. See gcc.gnu.org/PR86769. 6445 AttributedTypeLoc ATL; 6446 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6447 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6448 TL = ATL.getModifiedLoc()) { 6449 // The [[lifetimebound]] attribute can be applied to the implicit object 6450 // parameter of a non-static member function (other than a ctor or dtor) 6451 // by applying it to the function type. 6452 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6453 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6454 if (!MD || MD->isStatic()) { 6455 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6456 << !MD << A->getRange(); 6457 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6458 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6459 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6460 } 6461 } 6462 } 6463 } 6464 } 6465 6466 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6467 NamedDecl *NewDecl, 6468 bool IsSpecialization, 6469 bool IsDefinition) { 6470 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6471 return; 6472 6473 bool IsTemplate = false; 6474 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6475 OldDecl = OldTD->getTemplatedDecl(); 6476 IsTemplate = true; 6477 if (!IsSpecialization) 6478 IsDefinition = false; 6479 } 6480 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6481 NewDecl = NewTD->getTemplatedDecl(); 6482 IsTemplate = true; 6483 } 6484 6485 if (!OldDecl || !NewDecl) 6486 return; 6487 6488 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6489 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6490 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6491 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6492 6493 // dllimport and dllexport are inheritable attributes so we have to exclude 6494 // inherited attribute instances. 6495 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6496 (NewExportAttr && !NewExportAttr->isInherited()); 6497 6498 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6499 // the only exception being explicit specializations. 6500 // Implicitly generated declarations are also excluded for now because there 6501 // is no other way to switch these to use dllimport or dllexport. 6502 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6503 6504 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6505 // Allow with a warning for free functions and global variables. 6506 bool JustWarn = false; 6507 if (!OldDecl->isCXXClassMember()) { 6508 auto *VD = dyn_cast<VarDecl>(OldDecl); 6509 if (VD && !VD->getDescribedVarTemplate()) 6510 JustWarn = true; 6511 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6512 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6513 JustWarn = true; 6514 } 6515 6516 // We cannot change a declaration that's been used because IR has already 6517 // been emitted. Dllimported functions will still work though (modulo 6518 // address equality) as they can use the thunk. 6519 if (OldDecl->isUsed()) 6520 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6521 JustWarn = false; 6522 6523 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6524 : diag::err_attribute_dll_redeclaration; 6525 S.Diag(NewDecl->getLocation(), DiagID) 6526 << NewDecl 6527 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6528 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6529 if (!JustWarn) { 6530 NewDecl->setInvalidDecl(); 6531 return; 6532 } 6533 } 6534 6535 // A redeclaration is not allowed to drop a dllimport attribute, the only 6536 // exceptions being inline function definitions (except for function 6537 // templates), local extern declarations, qualified friend declarations or 6538 // special MSVC extension: in the last case, the declaration is treated as if 6539 // it were marked dllexport. 6540 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6541 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 6542 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6543 // Ignore static data because out-of-line definitions are diagnosed 6544 // separately. 6545 IsStaticDataMember = VD->isStaticDataMember(); 6546 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6547 VarDecl::DeclarationOnly; 6548 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6549 IsInline = FD->isInlined(); 6550 IsQualifiedFriend = FD->getQualifier() && 6551 FD->getFriendObjectKind() == Decl::FOK_Declared; 6552 } 6553 6554 if (OldImportAttr && !HasNewAttr && 6555 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 6556 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6557 if (IsMicrosoftABI && IsDefinition) { 6558 S.Diag(NewDecl->getLocation(), 6559 diag::warn_redeclaration_without_import_attribute) 6560 << NewDecl; 6561 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6562 NewDecl->dropAttr<DLLImportAttr>(); 6563 NewDecl->addAttr( 6564 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6565 } else { 6566 S.Diag(NewDecl->getLocation(), 6567 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6568 << NewDecl << OldImportAttr; 6569 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6570 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6571 OldDecl->dropAttr<DLLImportAttr>(); 6572 NewDecl->dropAttr<DLLImportAttr>(); 6573 } 6574 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 6575 // In MinGW, seeing a function declared inline drops the dllimport 6576 // attribute. 6577 OldDecl->dropAttr<DLLImportAttr>(); 6578 NewDecl->dropAttr<DLLImportAttr>(); 6579 S.Diag(NewDecl->getLocation(), 6580 diag::warn_dllimport_dropped_from_inline_function) 6581 << NewDecl << OldImportAttr; 6582 } 6583 6584 // A specialization of a class template member function is processed here 6585 // since it's a redeclaration. If the parent class is dllexport, the 6586 // specialization inherits that attribute. This doesn't happen automatically 6587 // since the parent class isn't instantiated until later. 6588 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6589 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6590 !NewImportAttr && !NewExportAttr) { 6591 if (const DLLExportAttr *ParentExportAttr = 6592 MD->getParent()->getAttr<DLLExportAttr>()) { 6593 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6594 NewAttr->setInherited(true); 6595 NewDecl->addAttr(NewAttr); 6596 } 6597 } 6598 } 6599 } 6600 6601 /// Given that we are within the definition of the given function, 6602 /// will that definition behave like C99's 'inline', where the 6603 /// definition is discarded except for optimization purposes? 6604 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6605 // Try to avoid calling GetGVALinkageForFunction. 6606 6607 // All cases of this require the 'inline' keyword. 6608 if (!FD->isInlined()) return false; 6609 6610 // This is only possible in C++ with the gnu_inline attribute. 6611 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6612 return false; 6613 6614 // Okay, go ahead and call the relatively-more-expensive function. 6615 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6616 } 6617 6618 /// Determine whether a variable is extern "C" prior to attaching 6619 /// an initializer. We can't just call isExternC() here, because that 6620 /// will also compute and cache whether the declaration is externally 6621 /// visible, which might change when we attach the initializer. 6622 /// 6623 /// This can only be used if the declaration is known to not be a 6624 /// redeclaration of an internal linkage declaration. 6625 /// 6626 /// For instance: 6627 /// 6628 /// auto x = []{}; 6629 /// 6630 /// Attaching the initializer here makes this declaration not externally 6631 /// visible, because its type has internal linkage. 6632 /// 6633 /// FIXME: This is a hack. 6634 template<typename T> 6635 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6636 if (S.getLangOpts().CPlusPlus) { 6637 // In C++, the overloadable attribute negates the effects of extern "C". 6638 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6639 return false; 6640 6641 // So do CUDA's host/device attributes. 6642 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6643 D->template hasAttr<CUDAHostAttr>())) 6644 return false; 6645 } 6646 return D->isExternC(); 6647 } 6648 6649 static bool shouldConsiderLinkage(const VarDecl *VD) { 6650 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6651 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6652 isa<OMPDeclareMapperDecl>(DC)) 6653 return VD->hasExternalStorage(); 6654 if (DC->isFileContext()) 6655 return true; 6656 if (DC->isRecord()) 6657 return false; 6658 if (isa<RequiresExprBodyDecl>(DC)) 6659 return false; 6660 llvm_unreachable("Unexpected context"); 6661 } 6662 6663 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6664 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6665 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6666 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6667 return true; 6668 if (DC->isRecord()) 6669 return false; 6670 llvm_unreachable("Unexpected context"); 6671 } 6672 6673 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6674 ParsedAttr::Kind Kind) { 6675 // Check decl attributes on the DeclSpec. 6676 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6677 return true; 6678 6679 // Walk the declarator structure, checking decl attributes that were in a type 6680 // position to the decl itself. 6681 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6682 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6683 return true; 6684 } 6685 6686 // Finally, check attributes on the decl itself. 6687 return PD.getAttributes().hasAttribute(Kind); 6688 } 6689 6690 /// Adjust the \c DeclContext for a function or variable that might be a 6691 /// function-local external declaration. 6692 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6693 if (!DC->isFunctionOrMethod()) 6694 return false; 6695 6696 // If this is a local extern function or variable declared within a function 6697 // template, don't add it into the enclosing namespace scope until it is 6698 // instantiated; it might have a dependent type right now. 6699 if (DC->isDependentContext()) 6700 return true; 6701 6702 // C++11 [basic.link]p7: 6703 // When a block scope declaration of an entity with linkage is not found to 6704 // refer to some other declaration, then that entity is a member of the 6705 // innermost enclosing namespace. 6706 // 6707 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6708 // semantically-enclosing namespace, not a lexically-enclosing one. 6709 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6710 DC = DC->getParent(); 6711 return true; 6712 } 6713 6714 /// Returns true if given declaration has external C language linkage. 6715 static bool isDeclExternC(const Decl *D) { 6716 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6717 return FD->isExternC(); 6718 if (const auto *VD = dyn_cast<VarDecl>(D)) 6719 return VD->isExternC(); 6720 6721 llvm_unreachable("Unknown type of decl!"); 6722 } 6723 /// Returns true if there hasn't been any invalid type diagnosed. 6724 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, 6725 DeclContext *DC, QualType R) { 6726 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6727 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6728 // argument. 6729 if (R->isImageType() || R->isPipeType()) { 6730 Se.Diag(D.getIdentifierLoc(), 6731 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6732 << R; 6733 D.setInvalidType(); 6734 return false; 6735 } 6736 6737 // OpenCL v1.2 s6.9.r: 6738 // The event type cannot be used to declare a program scope variable. 6739 // OpenCL v2.0 s6.9.q: 6740 // The clk_event_t and reserve_id_t types cannot be declared in program 6741 // scope. 6742 if (NULL == S->getParent()) { 6743 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6744 Se.Diag(D.getIdentifierLoc(), 6745 diag::err_invalid_type_for_program_scope_var) 6746 << R; 6747 D.setInvalidType(); 6748 return false; 6749 } 6750 } 6751 6752 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6753 if (!Se.getOpenCLOptions().isEnabled("__cl_clang_function_pointers")) { 6754 QualType NR = R; 6755 while (NR->isPointerType() || NR->isMemberFunctionPointerType()) { 6756 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType()) { 6757 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6758 D.setInvalidType(); 6759 return false; 6760 } 6761 NR = NR->getPointeeType(); 6762 } 6763 } 6764 6765 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6766 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6767 // half array type (unless the cl_khr_fp16 extension is enabled). 6768 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6769 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6770 D.setInvalidType(); 6771 return false; 6772 } 6773 } 6774 6775 // OpenCL v1.2 s6.9.r: 6776 // The event type cannot be used with the __local, __constant and __global 6777 // address space qualifiers. 6778 if (R->isEventT()) { 6779 if (R.getAddressSpace() != LangAS::opencl_private) { 6780 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6781 D.setInvalidType(); 6782 return false; 6783 } 6784 } 6785 6786 // C++ for OpenCL does not allow the thread_local storage qualifier. 6787 // OpenCL C does not support thread_local either, and 6788 // also reject all other thread storage class specifiers. 6789 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6790 if (TSC != TSCS_unspecified) { 6791 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; 6792 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6793 diag::err_opencl_unknown_type_specifier) 6794 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() 6795 << DeclSpec::getSpecifierName(TSC) << 1; 6796 D.setInvalidType(); 6797 return false; 6798 } 6799 6800 if (R->isSamplerT()) { 6801 // OpenCL v1.2 s6.9.b p4: 6802 // The sampler type cannot be used with the __local and __global address 6803 // space qualifiers. 6804 if (R.getAddressSpace() == LangAS::opencl_local || 6805 R.getAddressSpace() == LangAS::opencl_global) { 6806 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6807 D.setInvalidType(); 6808 } 6809 6810 // OpenCL v1.2 s6.12.14.1: 6811 // A global sampler must be declared with either the constant address 6812 // space qualifier or with the const qualifier. 6813 if (DC->isTranslationUnit() && 6814 !(R.getAddressSpace() == LangAS::opencl_constant || 6815 R.isConstQualified())) { 6816 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6817 D.setInvalidType(); 6818 } 6819 if (D.isInvalidType()) 6820 return false; 6821 } 6822 return true; 6823 } 6824 6825 NamedDecl *Sema::ActOnVariableDeclarator( 6826 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6827 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6828 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6829 QualType R = TInfo->getType(); 6830 DeclarationName Name = GetNameForDeclarator(D).getName(); 6831 6832 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6833 6834 if (D.isDecompositionDeclarator()) { 6835 // Take the name of the first declarator as our name for diagnostic 6836 // purposes. 6837 auto &Decomp = D.getDecompositionDeclarator(); 6838 if (!Decomp.bindings().empty()) { 6839 II = Decomp.bindings()[0].Name; 6840 Name = II; 6841 } 6842 } else if (!II) { 6843 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6844 return nullptr; 6845 } 6846 6847 6848 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6849 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6850 6851 // dllimport globals without explicit storage class are treated as extern. We 6852 // have to change the storage class this early to get the right DeclContext. 6853 if (SC == SC_None && !DC->isRecord() && 6854 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6855 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6856 SC = SC_Extern; 6857 6858 DeclContext *OriginalDC = DC; 6859 bool IsLocalExternDecl = SC == SC_Extern && 6860 adjustContextForLocalExternDecl(DC); 6861 6862 if (SCSpec == DeclSpec::SCS_mutable) { 6863 // mutable can only appear on non-static class members, so it's always 6864 // an error here 6865 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6866 D.setInvalidType(); 6867 SC = SC_None; 6868 } 6869 6870 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6871 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6872 D.getDeclSpec().getStorageClassSpecLoc())) { 6873 // In C++11, the 'register' storage class specifier is deprecated. 6874 // Suppress the warning in system macros, it's used in macros in some 6875 // popular C system headers, such as in glibc's htonl() macro. 6876 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6877 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6878 : diag::warn_deprecated_register) 6879 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6880 } 6881 6882 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6883 6884 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6885 // C99 6.9p2: The storage-class specifiers auto and register shall not 6886 // appear in the declaration specifiers in an external declaration. 6887 // Global Register+Asm is a GNU extension we support. 6888 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6889 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6890 D.setInvalidType(); 6891 } 6892 } 6893 6894 // If this variable has a variable-modified type and an initializer, try to 6895 // fold to a constant-sized type. This is otherwise invalid. 6896 if (D.hasInitializer() && R->isVariablyModifiedType()) 6897 tryToFixVariablyModifiedVarType(*this, TInfo, R, D.getIdentifierLoc(), 6898 /*DiagID=*/0); 6899 6900 bool IsMemberSpecialization = false; 6901 bool IsVariableTemplateSpecialization = false; 6902 bool IsPartialSpecialization = false; 6903 bool IsVariableTemplate = false; 6904 VarDecl *NewVD = nullptr; 6905 VarTemplateDecl *NewTemplate = nullptr; 6906 TemplateParameterList *TemplateParams = nullptr; 6907 if (!getLangOpts().CPlusPlus) { 6908 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6909 II, R, TInfo, SC); 6910 6911 if (R->getContainedDeducedType()) 6912 ParsingInitForAutoVars.insert(NewVD); 6913 6914 if (D.isInvalidType()) 6915 NewVD->setInvalidDecl(); 6916 6917 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6918 NewVD->hasLocalStorage()) 6919 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6920 NTCUC_AutoVar, NTCUK_Destruct); 6921 } else { 6922 bool Invalid = false; 6923 6924 if (DC->isRecord() && !CurContext->isRecord()) { 6925 // This is an out-of-line definition of a static data member. 6926 switch (SC) { 6927 case SC_None: 6928 break; 6929 case SC_Static: 6930 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6931 diag::err_static_out_of_line) 6932 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6933 break; 6934 case SC_Auto: 6935 case SC_Register: 6936 case SC_Extern: 6937 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6938 // to names of variables declared in a block or to function parameters. 6939 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6940 // of class members 6941 6942 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6943 diag::err_storage_class_for_static_member) 6944 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6945 break; 6946 case SC_PrivateExtern: 6947 llvm_unreachable("C storage class in c++!"); 6948 } 6949 } 6950 6951 if (SC == SC_Static && CurContext->isRecord()) { 6952 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6953 // Walk up the enclosing DeclContexts to check for any that are 6954 // incompatible with static data members. 6955 const DeclContext *FunctionOrMethod = nullptr; 6956 const CXXRecordDecl *AnonStruct = nullptr; 6957 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 6958 if (Ctxt->isFunctionOrMethod()) { 6959 FunctionOrMethod = Ctxt; 6960 break; 6961 } 6962 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 6963 if (ParentDecl && !ParentDecl->getDeclName()) { 6964 AnonStruct = ParentDecl; 6965 break; 6966 } 6967 } 6968 if (FunctionOrMethod) { 6969 // C++ [class.static.data]p5: A local class shall not have static data 6970 // members. 6971 Diag(D.getIdentifierLoc(), 6972 diag::err_static_data_member_not_allowed_in_local_class) 6973 << Name << RD->getDeclName() << RD->getTagKind(); 6974 } else if (AnonStruct) { 6975 // C++ [class.static.data]p4: Unnamed classes and classes contained 6976 // directly or indirectly within unnamed classes shall not contain 6977 // static data members. 6978 Diag(D.getIdentifierLoc(), 6979 diag::err_static_data_member_not_allowed_in_anon_struct) 6980 << Name << AnonStruct->getTagKind(); 6981 Invalid = true; 6982 } else if (RD->isUnion()) { 6983 // C++98 [class.union]p1: If a union contains a static data member, 6984 // the program is ill-formed. C++11 drops this restriction. 6985 Diag(D.getIdentifierLoc(), 6986 getLangOpts().CPlusPlus11 6987 ? diag::warn_cxx98_compat_static_data_member_in_union 6988 : diag::ext_static_data_member_in_union) << Name; 6989 } 6990 } 6991 } 6992 6993 // Match up the template parameter lists with the scope specifier, then 6994 // determine whether we have a template or a template specialization. 6995 bool InvalidScope = false; 6996 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6997 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6998 D.getCXXScopeSpec(), 6999 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7000 ? D.getName().TemplateId 7001 : nullptr, 7002 TemplateParamLists, 7003 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7004 Invalid |= InvalidScope; 7005 7006 if (TemplateParams) { 7007 if (!TemplateParams->size() && 7008 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7009 // There is an extraneous 'template<>' for this variable. Complain 7010 // about it, but allow the declaration of the variable. 7011 Diag(TemplateParams->getTemplateLoc(), 7012 diag::err_template_variable_noparams) 7013 << II 7014 << SourceRange(TemplateParams->getTemplateLoc(), 7015 TemplateParams->getRAngleLoc()); 7016 TemplateParams = nullptr; 7017 } else { 7018 // Check that we can declare a template here. 7019 if (CheckTemplateDeclScope(S, TemplateParams)) 7020 return nullptr; 7021 7022 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7023 // This is an explicit specialization or a partial specialization. 7024 IsVariableTemplateSpecialization = true; 7025 IsPartialSpecialization = TemplateParams->size() > 0; 7026 } else { // if (TemplateParams->size() > 0) 7027 // This is a template declaration. 7028 IsVariableTemplate = true; 7029 7030 // Only C++1y supports variable templates (N3651). 7031 Diag(D.getIdentifierLoc(), 7032 getLangOpts().CPlusPlus14 7033 ? diag::warn_cxx11_compat_variable_template 7034 : diag::ext_variable_template); 7035 } 7036 } 7037 } else { 7038 // Check that we can declare a member specialization here. 7039 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7040 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7041 return nullptr; 7042 assert((Invalid || 7043 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7044 "should have a 'template<>' for this decl"); 7045 } 7046 7047 if (IsVariableTemplateSpecialization) { 7048 SourceLocation TemplateKWLoc = 7049 TemplateParamLists.size() > 0 7050 ? TemplateParamLists[0]->getTemplateLoc() 7051 : SourceLocation(); 7052 DeclResult Res = ActOnVarTemplateSpecialization( 7053 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7054 IsPartialSpecialization); 7055 if (Res.isInvalid()) 7056 return nullptr; 7057 NewVD = cast<VarDecl>(Res.get()); 7058 AddToScope = false; 7059 } else if (D.isDecompositionDeclarator()) { 7060 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7061 D.getIdentifierLoc(), R, TInfo, SC, 7062 Bindings); 7063 } else 7064 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7065 D.getIdentifierLoc(), II, R, TInfo, SC); 7066 7067 // If this is supposed to be a variable template, create it as such. 7068 if (IsVariableTemplate) { 7069 NewTemplate = 7070 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7071 TemplateParams, NewVD); 7072 NewVD->setDescribedVarTemplate(NewTemplate); 7073 } 7074 7075 // If this decl has an auto type in need of deduction, make a note of the 7076 // Decl so we can diagnose uses of it in its own initializer. 7077 if (R->getContainedDeducedType()) 7078 ParsingInitForAutoVars.insert(NewVD); 7079 7080 if (D.isInvalidType() || Invalid) { 7081 NewVD->setInvalidDecl(); 7082 if (NewTemplate) 7083 NewTemplate->setInvalidDecl(); 7084 } 7085 7086 SetNestedNameSpecifier(*this, NewVD, D); 7087 7088 // If we have any template parameter lists that don't directly belong to 7089 // the variable (matching the scope specifier), store them. 7090 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7091 if (TemplateParamLists.size() > VDTemplateParamLists) 7092 NewVD->setTemplateParameterListsInfo( 7093 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7094 } 7095 7096 if (D.getDeclSpec().isInlineSpecified()) { 7097 if (!getLangOpts().CPlusPlus) { 7098 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7099 << 0; 7100 } else if (CurContext->isFunctionOrMethod()) { 7101 // 'inline' is not allowed on block scope variable declaration. 7102 Diag(D.getDeclSpec().getInlineSpecLoc(), 7103 diag::err_inline_declaration_block_scope) << Name 7104 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7105 } else { 7106 Diag(D.getDeclSpec().getInlineSpecLoc(), 7107 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7108 : diag::ext_inline_variable); 7109 NewVD->setInlineSpecified(); 7110 } 7111 } 7112 7113 // Set the lexical context. If the declarator has a C++ scope specifier, the 7114 // lexical context will be different from the semantic context. 7115 NewVD->setLexicalDeclContext(CurContext); 7116 if (NewTemplate) 7117 NewTemplate->setLexicalDeclContext(CurContext); 7118 7119 if (IsLocalExternDecl) { 7120 if (D.isDecompositionDeclarator()) 7121 for (auto *B : Bindings) 7122 B->setLocalExternDecl(); 7123 else 7124 NewVD->setLocalExternDecl(); 7125 } 7126 7127 bool EmitTLSUnsupportedError = false; 7128 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7129 // C++11 [dcl.stc]p4: 7130 // When thread_local is applied to a variable of block scope the 7131 // storage-class-specifier static is implied if it does not appear 7132 // explicitly. 7133 // Core issue: 'static' is not implied if the variable is declared 7134 // 'extern'. 7135 if (NewVD->hasLocalStorage() && 7136 (SCSpec != DeclSpec::SCS_unspecified || 7137 TSCS != DeclSpec::TSCS_thread_local || 7138 !DC->isFunctionOrMethod())) 7139 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7140 diag::err_thread_non_global) 7141 << DeclSpec::getSpecifierName(TSCS); 7142 else if (!Context.getTargetInfo().isTLSSupported()) { 7143 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7144 getLangOpts().SYCLIsDevice) { 7145 // Postpone error emission until we've collected attributes required to 7146 // figure out whether it's a host or device variable and whether the 7147 // error should be ignored. 7148 EmitTLSUnsupportedError = true; 7149 // We still need to mark the variable as TLS so it shows up in AST with 7150 // proper storage class for other tools to use even if we're not going 7151 // to emit any code for it. 7152 NewVD->setTSCSpec(TSCS); 7153 } else 7154 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7155 diag::err_thread_unsupported); 7156 } else 7157 NewVD->setTSCSpec(TSCS); 7158 } 7159 7160 switch (D.getDeclSpec().getConstexprSpecifier()) { 7161 case ConstexprSpecKind::Unspecified: 7162 break; 7163 7164 case ConstexprSpecKind::Consteval: 7165 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7166 diag::err_constexpr_wrong_decl_kind) 7167 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7168 LLVM_FALLTHROUGH; 7169 7170 case ConstexprSpecKind::Constexpr: 7171 NewVD->setConstexpr(true); 7172 MaybeAddCUDAConstantAttr(NewVD); 7173 // C++1z [dcl.spec.constexpr]p1: 7174 // A static data member declared with the constexpr specifier is 7175 // implicitly an inline variable. 7176 if (NewVD->isStaticDataMember() && 7177 (getLangOpts().CPlusPlus17 || 7178 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7179 NewVD->setImplicitlyInline(); 7180 break; 7181 7182 case ConstexprSpecKind::Constinit: 7183 if (!NewVD->hasGlobalStorage()) 7184 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7185 diag::err_constinit_local_variable); 7186 else 7187 NewVD->addAttr(ConstInitAttr::Create( 7188 Context, D.getDeclSpec().getConstexprSpecLoc(), 7189 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7190 break; 7191 } 7192 7193 // C99 6.7.4p3 7194 // An inline definition of a function with external linkage shall 7195 // not contain a definition of a modifiable object with static or 7196 // thread storage duration... 7197 // We only apply this when the function is required to be defined 7198 // elsewhere, i.e. when the function is not 'extern inline'. Note 7199 // that a local variable with thread storage duration still has to 7200 // be marked 'static'. Also note that it's possible to get these 7201 // semantics in C++ using __attribute__((gnu_inline)). 7202 if (SC == SC_Static && S->getFnParent() != nullptr && 7203 !NewVD->getType().isConstQualified()) { 7204 FunctionDecl *CurFD = getCurFunctionDecl(); 7205 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7206 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7207 diag::warn_static_local_in_extern_inline); 7208 MaybeSuggestAddingStaticToDecl(CurFD); 7209 } 7210 } 7211 7212 if (D.getDeclSpec().isModulePrivateSpecified()) { 7213 if (IsVariableTemplateSpecialization) 7214 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7215 << (IsPartialSpecialization ? 1 : 0) 7216 << FixItHint::CreateRemoval( 7217 D.getDeclSpec().getModulePrivateSpecLoc()); 7218 else if (IsMemberSpecialization) 7219 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7220 << 2 7221 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7222 else if (NewVD->hasLocalStorage()) 7223 Diag(NewVD->getLocation(), diag::err_module_private_local) 7224 << 0 << NewVD 7225 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7226 << FixItHint::CreateRemoval( 7227 D.getDeclSpec().getModulePrivateSpecLoc()); 7228 else { 7229 NewVD->setModulePrivate(); 7230 if (NewTemplate) 7231 NewTemplate->setModulePrivate(); 7232 for (auto *B : Bindings) 7233 B->setModulePrivate(); 7234 } 7235 } 7236 7237 if (getLangOpts().OpenCL) { 7238 7239 deduceOpenCLAddressSpace(NewVD); 7240 7241 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); 7242 } 7243 7244 // Handle attributes prior to checking for duplicates in MergeVarDecl 7245 ProcessDeclAttributes(S, NewVD, D); 7246 7247 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7248 getLangOpts().SYCLIsDevice) { 7249 if (EmitTLSUnsupportedError && 7250 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7251 (getLangOpts().OpenMPIsDevice && 7252 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7253 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7254 diag::err_thread_unsupported); 7255 7256 if (EmitTLSUnsupportedError && 7257 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7258 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7259 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7260 // storage [duration]." 7261 if (SC == SC_None && S->getFnParent() != nullptr && 7262 (NewVD->hasAttr<CUDASharedAttr>() || 7263 NewVD->hasAttr<CUDAConstantAttr>())) { 7264 NewVD->setStorageClass(SC_Static); 7265 } 7266 } 7267 7268 // Ensure that dllimport globals without explicit storage class are treated as 7269 // extern. The storage class is set above using parsed attributes. Now we can 7270 // check the VarDecl itself. 7271 assert(!NewVD->hasAttr<DLLImportAttr>() || 7272 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7273 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7274 7275 // In auto-retain/release, infer strong retension for variables of 7276 // retainable type. 7277 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7278 NewVD->setInvalidDecl(); 7279 7280 // Handle GNU asm-label extension (encoded as an attribute). 7281 if (Expr *E = (Expr*)D.getAsmLabel()) { 7282 // The parser guarantees this is a string. 7283 StringLiteral *SE = cast<StringLiteral>(E); 7284 StringRef Label = SE->getString(); 7285 if (S->getFnParent() != nullptr) { 7286 switch (SC) { 7287 case SC_None: 7288 case SC_Auto: 7289 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7290 break; 7291 case SC_Register: 7292 // Local Named register 7293 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7294 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7295 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7296 break; 7297 case SC_Static: 7298 case SC_Extern: 7299 case SC_PrivateExtern: 7300 break; 7301 } 7302 } else if (SC == SC_Register) { 7303 // Global Named register 7304 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7305 const auto &TI = Context.getTargetInfo(); 7306 bool HasSizeMismatch; 7307 7308 if (!TI.isValidGCCRegisterName(Label)) 7309 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7310 else if (!TI.validateGlobalRegisterVariable(Label, 7311 Context.getTypeSize(R), 7312 HasSizeMismatch)) 7313 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7314 else if (HasSizeMismatch) 7315 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7316 } 7317 7318 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7319 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7320 NewVD->setInvalidDecl(true); 7321 } 7322 } 7323 7324 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7325 /*IsLiteralLabel=*/true, 7326 SE->getStrTokenLoc(0))); 7327 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7328 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7329 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7330 if (I != ExtnameUndeclaredIdentifiers.end()) { 7331 if (isDeclExternC(NewVD)) { 7332 NewVD->addAttr(I->second); 7333 ExtnameUndeclaredIdentifiers.erase(I); 7334 } else 7335 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7336 << /*Variable*/1 << NewVD; 7337 } 7338 } 7339 7340 // Find the shadowed declaration before filtering for scope. 7341 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7342 ? getShadowedDeclaration(NewVD, Previous) 7343 : nullptr; 7344 7345 // Don't consider existing declarations that are in a different 7346 // scope and are out-of-semantic-context declarations (if the new 7347 // declaration has linkage). 7348 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7349 D.getCXXScopeSpec().isNotEmpty() || 7350 IsMemberSpecialization || 7351 IsVariableTemplateSpecialization); 7352 7353 // Check whether the previous declaration is in the same block scope. This 7354 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7355 if (getLangOpts().CPlusPlus && 7356 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7357 NewVD->setPreviousDeclInSameBlockScope( 7358 Previous.isSingleResult() && !Previous.isShadowed() && 7359 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7360 7361 if (!getLangOpts().CPlusPlus) { 7362 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7363 } else { 7364 // If this is an explicit specialization of a static data member, check it. 7365 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7366 CheckMemberSpecialization(NewVD, Previous)) 7367 NewVD->setInvalidDecl(); 7368 7369 // Merge the decl with the existing one if appropriate. 7370 if (!Previous.empty()) { 7371 if (Previous.isSingleResult() && 7372 isa<FieldDecl>(Previous.getFoundDecl()) && 7373 D.getCXXScopeSpec().isSet()) { 7374 // The user tried to define a non-static data member 7375 // out-of-line (C++ [dcl.meaning]p1). 7376 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7377 << D.getCXXScopeSpec().getRange(); 7378 Previous.clear(); 7379 NewVD->setInvalidDecl(); 7380 } 7381 } else if (D.getCXXScopeSpec().isSet()) { 7382 // No previous declaration in the qualifying scope. 7383 Diag(D.getIdentifierLoc(), diag::err_no_member) 7384 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7385 << D.getCXXScopeSpec().getRange(); 7386 NewVD->setInvalidDecl(); 7387 } 7388 7389 if (!IsVariableTemplateSpecialization) 7390 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7391 7392 if (NewTemplate) { 7393 VarTemplateDecl *PrevVarTemplate = 7394 NewVD->getPreviousDecl() 7395 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7396 : nullptr; 7397 7398 // Check the template parameter list of this declaration, possibly 7399 // merging in the template parameter list from the previous variable 7400 // template declaration. 7401 if (CheckTemplateParameterList( 7402 TemplateParams, 7403 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7404 : nullptr, 7405 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7406 DC->isDependentContext()) 7407 ? TPC_ClassTemplateMember 7408 : TPC_VarTemplate)) 7409 NewVD->setInvalidDecl(); 7410 7411 // If we are providing an explicit specialization of a static variable 7412 // template, make a note of that. 7413 if (PrevVarTemplate && 7414 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7415 PrevVarTemplate->setMemberSpecialization(); 7416 } 7417 } 7418 7419 // Diagnose shadowed variables iff this isn't a redeclaration. 7420 if (ShadowedDecl && !D.isRedeclaration()) 7421 CheckShadow(NewVD, ShadowedDecl, Previous); 7422 7423 ProcessPragmaWeak(S, NewVD); 7424 7425 // If this is the first declaration of an extern C variable, update 7426 // the map of such variables. 7427 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7428 isIncompleteDeclExternC(*this, NewVD)) 7429 RegisterLocallyScopedExternCDecl(NewVD, S); 7430 7431 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7432 MangleNumberingContext *MCtx; 7433 Decl *ManglingContextDecl; 7434 std::tie(MCtx, ManglingContextDecl) = 7435 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7436 if (MCtx) { 7437 Context.setManglingNumber( 7438 NewVD, MCtx->getManglingNumber( 7439 NewVD, getMSManglingNumber(getLangOpts(), S))); 7440 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7441 } 7442 } 7443 7444 // Special handling of variable named 'main'. 7445 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7446 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7447 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7448 7449 // C++ [basic.start.main]p3 7450 // A program that declares a variable main at global scope is ill-formed. 7451 if (getLangOpts().CPlusPlus) 7452 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7453 7454 // In C, and external-linkage variable named main results in undefined 7455 // behavior. 7456 else if (NewVD->hasExternalFormalLinkage()) 7457 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7458 } 7459 7460 if (D.isRedeclaration() && !Previous.empty()) { 7461 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7462 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7463 D.isFunctionDefinition()); 7464 } 7465 7466 if (NewTemplate) { 7467 if (NewVD->isInvalidDecl()) 7468 NewTemplate->setInvalidDecl(); 7469 ActOnDocumentableDecl(NewTemplate); 7470 return NewTemplate; 7471 } 7472 7473 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7474 CompleteMemberSpecialization(NewVD, Previous); 7475 7476 return NewVD; 7477 } 7478 7479 /// Enum describing the %select options in diag::warn_decl_shadow. 7480 enum ShadowedDeclKind { 7481 SDK_Local, 7482 SDK_Global, 7483 SDK_StaticMember, 7484 SDK_Field, 7485 SDK_Typedef, 7486 SDK_Using 7487 }; 7488 7489 /// Determine what kind of declaration we're shadowing. 7490 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7491 const DeclContext *OldDC) { 7492 if (isa<TypeAliasDecl>(ShadowedDecl)) 7493 return SDK_Using; 7494 else if (isa<TypedefDecl>(ShadowedDecl)) 7495 return SDK_Typedef; 7496 else if (isa<RecordDecl>(OldDC)) 7497 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7498 7499 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7500 } 7501 7502 /// Return the location of the capture if the given lambda captures the given 7503 /// variable \p VD, or an invalid source location otherwise. 7504 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7505 const VarDecl *VD) { 7506 for (const Capture &Capture : LSI->Captures) { 7507 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7508 return Capture.getLocation(); 7509 } 7510 return SourceLocation(); 7511 } 7512 7513 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7514 const LookupResult &R) { 7515 // Only diagnose if we're shadowing an unambiguous field or variable. 7516 if (R.getResultKind() != LookupResult::Found) 7517 return false; 7518 7519 // Return false if warning is ignored. 7520 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7521 } 7522 7523 /// Return the declaration shadowed by the given variable \p D, or null 7524 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7525 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7526 const LookupResult &R) { 7527 if (!shouldWarnIfShadowedDecl(Diags, R)) 7528 return nullptr; 7529 7530 // Don't diagnose declarations at file scope. 7531 if (D->hasGlobalStorage()) 7532 return nullptr; 7533 7534 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7535 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7536 ? ShadowedDecl 7537 : nullptr; 7538 } 7539 7540 /// Return the declaration shadowed by the given typedef \p D, or null 7541 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7542 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7543 const LookupResult &R) { 7544 // Don't warn if typedef declaration is part of a class 7545 if (D->getDeclContext()->isRecord()) 7546 return nullptr; 7547 7548 if (!shouldWarnIfShadowedDecl(Diags, R)) 7549 return nullptr; 7550 7551 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7552 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7553 } 7554 7555 /// Diagnose variable or built-in function shadowing. Implements 7556 /// -Wshadow. 7557 /// 7558 /// This method is called whenever a VarDecl is added to a "useful" 7559 /// scope. 7560 /// 7561 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7562 /// \param R the lookup of the name 7563 /// 7564 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7565 const LookupResult &R) { 7566 DeclContext *NewDC = D->getDeclContext(); 7567 7568 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7569 // Fields are not shadowed by variables in C++ static methods. 7570 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7571 if (MD->isStatic()) 7572 return; 7573 7574 // Fields shadowed by constructor parameters are a special case. Usually 7575 // the constructor initializes the field with the parameter. 7576 if (isa<CXXConstructorDecl>(NewDC)) 7577 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7578 // Remember that this was shadowed so we can either warn about its 7579 // modification or its existence depending on warning settings. 7580 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7581 return; 7582 } 7583 } 7584 7585 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7586 if (shadowedVar->isExternC()) { 7587 // For shadowing external vars, make sure that we point to the global 7588 // declaration, not a locally scoped extern declaration. 7589 for (auto I : shadowedVar->redecls()) 7590 if (I->isFileVarDecl()) { 7591 ShadowedDecl = I; 7592 break; 7593 } 7594 } 7595 7596 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7597 7598 unsigned WarningDiag = diag::warn_decl_shadow; 7599 SourceLocation CaptureLoc; 7600 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7601 isa<CXXMethodDecl>(NewDC)) { 7602 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7603 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7604 if (RD->getLambdaCaptureDefault() == LCD_None) { 7605 // Try to avoid warnings for lambdas with an explicit capture list. 7606 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7607 // Warn only when the lambda captures the shadowed decl explicitly. 7608 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7609 if (CaptureLoc.isInvalid()) 7610 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7611 } else { 7612 // Remember that this was shadowed so we can avoid the warning if the 7613 // shadowed decl isn't captured and the warning settings allow it. 7614 cast<LambdaScopeInfo>(getCurFunction()) 7615 ->ShadowingDecls.push_back( 7616 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7617 return; 7618 } 7619 } 7620 7621 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7622 // A variable can't shadow a local variable in an enclosing scope, if 7623 // they are separated by a non-capturing declaration context. 7624 for (DeclContext *ParentDC = NewDC; 7625 ParentDC && !ParentDC->Equals(OldDC); 7626 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7627 // Only block literals, captured statements, and lambda expressions 7628 // can capture; other scopes don't. 7629 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7630 !isLambdaCallOperator(ParentDC)) { 7631 return; 7632 } 7633 } 7634 } 7635 } 7636 } 7637 7638 // Only warn about certain kinds of shadowing for class members. 7639 if (NewDC && NewDC->isRecord()) { 7640 // In particular, don't warn about shadowing non-class members. 7641 if (!OldDC->isRecord()) 7642 return; 7643 7644 // TODO: should we warn about static data members shadowing 7645 // static data members from base classes? 7646 7647 // TODO: don't diagnose for inaccessible shadowed members. 7648 // This is hard to do perfectly because we might friend the 7649 // shadowing context, but that's just a false negative. 7650 } 7651 7652 7653 DeclarationName Name = R.getLookupName(); 7654 7655 // Emit warning and note. 7656 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7657 return; 7658 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7659 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7660 if (!CaptureLoc.isInvalid()) 7661 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7662 << Name << /*explicitly*/ 1; 7663 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7664 } 7665 7666 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7667 /// when these variables are captured by the lambda. 7668 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7669 for (const auto &Shadow : LSI->ShadowingDecls) { 7670 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7671 // Try to avoid the warning when the shadowed decl isn't captured. 7672 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7673 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7674 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7675 ? diag::warn_decl_shadow_uncaptured_local 7676 : diag::warn_decl_shadow) 7677 << Shadow.VD->getDeclName() 7678 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7679 if (!CaptureLoc.isInvalid()) 7680 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7681 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7682 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7683 } 7684 } 7685 7686 /// Check -Wshadow without the advantage of a previous lookup. 7687 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7688 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7689 return; 7690 7691 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7692 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7693 LookupName(R, S); 7694 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7695 CheckShadow(D, ShadowedDecl, R); 7696 } 7697 7698 /// Check if 'E', which is an expression that is about to be modified, refers 7699 /// to a constructor parameter that shadows a field. 7700 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7701 // Quickly ignore expressions that can't be shadowing ctor parameters. 7702 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7703 return; 7704 E = E->IgnoreParenImpCasts(); 7705 auto *DRE = dyn_cast<DeclRefExpr>(E); 7706 if (!DRE) 7707 return; 7708 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7709 auto I = ShadowingDecls.find(D); 7710 if (I == ShadowingDecls.end()) 7711 return; 7712 const NamedDecl *ShadowedDecl = I->second; 7713 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7714 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7715 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7716 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7717 7718 // Avoid issuing multiple warnings about the same decl. 7719 ShadowingDecls.erase(I); 7720 } 7721 7722 /// Check for conflict between this global or extern "C" declaration and 7723 /// previous global or extern "C" declarations. This is only used in C++. 7724 template<typename T> 7725 static bool checkGlobalOrExternCConflict( 7726 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7727 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7728 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7729 7730 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7731 // The common case: this global doesn't conflict with any extern "C" 7732 // declaration. 7733 return false; 7734 } 7735 7736 if (Prev) { 7737 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7738 // Both the old and new declarations have C language linkage. This is a 7739 // redeclaration. 7740 Previous.clear(); 7741 Previous.addDecl(Prev); 7742 return true; 7743 } 7744 7745 // This is a global, non-extern "C" declaration, and there is a previous 7746 // non-global extern "C" declaration. Diagnose if this is a variable 7747 // declaration. 7748 if (!isa<VarDecl>(ND)) 7749 return false; 7750 } else { 7751 // The declaration is extern "C". Check for any declaration in the 7752 // translation unit which might conflict. 7753 if (IsGlobal) { 7754 // We have already performed the lookup into the translation unit. 7755 IsGlobal = false; 7756 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7757 I != E; ++I) { 7758 if (isa<VarDecl>(*I)) { 7759 Prev = *I; 7760 break; 7761 } 7762 } 7763 } else { 7764 DeclContext::lookup_result R = 7765 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7766 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7767 I != E; ++I) { 7768 if (isa<VarDecl>(*I)) { 7769 Prev = *I; 7770 break; 7771 } 7772 // FIXME: If we have any other entity with this name in global scope, 7773 // the declaration is ill-formed, but that is a defect: it breaks the 7774 // 'stat' hack, for instance. Only variables can have mangled name 7775 // clashes with extern "C" declarations, so only they deserve a 7776 // diagnostic. 7777 } 7778 } 7779 7780 if (!Prev) 7781 return false; 7782 } 7783 7784 // Use the first declaration's location to ensure we point at something which 7785 // is lexically inside an extern "C" linkage-spec. 7786 assert(Prev && "should have found a previous declaration to diagnose"); 7787 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7788 Prev = FD->getFirstDecl(); 7789 else 7790 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7791 7792 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7793 << IsGlobal << ND; 7794 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7795 << IsGlobal; 7796 return false; 7797 } 7798 7799 /// Apply special rules for handling extern "C" declarations. Returns \c true 7800 /// if we have found that this is a redeclaration of some prior entity. 7801 /// 7802 /// Per C++ [dcl.link]p6: 7803 /// Two declarations [for a function or variable] with C language linkage 7804 /// with the same name that appear in different scopes refer to the same 7805 /// [entity]. An entity with C language linkage shall not be declared with 7806 /// the same name as an entity in global scope. 7807 template<typename T> 7808 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7809 LookupResult &Previous) { 7810 if (!S.getLangOpts().CPlusPlus) { 7811 // In C, when declaring a global variable, look for a corresponding 'extern' 7812 // variable declared in function scope. We don't need this in C++, because 7813 // we find local extern decls in the surrounding file-scope DeclContext. 7814 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7815 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7816 Previous.clear(); 7817 Previous.addDecl(Prev); 7818 return true; 7819 } 7820 } 7821 return false; 7822 } 7823 7824 // A declaration in the translation unit can conflict with an extern "C" 7825 // declaration. 7826 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7827 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7828 7829 // An extern "C" declaration can conflict with a declaration in the 7830 // translation unit or can be a redeclaration of an extern "C" declaration 7831 // in another scope. 7832 if (isIncompleteDeclExternC(S,ND)) 7833 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7834 7835 // Neither global nor extern "C": nothing to do. 7836 return false; 7837 } 7838 7839 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7840 // If the decl is already known invalid, don't check it. 7841 if (NewVD->isInvalidDecl()) 7842 return; 7843 7844 QualType T = NewVD->getType(); 7845 7846 // Defer checking an 'auto' type until its initializer is attached. 7847 if (T->isUndeducedType()) 7848 return; 7849 7850 if (NewVD->hasAttrs()) 7851 CheckAlignasUnderalignment(NewVD); 7852 7853 if (T->isObjCObjectType()) { 7854 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7855 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7856 T = Context.getObjCObjectPointerType(T); 7857 NewVD->setType(T); 7858 } 7859 7860 // Emit an error if an address space was applied to decl with local storage. 7861 // This includes arrays of objects with address space qualifiers, but not 7862 // automatic variables that point to other address spaces. 7863 // ISO/IEC TR 18037 S5.1.2 7864 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7865 T.getAddressSpace() != LangAS::Default) { 7866 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7867 NewVD->setInvalidDecl(); 7868 return; 7869 } 7870 7871 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7872 // scope. 7873 if (getLangOpts().OpenCLVersion == 120 && 7874 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7875 NewVD->isStaticLocal()) { 7876 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7877 NewVD->setInvalidDecl(); 7878 return; 7879 } 7880 7881 if (getLangOpts().OpenCL) { 7882 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7883 if (NewVD->hasAttr<BlocksAttr>()) { 7884 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7885 return; 7886 } 7887 7888 if (T->isBlockPointerType()) { 7889 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7890 // can't use 'extern' storage class. 7891 if (!T.isConstQualified()) { 7892 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7893 << 0 /*const*/; 7894 NewVD->setInvalidDecl(); 7895 return; 7896 } 7897 if (NewVD->hasExternalStorage()) { 7898 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7899 NewVD->setInvalidDecl(); 7900 return; 7901 } 7902 } 7903 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7904 // __constant address space. 7905 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7906 // variables inside a function can also be declared in the global 7907 // address space. 7908 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7909 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7910 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7911 NewVD->hasExternalStorage()) { 7912 if (!T->isSamplerT() && 7913 !T->isDependentType() && 7914 !(T.getAddressSpace() == LangAS::opencl_constant || 7915 (T.getAddressSpace() == LangAS::opencl_global && 7916 (getLangOpts().OpenCLVersion == 200 || 7917 getLangOpts().OpenCLCPlusPlus)))) { 7918 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7919 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7920 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7921 << Scope << "global or constant"; 7922 else 7923 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7924 << Scope << "constant"; 7925 NewVD->setInvalidDecl(); 7926 return; 7927 } 7928 } else { 7929 if (T.getAddressSpace() == LangAS::opencl_global) { 7930 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7931 << 1 /*is any function*/ << "global"; 7932 NewVD->setInvalidDecl(); 7933 return; 7934 } 7935 if (T.getAddressSpace() == LangAS::opencl_constant || 7936 T.getAddressSpace() == LangAS::opencl_local) { 7937 FunctionDecl *FD = getCurFunctionDecl(); 7938 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7939 // in functions. 7940 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7941 if (T.getAddressSpace() == LangAS::opencl_constant) 7942 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7943 << 0 /*non-kernel only*/ << "constant"; 7944 else 7945 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7946 << 0 /*non-kernel only*/ << "local"; 7947 NewVD->setInvalidDecl(); 7948 return; 7949 } 7950 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7951 // in the outermost scope of a kernel function. 7952 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7953 if (!getCurScope()->isFunctionScope()) { 7954 if (T.getAddressSpace() == LangAS::opencl_constant) 7955 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7956 << "constant"; 7957 else 7958 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7959 << "local"; 7960 NewVD->setInvalidDecl(); 7961 return; 7962 } 7963 } 7964 } else if (T.getAddressSpace() != LangAS::opencl_private && 7965 // If we are parsing a template we didn't deduce an addr 7966 // space yet. 7967 T.getAddressSpace() != LangAS::Default) { 7968 // Do not allow other address spaces on automatic variable. 7969 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7970 NewVD->setInvalidDecl(); 7971 return; 7972 } 7973 } 7974 } 7975 7976 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7977 && !NewVD->hasAttr<BlocksAttr>()) { 7978 if (getLangOpts().getGC() != LangOptions::NonGC) 7979 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7980 else { 7981 assert(!getLangOpts().ObjCAutoRefCount); 7982 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7983 } 7984 } 7985 7986 bool isVM = T->isVariablyModifiedType(); 7987 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7988 NewVD->hasAttr<BlocksAttr>()) 7989 setFunctionHasBranchProtectedScope(); 7990 7991 if ((isVM && NewVD->hasLinkage()) || 7992 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7993 bool SizeIsNegative; 7994 llvm::APSInt Oversized; 7995 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7996 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7997 QualType FixedT; 7998 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7999 FixedT = FixedTInfo->getType(); 8000 else if (FixedTInfo) { 8001 // Type and type-as-written are canonically different. We need to fix up 8002 // both types separately. 8003 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8004 Oversized); 8005 } 8006 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8007 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8008 // FIXME: This won't give the correct result for 8009 // int a[10][n]; 8010 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8011 8012 if (NewVD->isFileVarDecl()) 8013 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8014 << SizeRange; 8015 else if (NewVD->isStaticLocal()) 8016 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8017 << SizeRange; 8018 else 8019 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8020 << SizeRange; 8021 NewVD->setInvalidDecl(); 8022 return; 8023 } 8024 8025 if (!FixedTInfo) { 8026 if (NewVD->isFileVarDecl()) 8027 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8028 else 8029 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8030 NewVD->setInvalidDecl(); 8031 return; 8032 } 8033 8034 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8035 NewVD->setType(FixedT); 8036 NewVD->setTypeSourceInfo(FixedTInfo); 8037 } 8038 8039 if (T->isVoidType()) { 8040 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8041 // of objects and functions. 8042 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8043 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8044 << T; 8045 NewVD->setInvalidDecl(); 8046 return; 8047 } 8048 } 8049 8050 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8051 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8052 NewVD->setInvalidDecl(); 8053 return; 8054 } 8055 8056 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8057 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8058 NewVD->setInvalidDecl(); 8059 return; 8060 } 8061 8062 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8063 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8064 NewVD->setInvalidDecl(); 8065 return; 8066 } 8067 8068 if (NewVD->isConstexpr() && !T->isDependentType() && 8069 RequireLiteralType(NewVD->getLocation(), T, 8070 diag::err_constexpr_var_non_literal)) { 8071 NewVD->setInvalidDecl(); 8072 return; 8073 } 8074 8075 // PPC MMA non-pointer types are not allowed as non-local variable types. 8076 if (Context.getTargetInfo().getTriple().isPPC64() && 8077 !NewVD->isLocalVarDecl() && 8078 CheckPPCMMAType(T, NewVD->getLocation())) { 8079 NewVD->setInvalidDecl(); 8080 return; 8081 } 8082 } 8083 8084 /// Perform semantic checking on a newly-created variable 8085 /// declaration. 8086 /// 8087 /// This routine performs all of the type-checking required for a 8088 /// variable declaration once it has been built. It is used both to 8089 /// check variables after they have been parsed and their declarators 8090 /// have been translated into a declaration, and to check variables 8091 /// that have been instantiated from a template. 8092 /// 8093 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8094 /// 8095 /// Returns true if the variable declaration is a redeclaration. 8096 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8097 CheckVariableDeclarationType(NewVD); 8098 8099 // If the decl is already known invalid, don't check it. 8100 if (NewVD->isInvalidDecl()) 8101 return false; 8102 8103 // If we did not find anything by this name, look for a non-visible 8104 // extern "C" declaration with the same name. 8105 if (Previous.empty() && 8106 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8107 Previous.setShadowed(); 8108 8109 if (!Previous.empty()) { 8110 MergeVarDecl(NewVD, Previous); 8111 return true; 8112 } 8113 return false; 8114 } 8115 8116 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8117 /// and if so, check that it's a valid override and remember it. 8118 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8119 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8120 8121 // Look for methods in base classes that this method might override. 8122 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8123 /*DetectVirtual=*/false); 8124 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8125 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8126 DeclarationName Name = MD->getDeclName(); 8127 8128 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8129 // We really want to find the base class destructor here. 8130 QualType T = Context.getTypeDeclType(BaseRecord); 8131 CanQualType CT = Context.getCanonicalType(T); 8132 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8133 } 8134 8135 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8136 CXXMethodDecl *BaseMD = 8137 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8138 if (!BaseMD || !BaseMD->isVirtual() || 8139 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8140 /*ConsiderCudaAttrs=*/true, 8141 // C++2a [class.virtual]p2 does not consider requires 8142 // clauses when overriding. 8143 /*ConsiderRequiresClauses=*/false)) 8144 continue; 8145 8146 if (Overridden.insert(BaseMD).second) { 8147 MD->addOverriddenMethod(BaseMD); 8148 CheckOverridingFunctionReturnType(MD, BaseMD); 8149 CheckOverridingFunctionAttributes(MD, BaseMD); 8150 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8151 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8152 } 8153 8154 // A method can only override one function from each base class. We 8155 // don't track indirectly overridden methods from bases of bases. 8156 return true; 8157 } 8158 8159 return false; 8160 }; 8161 8162 DC->lookupInBases(VisitBase, Paths); 8163 return !Overridden.empty(); 8164 } 8165 8166 namespace { 8167 // Struct for holding all of the extra arguments needed by 8168 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8169 struct ActOnFDArgs { 8170 Scope *S; 8171 Declarator &D; 8172 MultiTemplateParamsArg TemplateParamLists; 8173 bool AddToScope; 8174 }; 8175 } // end anonymous namespace 8176 8177 namespace { 8178 8179 // Callback to only accept typo corrections that have a non-zero edit distance. 8180 // Also only accept corrections that have the same parent decl. 8181 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8182 public: 8183 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8184 CXXRecordDecl *Parent) 8185 : Context(Context), OriginalFD(TypoFD), 8186 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8187 8188 bool ValidateCandidate(const TypoCorrection &candidate) override { 8189 if (candidate.getEditDistance() == 0) 8190 return false; 8191 8192 SmallVector<unsigned, 1> MismatchedParams; 8193 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8194 CDeclEnd = candidate.end(); 8195 CDecl != CDeclEnd; ++CDecl) { 8196 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8197 8198 if (FD && !FD->hasBody() && 8199 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8200 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8201 CXXRecordDecl *Parent = MD->getParent(); 8202 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8203 return true; 8204 } else if (!ExpectedParent) { 8205 return true; 8206 } 8207 } 8208 } 8209 8210 return false; 8211 } 8212 8213 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8214 return std::make_unique<DifferentNameValidatorCCC>(*this); 8215 } 8216 8217 private: 8218 ASTContext &Context; 8219 FunctionDecl *OriginalFD; 8220 CXXRecordDecl *ExpectedParent; 8221 }; 8222 8223 } // end anonymous namespace 8224 8225 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8226 TypoCorrectedFunctionDefinitions.insert(F); 8227 } 8228 8229 /// Generate diagnostics for an invalid function redeclaration. 8230 /// 8231 /// This routine handles generating the diagnostic messages for an invalid 8232 /// function redeclaration, including finding possible similar declarations 8233 /// or performing typo correction if there are no previous declarations with 8234 /// the same name. 8235 /// 8236 /// Returns a NamedDecl iff typo correction was performed and substituting in 8237 /// the new declaration name does not cause new errors. 8238 static NamedDecl *DiagnoseInvalidRedeclaration( 8239 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8240 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8241 DeclarationName Name = NewFD->getDeclName(); 8242 DeclContext *NewDC = NewFD->getDeclContext(); 8243 SmallVector<unsigned, 1> MismatchedParams; 8244 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8245 TypoCorrection Correction; 8246 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8247 unsigned DiagMsg = 8248 IsLocalFriend ? diag::err_no_matching_local_friend : 8249 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8250 diag::err_member_decl_does_not_match; 8251 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8252 IsLocalFriend ? Sema::LookupLocalFriendName 8253 : Sema::LookupOrdinaryName, 8254 Sema::ForVisibleRedeclaration); 8255 8256 NewFD->setInvalidDecl(); 8257 if (IsLocalFriend) 8258 SemaRef.LookupName(Prev, S); 8259 else 8260 SemaRef.LookupQualifiedName(Prev, NewDC); 8261 assert(!Prev.isAmbiguous() && 8262 "Cannot have an ambiguity in previous-declaration lookup"); 8263 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8264 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8265 MD ? MD->getParent() : nullptr); 8266 if (!Prev.empty()) { 8267 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8268 Func != FuncEnd; ++Func) { 8269 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8270 if (FD && 8271 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8272 // Add 1 to the index so that 0 can mean the mismatch didn't 8273 // involve a parameter 8274 unsigned ParamNum = 8275 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8276 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8277 } 8278 } 8279 // If the qualified name lookup yielded nothing, try typo correction 8280 } else if ((Correction = SemaRef.CorrectTypo( 8281 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8282 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8283 IsLocalFriend ? nullptr : NewDC))) { 8284 // Set up everything for the call to ActOnFunctionDeclarator 8285 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8286 ExtraArgs.D.getIdentifierLoc()); 8287 Previous.clear(); 8288 Previous.setLookupName(Correction.getCorrection()); 8289 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8290 CDeclEnd = Correction.end(); 8291 CDecl != CDeclEnd; ++CDecl) { 8292 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8293 if (FD && !FD->hasBody() && 8294 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8295 Previous.addDecl(FD); 8296 } 8297 } 8298 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8299 8300 NamedDecl *Result; 8301 // Retry building the function declaration with the new previous 8302 // declarations, and with errors suppressed. 8303 { 8304 // Trap errors. 8305 Sema::SFINAETrap Trap(SemaRef); 8306 8307 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8308 // pieces need to verify the typo-corrected C++ declaration and hopefully 8309 // eliminate the need for the parameter pack ExtraArgs. 8310 Result = SemaRef.ActOnFunctionDeclarator( 8311 ExtraArgs.S, ExtraArgs.D, 8312 Correction.getCorrectionDecl()->getDeclContext(), 8313 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8314 ExtraArgs.AddToScope); 8315 8316 if (Trap.hasErrorOccurred()) 8317 Result = nullptr; 8318 } 8319 8320 if (Result) { 8321 // Determine which correction we picked. 8322 Decl *Canonical = Result->getCanonicalDecl(); 8323 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8324 I != E; ++I) 8325 if ((*I)->getCanonicalDecl() == Canonical) 8326 Correction.setCorrectionDecl(*I); 8327 8328 // Let Sema know about the correction. 8329 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8330 SemaRef.diagnoseTypo( 8331 Correction, 8332 SemaRef.PDiag(IsLocalFriend 8333 ? diag::err_no_matching_local_friend_suggest 8334 : diag::err_member_decl_does_not_match_suggest) 8335 << Name << NewDC << IsDefinition); 8336 return Result; 8337 } 8338 8339 // Pretend the typo correction never occurred 8340 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8341 ExtraArgs.D.getIdentifierLoc()); 8342 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8343 Previous.clear(); 8344 Previous.setLookupName(Name); 8345 } 8346 8347 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8348 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8349 8350 bool NewFDisConst = false; 8351 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8352 NewFDisConst = NewMD->isConst(); 8353 8354 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8355 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8356 NearMatch != NearMatchEnd; ++NearMatch) { 8357 FunctionDecl *FD = NearMatch->first; 8358 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8359 bool FDisConst = MD && MD->isConst(); 8360 bool IsMember = MD || !IsLocalFriend; 8361 8362 // FIXME: These notes are poorly worded for the local friend case. 8363 if (unsigned Idx = NearMatch->second) { 8364 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8365 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8366 if (Loc.isInvalid()) Loc = FD->getLocation(); 8367 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8368 : diag::note_local_decl_close_param_match) 8369 << Idx << FDParam->getType() 8370 << NewFD->getParamDecl(Idx - 1)->getType(); 8371 } else if (FDisConst != NewFDisConst) { 8372 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8373 << NewFDisConst << FD->getSourceRange().getEnd(); 8374 } else 8375 SemaRef.Diag(FD->getLocation(), 8376 IsMember ? diag::note_member_def_close_match 8377 : diag::note_local_decl_close_match); 8378 } 8379 return nullptr; 8380 } 8381 8382 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8383 switch (D.getDeclSpec().getStorageClassSpec()) { 8384 default: llvm_unreachable("Unknown storage class!"); 8385 case DeclSpec::SCS_auto: 8386 case DeclSpec::SCS_register: 8387 case DeclSpec::SCS_mutable: 8388 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8389 diag::err_typecheck_sclass_func); 8390 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8391 D.setInvalidType(); 8392 break; 8393 case DeclSpec::SCS_unspecified: break; 8394 case DeclSpec::SCS_extern: 8395 if (D.getDeclSpec().isExternInLinkageSpec()) 8396 return SC_None; 8397 return SC_Extern; 8398 case DeclSpec::SCS_static: { 8399 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8400 // C99 6.7.1p5: 8401 // The declaration of an identifier for a function that has 8402 // block scope shall have no explicit storage-class specifier 8403 // other than extern 8404 // See also (C++ [dcl.stc]p4). 8405 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8406 diag::err_static_block_func); 8407 break; 8408 } else 8409 return SC_Static; 8410 } 8411 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8412 } 8413 8414 // No explicit storage class has already been returned 8415 return SC_None; 8416 } 8417 8418 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8419 DeclContext *DC, QualType &R, 8420 TypeSourceInfo *TInfo, 8421 StorageClass SC, 8422 bool &IsVirtualOkay) { 8423 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8424 DeclarationName Name = NameInfo.getName(); 8425 8426 FunctionDecl *NewFD = nullptr; 8427 bool isInline = D.getDeclSpec().isInlineSpecified(); 8428 8429 if (!SemaRef.getLangOpts().CPlusPlus) { 8430 // Determine whether the function was written with a 8431 // prototype. This true when: 8432 // - there is a prototype in the declarator, or 8433 // - the type R of the function is some kind of typedef or other non- 8434 // attributed reference to a type name (which eventually refers to a 8435 // function type). 8436 bool HasPrototype = 8437 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8438 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8439 8440 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8441 R, TInfo, SC, isInline, HasPrototype, 8442 ConstexprSpecKind::Unspecified, 8443 /*TrailingRequiresClause=*/nullptr); 8444 if (D.isInvalidType()) 8445 NewFD->setInvalidDecl(); 8446 8447 return NewFD; 8448 } 8449 8450 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8451 8452 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8453 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8454 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8455 diag::err_constexpr_wrong_decl_kind) 8456 << static_cast<int>(ConstexprKind); 8457 ConstexprKind = ConstexprSpecKind::Unspecified; 8458 D.getMutableDeclSpec().ClearConstexprSpec(); 8459 } 8460 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8461 8462 // Check that the return type is not an abstract class type. 8463 // For record types, this is done by the AbstractClassUsageDiagnoser once 8464 // the class has been completely parsed. 8465 if (!DC->isRecord() && 8466 SemaRef.RequireNonAbstractType( 8467 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8468 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8469 D.setInvalidType(); 8470 8471 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8472 // This is a C++ constructor declaration. 8473 assert(DC->isRecord() && 8474 "Constructors can only be declared in a member context"); 8475 8476 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8477 return CXXConstructorDecl::Create( 8478 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8479 TInfo, ExplicitSpecifier, isInline, 8480 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8481 TrailingRequiresClause); 8482 8483 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8484 // This is a C++ destructor declaration. 8485 if (DC->isRecord()) { 8486 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8487 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8488 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8489 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8490 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8491 TrailingRequiresClause); 8492 8493 // If the destructor needs an implicit exception specification, set it 8494 // now. FIXME: It'd be nice to be able to create the right type to start 8495 // with, but the type needs to reference the destructor declaration. 8496 if (SemaRef.getLangOpts().CPlusPlus11) 8497 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8498 8499 IsVirtualOkay = true; 8500 return NewDD; 8501 8502 } else { 8503 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8504 D.setInvalidType(); 8505 8506 // Create a FunctionDecl to satisfy the function definition parsing 8507 // code path. 8508 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8509 D.getIdentifierLoc(), Name, R, TInfo, SC, 8510 isInline, 8511 /*hasPrototype=*/true, ConstexprKind, 8512 TrailingRequiresClause); 8513 } 8514 8515 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8516 if (!DC->isRecord()) { 8517 SemaRef.Diag(D.getIdentifierLoc(), 8518 diag::err_conv_function_not_member); 8519 return nullptr; 8520 } 8521 8522 SemaRef.CheckConversionDeclarator(D, R, SC); 8523 if (D.isInvalidType()) 8524 return nullptr; 8525 8526 IsVirtualOkay = true; 8527 return CXXConversionDecl::Create( 8528 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8529 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8530 TrailingRequiresClause); 8531 8532 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8533 if (TrailingRequiresClause) 8534 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8535 diag::err_trailing_requires_clause_on_deduction_guide) 8536 << TrailingRequiresClause->getSourceRange(); 8537 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8538 8539 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8540 ExplicitSpecifier, NameInfo, R, TInfo, 8541 D.getEndLoc()); 8542 } else if (DC->isRecord()) { 8543 // If the name of the function is the same as the name of the record, 8544 // then this must be an invalid constructor that has a return type. 8545 // (The parser checks for a return type and makes the declarator a 8546 // constructor if it has no return type). 8547 if (Name.getAsIdentifierInfo() && 8548 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8549 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8550 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8551 << SourceRange(D.getIdentifierLoc()); 8552 return nullptr; 8553 } 8554 8555 // This is a C++ method declaration. 8556 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8557 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8558 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8559 TrailingRequiresClause); 8560 IsVirtualOkay = !Ret->isStatic(); 8561 return Ret; 8562 } else { 8563 bool isFriend = 8564 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8565 if (!isFriend && SemaRef.CurContext->isRecord()) 8566 return nullptr; 8567 8568 // Determine whether the function was written with a 8569 // prototype. This true when: 8570 // - we're in C++ (where every function has a prototype), 8571 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8572 R, TInfo, SC, isInline, true /*HasPrototype*/, 8573 ConstexprKind, TrailingRequiresClause); 8574 } 8575 } 8576 8577 enum OpenCLParamType { 8578 ValidKernelParam, 8579 PtrPtrKernelParam, 8580 PtrKernelParam, 8581 InvalidAddrSpacePtrKernelParam, 8582 InvalidKernelParam, 8583 RecordKernelParam 8584 }; 8585 8586 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8587 // Size dependent types are just typedefs to normal integer types 8588 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8589 // integers other than by their names. 8590 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8591 8592 // Remove typedefs one by one until we reach a typedef 8593 // for a size dependent type. 8594 QualType DesugaredTy = Ty; 8595 do { 8596 ArrayRef<StringRef> Names(SizeTypeNames); 8597 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8598 if (Names.end() != Match) 8599 return true; 8600 8601 Ty = DesugaredTy; 8602 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8603 } while (DesugaredTy != Ty); 8604 8605 return false; 8606 } 8607 8608 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8609 if (PT->isPointerType()) { 8610 QualType PointeeType = PT->getPointeeType(); 8611 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8612 PointeeType.getAddressSpace() == LangAS::opencl_private || 8613 PointeeType.getAddressSpace() == LangAS::Default) 8614 return InvalidAddrSpacePtrKernelParam; 8615 8616 if (PointeeType->isPointerType()) { 8617 // This is a pointer to pointer parameter. 8618 // Recursively check inner type. 8619 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 8620 if (ParamKind == InvalidAddrSpacePtrKernelParam || 8621 ParamKind == InvalidKernelParam) 8622 return ParamKind; 8623 8624 return PtrPtrKernelParam; 8625 } 8626 return PtrKernelParam; 8627 } 8628 8629 // OpenCL v1.2 s6.9.k: 8630 // Arguments to kernel functions in a program cannot be declared with the 8631 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8632 // uintptr_t or a struct and/or union that contain fields declared to be one 8633 // of these built-in scalar types. 8634 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8635 return InvalidKernelParam; 8636 8637 if (PT->isImageType()) 8638 return PtrKernelParam; 8639 8640 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8641 return InvalidKernelParam; 8642 8643 // OpenCL extension spec v1.2 s9.5: 8644 // This extension adds support for half scalar and vector types as built-in 8645 // types that can be used for arithmetic operations, conversions etc. 8646 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8647 return InvalidKernelParam; 8648 8649 if (PT->isRecordType()) 8650 return RecordKernelParam; 8651 8652 // Look into an array argument to check if it has a forbidden type. 8653 if (PT->isArrayType()) { 8654 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8655 // Call ourself to check an underlying type of an array. Since the 8656 // getPointeeOrArrayElementType returns an innermost type which is not an 8657 // array, this recursive call only happens once. 8658 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8659 } 8660 8661 return ValidKernelParam; 8662 } 8663 8664 static void checkIsValidOpenCLKernelParameter( 8665 Sema &S, 8666 Declarator &D, 8667 ParmVarDecl *Param, 8668 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8669 QualType PT = Param->getType(); 8670 8671 // Cache the valid types we encounter to avoid rechecking structs that are 8672 // used again 8673 if (ValidTypes.count(PT.getTypePtr())) 8674 return; 8675 8676 switch (getOpenCLKernelParameterType(S, PT)) { 8677 case PtrPtrKernelParam: 8678 // OpenCL v3.0 s6.11.a: 8679 // A kernel function argument cannot be declared as a pointer to a pointer 8680 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 8681 if (S.getLangOpts().OpenCLVersion < 120 && 8682 !S.getLangOpts().OpenCLCPlusPlus) { 8683 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8684 D.setInvalidType(); 8685 return; 8686 } 8687 8688 ValidTypes.insert(PT.getTypePtr()); 8689 return; 8690 8691 case InvalidAddrSpacePtrKernelParam: 8692 // OpenCL v1.0 s6.5: 8693 // __kernel function arguments declared to be a pointer of a type can point 8694 // to one of the following address spaces only : __global, __local or 8695 // __constant. 8696 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8697 D.setInvalidType(); 8698 return; 8699 8700 // OpenCL v1.2 s6.9.k: 8701 // Arguments to kernel functions in a program cannot be declared with the 8702 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8703 // uintptr_t or a struct and/or union that contain fields declared to be 8704 // one of these built-in scalar types. 8705 8706 case InvalidKernelParam: 8707 // OpenCL v1.2 s6.8 n: 8708 // A kernel function argument cannot be declared 8709 // of event_t type. 8710 // Do not diagnose half type since it is diagnosed as invalid argument 8711 // type for any function elsewhere. 8712 if (!PT->isHalfType()) { 8713 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8714 8715 // Explain what typedefs are involved. 8716 const TypedefType *Typedef = nullptr; 8717 while ((Typedef = PT->getAs<TypedefType>())) { 8718 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8719 // SourceLocation may be invalid for a built-in type. 8720 if (Loc.isValid()) 8721 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8722 PT = Typedef->desugar(); 8723 } 8724 } 8725 8726 D.setInvalidType(); 8727 return; 8728 8729 case PtrKernelParam: 8730 case ValidKernelParam: 8731 ValidTypes.insert(PT.getTypePtr()); 8732 return; 8733 8734 case RecordKernelParam: 8735 break; 8736 } 8737 8738 // Track nested structs we will inspect 8739 SmallVector<const Decl *, 4> VisitStack; 8740 8741 // Track where we are in the nested structs. Items will migrate from 8742 // VisitStack to HistoryStack as we do the DFS for bad field. 8743 SmallVector<const FieldDecl *, 4> HistoryStack; 8744 HistoryStack.push_back(nullptr); 8745 8746 // At this point we already handled everything except of a RecordType or 8747 // an ArrayType of a RecordType. 8748 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8749 const RecordType *RecTy = 8750 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8751 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8752 8753 VisitStack.push_back(RecTy->getDecl()); 8754 assert(VisitStack.back() && "First decl null?"); 8755 8756 do { 8757 const Decl *Next = VisitStack.pop_back_val(); 8758 if (!Next) { 8759 assert(!HistoryStack.empty()); 8760 // Found a marker, we have gone up a level 8761 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8762 ValidTypes.insert(Hist->getType().getTypePtr()); 8763 8764 continue; 8765 } 8766 8767 // Adds everything except the original parameter declaration (which is not a 8768 // field itself) to the history stack. 8769 const RecordDecl *RD; 8770 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8771 HistoryStack.push_back(Field); 8772 8773 QualType FieldTy = Field->getType(); 8774 // Other field types (known to be valid or invalid) are handled while we 8775 // walk around RecordDecl::fields(). 8776 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8777 "Unexpected type."); 8778 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8779 8780 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8781 } else { 8782 RD = cast<RecordDecl>(Next); 8783 } 8784 8785 // Add a null marker so we know when we've gone back up a level 8786 VisitStack.push_back(nullptr); 8787 8788 for (const auto *FD : RD->fields()) { 8789 QualType QT = FD->getType(); 8790 8791 if (ValidTypes.count(QT.getTypePtr())) 8792 continue; 8793 8794 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8795 if (ParamType == ValidKernelParam) 8796 continue; 8797 8798 if (ParamType == RecordKernelParam) { 8799 VisitStack.push_back(FD); 8800 continue; 8801 } 8802 8803 // OpenCL v1.2 s6.9.p: 8804 // Arguments to kernel functions that are declared to be a struct or union 8805 // do not allow OpenCL objects to be passed as elements of the struct or 8806 // union. 8807 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8808 ParamType == InvalidAddrSpacePtrKernelParam) { 8809 S.Diag(Param->getLocation(), 8810 diag::err_record_with_pointers_kernel_param) 8811 << PT->isUnionType() 8812 << PT; 8813 } else { 8814 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8815 } 8816 8817 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8818 << OrigRecDecl->getDeclName(); 8819 8820 // We have an error, now let's go back up through history and show where 8821 // the offending field came from 8822 for (ArrayRef<const FieldDecl *>::const_iterator 8823 I = HistoryStack.begin() + 1, 8824 E = HistoryStack.end(); 8825 I != E; ++I) { 8826 const FieldDecl *OuterField = *I; 8827 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8828 << OuterField->getType(); 8829 } 8830 8831 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8832 << QT->isPointerType() 8833 << QT; 8834 D.setInvalidType(); 8835 return; 8836 } 8837 } while (!VisitStack.empty()); 8838 } 8839 8840 /// Find the DeclContext in which a tag is implicitly declared if we see an 8841 /// elaborated type specifier in the specified context, and lookup finds 8842 /// nothing. 8843 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8844 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8845 DC = DC->getParent(); 8846 return DC; 8847 } 8848 8849 /// Find the Scope in which a tag is implicitly declared if we see an 8850 /// elaborated type specifier in the specified context, and lookup finds 8851 /// nothing. 8852 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8853 while (S->isClassScope() || 8854 (LangOpts.CPlusPlus && 8855 S->isFunctionPrototypeScope()) || 8856 ((S->getFlags() & Scope::DeclScope) == 0) || 8857 (S->getEntity() && S->getEntity()->isTransparentContext())) 8858 S = S->getParent(); 8859 return S; 8860 } 8861 8862 NamedDecl* 8863 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8864 TypeSourceInfo *TInfo, LookupResult &Previous, 8865 MultiTemplateParamsArg TemplateParamListsRef, 8866 bool &AddToScope) { 8867 QualType R = TInfo->getType(); 8868 8869 assert(R->isFunctionType()); 8870 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 8871 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 8872 8873 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8874 for (TemplateParameterList *TPL : TemplateParamListsRef) 8875 TemplateParamLists.push_back(TPL); 8876 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8877 if (!TemplateParamLists.empty() && 8878 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8879 TemplateParamLists.back() = Invented; 8880 else 8881 TemplateParamLists.push_back(Invented); 8882 } 8883 8884 // TODO: consider using NameInfo for diagnostic. 8885 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8886 DeclarationName Name = NameInfo.getName(); 8887 StorageClass SC = getFunctionStorageClass(*this, D); 8888 8889 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8890 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8891 diag::err_invalid_thread) 8892 << DeclSpec::getSpecifierName(TSCS); 8893 8894 if (D.isFirstDeclarationOfMember()) 8895 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8896 D.getIdentifierLoc()); 8897 8898 bool isFriend = false; 8899 FunctionTemplateDecl *FunctionTemplate = nullptr; 8900 bool isMemberSpecialization = false; 8901 bool isFunctionTemplateSpecialization = false; 8902 8903 bool isDependentClassScopeExplicitSpecialization = false; 8904 bool HasExplicitTemplateArgs = false; 8905 TemplateArgumentListInfo TemplateArgs; 8906 8907 bool isVirtualOkay = false; 8908 8909 DeclContext *OriginalDC = DC; 8910 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8911 8912 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8913 isVirtualOkay); 8914 if (!NewFD) return nullptr; 8915 8916 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8917 NewFD->setTopLevelDeclInObjCContainer(); 8918 8919 // Set the lexical context. If this is a function-scope declaration, or has a 8920 // C++ scope specifier, or is the object of a friend declaration, the lexical 8921 // context will be different from the semantic context. 8922 NewFD->setLexicalDeclContext(CurContext); 8923 8924 if (IsLocalExternDecl) 8925 NewFD->setLocalExternDecl(); 8926 8927 if (getLangOpts().CPlusPlus) { 8928 bool isInline = D.getDeclSpec().isInlineSpecified(); 8929 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8930 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8931 isFriend = D.getDeclSpec().isFriendSpecified(); 8932 if (isFriend && !isInline && D.isFunctionDefinition()) { 8933 // C++ [class.friend]p5 8934 // A function can be defined in a friend declaration of a 8935 // class . . . . Such a function is implicitly inline. 8936 NewFD->setImplicitlyInline(); 8937 } 8938 8939 // If this is a method defined in an __interface, and is not a constructor 8940 // or an overloaded operator, then set the pure flag (isVirtual will already 8941 // return true). 8942 if (const CXXRecordDecl *Parent = 8943 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8944 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8945 NewFD->setPure(true); 8946 8947 // C++ [class.union]p2 8948 // A union can have member functions, but not virtual functions. 8949 if (isVirtual && Parent->isUnion()) 8950 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8951 } 8952 8953 SetNestedNameSpecifier(*this, NewFD, D); 8954 isMemberSpecialization = false; 8955 isFunctionTemplateSpecialization = false; 8956 if (D.isInvalidType()) 8957 NewFD->setInvalidDecl(); 8958 8959 // Match up the template parameter lists with the scope specifier, then 8960 // determine whether we have a template or a template specialization. 8961 bool Invalid = false; 8962 TemplateParameterList *TemplateParams = 8963 MatchTemplateParametersToScopeSpecifier( 8964 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8965 D.getCXXScopeSpec(), 8966 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8967 ? D.getName().TemplateId 8968 : nullptr, 8969 TemplateParamLists, isFriend, isMemberSpecialization, 8970 Invalid); 8971 if (TemplateParams) { 8972 // Check that we can declare a template here. 8973 if (CheckTemplateDeclScope(S, TemplateParams)) 8974 NewFD->setInvalidDecl(); 8975 8976 if (TemplateParams->size() > 0) { 8977 // This is a function template 8978 8979 // A destructor cannot be a template. 8980 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8981 Diag(NewFD->getLocation(), diag::err_destructor_template); 8982 NewFD->setInvalidDecl(); 8983 } 8984 8985 // If we're adding a template to a dependent context, we may need to 8986 // rebuilding some of the types used within the template parameter list, 8987 // now that we know what the current instantiation is. 8988 if (DC->isDependentContext()) { 8989 ContextRAII SavedContext(*this, DC); 8990 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8991 Invalid = true; 8992 } 8993 8994 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8995 NewFD->getLocation(), 8996 Name, TemplateParams, 8997 NewFD); 8998 FunctionTemplate->setLexicalDeclContext(CurContext); 8999 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9000 9001 // For source fidelity, store the other template param lists. 9002 if (TemplateParamLists.size() > 1) { 9003 NewFD->setTemplateParameterListsInfo(Context, 9004 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9005 .drop_back(1)); 9006 } 9007 } else { 9008 // This is a function template specialization. 9009 isFunctionTemplateSpecialization = true; 9010 // For source fidelity, store all the template param lists. 9011 if (TemplateParamLists.size() > 0) 9012 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9013 9014 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9015 if (isFriend) { 9016 // We want to remove the "template<>", found here. 9017 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9018 9019 // If we remove the template<> and the name is not a 9020 // template-id, we're actually silently creating a problem: 9021 // the friend declaration will refer to an untemplated decl, 9022 // and clearly the user wants a template specialization. So 9023 // we need to insert '<>' after the name. 9024 SourceLocation InsertLoc; 9025 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9026 InsertLoc = D.getName().getSourceRange().getEnd(); 9027 InsertLoc = getLocForEndOfToken(InsertLoc); 9028 } 9029 9030 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9031 << Name << RemoveRange 9032 << FixItHint::CreateRemoval(RemoveRange) 9033 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9034 } 9035 } 9036 } else { 9037 // Check that we can declare a template here. 9038 if (!TemplateParamLists.empty() && isMemberSpecialization && 9039 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9040 NewFD->setInvalidDecl(); 9041 9042 // All template param lists were matched against the scope specifier: 9043 // this is NOT (an explicit specialization of) a template. 9044 if (TemplateParamLists.size() > 0) 9045 // For source fidelity, store all the template param lists. 9046 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9047 } 9048 9049 if (Invalid) { 9050 NewFD->setInvalidDecl(); 9051 if (FunctionTemplate) 9052 FunctionTemplate->setInvalidDecl(); 9053 } 9054 9055 // C++ [dcl.fct.spec]p5: 9056 // The virtual specifier shall only be used in declarations of 9057 // nonstatic class member functions that appear within a 9058 // member-specification of a class declaration; see 10.3. 9059 // 9060 if (isVirtual && !NewFD->isInvalidDecl()) { 9061 if (!isVirtualOkay) { 9062 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9063 diag::err_virtual_non_function); 9064 } else if (!CurContext->isRecord()) { 9065 // 'virtual' was specified outside of the class. 9066 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9067 diag::err_virtual_out_of_class) 9068 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9069 } else if (NewFD->getDescribedFunctionTemplate()) { 9070 // C++ [temp.mem]p3: 9071 // A member function template shall not be virtual. 9072 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9073 diag::err_virtual_member_function_template) 9074 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9075 } else { 9076 // Okay: Add virtual to the method. 9077 NewFD->setVirtualAsWritten(true); 9078 } 9079 9080 if (getLangOpts().CPlusPlus14 && 9081 NewFD->getReturnType()->isUndeducedType()) 9082 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9083 } 9084 9085 if (getLangOpts().CPlusPlus14 && 9086 (NewFD->isDependentContext() || 9087 (isFriend && CurContext->isDependentContext())) && 9088 NewFD->getReturnType()->isUndeducedType()) { 9089 // If the function template is referenced directly (for instance, as a 9090 // member of the current instantiation), pretend it has a dependent type. 9091 // This is not really justified by the standard, but is the only sane 9092 // thing to do. 9093 // FIXME: For a friend function, we have not marked the function as being 9094 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9095 const FunctionProtoType *FPT = 9096 NewFD->getType()->castAs<FunctionProtoType>(); 9097 QualType Result = 9098 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9099 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9100 FPT->getExtProtoInfo())); 9101 } 9102 9103 // C++ [dcl.fct.spec]p3: 9104 // The inline specifier shall not appear on a block scope function 9105 // declaration. 9106 if (isInline && !NewFD->isInvalidDecl()) { 9107 if (CurContext->isFunctionOrMethod()) { 9108 // 'inline' is not allowed on block scope function declaration. 9109 Diag(D.getDeclSpec().getInlineSpecLoc(), 9110 diag::err_inline_declaration_block_scope) << Name 9111 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9112 } 9113 } 9114 9115 // C++ [dcl.fct.spec]p6: 9116 // The explicit specifier shall be used only in the declaration of a 9117 // constructor or conversion function within its class definition; 9118 // see 12.3.1 and 12.3.2. 9119 if (hasExplicit && !NewFD->isInvalidDecl() && 9120 !isa<CXXDeductionGuideDecl>(NewFD)) { 9121 if (!CurContext->isRecord()) { 9122 // 'explicit' was specified outside of the class. 9123 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9124 diag::err_explicit_out_of_class) 9125 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9126 } else if (!isa<CXXConstructorDecl>(NewFD) && 9127 !isa<CXXConversionDecl>(NewFD)) { 9128 // 'explicit' was specified on a function that wasn't a constructor 9129 // or conversion function. 9130 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9131 diag::err_explicit_non_ctor_or_conv_function) 9132 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9133 } 9134 } 9135 9136 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9137 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9138 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9139 // are implicitly inline. 9140 NewFD->setImplicitlyInline(); 9141 9142 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9143 // be either constructors or to return a literal type. Therefore, 9144 // destructors cannot be declared constexpr. 9145 if (isa<CXXDestructorDecl>(NewFD) && 9146 (!getLangOpts().CPlusPlus20 || 9147 ConstexprKind == ConstexprSpecKind::Consteval)) { 9148 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9149 << static_cast<int>(ConstexprKind); 9150 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9151 ? ConstexprSpecKind::Unspecified 9152 : ConstexprSpecKind::Constexpr); 9153 } 9154 // C++20 [dcl.constexpr]p2: An allocation function, or a 9155 // deallocation function shall not be declared with the consteval 9156 // specifier. 9157 if (ConstexprKind == ConstexprSpecKind::Consteval && 9158 (NewFD->getOverloadedOperator() == OO_New || 9159 NewFD->getOverloadedOperator() == OO_Array_New || 9160 NewFD->getOverloadedOperator() == OO_Delete || 9161 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9162 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9163 diag::err_invalid_consteval_decl_kind) 9164 << NewFD; 9165 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9166 } 9167 } 9168 9169 // If __module_private__ was specified, mark the function accordingly. 9170 if (D.getDeclSpec().isModulePrivateSpecified()) { 9171 if (isFunctionTemplateSpecialization) { 9172 SourceLocation ModulePrivateLoc 9173 = D.getDeclSpec().getModulePrivateSpecLoc(); 9174 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9175 << 0 9176 << FixItHint::CreateRemoval(ModulePrivateLoc); 9177 } else { 9178 NewFD->setModulePrivate(); 9179 if (FunctionTemplate) 9180 FunctionTemplate->setModulePrivate(); 9181 } 9182 } 9183 9184 if (isFriend) { 9185 if (FunctionTemplate) { 9186 FunctionTemplate->setObjectOfFriendDecl(); 9187 FunctionTemplate->setAccess(AS_public); 9188 } 9189 NewFD->setObjectOfFriendDecl(); 9190 NewFD->setAccess(AS_public); 9191 } 9192 9193 // If a function is defined as defaulted or deleted, mark it as such now. 9194 // We'll do the relevant checks on defaulted / deleted functions later. 9195 switch (D.getFunctionDefinitionKind()) { 9196 case FunctionDefinitionKind::Declaration: 9197 case FunctionDefinitionKind::Definition: 9198 break; 9199 9200 case FunctionDefinitionKind::Defaulted: 9201 NewFD->setDefaulted(); 9202 break; 9203 9204 case FunctionDefinitionKind::Deleted: 9205 NewFD->setDeletedAsWritten(); 9206 break; 9207 } 9208 9209 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9210 D.isFunctionDefinition()) { 9211 // C++ [class.mfct]p2: 9212 // A member function may be defined (8.4) in its class definition, in 9213 // which case it is an inline member function (7.1.2) 9214 NewFD->setImplicitlyInline(); 9215 } 9216 9217 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9218 !CurContext->isRecord()) { 9219 // C++ [class.static]p1: 9220 // A data or function member of a class may be declared static 9221 // in a class definition, in which case it is a static member of 9222 // the class. 9223 9224 // Complain about the 'static' specifier if it's on an out-of-line 9225 // member function definition. 9226 9227 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9228 // member function template declaration and class member template 9229 // declaration (MSVC versions before 2015), warn about this. 9230 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9231 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9232 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9233 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9234 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9235 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9236 } 9237 9238 // C++11 [except.spec]p15: 9239 // A deallocation function with no exception-specification is treated 9240 // as if it were specified with noexcept(true). 9241 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9242 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9243 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9244 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9245 NewFD->setType(Context.getFunctionType( 9246 FPT->getReturnType(), FPT->getParamTypes(), 9247 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9248 } 9249 9250 // Filter out previous declarations that don't match the scope. 9251 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9252 D.getCXXScopeSpec().isNotEmpty() || 9253 isMemberSpecialization || 9254 isFunctionTemplateSpecialization); 9255 9256 // Handle GNU asm-label extension (encoded as an attribute). 9257 if (Expr *E = (Expr*) D.getAsmLabel()) { 9258 // The parser guarantees this is a string. 9259 StringLiteral *SE = cast<StringLiteral>(E); 9260 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9261 /*IsLiteralLabel=*/true, 9262 SE->getStrTokenLoc(0))); 9263 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9264 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9265 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9266 if (I != ExtnameUndeclaredIdentifiers.end()) { 9267 if (isDeclExternC(NewFD)) { 9268 NewFD->addAttr(I->second); 9269 ExtnameUndeclaredIdentifiers.erase(I); 9270 } else 9271 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9272 << /*Variable*/0 << NewFD; 9273 } 9274 } 9275 9276 // Copy the parameter declarations from the declarator D to the function 9277 // declaration NewFD, if they are available. First scavenge them into Params. 9278 SmallVector<ParmVarDecl*, 16> Params; 9279 unsigned FTIIdx; 9280 if (D.isFunctionDeclarator(FTIIdx)) { 9281 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9282 9283 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9284 // function that takes no arguments, not a function that takes a 9285 // single void argument. 9286 // We let through "const void" here because Sema::GetTypeForDeclarator 9287 // already checks for that case. 9288 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9289 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9290 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9291 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9292 Param->setDeclContext(NewFD); 9293 Params.push_back(Param); 9294 9295 if (Param->isInvalidDecl()) 9296 NewFD->setInvalidDecl(); 9297 } 9298 } 9299 9300 if (!getLangOpts().CPlusPlus) { 9301 // In C, find all the tag declarations from the prototype and move them 9302 // into the function DeclContext. Remove them from the surrounding tag 9303 // injection context of the function, which is typically but not always 9304 // the TU. 9305 DeclContext *PrototypeTagContext = 9306 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9307 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9308 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9309 9310 // We don't want to reparent enumerators. Look at their parent enum 9311 // instead. 9312 if (!TD) { 9313 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9314 TD = cast<EnumDecl>(ECD->getDeclContext()); 9315 } 9316 if (!TD) 9317 continue; 9318 DeclContext *TagDC = TD->getLexicalDeclContext(); 9319 if (!TagDC->containsDecl(TD)) 9320 continue; 9321 TagDC->removeDecl(TD); 9322 TD->setDeclContext(NewFD); 9323 NewFD->addDecl(TD); 9324 9325 // Preserve the lexical DeclContext if it is not the surrounding tag 9326 // injection context of the FD. In this example, the semantic context of 9327 // E will be f and the lexical context will be S, while both the 9328 // semantic and lexical contexts of S will be f: 9329 // void f(struct S { enum E { a } f; } s); 9330 if (TagDC != PrototypeTagContext) 9331 TD->setLexicalDeclContext(TagDC); 9332 } 9333 } 9334 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9335 // When we're declaring a function with a typedef, typeof, etc as in the 9336 // following example, we'll need to synthesize (unnamed) 9337 // parameters for use in the declaration. 9338 // 9339 // @code 9340 // typedef void fn(int); 9341 // fn f; 9342 // @endcode 9343 9344 // Synthesize a parameter for each argument type. 9345 for (const auto &AI : FT->param_types()) { 9346 ParmVarDecl *Param = 9347 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9348 Param->setScopeInfo(0, Params.size()); 9349 Params.push_back(Param); 9350 } 9351 } else { 9352 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9353 "Should not need args for typedef of non-prototype fn"); 9354 } 9355 9356 // Finally, we know we have the right number of parameters, install them. 9357 NewFD->setParams(Params); 9358 9359 if (D.getDeclSpec().isNoreturnSpecified()) 9360 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9361 D.getDeclSpec().getNoreturnSpecLoc(), 9362 AttributeCommonInfo::AS_Keyword)); 9363 9364 // Functions returning a variably modified type violate C99 6.7.5.2p2 9365 // because all functions have linkage. 9366 if (!NewFD->isInvalidDecl() && 9367 NewFD->getReturnType()->isVariablyModifiedType()) { 9368 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9369 NewFD->setInvalidDecl(); 9370 } 9371 9372 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9373 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9374 !NewFD->hasAttr<SectionAttr>()) 9375 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9376 Context, PragmaClangTextSection.SectionName, 9377 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9378 9379 // Apply an implicit SectionAttr if #pragma code_seg is active. 9380 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9381 !NewFD->hasAttr<SectionAttr>()) { 9382 NewFD->addAttr(SectionAttr::CreateImplicit( 9383 Context, CodeSegStack.CurrentValue->getString(), 9384 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9385 SectionAttr::Declspec_allocate)); 9386 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9387 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9388 ASTContext::PSF_Read, 9389 NewFD)) 9390 NewFD->dropAttr<SectionAttr>(); 9391 } 9392 9393 // Apply an implicit CodeSegAttr from class declspec or 9394 // apply an implicit SectionAttr from #pragma code_seg if active. 9395 if (!NewFD->hasAttr<CodeSegAttr>()) { 9396 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9397 D.isFunctionDefinition())) { 9398 NewFD->addAttr(SAttr); 9399 } 9400 } 9401 9402 // Handle attributes. 9403 ProcessDeclAttributes(S, NewFD, D); 9404 9405 if (getLangOpts().OpenCL) { 9406 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9407 // type declaration will generate a compilation error. 9408 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9409 if (AddressSpace != LangAS::Default) { 9410 Diag(NewFD->getLocation(), 9411 diag::err_opencl_return_value_with_address_space); 9412 NewFD->setInvalidDecl(); 9413 } 9414 } 9415 9416 if (!getLangOpts().CPlusPlus) { 9417 // Perform semantic checking on the function declaration. 9418 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9419 CheckMain(NewFD, D.getDeclSpec()); 9420 9421 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9422 CheckMSVCRTEntryPoint(NewFD); 9423 9424 if (!NewFD->isInvalidDecl()) 9425 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9426 isMemberSpecialization)); 9427 else if (!Previous.empty()) 9428 // Recover gracefully from an invalid redeclaration. 9429 D.setRedeclaration(true); 9430 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9431 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9432 "previous declaration set still overloaded"); 9433 9434 // Diagnose no-prototype function declarations with calling conventions that 9435 // don't support variadic calls. Only do this in C and do it after merging 9436 // possibly prototyped redeclarations. 9437 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9438 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9439 CallingConv CC = FT->getExtInfo().getCC(); 9440 if (!supportsVariadicCall(CC)) { 9441 // Windows system headers sometimes accidentally use stdcall without 9442 // (void) parameters, so we relax this to a warning. 9443 int DiagID = 9444 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9445 Diag(NewFD->getLocation(), DiagID) 9446 << FunctionType::getNameForCallConv(CC); 9447 } 9448 } 9449 9450 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9451 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9452 checkNonTrivialCUnion(NewFD->getReturnType(), 9453 NewFD->getReturnTypeSourceRange().getBegin(), 9454 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9455 } else { 9456 // C++11 [replacement.functions]p3: 9457 // The program's definitions shall not be specified as inline. 9458 // 9459 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9460 // 9461 // Suppress the diagnostic if the function is __attribute__((used)), since 9462 // that forces an external definition to be emitted. 9463 if (D.getDeclSpec().isInlineSpecified() && 9464 NewFD->isReplaceableGlobalAllocationFunction() && 9465 !NewFD->hasAttr<UsedAttr>()) 9466 Diag(D.getDeclSpec().getInlineSpecLoc(), 9467 diag::ext_operator_new_delete_declared_inline) 9468 << NewFD->getDeclName(); 9469 9470 // If the declarator is a template-id, translate the parser's template 9471 // argument list into our AST format. 9472 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9473 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9474 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9475 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9476 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9477 TemplateId->NumArgs); 9478 translateTemplateArguments(TemplateArgsPtr, 9479 TemplateArgs); 9480 9481 HasExplicitTemplateArgs = true; 9482 9483 if (NewFD->isInvalidDecl()) { 9484 HasExplicitTemplateArgs = false; 9485 } else if (FunctionTemplate) { 9486 // Function template with explicit template arguments. 9487 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9488 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9489 9490 HasExplicitTemplateArgs = false; 9491 } else { 9492 assert((isFunctionTemplateSpecialization || 9493 D.getDeclSpec().isFriendSpecified()) && 9494 "should have a 'template<>' for this decl"); 9495 // "friend void foo<>(int);" is an implicit specialization decl. 9496 isFunctionTemplateSpecialization = true; 9497 } 9498 } else if (isFriend && isFunctionTemplateSpecialization) { 9499 // This combination is only possible in a recovery case; the user 9500 // wrote something like: 9501 // template <> friend void foo(int); 9502 // which we're recovering from as if the user had written: 9503 // friend void foo<>(int); 9504 // Go ahead and fake up a template id. 9505 HasExplicitTemplateArgs = true; 9506 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9507 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9508 } 9509 9510 // We do not add HD attributes to specializations here because 9511 // they may have different constexpr-ness compared to their 9512 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9513 // may end up with different effective targets. Instead, a 9514 // specialization inherits its target attributes from its template 9515 // in the CheckFunctionTemplateSpecialization() call below. 9516 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9517 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9518 9519 // If it's a friend (and only if it's a friend), it's possible 9520 // that either the specialized function type or the specialized 9521 // template is dependent, and therefore matching will fail. In 9522 // this case, don't check the specialization yet. 9523 if (isFunctionTemplateSpecialization && isFriend && 9524 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9525 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 9526 TemplateArgs.arguments()))) { 9527 assert(HasExplicitTemplateArgs && 9528 "friend function specialization without template args"); 9529 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9530 Previous)) 9531 NewFD->setInvalidDecl(); 9532 } else if (isFunctionTemplateSpecialization) { 9533 if (CurContext->isDependentContext() && CurContext->isRecord() 9534 && !isFriend) { 9535 isDependentClassScopeExplicitSpecialization = true; 9536 } else if (!NewFD->isInvalidDecl() && 9537 CheckFunctionTemplateSpecialization( 9538 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9539 Previous)) 9540 NewFD->setInvalidDecl(); 9541 9542 // C++ [dcl.stc]p1: 9543 // A storage-class-specifier shall not be specified in an explicit 9544 // specialization (14.7.3) 9545 FunctionTemplateSpecializationInfo *Info = 9546 NewFD->getTemplateSpecializationInfo(); 9547 if (Info && SC != SC_None) { 9548 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9549 Diag(NewFD->getLocation(), 9550 diag::err_explicit_specialization_inconsistent_storage_class) 9551 << SC 9552 << FixItHint::CreateRemoval( 9553 D.getDeclSpec().getStorageClassSpecLoc()); 9554 9555 else 9556 Diag(NewFD->getLocation(), 9557 diag::ext_explicit_specialization_storage_class) 9558 << FixItHint::CreateRemoval( 9559 D.getDeclSpec().getStorageClassSpecLoc()); 9560 } 9561 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9562 if (CheckMemberSpecialization(NewFD, Previous)) 9563 NewFD->setInvalidDecl(); 9564 } 9565 9566 // Perform semantic checking on the function declaration. 9567 if (!isDependentClassScopeExplicitSpecialization) { 9568 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9569 CheckMain(NewFD, D.getDeclSpec()); 9570 9571 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9572 CheckMSVCRTEntryPoint(NewFD); 9573 9574 if (!NewFD->isInvalidDecl()) 9575 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9576 isMemberSpecialization)); 9577 else if (!Previous.empty()) 9578 // Recover gracefully from an invalid redeclaration. 9579 D.setRedeclaration(true); 9580 } 9581 9582 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9583 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9584 "previous declaration set still overloaded"); 9585 9586 NamedDecl *PrincipalDecl = (FunctionTemplate 9587 ? cast<NamedDecl>(FunctionTemplate) 9588 : NewFD); 9589 9590 if (isFriend && NewFD->getPreviousDecl()) { 9591 AccessSpecifier Access = AS_public; 9592 if (!NewFD->isInvalidDecl()) 9593 Access = NewFD->getPreviousDecl()->getAccess(); 9594 9595 NewFD->setAccess(Access); 9596 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9597 } 9598 9599 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9600 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9601 PrincipalDecl->setNonMemberOperator(); 9602 9603 // If we have a function template, check the template parameter 9604 // list. This will check and merge default template arguments. 9605 if (FunctionTemplate) { 9606 FunctionTemplateDecl *PrevTemplate = 9607 FunctionTemplate->getPreviousDecl(); 9608 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9609 PrevTemplate ? PrevTemplate->getTemplateParameters() 9610 : nullptr, 9611 D.getDeclSpec().isFriendSpecified() 9612 ? (D.isFunctionDefinition() 9613 ? TPC_FriendFunctionTemplateDefinition 9614 : TPC_FriendFunctionTemplate) 9615 : (D.getCXXScopeSpec().isSet() && 9616 DC && DC->isRecord() && 9617 DC->isDependentContext()) 9618 ? TPC_ClassTemplateMember 9619 : TPC_FunctionTemplate); 9620 } 9621 9622 if (NewFD->isInvalidDecl()) { 9623 // Ignore all the rest of this. 9624 } else if (!D.isRedeclaration()) { 9625 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9626 AddToScope }; 9627 // Fake up an access specifier if it's supposed to be a class member. 9628 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9629 NewFD->setAccess(AS_public); 9630 9631 // Qualified decls generally require a previous declaration. 9632 if (D.getCXXScopeSpec().isSet()) { 9633 // ...with the major exception of templated-scope or 9634 // dependent-scope friend declarations. 9635 9636 // TODO: we currently also suppress this check in dependent 9637 // contexts because (1) the parameter depth will be off when 9638 // matching friend templates and (2) we might actually be 9639 // selecting a friend based on a dependent factor. But there 9640 // are situations where these conditions don't apply and we 9641 // can actually do this check immediately. 9642 // 9643 // Unless the scope is dependent, it's always an error if qualified 9644 // redeclaration lookup found nothing at all. Diagnose that now; 9645 // nothing will diagnose that error later. 9646 if (isFriend && 9647 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9648 (!Previous.empty() && CurContext->isDependentContext()))) { 9649 // ignore these 9650 } else { 9651 // The user tried to provide an out-of-line definition for a 9652 // function that is a member of a class or namespace, but there 9653 // was no such member function declared (C++ [class.mfct]p2, 9654 // C++ [namespace.memdef]p2). For example: 9655 // 9656 // class X { 9657 // void f() const; 9658 // }; 9659 // 9660 // void X::f() { } // ill-formed 9661 // 9662 // Complain about this problem, and attempt to suggest close 9663 // matches (e.g., those that differ only in cv-qualifiers and 9664 // whether the parameter types are references). 9665 9666 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9667 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9668 AddToScope = ExtraArgs.AddToScope; 9669 return Result; 9670 } 9671 } 9672 9673 // Unqualified local friend declarations are required to resolve 9674 // to something. 9675 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9676 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9677 *this, Previous, NewFD, ExtraArgs, true, S)) { 9678 AddToScope = ExtraArgs.AddToScope; 9679 return Result; 9680 } 9681 } 9682 } else if (!D.isFunctionDefinition() && 9683 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9684 !isFriend && !isFunctionTemplateSpecialization && 9685 !isMemberSpecialization) { 9686 // An out-of-line member function declaration must also be a 9687 // definition (C++ [class.mfct]p2). 9688 // Note that this is not the case for explicit specializations of 9689 // function templates or member functions of class templates, per 9690 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9691 // extension for compatibility with old SWIG code which likes to 9692 // generate them. 9693 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9694 << D.getCXXScopeSpec().getRange(); 9695 } 9696 } 9697 9698 // If this is the first declaration of a library builtin function, add 9699 // attributes as appropriate. 9700 if (!D.isRedeclaration() && 9701 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 9702 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 9703 if (unsigned BuiltinID = II->getBuiltinID()) { 9704 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 9705 // Validate the type matches unless this builtin is specified as 9706 // matching regardless of its declared type. 9707 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 9708 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9709 } else { 9710 ASTContext::GetBuiltinTypeError Error; 9711 LookupNecessaryTypesForBuiltin(S, BuiltinID); 9712 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 9713 9714 if (!Error && !BuiltinType.isNull() && 9715 Context.hasSameFunctionTypeIgnoringExceptionSpec( 9716 NewFD->getType(), BuiltinType)) 9717 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9718 } 9719 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 9720 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9721 // FIXME: We should consider this a builtin only in the std namespace. 9722 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9723 } 9724 } 9725 } 9726 } 9727 9728 ProcessPragmaWeak(S, NewFD); 9729 checkAttributesAfterMerging(*this, *NewFD); 9730 9731 AddKnownFunctionAttributes(NewFD); 9732 9733 if (NewFD->hasAttr<OverloadableAttr>() && 9734 !NewFD->getType()->getAs<FunctionProtoType>()) { 9735 Diag(NewFD->getLocation(), 9736 diag::err_attribute_overloadable_no_prototype) 9737 << NewFD; 9738 9739 // Turn this into a variadic function with no parameters. 9740 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9741 FunctionProtoType::ExtProtoInfo EPI( 9742 Context.getDefaultCallingConvention(true, false)); 9743 EPI.Variadic = true; 9744 EPI.ExtInfo = FT->getExtInfo(); 9745 9746 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9747 NewFD->setType(R); 9748 } 9749 9750 // If there's a #pragma GCC visibility in scope, and this isn't a class 9751 // member, set the visibility of this function. 9752 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9753 AddPushedVisibilityAttribute(NewFD); 9754 9755 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9756 // marking the function. 9757 AddCFAuditedAttribute(NewFD); 9758 9759 // If this is a function definition, check if we have to apply optnone due to 9760 // a pragma. 9761 if(D.isFunctionDefinition()) 9762 AddRangeBasedOptnone(NewFD); 9763 9764 // If this is the first declaration of an extern C variable, update 9765 // the map of such variables. 9766 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9767 isIncompleteDeclExternC(*this, NewFD)) 9768 RegisterLocallyScopedExternCDecl(NewFD, S); 9769 9770 // Set this FunctionDecl's range up to the right paren. 9771 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9772 9773 if (D.isRedeclaration() && !Previous.empty()) { 9774 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9775 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9776 isMemberSpecialization || 9777 isFunctionTemplateSpecialization, 9778 D.isFunctionDefinition()); 9779 } 9780 9781 if (getLangOpts().CUDA) { 9782 IdentifierInfo *II = NewFD->getIdentifier(); 9783 if (II && II->isStr(getCudaConfigureFuncName()) && 9784 !NewFD->isInvalidDecl() && 9785 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9786 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9787 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9788 << getCudaConfigureFuncName(); 9789 Context.setcudaConfigureCallDecl(NewFD); 9790 } 9791 9792 // Variadic functions, other than a *declaration* of printf, are not allowed 9793 // in device-side CUDA code, unless someone passed 9794 // -fcuda-allow-variadic-functions. 9795 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9796 (NewFD->hasAttr<CUDADeviceAttr>() || 9797 NewFD->hasAttr<CUDAGlobalAttr>()) && 9798 !(II && II->isStr("printf") && NewFD->isExternC() && 9799 !D.isFunctionDefinition())) { 9800 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9801 } 9802 } 9803 9804 MarkUnusedFileScopedDecl(NewFD); 9805 9806 9807 9808 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9809 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9810 if ((getLangOpts().OpenCLVersion >= 120) 9811 && (SC == SC_Static)) { 9812 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9813 D.setInvalidType(); 9814 } 9815 9816 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9817 if (!NewFD->getReturnType()->isVoidType()) { 9818 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9819 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9820 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9821 : FixItHint()); 9822 D.setInvalidType(); 9823 } 9824 9825 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9826 for (auto Param : NewFD->parameters()) 9827 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9828 9829 if (getLangOpts().OpenCLCPlusPlus) { 9830 if (DC->isRecord()) { 9831 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9832 D.setInvalidType(); 9833 } 9834 if (FunctionTemplate) { 9835 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9836 D.setInvalidType(); 9837 } 9838 } 9839 } 9840 9841 if (getLangOpts().CPlusPlus) { 9842 if (FunctionTemplate) { 9843 if (NewFD->isInvalidDecl()) 9844 FunctionTemplate->setInvalidDecl(); 9845 return FunctionTemplate; 9846 } 9847 9848 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9849 CompleteMemberSpecialization(NewFD, Previous); 9850 } 9851 9852 for (const ParmVarDecl *Param : NewFD->parameters()) { 9853 QualType PT = Param->getType(); 9854 9855 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9856 // types. 9857 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9858 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9859 QualType ElemTy = PipeTy->getElementType(); 9860 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9861 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9862 D.setInvalidType(); 9863 } 9864 } 9865 } 9866 } 9867 9868 // Here we have an function template explicit specialization at class scope. 9869 // The actual specialization will be postponed to template instatiation 9870 // time via the ClassScopeFunctionSpecializationDecl node. 9871 if (isDependentClassScopeExplicitSpecialization) { 9872 ClassScopeFunctionSpecializationDecl *NewSpec = 9873 ClassScopeFunctionSpecializationDecl::Create( 9874 Context, CurContext, NewFD->getLocation(), 9875 cast<CXXMethodDecl>(NewFD), 9876 HasExplicitTemplateArgs, TemplateArgs); 9877 CurContext->addDecl(NewSpec); 9878 AddToScope = false; 9879 } 9880 9881 // Diagnose availability attributes. Availability cannot be used on functions 9882 // that are run during load/unload. 9883 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9884 if (NewFD->hasAttr<ConstructorAttr>()) { 9885 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9886 << 1; 9887 NewFD->dropAttr<AvailabilityAttr>(); 9888 } 9889 if (NewFD->hasAttr<DestructorAttr>()) { 9890 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9891 << 2; 9892 NewFD->dropAttr<AvailabilityAttr>(); 9893 } 9894 } 9895 9896 // Diagnose no_builtin attribute on function declaration that are not a 9897 // definition. 9898 // FIXME: We should really be doing this in 9899 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9900 // the FunctionDecl and at this point of the code 9901 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9902 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9903 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9904 switch (D.getFunctionDefinitionKind()) { 9905 case FunctionDefinitionKind::Defaulted: 9906 case FunctionDefinitionKind::Deleted: 9907 Diag(NBA->getLocation(), 9908 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9909 << NBA->getSpelling(); 9910 break; 9911 case FunctionDefinitionKind::Declaration: 9912 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9913 << NBA->getSpelling(); 9914 break; 9915 case FunctionDefinitionKind::Definition: 9916 break; 9917 } 9918 9919 return NewFD; 9920 } 9921 9922 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9923 /// when __declspec(code_seg) "is applied to a class, all member functions of 9924 /// the class and nested classes -- this includes compiler-generated special 9925 /// member functions -- are put in the specified segment." 9926 /// The actual behavior is a little more complicated. The Microsoft compiler 9927 /// won't check outer classes if there is an active value from #pragma code_seg. 9928 /// The CodeSeg is always applied from the direct parent but only from outer 9929 /// classes when the #pragma code_seg stack is empty. See: 9930 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9931 /// available since MS has removed the page. 9932 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9933 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9934 if (!Method) 9935 return nullptr; 9936 const CXXRecordDecl *Parent = Method->getParent(); 9937 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9938 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9939 NewAttr->setImplicit(true); 9940 return NewAttr; 9941 } 9942 9943 // The Microsoft compiler won't check outer classes for the CodeSeg 9944 // when the #pragma code_seg stack is active. 9945 if (S.CodeSegStack.CurrentValue) 9946 return nullptr; 9947 9948 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9949 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9950 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9951 NewAttr->setImplicit(true); 9952 return NewAttr; 9953 } 9954 } 9955 return nullptr; 9956 } 9957 9958 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9959 /// containing class. Otherwise it will return implicit SectionAttr if the 9960 /// function is a definition and there is an active value on CodeSegStack 9961 /// (from the current #pragma code-seg value). 9962 /// 9963 /// \param FD Function being declared. 9964 /// \param IsDefinition Whether it is a definition or just a declarartion. 9965 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9966 /// nullptr if no attribute should be added. 9967 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9968 bool IsDefinition) { 9969 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9970 return A; 9971 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9972 CodeSegStack.CurrentValue) 9973 return SectionAttr::CreateImplicit( 9974 getASTContext(), CodeSegStack.CurrentValue->getString(), 9975 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9976 SectionAttr::Declspec_allocate); 9977 return nullptr; 9978 } 9979 9980 /// Determines if we can perform a correct type check for \p D as a 9981 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9982 /// best-effort check. 9983 /// 9984 /// \param NewD The new declaration. 9985 /// \param OldD The old declaration. 9986 /// \param NewT The portion of the type of the new declaration to check. 9987 /// \param OldT The portion of the type of the old declaration to check. 9988 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9989 QualType NewT, QualType OldT) { 9990 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9991 return true; 9992 9993 // For dependently-typed local extern declarations and friends, we can't 9994 // perform a correct type check in general until instantiation: 9995 // 9996 // int f(); 9997 // template<typename T> void g() { T f(); } 9998 // 9999 // (valid if g() is only instantiated with T = int). 10000 if (NewT->isDependentType() && 10001 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10002 return false; 10003 10004 // Similarly, if the previous declaration was a dependent local extern 10005 // declaration, we don't really know its type yet. 10006 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10007 return false; 10008 10009 return true; 10010 } 10011 10012 /// Checks if the new declaration declared in dependent context must be 10013 /// put in the same redeclaration chain as the specified declaration. 10014 /// 10015 /// \param D Declaration that is checked. 10016 /// \param PrevDecl Previous declaration found with proper lookup method for the 10017 /// same declaration name. 10018 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10019 /// belongs to. 10020 /// 10021 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10022 if (!D->getLexicalDeclContext()->isDependentContext()) 10023 return true; 10024 10025 // Don't chain dependent friend function definitions until instantiation, to 10026 // permit cases like 10027 // 10028 // void func(); 10029 // template<typename T> class C1 { friend void func() {} }; 10030 // template<typename T> class C2 { friend void func() {} }; 10031 // 10032 // ... which is valid if only one of C1 and C2 is ever instantiated. 10033 // 10034 // FIXME: This need only apply to function definitions. For now, we proxy 10035 // this by checking for a file-scope function. We do not want this to apply 10036 // to friend declarations nominating member functions, because that gets in 10037 // the way of access checks. 10038 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10039 return false; 10040 10041 auto *VD = dyn_cast<ValueDecl>(D); 10042 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10043 return !VD || !PrevVD || 10044 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10045 PrevVD->getType()); 10046 } 10047 10048 /// Check the target attribute of the function for MultiVersion 10049 /// validity. 10050 /// 10051 /// Returns true if there was an error, false otherwise. 10052 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10053 const auto *TA = FD->getAttr<TargetAttr>(); 10054 assert(TA && "MultiVersion Candidate requires a target attribute"); 10055 ParsedTargetAttr ParseInfo = TA->parse(); 10056 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10057 enum ErrType { Feature = 0, Architecture = 1 }; 10058 10059 if (!ParseInfo.Architecture.empty() && 10060 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10061 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10062 << Architecture << ParseInfo.Architecture; 10063 return true; 10064 } 10065 10066 for (const auto &Feat : ParseInfo.Features) { 10067 auto BareFeat = StringRef{Feat}.substr(1); 10068 if (Feat[0] == '-') { 10069 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10070 << Feature << ("no-" + BareFeat).str(); 10071 return true; 10072 } 10073 10074 if (!TargetInfo.validateCpuSupports(BareFeat) || 10075 !TargetInfo.isValidFeatureName(BareFeat)) { 10076 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10077 << Feature << BareFeat; 10078 return true; 10079 } 10080 } 10081 return false; 10082 } 10083 10084 // Provide a white-list of attributes that are allowed to be combined with 10085 // multiversion functions. 10086 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10087 MultiVersionKind MVType) { 10088 // Note: this list/diagnosis must match the list in 10089 // checkMultiversionAttributesAllSame. 10090 switch (Kind) { 10091 default: 10092 return false; 10093 case attr::Used: 10094 return MVType == MultiVersionKind::Target; 10095 case attr::NonNull: 10096 case attr::NoThrow: 10097 return true; 10098 } 10099 } 10100 10101 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10102 const FunctionDecl *FD, 10103 const FunctionDecl *CausedFD, 10104 MultiVersionKind MVType) { 10105 bool IsCPUSpecificCPUDispatchMVType = 10106 MVType == MultiVersionKind::CPUDispatch || 10107 MVType == MultiVersionKind::CPUSpecific; 10108 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType]( 10109 Sema &S, const Attr *A) { 10110 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10111 << IsCPUSpecificCPUDispatchMVType << A; 10112 if (CausedFD) 10113 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10114 return true; 10115 }; 10116 10117 for (const Attr *A : FD->attrs()) { 10118 switch (A->getKind()) { 10119 case attr::CPUDispatch: 10120 case attr::CPUSpecific: 10121 if (MVType != MultiVersionKind::CPUDispatch && 10122 MVType != MultiVersionKind::CPUSpecific) 10123 return Diagnose(S, A); 10124 break; 10125 case attr::Target: 10126 if (MVType != MultiVersionKind::Target) 10127 return Diagnose(S, A); 10128 break; 10129 default: 10130 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10131 return Diagnose(S, A); 10132 break; 10133 } 10134 } 10135 return false; 10136 } 10137 10138 bool Sema::areMultiversionVariantFunctionsCompatible( 10139 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10140 const PartialDiagnostic &NoProtoDiagID, 10141 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10142 const PartialDiagnosticAt &NoSupportDiagIDAt, 10143 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10144 bool ConstexprSupported, bool CLinkageMayDiffer) { 10145 enum DoesntSupport { 10146 FuncTemplates = 0, 10147 VirtFuncs = 1, 10148 DeducedReturn = 2, 10149 Constructors = 3, 10150 Destructors = 4, 10151 DeletedFuncs = 5, 10152 DefaultedFuncs = 6, 10153 ConstexprFuncs = 7, 10154 ConstevalFuncs = 8, 10155 }; 10156 enum Different { 10157 CallingConv = 0, 10158 ReturnType = 1, 10159 ConstexprSpec = 2, 10160 InlineSpec = 3, 10161 StorageClass = 4, 10162 Linkage = 5, 10163 }; 10164 10165 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10166 !OldFD->getType()->getAs<FunctionProtoType>()) { 10167 Diag(OldFD->getLocation(), NoProtoDiagID); 10168 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10169 return true; 10170 } 10171 10172 if (NoProtoDiagID.getDiagID() != 0 && 10173 !NewFD->getType()->getAs<FunctionProtoType>()) 10174 return Diag(NewFD->getLocation(), NoProtoDiagID); 10175 10176 if (!TemplatesSupported && 10177 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10178 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10179 << FuncTemplates; 10180 10181 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10182 if (NewCXXFD->isVirtual()) 10183 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10184 << VirtFuncs; 10185 10186 if (isa<CXXConstructorDecl>(NewCXXFD)) 10187 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10188 << Constructors; 10189 10190 if (isa<CXXDestructorDecl>(NewCXXFD)) 10191 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10192 << Destructors; 10193 } 10194 10195 if (NewFD->isDeleted()) 10196 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10197 << DeletedFuncs; 10198 10199 if (NewFD->isDefaulted()) 10200 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10201 << DefaultedFuncs; 10202 10203 if (!ConstexprSupported && NewFD->isConstexpr()) 10204 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10205 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10206 10207 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10208 const auto *NewType = cast<FunctionType>(NewQType); 10209 QualType NewReturnType = NewType->getReturnType(); 10210 10211 if (NewReturnType->isUndeducedType()) 10212 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10213 << DeducedReturn; 10214 10215 // Ensure the return type is identical. 10216 if (OldFD) { 10217 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10218 const auto *OldType = cast<FunctionType>(OldQType); 10219 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10220 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10221 10222 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10223 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10224 10225 QualType OldReturnType = OldType->getReturnType(); 10226 10227 if (OldReturnType != NewReturnType) 10228 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10229 10230 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10231 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10232 10233 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10234 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10235 10236 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10237 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10238 10239 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10240 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10241 10242 if (CheckEquivalentExceptionSpec( 10243 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10244 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10245 return true; 10246 } 10247 return false; 10248 } 10249 10250 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10251 const FunctionDecl *NewFD, 10252 bool CausesMV, 10253 MultiVersionKind MVType) { 10254 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10255 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10256 if (OldFD) 10257 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10258 return true; 10259 } 10260 10261 bool IsCPUSpecificCPUDispatchMVType = 10262 MVType == MultiVersionKind::CPUDispatch || 10263 MVType == MultiVersionKind::CPUSpecific; 10264 10265 if (CausesMV && OldFD && 10266 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType)) 10267 return true; 10268 10269 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType)) 10270 return true; 10271 10272 // Only allow transition to MultiVersion if it hasn't been used. 10273 if (OldFD && CausesMV && OldFD->isUsed(false)) 10274 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10275 10276 return S.areMultiversionVariantFunctionsCompatible( 10277 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10278 PartialDiagnosticAt(NewFD->getLocation(), 10279 S.PDiag(diag::note_multiversioning_caused_here)), 10280 PartialDiagnosticAt(NewFD->getLocation(), 10281 S.PDiag(diag::err_multiversion_doesnt_support) 10282 << IsCPUSpecificCPUDispatchMVType), 10283 PartialDiagnosticAt(NewFD->getLocation(), 10284 S.PDiag(diag::err_multiversion_diff)), 10285 /*TemplatesSupported=*/false, 10286 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10287 /*CLinkageMayDiffer=*/false); 10288 } 10289 10290 /// Check the validity of a multiversion function declaration that is the 10291 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10292 /// 10293 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10294 /// 10295 /// Returns true if there was an error, false otherwise. 10296 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10297 MultiVersionKind MVType, 10298 const TargetAttr *TA) { 10299 assert(MVType != MultiVersionKind::None && 10300 "Function lacks multiversion attribute"); 10301 10302 // Target only causes MV if it is default, otherwise this is a normal 10303 // function. 10304 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10305 return false; 10306 10307 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10308 FD->setInvalidDecl(); 10309 return true; 10310 } 10311 10312 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10313 FD->setInvalidDecl(); 10314 return true; 10315 } 10316 10317 FD->setIsMultiVersion(); 10318 return false; 10319 } 10320 10321 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10322 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10323 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10324 return true; 10325 } 10326 10327 return false; 10328 } 10329 10330 static bool CheckTargetCausesMultiVersioning( 10331 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10332 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10333 LookupResult &Previous) { 10334 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10335 ParsedTargetAttr NewParsed = NewTA->parse(); 10336 // Sort order doesn't matter, it just needs to be consistent. 10337 llvm::sort(NewParsed.Features); 10338 10339 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10340 // to change, this is a simple redeclaration. 10341 if (!NewTA->isDefaultVersion() && 10342 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10343 return false; 10344 10345 // Otherwise, this decl causes MultiVersioning. 10346 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10347 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10348 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10349 NewFD->setInvalidDecl(); 10350 return true; 10351 } 10352 10353 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10354 MultiVersionKind::Target)) { 10355 NewFD->setInvalidDecl(); 10356 return true; 10357 } 10358 10359 if (CheckMultiVersionValue(S, NewFD)) { 10360 NewFD->setInvalidDecl(); 10361 return true; 10362 } 10363 10364 // If this is 'default', permit the forward declaration. 10365 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10366 Redeclaration = true; 10367 OldDecl = OldFD; 10368 OldFD->setIsMultiVersion(); 10369 NewFD->setIsMultiVersion(); 10370 return false; 10371 } 10372 10373 if (CheckMultiVersionValue(S, OldFD)) { 10374 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10375 NewFD->setInvalidDecl(); 10376 return true; 10377 } 10378 10379 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10380 10381 if (OldParsed == NewParsed) { 10382 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10383 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10384 NewFD->setInvalidDecl(); 10385 return true; 10386 } 10387 10388 for (const auto *FD : OldFD->redecls()) { 10389 const auto *CurTA = FD->getAttr<TargetAttr>(); 10390 // We allow forward declarations before ANY multiversioning attributes, but 10391 // nothing after the fact. 10392 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10393 (!CurTA || CurTA->isInherited())) { 10394 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10395 << 0; 10396 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10397 NewFD->setInvalidDecl(); 10398 return true; 10399 } 10400 } 10401 10402 OldFD->setIsMultiVersion(); 10403 NewFD->setIsMultiVersion(); 10404 Redeclaration = false; 10405 MergeTypeWithPrevious = false; 10406 OldDecl = nullptr; 10407 Previous.clear(); 10408 return false; 10409 } 10410 10411 /// Check the validity of a new function declaration being added to an existing 10412 /// multiversioned declaration collection. 10413 static bool CheckMultiVersionAdditionalDecl( 10414 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10415 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10416 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10417 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10418 LookupResult &Previous) { 10419 10420 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10421 // Disallow mixing of multiversioning types. 10422 if ((OldMVType == MultiVersionKind::Target && 10423 NewMVType != MultiVersionKind::Target) || 10424 (NewMVType == MultiVersionKind::Target && 10425 OldMVType != MultiVersionKind::Target)) { 10426 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10427 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10428 NewFD->setInvalidDecl(); 10429 return true; 10430 } 10431 10432 ParsedTargetAttr NewParsed; 10433 if (NewTA) { 10434 NewParsed = NewTA->parse(); 10435 llvm::sort(NewParsed.Features); 10436 } 10437 10438 bool UseMemberUsingDeclRules = 10439 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10440 10441 // Next, check ALL non-overloads to see if this is a redeclaration of a 10442 // previous member of the MultiVersion set. 10443 for (NamedDecl *ND : Previous) { 10444 FunctionDecl *CurFD = ND->getAsFunction(); 10445 if (!CurFD) 10446 continue; 10447 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10448 continue; 10449 10450 if (NewMVType == MultiVersionKind::Target) { 10451 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10452 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10453 NewFD->setIsMultiVersion(); 10454 Redeclaration = true; 10455 OldDecl = ND; 10456 return false; 10457 } 10458 10459 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10460 if (CurParsed == NewParsed) { 10461 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10462 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10463 NewFD->setInvalidDecl(); 10464 return true; 10465 } 10466 } else { 10467 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10468 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10469 // Handle CPUDispatch/CPUSpecific versions. 10470 // Only 1 CPUDispatch function is allowed, this will make it go through 10471 // the redeclaration errors. 10472 if (NewMVType == MultiVersionKind::CPUDispatch && 10473 CurFD->hasAttr<CPUDispatchAttr>()) { 10474 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10475 std::equal( 10476 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10477 NewCPUDisp->cpus_begin(), 10478 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10479 return Cur->getName() == New->getName(); 10480 })) { 10481 NewFD->setIsMultiVersion(); 10482 Redeclaration = true; 10483 OldDecl = ND; 10484 return false; 10485 } 10486 10487 // If the declarations don't match, this is an error condition. 10488 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10489 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10490 NewFD->setInvalidDecl(); 10491 return true; 10492 } 10493 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10494 10495 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10496 std::equal( 10497 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10498 NewCPUSpec->cpus_begin(), 10499 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10500 return Cur->getName() == New->getName(); 10501 })) { 10502 NewFD->setIsMultiVersion(); 10503 Redeclaration = true; 10504 OldDecl = ND; 10505 return false; 10506 } 10507 10508 // Only 1 version of CPUSpecific is allowed for each CPU. 10509 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10510 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10511 if (CurII == NewII) { 10512 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10513 << NewII; 10514 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10515 NewFD->setInvalidDecl(); 10516 return true; 10517 } 10518 } 10519 } 10520 } 10521 // If the two decls aren't the same MVType, there is no possible error 10522 // condition. 10523 } 10524 } 10525 10526 // Else, this is simply a non-redecl case. Checking the 'value' is only 10527 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10528 // handled in the attribute adding step. 10529 if (NewMVType == MultiVersionKind::Target && 10530 CheckMultiVersionValue(S, NewFD)) { 10531 NewFD->setInvalidDecl(); 10532 return true; 10533 } 10534 10535 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10536 !OldFD->isMultiVersion(), NewMVType)) { 10537 NewFD->setInvalidDecl(); 10538 return true; 10539 } 10540 10541 // Permit forward declarations in the case where these two are compatible. 10542 if (!OldFD->isMultiVersion()) { 10543 OldFD->setIsMultiVersion(); 10544 NewFD->setIsMultiVersion(); 10545 Redeclaration = true; 10546 OldDecl = OldFD; 10547 return false; 10548 } 10549 10550 NewFD->setIsMultiVersion(); 10551 Redeclaration = false; 10552 MergeTypeWithPrevious = false; 10553 OldDecl = nullptr; 10554 Previous.clear(); 10555 return false; 10556 } 10557 10558 10559 /// Check the validity of a mulitversion function declaration. 10560 /// Also sets the multiversion'ness' of the function itself. 10561 /// 10562 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10563 /// 10564 /// Returns true if there was an error, false otherwise. 10565 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10566 bool &Redeclaration, NamedDecl *&OldDecl, 10567 bool &MergeTypeWithPrevious, 10568 LookupResult &Previous) { 10569 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10570 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10571 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10572 10573 // Mixing Multiversioning types is prohibited. 10574 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10575 (NewCPUDisp && NewCPUSpec)) { 10576 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10577 NewFD->setInvalidDecl(); 10578 return true; 10579 } 10580 10581 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10582 10583 // Main isn't allowed to become a multiversion function, however it IS 10584 // permitted to have 'main' be marked with the 'target' optimization hint. 10585 if (NewFD->isMain()) { 10586 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10587 MVType == MultiVersionKind::CPUDispatch || 10588 MVType == MultiVersionKind::CPUSpecific) { 10589 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10590 NewFD->setInvalidDecl(); 10591 return true; 10592 } 10593 return false; 10594 } 10595 10596 if (!OldDecl || !OldDecl->getAsFunction() || 10597 OldDecl->getDeclContext()->getRedeclContext() != 10598 NewFD->getDeclContext()->getRedeclContext()) { 10599 // If there's no previous declaration, AND this isn't attempting to cause 10600 // multiversioning, this isn't an error condition. 10601 if (MVType == MultiVersionKind::None) 10602 return false; 10603 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10604 } 10605 10606 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10607 10608 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10609 return false; 10610 10611 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10612 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10613 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10614 NewFD->setInvalidDecl(); 10615 return true; 10616 } 10617 10618 // Handle the target potentially causes multiversioning case. 10619 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10620 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10621 Redeclaration, OldDecl, 10622 MergeTypeWithPrevious, Previous); 10623 10624 // At this point, we have a multiversion function decl (in OldFD) AND an 10625 // appropriate attribute in the current function decl. Resolve that these are 10626 // still compatible with previous declarations. 10627 return CheckMultiVersionAdditionalDecl( 10628 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10629 OldDecl, MergeTypeWithPrevious, Previous); 10630 } 10631 10632 /// Perform semantic checking of a new function declaration. 10633 /// 10634 /// Performs semantic analysis of the new function declaration 10635 /// NewFD. This routine performs all semantic checking that does not 10636 /// require the actual declarator involved in the declaration, and is 10637 /// used both for the declaration of functions as they are parsed 10638 /// (called via ActOnDeclarator) and for the declaration of functions 10639 /// that have been instantiated via C++ template instantiation (called 10640 /// via InstantiateDecl). 10641 /// 10642 /// \param IsMemberSpecialization whether this new function declaration is 10643 /// a member specialization (that replaces any definition provided by the 10644 /// previous declaration). 10645 /// 10646 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10647 /// 10648 /// \returns true if the function declaration is a redeclaration. 10649 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10650 LookupResult &Previous, 10651 bool IsMemberSpecialization) { 10652 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10653 "Variably modified return types are not handled here"); 10654 10655 // Determine whether the type of this function should be merged with 10656 // a previous visible declaration. This never happens for functions in C++, 10657 // and always happens in C if the previous declaration was visible. 10658 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10659 !Previous.isShadowed(); 10660 10661 bool Redeclaration = false; 10662 NamedDecl *OldDecl = nullptr; 10663 bool MayNeedOverloadableChecks = false; 10664 10665 // Merge or overload the declaration with an existing declaration of 10666 // the same name, if appropriate. 10667 if (!Previous.empty()) { 10668 // Determine whether NewFD is an overload of PrevDecl or 10669 // a declaration that requires merging. If it's an overload, 10670 // there's no more work to do here; we'll just add the new 10671 // function to the scope. 10672 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10673 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10674 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10675 Redeclaration = true; 10676 OldDecl = Candidate; 10677 } 10678 } else { 10679 MayNeedOverloadableChecks = true; 10680 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10681 /*NewIsUsingDecl*/ false)) { 10682 case Ovl_Match: 10683 Redeclaration = true; 10684 break; 10685 10686 case Ovl_NonFunction: 10687 Redeclaration = true; 10688 break; 10689 10690 case Ovl_Overload: 10691 Redeclaration = false; 10692 break; 10693 } 10694 } 10695 } 10696 10697 // Check for a previous extern "C" declaration with this name. 10698 if (!Redeclaration && 10699 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10700 if (!Previous.empty()) { 10701 // This is an extern "C" declaration with the same name as a previous 10702 // declaration, and thus redeclares that entity... 10703 Redeclaration = true; 10704 OldDecl = Previous.getFoundDecl(); 10705 MergeTypeWithPrevious = false; 10706 10707 // ... except in the presence of __attribute__((overloadable)). 10708 if (OldDecl->hasAttr<OverloadableAttr>() || 10709 NewFD->hasAttr<OverloadableAttr>()) { 10710 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10711 MayNeedOverloadableChecks = true; 10712 Redeclaration = false; 10713 OldDecl = nullptr; 10714 } 10715 } 10716 } 10717 } 10718 10719 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10720 MergeTypeWithPrevious, Previous)) 10721 return Redeclaration; 10722 10723 // PPC MMA non-pointer types are not allowed as function return types. 10724 if (Context.getTargetInfo().getTriple().isPPC64() && 10725 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 10726 NewFD->setInvalidDecl(); 10727 } 10728 10729 // C++11 [dcl.constexpr]p8: 10730 // A constexpr specifier for a non-static member function that is not 10731 // a constructor declares that member function to be const. 10732 // 10733 // This needs to be delayed until we know whether this is an out-of-line 10734 // definition of a static member function. 10735 // 10736 // This rule is not present in C++1y, so we produce a backwards 10737 // compatibility warning whenever it happens in C++11. 10738 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10739 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10740 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10741 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10742 CXXMethodDecl *OldMD = nullptr; 10743 if (OldDecl) 10744 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10745 if (!OldMD || !OldMD->isStatic()) { 10746 const FunctionProtoType *FPT = 10747 MD->getType()->castAs<FunctionProtoType>(); 10748 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10749 EPI.TypeQuals.addConst(); 10750 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10751 FPT->getParamTypes(), EPI)); 10752 10753 // Warn that we did this, if we're not performing template instantiation. 10754 // In that case, we'll have warned already when the template was defined. 10755 if (!inTemplateInstantiation()) { 10756 SourceLocation AddConstLoc; 10757 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10758 .IgnoreParens().getAs<FunctionTypeLoc>()) 10759 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10760 10761 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10762 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10763 } 10764 } 10765 } 10766 10767 if (Redeclaration) { 10768 // NewFD and OldDecl represent declarations that need to be 10769 // merged. 10770 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10771 NewFD->setInvalidDecl(); 10772 return Redeclaration; 10773 } 10774 10775 Previous.clear(); 10776 Previous.addDecl(OldDecl); 10777 10778 if (FunctionTemplateDecl *OldTemplateDecl = 10779 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10780 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10781 FunctionTemplateDecl *NewTemplateDecl 10782 = NewFD->getDescribedFunctionTemplate(); 10783 assert(NewTemplateDecl && "Template/non-template mismatch"); 10784 10785 // The call to MergeFunctionDecl above may have created some state in 10786 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10787 // can add it as a redeclaration. 10788 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10789 10790 NewFD->setPreviousDeclaration(OldFD); 10791 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10792 if (NewFD->isCXXClassMember()) { 10793 NewFD->setAccess(OldTemplateDecl->getAccess()); 10794 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10795 } 10796 10797 // If this is an explicit specialization of a member that is a function 10798 // template, mark it as a member specialization. 10799 if (IsMemberSpecialization && 10800 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10801 NewTemplateDecl->setMemberSpecialization(); 10802 assert(OldTemplateDecl->isMemberSpecialization()); 10803 // Explicit specializations of a member template do not inherit deleted 10804 // status from the parent member template that they are specializing. 10805 if (OldFD->isDeleted()) { 10806 // FIXME: This assert will not hold in the presence of modules. 10807 assert(OldFD->getCanonicalDecl() == OldFD); 10808 // FIXME: We need an update record for this AST mutation. 10809 OldFD->setDeletedAsWritten(false); 10810 } 10811 } 10812 10813 } else { 10814 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10815 auto *OldFD = cast<FunctionDecl>(OldDecl); 10816 // This needs to happen first so that 'inline' propagates. 10817 NewFD->setPreviousDeclaration(OldFD); 10818 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10819 if (NewFD->isCXXClassMember()) 10820 NewFD->setAccess(OldFD->getAccess()); 10821 } 10822 } 10823 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10824 !NewFD->getAttr<OverloadableAttr>()) { 10825 assert((Previous.empty() || 10826 llvm::any_of(Previous, 10827 [](const NamedDecl *ND) { 10828 return ND->hasAttr<OverloadableAttr>(); 10829 })) && 10830 "Non-redecls shouldn't happen without overloadable present"); 10831 10832 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10833 const auto *FD = dyn_cast<FunctionDecl>(ND); 10834 return FD && !FD->hasAttr<OverloadableAttr>(); 10835 }); 10836 10837 if (OtherUnmarkedIter != Previous.end()) { 10838 Diag(NewFD->getLocation(), 10839 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10840 Diag((*OtherUnmarkedIter)->getLocation(), 10841 diag::note_attribute_overloadable_prev_overload) 10842 << false; 10843 10844 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10845 } 10846 } 10847 10848 if (LangOpts.OpenMP) 10849 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 10850 10851 // Semantic checking for this function declaration (in isolation). 10852 10853 if (getLangOpts().CPlusPlus) { 10854 // C++-specific checks. 10855 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10856 CheckConstructor(Constructor); 10857 } else if (CXXDestructorDecl *Destructor = 10858 dyn_cast<CXXDestructorDecl>(NewFD)) { 10859 CXXRecordDecl *Record = Destructor->getParent(); 10860 QualType ClassType = Context.getTypeDeclType(Record); 10861 10862 // FIXME: Shouldn't we be able to perform this check even when the class 10863 // type is dependent? Both gcc and edg can handle that. 10864 if (!ClassType->isDependentType()) { 10865 DeclarationName Name 10866 = Context.DeclarationNames.getCXXDestructorName( 10867 Context.getCanonicalType(ClassType)); 10868 if (NewFD->getDeclName() != Name) { 10869 Diag(NewFD->getLocation(), diag::err_destructor_name); 10870 NewFD->setInvalidDecl(); 10871 return Redeclaration; 10872 } 10873 } 10874 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10875 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10876 CheckDeductionGuideTemplate(TD); 10877 10878 // A deduction guide is not on the list of entities that can be 10879 // explicitly specialized. 10880 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10881 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10882 << /*explicit specialization*/ 1; 10883 } 10884 10885 // Find any virtual functions that this function overrides. 10886 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10887 if (!Method->isFunctionTemplateSpecialization() && 10888 !Method->getDescribedFunctionTemplate() && 10889 Method->isCanonicalDecl()) { 10890 AddOverriddenMethods(Method->getParent(), Method); 10891 } 10892 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10893 // C++2a [class.virtual]p6 10894 // A virtual method shall not have a requires-clause. 10895 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10896 diag::err_constrained_virtual_method); 10897 10898 if (Method->isStatic()) 10899 checkThisInStaticMemberFunctionType(Method); 10900 } 10901 10902 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 10903 ActOnConversionDeclarator(Conversion); 10904 10905 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10906 if (NewFD->isOverloadedOperator() && 10907 CheckOverloadedOperatorDeclaration(NewFD)) { 10908 NewFD->setInvalidDecl(); 10909 return Redeclaration; 10910 } 10911 10912 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10913 if (NewFD->getLiteralIdentifier() && 10914 CheckLiteralOperatorDeclaration(NewFD)) { 10915 NewFD->setInvalidDecl(); 10916 return Redeclaration; 10917 } 10918 10919 // In C++, check default arguments now that we have merged decls. Unless 10920 // the lexical context is the class, because in this case this is done 10921 // during delayed parsing anyway. 10922 if (!CurContext->isRecord()) 10923 CheckCXXDefaultArguments(NewFD); 10924 10925 // If this function declares a builtin function, check the type of this 10926 // declaration against the expected type for the builtin. 10927 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10928 ASTContext::GetBuiltinTypeError Error; 10929 LookupNecessaryTypesForBuiltin(S, BuiltinID); 10930 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10931 // If the type of the builtin differs only in its exception 10932 // specification, that's OK. 10933 // FIXME: If the types do differ in this way, it would be better to 10934 // retain the 'noexcept' form of the type. 10935 if (!T.isNull() && 10936 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10937 NewFD->getType())) 10938 // The type of this function differs from the type of the builtin, 10939 // so forget about the builtin entirely. 10940 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10941 } 10942 10943 // If this function is declared as being extern "C", then check to see if 10944 // the function returns a UDT (class, struct, or union type) that is not C 10945 // compatible, and if it does, warn the user. 10946 // But, issue any diagnostic on the first declaration only. 10947 if (Previous.empty() && NewFD->isExternC()) { 10948 QualType R = NewFD->getReturnType(); 10949 if (R->isIncompleteType() && !R->isVoidType()) 10950 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10951 << NewFD << R; 10952 else if (!R.isPODType(Context) && !R->isVoidType() && 10953 !R->isObjCObjectPointerType()) 10954 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10955 } 10956 10957 // C++1z [dcl.fct]p6: 10958 // [...] whether the function has a non-throwing exception-specification 10959 // [is] part of the function type 10960 // 10961 // This results in an ABI break between C++14 and C++17 for functions whose 10962 // declared type includes an exception-specification in a parameter or 10963 // return type. (Exception specifications on the function itself are OK in 10964 // most cases, and exception specifications are not permitted in most other 10965 // contexts where they could make it into a mangling.) 10966 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10967 auto HasNoexcept = [&](QualType T) -> bool { 10968 // Strip off declarator chunks that could be between us and a function 10969 // type. We don't need to look far, exception specifications are very 10970 // restricted prior to C++17. 10971 if (auto *RT = T->getAs<ReferenceType>()) 10972 T = RT->getPointeeType(); 10973 else if (T->isAnyPointerType()) 10974 T = T->getPointeeType(); 10975 else if (auto *MPT = T->getAs<MemberPointerType>()) 10976 T = MPT->getPointeeType(); 10977 if (auto *FPT = T->getAs<FunctionProtoType>()) 10978 if (FPT->isNothrow()) 10979 return true; 10980 return false; 10981 }; 10982 10983 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10984 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10985 for (QualType T : FPT->param_types()) 10986 AnyNoexcept |= HasNoexcept(T); 10987 if (AnyNoexcept) 10988 Diag(NewFD->getLocation(), 10989 diag::warn_cxx17_compat_exception_spec_in_signature) 10990 << NewFD; 10991 } 10992 10993 if (!Redeclaration && LangOpts.CUDA) 10994 checkCUDATargetOverload(NewFD, Previous); 10995 } 10996 return Redeclaration; 10997 } 10998 10999 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11000 // C++11 [basic.start.main]p3: 11001 // A program that [...] declares main to be inline, static or 11002 // constexpr is ill-formed. 11003 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11004 // appear in a declaration of main. 11005 // static main is not an error under C99, but we should warn about it. 11006 // We accept _Noreturn main as an extension. 11007 if (FD->getStorageClass() == SC_Static) 11008 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11009 ? diag::err_static_main : diag::warn_static_main) 11010 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11011 if (FD->isInlineSpecified()) 11012 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11013 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11014 if (DS.isNoreturnSpecified()) { 11015 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11016 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11017 Diag(NoreturnLoc, diag::ext_noreturn_main); 11018 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11019 << FixItHint::CreateRemoval(NoreturnRange); 11020 } 11021 if (FD->isConstexpr()) { 11022 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11023 << FD->isConsteval() 11024 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11025 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11026 } 11027 11028 if (getLangOpts().OpenCL) { 11029 Diag(FD->getLocation(), diag::err_opencl_no_main) 11030 << FD->hasAttr<OpenCLKernelAttr>(); 11031 FD->setInvalidDecl(); 11032 return; 11033 } 11034 11035 QualType T = FD->getType(); 11036 assert(T->isFunctionType() && "function decl is not of function type"); 11037 const FunctionType* FT = T->castAs<FunctionType>(); 11038 11039 // Set default calling convention for main() 11040 if (FT->getCallConv() != CC_C) { 11041 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11042 FD->setType(QualType(FT, 0)); 11043 T = Context.getCanonicalType(FD->getType()); 11044 } 11045 11046 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11047 // In C with GNU extensions we allow main() to have non-integer return 11048 // type, but we should warn about the extension, and we disable the 11049 // implicit-return-zero rule. 11050 11051 // GCC in C mode accepts qualified 'int'. 11052 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11053 FD->setHasImplicitReturnZero(true); 11054 else { 11055 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11056 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11057 if (RTRange.isValid()) 11058 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11059 << FixItHint::CreateReplacement(RTRange, "int"); 11060 } 11061 } else { 11062 // In C and C++, main magically returns 0 if you fall off the end; 11063 // set the flag which tells us that. 11064 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11065 11066 // All the standards say that main() should return 'int'. 11067 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11068 FD->setHasImplicitReturnZero(true); 11069 else { 11070 // Otherwise, this is just a flat-out error. 11071 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11072 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11073 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11074 : FixItHint()); 11075 FD->setInvalidDecl(true); 11076 } 11077 } 11078 11079 // Treat protoless main() as nullary. 11080 if (isa<FunctionNoProtoType>(FT)) return; 11081 11082 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11083 unsigned nparams = FTP->getNumParams(); 11084 assert(FD->getNumParams() == nparams); 11085 11086 bool HasExtraParameters = (nparams > 3); 11087 11088 if (FTP->isVariadic()) { 11089 Diag(FD->getLocation(), diag::ext_variadic_main); 11090 // FIXME: if we had information about the location of the ellipsis, we 11091 // could add a FixIt hint to remove it as a parameter. 11092 } 11093 11094 // Darwin passes an undocumented fourth argument of type char**. If 11095 // other platforms start sprouting these, the logic below will start 11096 // getting shifty. 11097 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11098 HasExtraParameters = false; 11099 11100 if (HasExtraParameters) { 11101 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11102 FD->setInvalidDecl(true); 11103 nparams = 3; 11104 } 11105 11106 // FIXME: a lot of the following diagnostics would be improved 11107 // if we had some location information about types. 11108 11109 QualType CharPP = 11110 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11111 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11112 11113 for (unsigned i = 0; i < nparams; ++i) { 11114 QualType AT = FTP->getParamType(i); 11115 11116 bool mismatch = true; 11117 11118 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11119 mismatch = false; 11120 else if (Expected[i] == CharPP) { 11121 // As an extension, the following forms are okay: 11122 // char const ** 11123 // char const * const * 11124 // char * const * 11125 11126 QualifierCollector qs; 11127 const PointerType* PT; 11128 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11129 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11130 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11131 Context.CharTy)) { 11132 qs.removeConst(); 11133 mismatch = !qs.empty(); 11134 } 11135 } 11136 11137 if (mismatch) { 11138 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11139 // TODO: suggest replacing given type with expected type 11140 FD->setInvalidDecl(true); 11141 } 11142 } 11143 11144 if (nparams == 1 && !FD->isInvalidDecl()) { 11145 Diag(FD->getLocation(), diag::warn_main_one_arg); 11146 } 11147 11148 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11149 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11150 FD->setInvalidDecl(); 11151 } 11152 } 11153 11154 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11155 QualType T = FD->getType(); 11156 assert(T->isFunctionType() && "function decl is not of function type"); 11157 const FunctionType *FT = T->castAs<FunctionType>(); 11158 11159 // Set an implicit return of 'zero' if the function can return some integral, 11160 // enumeration, pointer or nullptr type. 11161 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11162 FT->getReturnType()->isAnyPointerType() || 11163 FT->getReturnType()->isNullPtrType()) 11164 // DllMain is exempt because a return value of zero means it failed. 11165 if (FD->getName() != "DllMain") 11166 FD->setHasImplicitReturnZero(true); 11167 11168 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11169 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11170 FD->setInvalidDecl(); 11171 } 11172 } 11173 11174 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11175 // FIXME: Need strict checking. In C89, we need to check for 11176 // any assignment, increment, decrement, function-calls, or 11177 // commas outside of a sizeof. In C99, it's the same list, 11178 // except that the aforementioned are allowed in unevaluated 11179 // expressions. Everything else falls under the 11180 // "may accept other forms of constant expressions" exception. 11181 // 11182 // Regular C++ code will not end up here (exceptions: language extensions, 11183 // OpenCL C++ etc), so the constant expression rules there don't matter. 11184 if (Init->isValueDependent()) { 11185 assert(Init->containsErrors() && 11186 "Dependent code should only occur in error-recovery path."); 11187 return true; 11188 } 11189 const Expr *Culprit; 11190 if (Init->isConstantInitializer(Context, false, &Culprit)) 11191 return false; 11192 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11193 << Culprit->getSourceRange(); 11194 return true; 11195 } 11196 11197 namespace { 11198 // Visits an initialization expression to see if OrigDecl is evaluated in 11199 // its own initialization and throws a warning if it does. 11200 class SelfReferenceChecker 11201 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11202 Sema &S; 11203 Decl *OrigDecl; 11204 bool isRecordType; 11205 bool isPODType; 11206 bool isReferenceType; 11207 11208 bool isInitList; 11209 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11210 11211 public: 11212 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11213 11214 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11215 S(S), OrigDecl(OrigDecl) { 11216 isPODType = false; 11217 isRecordType = false; 11218 isReferenceType = false; 11219 isInitList = false; 11220 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11221 isPODType = VD->getType().isPODType(S.Context); 11222 isRecordType = VD->getType()->isRecordType(); 11223 isReferenceType = VD->getType()->isReferenceType(); 11224 } 11225 } 11226 11227 // For most expressions, just call the visitor. For initializer lists, 11228 // track the index of the field being initialized since fields are 11229 // initialized in order allowing use of previously initialized fields. 11230 void CheckExpr(Expr *E) { 11231 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11232 if (!InitList) { 11233 Visit(E); 11234 return; 11235 } 11236 11237 // Track and increment the index here. 11238 isInitList = true; 11239 InitFieldIndex.push_back(0); 11240 for (auto Child : InitList->children()) { 11241 CheckExpr(cast<Expr>(Child)); 11242 ++InitFieldIndex.back(); 11243 } 11244 InitFieldIndex.pop_back(); 11245 } 11246 11247 // Returns true if MemberExpr is checked and no further checking is needed. 11248 // Returns false if additional checking is required. 11249 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11250 llvm::SmallVector<FieldDecl*, 4> Fields; 11251 Expr *Base = E; 11252 bool ReferenceField = false; 11253 11254 // Get the field members used. 11255 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11256 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11257 if (!FD) 11258 return false; 11259 Fields.push_back(FD); 11260 if (FD->getType()->isReferenceType()) 11261 ReferenceField = true; 11262 Base = ME->getBase()->IgnoreParenImpCasts(); 11263 } 11264 11265 // Keep checking only if the base Decl is the same. 11266 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11267 if (!DRE || DRE->getDecl() != OrigDecl) 11268 return false; 11269 11270 // A reference field can be bound to an unininitialized field. 11271 if (CheckReference && !ReferenceField) 11272 return true; 11273 11274 // Convert FieldDecls to their index number. 11275 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11276 for (const FieldDecl *I : llvm::reverse(Fields)) 11277 UsedFieldIndex.push_back(I->getFieldIndex()); 11278 11279 // See if a warning is needed by checking the first difference in index 11280 // numbers. If field being used has index less than the field being 11281 // initialized, then the use is safe. 11282 for (auto UsedIter = UsedFieldIndex.begin(), 11283 UsedEnd = UsedFieldIndex.end(), 11284 OrigIter = InitFieldIndex.begin(), 11285 OrigEnd = InitFieldIndex.end(); 11286 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11287 if (*UsedIter < *OrigIter) 11288 return true; 11289 if (*UsedIter > *OrigIter) 11290 break; 11291 } 11292 11293 // TODO: Add a different warning which will print the field names. 11294 HandleDeclRefExpr(DRE); 11295 return true; 11296 } 11297 11298 // For most expressions, the cast is directly above the DeclRefExpr. 11299 // For conditional operators, the cast can be outside the conditional 11300 // operator if both expressions are DeclRefExpr's. 11301 void HandleValue(Expr *E) { 11302 E = E->IgnoreParens(); 11303 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11304 HandleDeclRefExpr(DRE); 11305 return; 11306 } 11307 11308 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11309 Visit(CO->getCond()); 11310 HandleValue(CO->getTrueExpr()); 11311 HandleValue(CO->getFalseExpr()); 11312 return; 11313 } 11314 11315 if (BinaryConditionalOperator *BCO = 11316 dyn_cast<BinaryConditionalOperator>(E)) { 11317 Visit(BCO->getCond()); 11318 HandleValue(BCO->getFalseExpr()); 11319 return; 11320 } 11321 11322 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11323 HandleValue(OVE->getSourceExpr()); 11324 return; 11325 } 11326 11327 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11328 if (BO->getOpcode() == BO_Comma) { 11329 Visit(BO->getLHS()); 11330 HandleValue(BO->getRHS()); 11331 return; 11332 } 11333 } 11334 11335 if (isa<MemberExpr>(E)) { 11336 if (isInitList) { 11337 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11338 false /*CheckReference*/)) 11339 return; 11340 } 11341 11342 Expr *Base = E->IgnoreParenImpCasts(); 11343 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11344 // Check for static member variables and don't warn on them. 11345 if (!isa<FieldDecl>(ME->getMemberDecl())) 11346 return; 11347 Base = ME->getBase()->IgnoreParenImpCasts(); 11348 } 11349 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11350 HandleDeclRefExpr(DRE); 11351 return; 11352 } 11353 11354 Visit(E); 11355 } 11356 11357 // Reference types not handled in HandleValue are handled here since all 11358 // uses of references are bad, not just r-value uses. 11359 void VisitDeclRefExpr(DeclRefExpr *E) { 11360 if (isReferenceType) 11361 HandleDeclRefExpr(E); 11362 } 11363 11364 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11365 if (E->getCastKind() == CK_LValueToRValue) { 11366 HandleValue(E->getSubExpr()); 11367 return; 11368 } 11369 11370 Inherited::VisitImplicitCastExpr(E); 11371 } 11372 11373 void VisitMemberExpr(MemberExpr *E) { 11374 if (isInitList) { 11375 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11376 return; 11377 } 11378 11379 // Don't warn on arrays since they can be treated as pointers. 11380 if (E->getType()->canDecayToPointerType()) return; 11381 11382 // Warn when a non-static method call is followed by non-static member 11383 // field accesses, which is followed by a DeclRefExpr. 11384 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11385 bool Warn = (MD && !MD->isStatic()); 11386 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11387 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11388 if (!isa<FieldDecl>(ME->getMemberDecl())) 11389 Warn = false; 11390 Base = ME->getBase()->IgnoreParenImpCasts(); 11391 } 11392 11393 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11394 if (Warn) 11395 HandleDeclRefExpr(DRE); 11396 return; 11397 } 11398 11399 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11400 // Visit that expression. 11401 Visit(Base); 11402 } 11403 11404 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11405 Expr *Callee = E->getCallee(); 11406 11407 if (isa<UnresolvedLookupExpr>(Callee)) 11408 return Inherited::VisitCXXOperatorCallExpr(E); 11409 11410 Visit(Callee); 11411 for (auto Arg: E->arguments()) 11412 HandleValue(Arg->IgnoreParenImpCasts()); 11413 } 11414 11415 void VisitUnaryOperator(UnaryOperator *E) { 11416 // For POD record types, addresses of its own members are well-defined. 11417 if (E->getOpcode() == UO_AddrOf && isRecordType && 11418 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11419 if (!isPODType) 11420 HandleValue(E->getSubExpr()); 11421 return; 11422 } 11423 11424 if (E->isIncrementDecrementOp()) { 11425 HandleValue(E->getSubExpr()); 11426 return; 11427 } 11428 11429 Inherited::VisitUnaryOperator(E); 11430 } 11431 11432 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11433 11434 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11435 if (E->getConstructor()->isCopyConstructor()) { 11436 Expr *ArgExpr = E->getArg(0); 11437 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11438 if (ILE->getNumInits() == 1) 11439 ArgExpr = ILE->getInit(0); 11440 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11441 if (ICE->getCastKind() == CK_NoOp) 11442 ArgExpr = ICE->getSubExpr(); 11443 HandleValue(ArgExpr); 11444 return; 11445 } 11446 Inherited::VisitCXXConstructExpr(E); 11447 } 11448 11449 void VisitCallExpr(CallExpr *E) { 11450 // Treat std::move as a use. 11451 if (E->isCallToStdMove()) { 11452 HandleValue(E->getArg(0)); 11453 return; 11454 } 11455 11456 Inherited::VisitCallExpr(E); 11457 } 11458 11459 void VisitBinaryOperator(BinaryOperator *E) { 11460 if (E->isCompoundAssignmentOp()) { 11461 HandleValue(E->getLHS()); 11462 Visit(E->getRHS()); 11463 return; 11464 } 11465 11466 Inherited::VisitBinaryOperator(E); 11467 } 11468 11469 // A custom visitor for BinaryConditionalOperator is needed because the 11470 // regular visitor would check the condition and true expression separately 11471 // but both point to the same place giving duplicate diagnostics. 11472 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11473 Visit(E->getCond()); 11474 Visit(E->getFalseExpr()); 11475 } 11476 11477 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11478 Decl* ReferenceDecl = DRE->getDecl(); 11479 if (OrigDecl != ReferenceDecl) return; 11480 unsigned diag; 11481 if (isReferenceType) { 11482 diag = diag::warn_uninit_self_reference_in_reference_init; 11483 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11484 diag = diag::warn_static_self_reference_in_init; 11485 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11486 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11487 DRE->getDecl()->getType()->isRecordType()) { 11488 diag = diag::warn_uninit_self_reference_in_init; 11489 } else { 11490 // Local variables will be handled by the CFG analysis. 11491 return; 11492 } 11493 11494 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11495 S.PDiag(diag) 11496 << DRE->getDecl() << OrigDecl->getLocation() 11497 << DRE->getSourceRange()); 11498 } 11499 }; 11500 11501 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11502 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11503 bool DirectInit) { 11504 // Parameters arguments are occassionially constructed with itself, 11505 // for instance, in recursive functions. Skip them. 11506 if (isa<ParmVarDecl>(OrigDecl)) 11507 return; 11508 11509 E = E->IgnoreParens(); 11510 11511 // Skip checking T a = a where T is not a record or reference type. 11512 // Doing so is a way to silence uninitialized warnings. 11513 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11514 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11515 if (ICE->getCastKind() == CK_LValueToRValue) 11516 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11517 if (DRE->getDecl() == OrigDecl) 11518 return; 11519 11520 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11521 } 11522 } // end anonymous namespace 11523 11524 namespace { 11525 // Simple wrapper to add the name of a variable or (if no variable is 11526 // available) a DeclarationName into a diagnostic. 11527 struct VarDeclOrName { 11528 VarDecl *VDecl; 11529 DeclarationName Name; 11530 11531 friend const Sema::SemaDiagnosticBuilder & 11532 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11533 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11534 } 11535 }; 11536 } // end anonymous namespace 11537 11538 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11539 DeclarationName Name, QualType Type, 11540 TypeSourceInfo *TSI, 11541 SourceRange Range, bool DirectInit, 11542 Expr *Init) { 11543 bool IsInitCapture = !VDecl; 11544 assert((!VDecl || !VDecl->isInitCapture()) && 11545 "init captures are expected to be deduced prior to initialization"); 11546 11547 VarDeclOrName VN{VDecl, Name}; 11548 11549 DeducedType *Deduced = Type->getContainedDeducedType(); 11550 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11551 11552 // C++11 [dcl.spec.auto]p3 11553 if (!Init) { 11554 assert(VDecl && "no init for init capture deduction?"); 11555 11556 // Except for class argument deduction, and then for an initializing 11557 // declaration only, i.e. no static at class scope or extern. 11558 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11559 VDecl->hasExternalStorage() || 11560 VDecl->isStaticDataMember()) { 11561 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11562 << VDecl->getDeclName() << Type; 11563 return QualType(); 11564 } 11565 } 11566 11567 ArrayRef<Expr*> DeduceInits; 11568 if (Init) 11569 DeduceInits = Init; 11570 11571 if (DirectInit) { 11572 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11573 DeduceInits = PL->exprs(); 11574 } 11575 11576 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11577 assert(VDecl && "non-auto type for init capture deduction?"); 11578 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11579 InitializationKind Kind = InitializationKind::CreateForInit( 11580 VDecl->getLocation(), DirectInit, Init); 11581 // FIXME: Initialization should not be taking a mutable list of inits. 11582 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11583 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11584 InitsCopy); 11585 } 11586 11587 if (DirectInit) { 11588 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11589 DeduceInits = IL->inits(); 11590 } 11591 11592 // Deduction only works if we have exactly one source expression. 11593 if (DeduceInits.empty()) { 11594 // It isn't possible to write this directly, but it is possible to 11595 // end up in this situation with "auto x(some_pack...);" 11596 Diag(Init->getBeginLoc(), IsInitCapture 11597 ? diag::err_init_capture_no_expression 11598 : diag::err_auto_var_init_no_expression) 11599 << VN << Type << Range; 11600 return QualType(); 11601 } 11602 11603 if (DeduceInits.size() > 1) { 11604 Diag(DeduceInits[1]->getBeginLoc(), 11605 IsInitCapture ? diag::err_init_capture_multiple_expressions 11606 : diag::err_auto_var_init_multiple_expressions) 11607 << VN << Type << Range; 11608 return QualType(); 11609 } 11610 11611 Expr *DeduceInit = DeduceInits[0]; 11612 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11613 Diag(Init->getBeginLoc(), IsInitCapture 11614 ? diag::err_init_capture_paren_braces 11615 : diag::err_auto_var_init_paren_braces) 11616 << isa<InitListExpr>(Init) << VN << Type << Range; 11617 return QualType(); 11618 } 11619 11620 // Expressions default to 'id' when we're in a debugger. 11621 bool DefaultedAnyToId = false; 11622 if (getLangOpts().DebuggerCastResultToId && 11623 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11624 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11625 if (Result.isInvalid()) { 11626 return QualType(); 11627 } 11628 Init = Result.get(); 11629 DefaultedAnyToId = true; 11630 } 11631 11632 // C++ [dcl.decomp]p1: 11633 // If the assignment-expression [...] has array type A and no ref-qualifier 11634 // is present, e has type cv A 11635 if (VDecl && isa<DecompositionDecl>(VDecl) && 11636 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11637 DeduceInit->getType()->isConstantArrayType()) 11638 return Context.getQualifiedType(DeduceInit->getType(), 11639 Type.getQualifiers()); 11640 11641 QualType DeducedType; 11642 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11643 if (!IsInitCapture) 11644 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11645 else if (isa<InitListExpr>(Init)) 11646 Diag(Range.getBegin(), 11647 diag::err_init_capture_deduction_failure_from_init_list) 11648 << VN 11649 << (DeduceInit->getType().isNull() ? TSI->getType() 11650 : DeduceInit->getType()) 11651 << DeduceInit->getSourceRange(); 11652 else 11653 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11654 << VN << TSI->getType() 11655 << (DeduceInit->getType().isNull() ? TSI->getType() 11656 : DeduceInit->getType()) 11657 << DeduceInit->getSourceRange(); 11658 } 11659 11660 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11661 // 'id' instead of a specific object type prevents most of our usual 11662 // checks. 11663 // We only want to warn outside of template instantiations, though: 11664 // inside a template, the 'id' could have come from a parameter. 11665 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11666 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11667 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11668 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11669 } 11670 11671 return DeducedType; 11672 } 11673 11674 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11675 Expr *Init) { 11676 assert(!Init || !Init->containsErrors()); 11677 QualType DeducedType = deduceVarTypeFromInitializer( 11678 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11679 VDecl->getSourceRange(), DirectInit, Init); 11680 if (DeducedType.isNull()) { 11681 VDecl->setInvalidDecl(); 11682 return true; 11683 } 11684 11685 VDecl->setType(DeducedType); 11686 assert(VDecl->isLinkageValid()); 11687 11688 // In ARC, infer lifetime. 11689 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11690 VDecl->setInvalidDecl(); 11691 11692 if (getLangOpts().OpenCL) 11693 deduceOpenCLAddressSpace(VDecl); 11694 11695 // If this is a redeclaration, check that the type we just deduced matches 11696 // the previously declared type. 11697 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11698 // We never need to merge the type, because we cannot form an incomplete 11699 // array of auto, nor deduce such a type. 11700 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11701 } 11702 11703 // Check the deduced type is valid for a variable declaration. 11704 CheckVariableDeclarationType(VDecl); 11705 return VDecl->isInvalidDecl(); 11706 } 11707 11708 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11709 SourceLocation Loc) { 11710 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11711 Init = EWC->getSubExpr(); 11712 11713 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11714 Init = CE->getSubExpr(); 11715 11716 QualType InitType = Init->getType(); 11717 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11718 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11719 "shouldn't be called if type doesn't have a non-trivial C struct"); 11720 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11721 for (auto I : ILE->inits()) { 11722 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11723 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11724 continue; 11725 SourceLocation SL = I->getExprLoc(); 11726 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11727 } 11728 return; 11729 } 11730 11731 if (isa<ImplicitValueInitExpr>(Init)) { 11732 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11733 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11734 NTCUK_Init); 11735 } else { 11736 // Assume all other explicit initializers involving copying some existing 11737 // object. 11738 // TODO: ignore any explicit initializers where we can guarantee 11739 // copy-elision. 11740 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11741 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11742 } 11743 } 11744 11745 namespace { 11746 11747 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11748 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11749 // in the source code or implicitly by the compiler if it is in a union 11750 // defined in a system header and has non-trivial ObjC ownership 11751 // qualifications. We don't want those fields to participate in determining 11752 // whether the containing union is non-trivial. 11753 return FD->hasAttr<UnavailableAttr>(); 11754 } 11755 11756 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11757 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11758 void> { 11759 using Super = 11760 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11761 void>; 11762 11763 DiagNonTrivalCUnionDefaultInitializeVisitor( 11764 QualType OrigTy, SourceLocation OrigLoc, 11765 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11766 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11767 11768 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11769 const FieldDecl *FD, bool InNonTrivialUnion) { 11770 if (const auto *AT = S.Context.getAsArrayType(QT)) 11771 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11772 InNonTrivialUnion); 11773 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11774 } 11775 11776 void visitARCStrong(QualType QT, const FieldDecl *FD, 11777 bool InNonTrivialUnion) { 11778 if (InNonTrivialUnion) 11779 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11780 << 1 << 0 << QT << FD->getName(); 11781 } 11782 11783 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11784 if (InNonTrivialUnion) 11785 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11786 << 1 << 0 << QT << FD->getName(); 11787 } 11788 11789 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11790 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11791 if (RD->isUnion()) { 11792 if (OrigLoc.isValid()) { 11793 bool IsUnion = false; 11794 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11795 IsUnion = OrigRD->isUnion(); 11796 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11797 << 0 << OrigTy << IsUnion << UseContext; 11798 // Reset OrigLoc so that this diagnostic is emitted only once. 11799 OrigLoc = SourceLocation(); 11800 } 11801 InNonTrivialUnion = true; 11802 } 11803 11804 if (InNonTrivialUnion) 11805 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11806 << 0 << 0 << QT.getUnqualifiedType() << ""; 11807 11808 for (const FieldDecl *FD : RD->fields()) 11809 if (!shouldIgnoreForRecordTriviality(FD)) 11810 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11811 } 11812 11813 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11814 11815 // The non-trivial C union type or the struct/union type that contains a 11816 // non-trivial C union. 11817 QualType OrigTy; 11818 SourceLocation OrigLoc; 11819 Sema::NonTrivialCUnionContext UseContext; 11820 Sema &S; 11821 }; 11822 11823 struct DiagNonTrivalCUnionDestructedTypeVisitor 11824 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11825 using Super = 11826 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11827 11828 DiagNonTrivalCUnionDestructedTypeVisitor( 11829 QualType OrigTy, SourceLocation OrigLoc, 11830 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11831 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11832 11833 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11834 const FieldDecl *FD, bool InNonTrivialUnion) { 11835 if (const auto *AT = S.Context.getAsArrayType(QT)) 11836 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11837 InNonTrivialUnion); 11838 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11839 } 11840 11841 void visitARCStrong(QualType QT, const FieldDecl *FD, 11842 bool InNonTrivialUnion) { 11843 if (InNonTrivialUnion) 11844 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11845 << 1 << 1 << QT << FD->getName(); 11846 } 11847 11848 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11849 if (InNonTrivialUnion) 11850 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11851 << 1 << 1 << QT << FD->getName(); 11852 } 11853 11854 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11855 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11856 if (RD->isUnion()) { 11857 if (OrigLoc.isValid()) { 11858 bool IsUnion = false; 11859 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11860 IsUnion = OrigRD->isUnion(); 11861 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11862 << 1 << OrigTy << IsUnion << UseContext; 11863 // Reset OrigLoc so that this diagnostic is emitted only once. 11864 OrigLoc = SourceLocation(); 11865 } 11866 InNonTrivialUnion = true; 11867 } 11868 11869 if (InNonTrivialUnion) 11870 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11871 << 0 << 1 << QT.getUnqualifiedType() << ""; 11872 11873 for (const FieldDecl *FD : RD->fields()) 11874 if (!shouldIgnoreForRecordTriviality(FD)) 11875 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11876 } 11877 11878 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11879 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11880 bool InNonTrivialUnion) {} 11881 11882 // The non-trivial C union type or the struct/union type that contains a 11883 // non-trivial C union. 11884 QualType OrigTy; 11885 SourceLocation OrigLoc; 11886 Sema::NonTrivialCUnionContext UseContext; 11887 Sema &S; 11888 }; 11889 11890 struct DiagNonTrivalCUnionCopyVisitor 11891 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11892 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11893 11894 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11895 Sema::NonTrivialCUnionContext UseContext, 11896 Sema &S) 11897 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11898 11899 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11900 const FieldDecl *FD, bool InNonTrivialUnion) { 11901 if (const auto *AT = S.Context.getAsArrayType(QT)) 11902 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11903 InNonTrivialUnion); 11904 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11905 } 11906 11907 void visitARCStrong(QualType QT, const FieldDecl *FD, 11908 bool InNonTrivialUnion) { 11909 if (InNonTrivialUnion) 11910 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11911 << 1 << 2 << QT << FD->getName(); 11912 } 11913 11914 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11915 if (InNonTrivialUnion) 11916 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11917 << 1 << 2 << QT << FD->getName(); 11918 } 11919 11920 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11921 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11922 if (RD->isUnion()) { 11923 if (OrigLoc.isValid()) { 11924 bool IsUnion = false; 11925 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11926 IsUnion = OrigRD->isUnion(); 11927 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11928 << 2 << OrigTy << IsUnion << UseContext; 11929 // Reset OrigLoc so that this diagnostic is emitted only once. 11930 OrigLoc = SourceLocation(); 11931 } 11932 InNonTrivialUnion = true; 11933 } 11934 11935 if (InNonTrivialUnion) 11936 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11937 << 0 << 2 << QT.getUnqualifiedType() << ""; 11938 11939 for (const FieldDecl *FD : RD->fields()) 11940 if (!shouldIgnoreForRecordTriviality(FD)) 11941 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11942 } 11943 11944 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 11945 const FieldDecl *FD, bool InNonTrivialUnion) {} 11946 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11947 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 11948 bool InNonTrivialUnion) {} 11949 11950 // The non-trivial C union type or the struct/union type that contains a 11951 // non-trivial C union. 11952 QualType OrigTy; 11953 SourceLocation OrigLoc; 11954 Sema::NonTrivialCUnionContext UseContext; 11955 Sema &S; 11956 }; 11957 11958 } // namespace 11959 11960 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 11961 NonTrivialCUnionContext UseContext, 11962 unsigned NonTrivialKind) { 11963 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11964 QT.hasNonTrivialToPrimitiveDestructCUnion() || 11965 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 11966 "shouldn't be called if type doesn't have a non-trivial C union"); 11967 11968 if ((NonTrivialKind & NTCUK_Init) && 11969 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11970 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 11971 .visit(QT, nullptr, false); 11972 if ((NonTrivialKind & NTCUK_Destruct) && 11973 QT.hasNonTrivialToPrimitiveDestructCUnion()) 11974 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 11975 .visit(QT, nullptr, false); 11976 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 11977 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 11978 .visit(QT, nullptr, false); 11979 } 11980 11981 /// AddInitializerToDecl - Adds the initializer Init to the 11982 /// declaration dcl. If DirectInit is true, this is C++ direct 11983 /// initialization rather than copy initialization. 11984 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11985 // If there is no declaration, there was an error parsing it. Just ignore 11986 // the initializer. 11987 if (!RealDecl || RealDecl->isInvalidDecl()) { 11988 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11989 return; 11990 } 11991 11992 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11993 // Pure-specifiers are handled in ActOnPureSpecifier. 11994 Diag(Method->getLocation(), diag::err_member_function_initialization) 11995 << Method->getDeclName() << Init->getSourceRange(); 11996 Method->setInvalidDecl(); 11997 return; 11998 } 11999 12000 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12001 if (!VDecl) { 12002 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 12003 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12004 RealDecl->setInvalidDecl(); 12005 return; 12006 } 12007 12008 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12009 if (VDecl->getType()->isUndeducedType()) { 12010 // Attempt typo correction early so that the type of the init expression can 12011 // be deduced based on the chosen correction if the original init contains a 12012 // TypoExpr. 12013 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12014 if (!Res.isUsable()) { 12015 // There are unresolved typos in Init, just drop them. 12016 // FIXME: improve the recovery strategy to preserve the Init. 12017 RealDecl->setInvalidDecl(); 12018 return; 12019 } 12020 if (Res.get()->containsErrors()) { 12021 // Invalidate the decl as we don't know the type for recovery-expr yet. 12022 RealDecl->setInvalidDecl(); 12023 VDecl->setInit(Res.get()); 12024 return; 12025 } 12026 Init = Res.get(); 12027 12028 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12029 return; 12030 } 12031 12032 // dllimport cannot be used on variable definitions. 12033 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12034 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12035 VDecl->setInvalidDecl(); 12036 return; 12037 } 12038 12039 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12040 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12041 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12042 VDecl->setInvalidDecl(); 12043 return; 12044 } 12045 12046 if (!VDecl->getType()->isDependentType()) { 12047 // A definition must end up with a complete type, which means it must be 12048 // complete with the restriction that an array type might be completed by 12049 // the initializer; note that later code assumes this restriction. 12050 QualType BaseDeclType = VDecl->getType(); 12051 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12052 BaseDeclType = Array->getElementType(); 12053 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12054 diag::err_typecheck_decl_incomplete_type)) { 12055 RealDecl->setInvalidDecl(); 12056 return; 12057 } 12058 12059 // The variable can not have an abstract class type. 12060 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12061 diag::err_abstract_type_in_decl, 12062 AbstractVariableType)) 12063 VDecl->setInvalidDecl(); 12064 } 12065 12066 // If adding the initializer will turn this declaration into a definition, 12067 // and we already have a definition for this variable, diagnose or otherwise 12068 // handle the situation. 12069 VarDecl *Def; 12070 if ((Def = VDecl->getDefinition()) && Def != VDecl && 12071 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12072 !VDecl->isThisDeclarationADemotedDefinition() && 12073 checkVarDeclRedefinition(Def, VDecl)) 12074 return; 12075 12076 if (getLangOpts().CPlusPlus) { 12077 // C++ [class.static.data]p4 12078 // If a static data member is of const integral or const 12079 // enumeration type, its declaration in the class definition can 12080 // specify a constant-initializer which shall be an integral 12081 // constant expression (5.19). In that case, the member can appear 12082 // in integral constant expressions. The member shall still be 12083 // defined in a namespace scope if it is used in the program and the 12084 // namespace scope definition shall not contain an initializer. 12085 // 12086 // We already performed a redefinition check above, but for static 12087 // data members we also need to check whether there was an in-class 12088 // declaration with an initializer. 12089 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12090 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12091 << VDecl->getDeclName(); 12092 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12093 diag::note_previous_initializer) 12094 << 0; 12095 return; 12096 } 12097 12098 if (VDecl->hasLocalStorage()) 12099 setFunctionHasBranchProtectedScope(); 12100 12101 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12102 VDecl->setInvalidDecl(); 12103 return; 12104 } 12105 } 12106 12107 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12108 // a kernel function cannot be initialized." 12109 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12110 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12111 VDecl->setInvalidDecl(); 12112 return; 12113 } 12114 12115 // The LoaderUninitialized attribute acts as a definition (of undef). 12116 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12117 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12118 VDecl->setInvalidDecl(); 12119 return; 12120 } 12121 12122 // Get the decls type and save a reference for later, since 12123 // CheckInitializerTypes may change it. 12124 QualType DclT = VDecl->getType(), SavT = DclT; 12125 12126 // Expressions default to 'id' when we're in a debugger 12127 // and we are assigning it to a variable of Objective-C pointer type. 12128 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12129 Init->getType() == Context.UnknownAnyTy) { 12130 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12131 if (Result.isInvalid()) { 12132 VDecl->setInvalidDecl(); 12133 return; 12134 } 12135 Init = Result.get(); 12136 } 12137 12138 // Perform the initialization. 12139 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12140 if (!VDecl->isInvalidDecl()) { 12141 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12142 InitializationKind Kind = InitializationKind::CreateForInit( 12143 VDecl->getLocation(), DirectInit, Init); 12144 12145 MultiExprArg Args = Init; 12146 if (CXXDirectInit) 12147 Args = MultiExprArg(CXXDirectInit->getExprs(), 12148 CXXDirectInit->getNumExprs()); 12149 12150 // Try to correct any TypoExprs in the initialization arguments. 12151 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12152 ExprResult Res = CorrectDelayedTyposInExpr( 12153 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12154 [this, Entity, Kind](Expr *E) { 12155 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12156 return Init.Failed() ? ExprError() : E; 12157 }); 12158 if (Res.isInvalid()) { 12159 VDecl->setInvalidDecl(); 12160 } else if (Res.get() != Args[Idx]) { 12161 Args[Idx] = Res.get(); 12162 } 12163 } 12164 if (VDecl->isInvalidDecl()) 12165 return; 12166 12167 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12168 /*TopLevelOfInitList=*/false, 12169 /*TreatUnavailableAsInvalid=*/false); 12170 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12171 if (Result.isInvalid()) { 12172 // If the provied initializer fails to initialize the var decl, 12173 // we attach a recovery expr for better recovery. 12174 auto RecoveryExpr = 12175 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12176 if (RecoveryExpr.get()) 12177 VDecl->setInit(RecoveryExpr.get()); 12178 return; 12179 } 12180 12181 Init = Result.getAs<Expr>(); 12182 } 12183 12184 // Check for self-references within variable initializers. 12185 // Variables declared within a function/method body (except for references) 12186 // are handled by a dataflow analysis. 12187 // This is undefined behavior in C++, but valid in C. 12188 if (getLangOpts().CPlusPlus) { 12189 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12190 VDecl->getType()->isReferenceType()) { 12191 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12192 } 12193 } 12194 12195 // If the type changed, it means we had an incomplete type that was 12196 // completed by the initializer. For example: 12197 // int ary[] = { 1, 3, 5 }; 12198 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12199 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12200 VDecl->setType(DclT); 12201 12202 if (!VDecl->isInvalidDecl()) { 12203 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12204 12205 if (VDecl->hasAttr<BlocksAttr>()) 12206 checkRetainCycles(VDecl, Init); 12207 12208 // It is safe to assign a weak reference into a strong variable. 12209 // Although this code can still have problems: 12210 // id x = self.weakProp; 12211 // id y = self.weakProp; 12212 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12213 // paths through the function. This should be revisited if 12214 // -Wrepeated-use-of-weak is made flow-sensitive. 12215 if (FunctionScopeInfo *FSI = getCurFunction()) 12216 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12217 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12218 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12219 Init->getBeginLoc())) 12220 FSI->markSafeWeakUse(Init); 12221 } 12222 12223 // The initialization is usually a full-expression. 12224 // 12225 // FIXME: If this is a braced initialization of an aggregate, it is not 12226 // an expression, and each individual field initializer is a separate 12227 // full-expression. For instance, in: 12228 // 12229 // struct Temp { ~Temp(); }; 12230 // struct S { S(Temp); }; 12231 // struct T { S a, b; } t = { Temp(), Temp() } 12232 // 12233 // we should destroy the first Temp before constructing the second. 12234 ExprResult Result = 12235 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12236 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12237 if (Result.isInvalid()) { 12238 VDecl->setInvalidDecl(); 12239 return; 12240 } 12241 Init = Result.get(); 12242 12243 // Attach the initializer to the decl. 12244 VDecl->setInit(Init); 12245 12246 if (VDecl->isLocalVarDecl()) { 12247 // Don't check the initializer if the declaration is malformed. 12248 if (VDecl->isInvalidDecl()) { 12249 // do nothing 12250 12251 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12252 // This is true even in C++ for OpenCL. 12253 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12254 CheckForConstantInitializer(Init, DclT); 12255 12256 // Otherwise, C++ does not restrict the initializer. 12257 } else if (getLangOpts().CPlusPlus) { 12258 // do nothing 12259 12260 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12261 // static storage duration shall be constant expressions or string literals. 12262 } else if (VDecl->getStorageClass() == SC_Static) { 12263 CheckForConstantInitializer(Init, DclT); 12264 12265 // C89 is stricter than C99 for aggregate initializers. 12266 // C89 6.5.7p3: All the expressions [...] in an initializer list 12267 // for an object that has aggregate or union type shall be 12268 // constant expressions. 12269 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12270 isa<InitListExpr>(Init)) { 12271 const Expr *Culprit; 12272 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12273 Diag(Culprit->getExprLoc(), 12274 diag::ext_aggregate_init_not_constant) 12275 << Culprit->getSourceRange(); 12276 } 12277 } 12278 12279 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12280 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12281 if (VDecl->hasLocalStorage()) 12282 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12283 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12284 VDecl->getLexicalDeclContext()->isRecord()) { 12285 // This is an in-class initialization for a static data member, e.g., 12286 // 12287 // struct S { 12288 // static const int value = 17; 12289 // }; 12290 12291 // C++ [class.mem]p4: 12292 // A member-declarator can contain a constant-initializer only 12293 // if it declares a static member (9.4) of const integral or 12294 // const enumeration type, see 9.4.2. 12295 // 12296 // C++11 [class.static.data]p3: 12297 // If a non-volatile non-inline const static data member is of integral 12298 // or enumeration type, its declaration in the class definition can 12299 // specify a brace-or-equal-initializer in which every initializer-clause 12300 // that is an assignment-expression is a constant expression. A static 12301 // data member of literal type can be declared in the class definition 12302 // with the constexpr specifier; if so, its declaration shall specify a 12303 // brace-or-equal-initializer in which every initializer-clause that is 12304 // an assignment-expression is a constant expression. 12305 12306 // Do nothing on dependent types. 12307 if (DclT->isDependentType()) { 12308 12309 // Allow any 'static constexpr' members, whether or not they are of literal 12310 // type. We separately check that every constexpr variable is of literal 12311 // type. 12312 } else if (VDecl->isConstexpr()) { 12313 12314 // Require constness. 12315 } else if (!DclT.isConstQualified()) { 12316 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12317 << Init->getSourceRange(); 12318 VDecl->setInvalidDecl(); 12319 12320 // We allow integer constant expressions in all cases. 12321 } else if (DclT->isIntegralOrEnumerationType()) { 12322 // Check whether the expression is a constant expression. 12323 SourceLocation Loc; 12324 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12325 // In C++11, a non-constexpr const static data member with an 12326 // in-class initializer cannot be volatile. 12327 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12328 else if (Init->isValueDependent()) 12329 ; // Nothing to check. 12330 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12331 ; // Ok, it's an ICE! 12332 else if (Init->getType()->isScopedEnumeralType() && 12333 Init->isCXX11ConstantExpr(Context)) 12334 ; // Ok, it is a scoped-enum constant expression. 12335 else if (Init->isEvaluatable(Context)) { 12336 // If we can constant fold the initializer through heroics, accept it, 12337 // but report this as a use of an extension for -pedantic. 12338 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12339 << Init->getSourceRange(); 12340 } else { 12341 // Otherwise, this is some crazy unknown case. Report the issue at the 12342 // location provided by the isIntegerConstantExpr failed check. 12343 Diag(Loc, diag::err_in_class_initializer_non_constant) 12344 << Init->getSourceRange(); 12345 VDecl->setInvalidDecl(); 12346 } 12347 12348 // We allow foldable floating-point constants as an extension. 12349 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12350 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12351 // it anyway and provide a fixit to add the 'constexpr'. 12352 if (getLangOpts().CPlusPlus11) { 12353 Diag(VDecl->getLocation(), 12354 diag::ext_in_class_initializer_float_type_cxx11) 12355 << DclT << Init->getSourceRange(); 12356 Diag(VDecl->getBeginLoc(), 12357 diag::note_in_class_initializer_float_type_cxx11) 12358 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12359 } else { 12360 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12361 << DclT << Init->getSourceRange(); 12362 12363 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12364 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12365 << Init->getSourceRange(); 12366 VDecl->setInvalidDecl(); 12367 } 12368 } 12369 12370 // Suggest adding 'constexpr' in C++11 for literal types. 12371 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12372 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12373 << DclT << Init->getSourceRange() 12374 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12375 VDecl->setConstexpr(true); 12376 12377 } else { 12378 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12379 << DclT << Init->getSourceRange(); 12380 VDecl->setInvalidDecl(); 12381 } 12382 } else if (VDecl->isFileVarDecl()) { 12383 // In C, extern is typically used to avoid tentative definitions when 12384 // declaring variables in headers, but adding an intializer makes it a 12385 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12386 // In C++, extern is often used to give implictly static const variables 12387 // external linkage, so don't warn in that case. If selectany is present, 12388 // this might be header code intended for C and C++ inclusion, so apply the 12389 // C++ rules. 12390 if (VDecl->getStorageClass() == SC_Extern && 12391 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12392 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12393 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12394 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12395 Diag(VDecl->getLocation(), diag::warn_extern_init); 12396 12397 // In Microsoft C++ mode, a const variable defined in namespace scope has 12398 // external linkage by default if the variable is declared with 12399 // __declspec(dllexport). 12400 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12401 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12402 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12403 VDecl->setStorageClass(SC_Extern); 12404 12405 // C99 6.7.8p4. All file scoped initializers need to be constant. 12406 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12407 CheckForConstantInitializer(Init, DclT); 12408 } 12409 12410 QualType InitType = Init->getType(); 12411 if (!InitType.isNull() && 12412 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12413 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12414 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12415 12416 // We will represent direct-initialization similarly to copy-initialization: 12417 // int x(1); -as-> int x = 1; 12418 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12419 // 12420 // Clients that want to distinguish between the two forms, can check for 12421 // direct initializer using VarDecl::getInitStyle(). 12422 // A major benefit is that clients that don't particularly care about which 12423 // exactly form was it (like the CodeGen) can handle both cases without 12424 // special case code. 12425 12426 // C++ 8.5p11: 12427 // The form of initialization (using parentheses or '=') is generally 12428 // insignificant, but does matter when the entity being initialized has a 12429 // class type. 12430 if (CXXDirectInit) { 12431 assert(DirectInit && "Call-style initializer must be direct init."); 12432 VDecl->setInitStyle(VarDecl::CallInit); 12433 } else if (DirectInit) { 12434 // This must be list-initialization. No other way is direct-initialization. 12435 VDecl->setInitStyle(VarDecl::ListInit); 12436 } 12437 12438 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12439 DeclsToCheckForDeferredDiags.push_back(VDecl); 12440 CheckCompleteVariableDeclaration(VDecl); 12441 } 12442 12443 /// ActOnInitializerError - Given that there was an error parsing an 12444 /// initializer for the given declaration, try to return to some form 12445 /// of sanity. 12446 void Sema::ActOnInitializerError(Decl *D) { 12447 // Our main concern here is re-establishing invariants like "a 12448 // variable's type is either dependent or complete". 12449 if (!D || D->isInvalidDecl()) return; 12450 12451 VarDecl *VD = dyn_cast<VarDecl>(D); 12452 if (!VD) return; 12453 12454 // Bindings are not usable if we can't make sense of the initializer. 12455 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12456 for (auto *BD : DD->bindings()) 12457 BD->setInvalidDecl(); 12458 12459 // Auto types are meaningless if we can't make sense of the initializer. 12460 if (VD->getType()->isUndeducedType()) { 12461 D->setInvalidDecl(); 12462 return; 12463 } 12464 12465 QualType Ty = VD->getType(); 12466 if (Ty->isDependentType()) return; 12467 12468 // Require a complete type. 12469 if (RequireCompleteType(VD->getLocation(), 12470 Context.getBaseElementType(Ty), 12471 diag::err_typecheck_decl_incomplete_type)) { 12472 VD->setInvalidDecl(); 12473 return; 12474 } 12475 12476 // Require a non-abstract type. 12477 if (RequireNonAbstractType(VD->getLocation(), Ty, 12478 diag::err_abstract_type_in_decl, 12479 AbstractVariableType)) { 12480 VD->setInvalidDecl(); 12481 return; 12482 } 12483 12484 // Don't bother complaining about constructors or destructors, 12485 // though. 12486 } 12487 12488 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12489 // If there is no declaration, there was an error parsing it. Just ignore it. 12490 if (!RealDecl) 12491 return; 12492 12493 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12494 QualType Type = Var->getType(); 12495 12496 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12497 if (isa<DecompositionDecl>(RealDecl)) { 12498 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12499 Var->setInvalidDecl(); 12500 return; 12501 } 12502 12503 if (Type->isUndeducedType() && 12504 DeduceVariableDeclarationType(Var, false, nullptr)) 12505 return; 12506 12507 // C++11 [class.static.data]p3: A static data member can be declared with 12508 // the constexpr specifier; if so, its declaration shall specify 12509 // a brace-or-equal-initializer. 12510 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12511 // the definition of a variable [...] or the declaration of a static data 12512 // member. 12513 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12514 !Var->isThisDeclarationADemotedDefinition()) { 12515 if (Var->isStaticDataMember()) { 12516 // C++1z removes the relevant rule; the in-class declaration is always 12517 // a definition there. 12518 if (!getLangOpts().CPlusPlus17 && 12519 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12520 Diag(Var->getLocation(), 12521 diag::err_constexpr_static_mem_var_requires_init) 12522 << Var; 12523 Var->setInvalidDecl(); 12524 return; 12525 } 12526 } else { 12527 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12528 Var->setInvalidDecl(); 12529 return; 12530 } 12531 } 12532 12533 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12534 // be initialized. 12535 if (!Var->isInvalidDecl() && 12536 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12537 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12538 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12539 Var->setInvalidDecl(); 12540 return; 12541 } 12542 12543 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12544 if (Var->getStorageClass() == SC_Extern) { 12545 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12546 << Var; 12547 Var->setInvalidDecl(); 12548 return; 12549 } 12550 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12551 diag::err_typecheck_decl_incomplete_type)) { 12552 Var->setInvalidDecl(); 12553 return; 12554 } 12555 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12556 if (!RD->hasTrivialDefaultConstructor()) { 12557 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12558 Var->setInvalidDecl(); 12559 return; 12560 } 12561 } 12562 } 12563 12564 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12565 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12566 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12567 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12568 NTCUC_DefaultInitializedObject, NTCUK_Init); 12569 12570 12571 switch (DefKind) { 12572 case VarDecl::Definition: 12573 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12574 break; 12575 12576 // We have an out-of-line definition of a static data member 12577 // that has an in-class initializer, so we type-check this like 12578 // a declaration. 12579 // 12580 LLVM_FALLTHROUGH; 12581 12582 case VarDecl::DeclarationOnly: 12583 // It's only a declaration. 12584 12585 // Block scope. C99 6.7p7: If an identifier for an object is 12586 // declared with no linkage (C99 6.2.2p6), the type for the 12587 // object shall be complete. 12588 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12589 !Var->hasLinkage() && !Var->isInvalidDecl() && 12590 RequireCompleteType(Var->getLocation(), Type, 12591 diag::err_typecheck_decl_incomplete_type)) 12592 Var->setInvalidDecl(); 12593 12594 // Make sure that the type is not abstract. 12595 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12596 RequireNonAbstractType(Var->getLocation(), Type, 12597 diag::err_abstract_type_in_decl, 12598 AbstractVariableType)) 12599 Var->setInvalidDecl(); 12600 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12601 Var->getStorageClass() == SC_PrivateExtern) { 12602 Diag(Var->getLocation(), diag::warn_private_extern); 12603 Diag(Var->getLocation(), diag::note_private_extern); 12604 } 12605 12606 if (Context.getTargetInfo().allowDebugInfoForExternalVar() && 12607 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12608 ExternalDeclarations.push_back(Var); 12609 12610 return; 12611 12612 case VarDecl::TentativeDefinition: 12613 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12614 // object that has file scope without an initializer, and without a 12615 // storage-class specifier or with the storage-class specifier "static", 12616 // constitutes a tentative definition. Note: A tentative definition with 12617 // external linkage is valid (C99 6.2.2p5). 12618 if (!Var->isInvalidDecl()) { 12619 if (const IncompleteArrayType *ArrayT 12620 = Context.getAsIncompleteArrayType(Type)) { 12621 if (RequireCompleteSizedType( 12622 Var->getLocation(), ArrayT->getElementType(), 12623 diag::err_array_incomplete_or_sizeless_type)) 12624 Var->setInvalidDecl(); 12625 } else if (Var->getStorageClass() == SC_Static) { 12626 // C99 6.9.2p3: If the declaration of an identifier for an object is 12627 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12628 // declared type shall not be an incomplete type. 12629 // NOTE: code such as the following 12630 // static struct s; 12631 // struct s { int a; }; 12632 // is accepted by gcc. Hence here we issue a warning instead of 12633 // an error and we do not invalidate the static declaration. 12634 // NOTE: to avoid multiple warnings, only check the first declaration. 12635 if (Var->isFirstDecl()) 12636 RequireCompleteType(Var->getLocation(), Type, 12637 diag::ext_typecheck_decl_incomplete_type); 12638 } 12639 } 12640 12641 // Record the tentative definition; we're done. 12642 if (!Var->isInvalidDecl()) 12643 TentativeDefinitions.push_back(Var); 12644 return; 12645 } 12646 12647 // Provide a specific diagnostic for uninitialized variable 12648 // definitions with incomplete array type. 12649 if (Type->isIncompleteArrayType()) { 12650 Diag(Var->getLocation(), 12651 diag::err_typecheck_incomplete_array_needs_initializer); 12652 Var->setInvalidDecl(); 12653 return; 12654 } 12655 12656 // Provide a specific diagnostic for uninitialized variable 12657 // definitions with reference type. 12658 if (Type->isReferenceType()) { 12659 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12660 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 12661 Var->setInvalidDecl(); 12662 return; 12663 } 12664 12665 // Do not attempt to type-check the default initializer for a 12666 // variable with dependent type. 12667 if (Type->isDependentType()) 12668 return; 12669 12670 if (Var->isInvalidDecl()) 12671 return; 12672 12673 if (!Var->hasAttr<AliasAttr>()) { 12674 if (RequireCompleteType(Var->getLocation(), 12675 Context.getBaseElementType(Type), 12676 diag::err_typecheck_decl_incomplete_type)) { 12677 Var->setInvalidDecl(); 12678 return; 12679 } 12680 } else { 12681 return; 12682 } 12683 12684 // The variable can not have an abstract class type. 12685 if (RequireNonAbstractType(Var->getLocation(), Type, 12686 diag::err_abstract_type_in_decl, 12687 AbstractVariableType)) { 12688 Var->setInvalidDecl(); 12689 return; 12690 } 12691 12692 // Check for jumps past the implicit initializer. C++0x 12693 // clarifies that this applies to a "variable with automatic 12694 // storage duration", not a "local variable". 12695 // C++11 [stmt.dcl]p3 12696 // A program that jumps from a point where a variable with automatic 12697 // storage duration is not in scope to a point where it is in scope is 12698 // ill-formed unless the variable has scalar type, class type with a 12699 // trivial default constructor and a trivial destructor, a cv-qualified 12700 // version of one of these types, or an array of one of the preceding 12701 // types and is declared without an initializer. 12702 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12703 if (const RecordType *Record 12704 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12705 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12706 // Mark the function (if we're in one) for further checking even if the 12707 // looser rules of C++11 do not require such checks, so that we can 12708 // diagnose incompatibilities with C++98. 12709 if (!CXXRecord->isPOD()) 12710 setFunctionHasBranchProtectedScope(); 12711 } 12712 } 12713 // In OpenCL, we can't initialize objects in the __local address space, 12714 // even implicitly, so don't synthesize an implicit initializer. 12715 if (getLangOpts().OpenCL && 12716 Var->getType().getAddressSpace() == LangAS::opencl_local) 12717 return; 12718 // C++03 [dcl.init]p9: 12719 // If no initializer is specified for an object, and the 12720 // object is of (possibly cv-qualified) non-POD class type (or 12721 // array thereof), the object shall be default-initialized; if 12722 // the object is of const-qualified type, the underlying class 12723 // type shall have a user-declared default 12724 // constructor. Otherwise, if no initializer is specified for 12725 // a non- static object, the object and its subobjects, if 12726 // any, have an indeterminate initial value); if the object 12727 // or any of its subobjects are of const-qualified type, the 12728 // program is ill-formed. 12729 // C++0x [dcl.init]p11: 12730 // If no initializer is specified for an object, the object is 12731 // default-initialized; [...]. 12732 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12733 InitializationKind Kind 12734 = InitializationKind::CreateDefault(Var->getLocation()); 12735 12736 InitializationSequence InitSeq(*this, Entity, Kind, None); 12737 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12738 12739 if (Init.get()) { 12740 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12741 // This is important for template substitution. 12742 Var->setInitStyle(VarDecl::CallInit); 12743 } else if (Init.isInvalid()) { 12744 // If default-init fails, attach a recovery-expr initializer to track 12745 // that initialization was attempted and failed. 12746 auto RecoveryExpr = 12747 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12748 if (RecoveryExpr.get()) 12749 Var->setInit(RecoveryExpr.get()); 12750 } 12751 12752 CheckCompleteVariableDeclaration(Var); 12753 } 12754 } 12755 12756 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12757 // If there is no declaration, there was an error parsing it. Ignore it. 12758 if (!D) 12759 return; 12760 12761 VarDecl *VD = dyn_cast<VarDecl>(D); 12762 if (!VD) { 12763 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12764 D->setInvalidDecl(); 12765 return; 12766 } 12767 12768 VD->setCXXForRangeDecl(true); 12769 12770 // for-range-declaration cannot be given a storage class specifier. 12771 int Error = -1; 12772 switch (VD->getStorageClass()) { 12773 case SC_None: 12774 break; 12775 case SC_Extern: 12776 Error = 0; 12777 break; 12778 case SC_Static: 12779 Error = 1; 12780 break; 12781 case SC_PrivateExtern: 12782 Error = 2; 12783 break; 12784 case SC_Auto: 12785 Error = 3; 12786 break; 12787 case SC_Register: 12788 Error = 4; 12789 break; 12790 } 12791 12792 // for-range-declaration cannot be given a storage class specifier con't. 12793 switch (VD->getTSCSpec()) { 12794 case TSCS_thread_local: 12795 Error = 6; 12796 break; 12797 case TSCS___thread: 12798 case TSCS__Thread_local: 12799 case TSCS_unspecified: 12800 break; 12801 } 12802 12803 if (Error != -1) { 12804 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12805 << VD << Error; 12806 D->setInvalidDecl(); 12807 } 12808 } 12809 12810 StmtResult 12811 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12812 IdentifierInfo *Ident, 12813 ParsedAttributes &Attrs, 12814 SourceLocation AttrEnd) { 12815 // C++1y [stmt.iter]p1: 12816 // A range-based for statement of the form 12817 // for ( for-range-identifier : for-range-initializer ) statement 12818 // is equivalent to 12819 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12820 DeclSpec DS(Attrs.getPool().getFactory()); 12821 12822 const char *PrevSpec; 12823 unsigned DiagID; 12824 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12825 getPrintingPolicy()); 12826 12827 Declarator D(DS, DeclaratorContext::ForInit); 12828 D.SetIdentifier(Ident, IdentLoc); 12829 D.takeAttributes(Attrs, AttrEnd); 12830 12831 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12832 IdentLoc); 12833 Decl *Var = ActOnDeclarator(S, D); 12834 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12835 FinalizeDeclaration(Var); 12836 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12837 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12838 } 12839 12840 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12841 if (var->isInvalidDecl()) return; 12842 12843 if (getLangOpts().OpenCL) { 12844 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12845 // initialiser 12846 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12847 !var->hasInit()) { 12848 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12849 << 1 /*Init*/; 12850 var->setInvalidDecl(); 12851 return; 12852 } 12853 } 12854 12855 // In Objective-C, don't allow jumps past the implicit initialization of a 12856 // local retaining variable. 12857 if (getLangOpts().ObjC && 12858 var->hasLocalStorage()) { 12859 switch (var->getType().getObjCLifetime()) { 12860 case Qualifiers::OCL_None: 12861 case Qualifiers::OCL_ExplicitNone: 12862 case Qualifiers::OCL_Autoreleasing: 12863 break; 12864 12865 case Qualifiers::OCL_Weak: 12866 case Qualifiers::OCL_Strong: 12867 setFunctionHasBranchProtectedScope(); 12868 break; 12869 } 12870 } 12871 12872 if (var->hasLocalStorage() && 12873 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12874 setFunctionHasBranchProtectedScope(); 12875 12876 // Warn about externally-visible variables being defined without a 12877 // prior declaration. We only want to do this for global 12878 // declarations, but we also specifically need to avoid doing it for 12879 // class members because the linkage of an anonymous class can 12880 // change if it's later given a typedef name. 12881 if (var->isThisDeclarationADefinition() && 12882 var->getDeclContext()->getRedeclContext()->isFileContext() && 12883 var->isExternallyVisible() && var->hasLinkage() && 12884 !var->isInline() && !var->getDescribedVarTemplate() && 12885 !isa<VarTemplatePartialSpecializationDecl>(var) && 12886 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12887 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12888 var->getLocation())) { 12889 // Find a previous declaration that's not a definition. 12890 VarDecl *prev = var->getPreviousDecl(); 12891 while (prev && prev->isThisDeclarationADefinition()) 12892 prev = prev->getPreviousDecl(); 12893 12894 if (!prev) { 12895 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12896 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12897 << /* variable */ 0; 12898 } 12899 } 12900 12901 // Cache the result of checking for constant initialization. 12902 Optional<bool> CacheHasConstInit; 12903 const Expr *CacheCulprit = nullptr; 12904 auto checkConstInit = [&]() mutable { 12905 if (!CacheHasConstInit) 12906 CacheHasConstInit = var->getInit()->isConstantInitializer( 12907 Context, var->getType()->isReferenceType(), &CacheCulprit); 12908 return *CacheHasConstInit; 12909 }; 12910 12911 if (var->getTLSKind() == VarDecl::TLS_Static) { 12912 if (var->getType().isDestructedType()) { 12913 // GNU C++98 edits for __thread, [basic.start.term]p3: 12914 // The type of an object with thread storage duration shall not 12915 // have a non-trivial destructor. 12916 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12917 if (getLangOpts().CPlusPlus11) 12918 Diag(var->getLocation(), diag::note_use_thread_local); 12919 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12920 if (!checkConstInit()) { 12921 // GNU C++98 edits for __thread, [basic.start.init]p4: 12922 // An object of thread storage duration shall not require dynamic 12923 // initialization. 12924 // FIXME: Need strict checking here. 12925 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12926 << CacheCulprit->getSourceRange(); 12927 if (getLangOpts().CPlusPlus11) 12928 Diag(var->getLocation(), diag::note_use_thread_local); 12929 } 12930 } 12931 } 12932 12933 // Apply section attributes and pragmas to global variables. 12934 bool GlobalStorage = var->hasGlobalStorage(); 12935 if (GlobalStorage && var->isThisDeclarationADefinition() && 12936 !inTemplateInstantiation()) { 12937 PragmaStack<StringLiteral *> *Stack = nullptr; 12938 int SectionFlags = ASTContext::PSF_Read; 12939 if (var->getType().isConstQualified()) 12940 Stack = &ConstSegStack; 12941 else if (!var->getInit()) { 12942 Stack = &BSSSegStack; 12943 SectionFlags |= ASTContext::PSF_Write; 12944 } else { 12945 Stack = &DataSegStack; 12946 SectionFlags |= ASTContext::PSF_Write; 12947 } 12948 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 12949 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 12950 SectionFlags |= ASTContext::PSF_Implicit; 12951 UnifySection(SA->getName(), SectionFlags, var); 12952 } else if (Stack->CurrentValue) { 12953 SectionFlags |= ASTContext::PSF_Implicit; 12954 auto SectionName = Stack->CurrentValue->getString(); 12955 var->addAttr(SectionAttr::CreateImplicit( 12956 Context, SectionName, Stack->CurrentPragmaLocation, 12957 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 12958 if (UnifySection(SectionName, SectionFlags, var)) 12959 var->dropAttr<SectionAttr>(); 12960 } 12961 12962 // Apply the init_seg attribute if this has an initializer. If the 12963 // initializer turns out to not be dynamic, we'll end up ignoring this 12964 // attribute. 12965 if (CurInitSeg && var->getInit()) 12966 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 12967 CurInitSegLoc, 12968 AttributeCommonInfo::AS_Pragma)); 12969 } 12970 12971 if (!var->getType()->isStructureType() && var->hasInit() && 12972 isa<InitListExpr>(var->getInit())) { 12973 const auto *ILE = cast<InitListExpr>(var->getInit()); 12974 unsigned NumInits = ILE->getNumInits(); 12975 if (NumInits > 2) 12976 for (unsigned I = 0; I < NumInits; ++I) { 12977 const auto *Init = ILE->getInit(I); 12978 if (!Init) 12979 break; 12980 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 12981 if (!SL) 12982 break; 12983 12984 unsigned NumConcat = SL->getNumConcatenated(); 12985 // Diagnose missing comma in string array initialization. 12986 // Do not warn when all the elements in the initializer are concatenated 12987 // together. Do not warn for macros too. 12988 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 12989 bool OnlyOneMissingComma = true; 12990 for (unsigned J = I + 1; J < NumInits; ++J) { 12991 const auto *Init = ILE->getInit(J); 12992 if (!Init) 12993 break; 12994 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 12995 if (!SLJ || SLJ->getNumConcatenated() > 1) { 12996 OnlyOneMissingComma = false; 12997 break; 12998 } 12999 } 13000 13001 if (OnlyOneMissingComma) { 13002 SmallVector<FixItHint, 1> Hints; 13003 for (unsigned i = 0; i < NumConcat - 1; ++i) 13004 Hints.push_back(FixItHint::CreateInsertion( 13005 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13006 13007 Diag(SL->getStrTokenLoc(1), 13008 diag::warn_concatenated_literal_array_init) 13009 << Hints; 13010 Diag(SL->getBeginLoc(), 13011 diag::note_concatenated_string_literal_silence); 13012 } 13013 // In any case, stop now. 13014 break; 13015 } 13016 } 13017 } 13018 13019 // All the following checks are C++ only. 13020 if (!getLangOpts().CPlusPlus) { 13021 // If this variable must be emitted, add it as an initializer for the 13022 // current module. 13023 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13024 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13025 return; 13026 } 13027 13028 QualType type = var->getType(); 13029 13030 if (var->hasAttr<BlocksAttr>()) 13031 getCurFunction()->addByrefBlockVar(var); 13032 13033 Expr *Init = var->getInit(); 13034 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13035 QualType baseType = Context.getBaseElementType(type); 13036 13037 // Check whether the initializer is sufficiently constant. 13038 if (!type->isDependentType() && Init && !Init->isValueDependent() && 13039 (GlobalStorage || var->isConstexpr() || 13040 var->mightBeUsableInConstantExpressions(Context))) { 13041 // If this variable might have a constant initializer or might be usable in 13042 // constant expressions, check whether or not it actually is now. We can't 13043 // do this lazily, because the result might depend on things that change 13044 // later, such as which constexpr functions happen to be defined. 13045 SmallVector<PartialDiagnosticAt, 8> Notes; 13046 bool HasConstInit; 13047 if (!getLangOpts().CPlusPlus11) { 13048 // Prior to C++11, in contexts where a constant initializer is required, 13049 // the set of valid constant initializers is described by syntactic rules 13050 // in [expr.const]p2-6. 13051 // FIXME: Stricter checking for these rules would be useful for constinit / 13052 // -Wglobal-constructors. 13053 HasConstInit = checkConstInit(); 13054 13055 // Compute and cache the constant value, and remember that we have a 13056 // constant initializer. 13057 if (HasConstInit) { 13058 (void)var->checkForConstantInitialization(Notes); 13059 Notes.clear(); 13060 } else if (CacheCulprit) { 13061 Notes.emplace_back(CacheCulprit->getExprLoc(), 13062 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13063 Notes.back().second << CacheCulprit->getSourceRange(); 13064 } 13065 } else { 13066 // Evaluate the initializer to see if it's a constant initializer. 13067 HasConstInit = var->checkForConstantInitialization(Notes); 13068 } 13069 13070 if (HasConstInit) { 13071 // FIXME: Consider replacing the initializer with a ConstantExpr. 13072 } else if (var->isConstexpr()) { 13073 SourceLocation DiagLoc = var->getLocation(); 13074 // If the note doesn't add any useful information other than a source 13075 // location, fold it into the primary diagnostic. 13076 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13077 diag::note_invalid_subexpr_in_const_expr) { 13078 DiagLoc = Notes[0].first; 13079 Notes.clear(); 13080 } 13081 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13082 << var << Init->getSourceRange(); 13083 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13084 Diag(Notes[I].first, Notes[I].second); 13085 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13086 auto *Attr = var->getAttr<ConstInitAttr>(); 13087 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13088 << Init->getSourceRange(); 13089 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13090 << Attr->getRange() << Attr->isConstinit(); 13091 for (auto &it : Notes) 13092 Diag(it.first, it.second); 13093 } else if (IsGlobal && 13094 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13095 var->getLocation())) { 13096 // Warn about globals which don't have a constant initializer. Don't 13097 // warn about globals with a non-trivial destructor because we already 13098 // warned about them. 13099 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13100 if (!(RD && !RD->hasTrivialDestructor())) { 13101 // checkConstInit() here permits trivial default initialization even in 13102 // C++11 onwards, where such an initializer is not a constant initializer 13103 // but nonetheless doesn't require a global constructor. 13104 if (!checkConstInit()) 13105 Diag(var->getLocation(), diag::warn_global_constructor) 13106 << Init->getSourceRange(); 13107 } 13108 } 13109 } 13110 13111 // Require the destructor. 13112 if (!type->isDependentType()) 13113 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13114 FinalizeVarWithDestructor(var, recordType); 13115 13116 // If this variable must be emitted, add it as an initializer for the current 13117 // module. 13118 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13119 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13120 13121 // Build the bindings if this is a structured binding declaration. 13122 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13123 CheckCompleteDecompositionDeclaration(DD); 13124 } 13125 13126 /// Determines if a variable's alignment is dependent. 13127 static bool hasDependentAlignment(VarDecl *VD) { 13128 if (VD->getType()->isDependentType()) 13129 return true; 13130 for (auto *I : VD->specific_attrs<AlignedAttr>()) 13131 if (I->isAlignmentDependent()) 13132 return true; 13133 return false; 13134 } 13135 13136 /// Check if VD needs to be dllexport/dllimport due to being in a 13137 /// dllexport/import function. 13138 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13139 assert(VD->isStaticLocal()); 13140 13141 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13142 13143 // Find outermost function when VD is in lambda function. 13144 while (FD && !getDLLAttr(FD) && 13145 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13146 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13147 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13148 } 13149 13150 if (!FD) 13151 return; 13152 13153 // Static locals inherit dll attributes from their function. 13154 if (Attr *A = getDLLAttr(FD)) { 13155 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13156 NewAttr->setInherited(true); 13157 VD->addAttr(NewAttr); 13158 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13159 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13160 NewAttr->setInherited(true); 13161 VD->addAttr(NewAttr); 13162 13163 // Export this function to enforce exporting this static variable even 13164 // if it is not used in this compilation unit. 13165 if (!FD->hasAttr<DLLExportAttr>()) 13166 FD->addAttr(NewAttr); 13167 13168 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13169 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13170 NewAttr->setInherited(true); 13171 VD->addAttr(NewAttr); 13172 } 13173 } 13174 13175 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13176 /// any semantic actions necessary after any initializer has been attached. 13177 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13178 // Note that we are no longer parsing the initializer for this declaration. 13179 ParsingInitForAutoVars.erase(ThisDecl); 13180 13181 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13182 if (!VD) 13183 return; 13184 13185 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13186 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13187 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13188 if (PragmaClangBSSSection.Valid) 13189 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13190 Context, PragmaClangBSSSection.SectionName, 13191 PragmaClangBSSSection.PragmaLocation, 13192 AttributeCommonInfo::AS_Pragma)); 13193 if (PragmaClangDataSection.Valid) 13194 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13195 Context, PragmaClangDataSection.SectionName, 13196 PragmaClangDataSection.PragmaLocation, 13197 AttributeCommonInfo::AS_Pragma)); 13198 if (PragmaClangRodataSection.Valid) 13199 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13200 Context, PragmaClangRodataSection.SectionName, 13201 PragmaClangRodataSection.PragmaLocation, 13202 AttributeCommonInfo::AS_Pragma)); 13203 if (PragmaClangRelroSection.Valid) 13204 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13205 Context, PragmaClangRelroSection.SectionName, 13206 PragmaClangRelroSection.PragmaLocation, 13207 AttributeCommonInfo::AS_Pragma)); 13208 } 13209 13210 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13211 for (auto *BD : DD->bindings()) { 13212 FinalizeDeclaration(BD); 13213 } 13214 } 13215 13216 checkAttributesAfterMerging(*this, *VD); 13217 13218 // Perform TLS alignment check here after attributes attached to the variable 13219 // which may affect the alignment have been processed. Only perform the check 13220 // if the target has a maximum TLS alignment (zero means no constraints). 13221 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13222 // Protect the check so that it's not performed on dependent types and 13223 // dependent alignments (we can't determine the alignment in that case). 13224 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 13225 !VD->isInvalidDecl()) { 13226 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13227 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13228 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13229 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13230 << (unsigned)MaxAlignChars.getQuantity(); 13231 } 13232 } 13233 } 13234 13235 if (VD->isStaticLocal()) 13236 CheckStaticLocalForDllExport(VD); 13237 13238 // Perform check for initializers of device-side global variables. 13239 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13240 // 7.5). We must also apply the same checks to all __shared__ 13241 // variables whether they are local or not. CUDA also allows 13242 // constant initializers for __constant__ and __device__ variables. 13243 if (getLangOpts().CUDA) 13244 checkAllowedCUDAInitializer(VD); 13245 13246 // Grab the dllimport or dllexport attribute off of the VarDecl. 13247 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13248 13249 // Imported static data members cannot be defined out-of-line. 13250 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13251 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13252 VD->isThisDeclarationADefinition()) { 13253 // We allow definitions of dllimport class template static data members 13254 // with a warning. 13255 CXXRecordDecl *Context = 13256 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13257 bool IsClassTemplateMember = 13258 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13259 Context->getDescribedClassTemplate(); 13260 13261 Diag(VD->getLocation(), 13262 IsClassTemplateMember 13263 ? diag::warn_attribute_dllimport_static_field_definition 13264 : diag::err_attribute_dllimport_static_field_definition); 13265 Diag(IA->getLocation(), diag::note_attribute); 13266 if (!IsClassTemplateMember) 13267 VD->setInvalidDecl(); 13268 } 13269 } 13270 13271 // dllimport/dllexport variables cannot be thread local, their TLS index 13272 // isn't exported with the variable. 13273 if (DLLAttr && VD->getTLSKind()) { 13274 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13275 if (F && getDLLAttr(F)) { 13276 assert(VD->isStaticLocal()); 13277 // But if this is a static local in a dlimport/dllexport function, the 13278 // function will never be inlined, which means the var would never be 13279 // imported, so having it marked import/export is safe. 13280 } else { 13281 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13282 << DLLAttr; 13283 VD->setInvalidDecl(); 13284 } 13285 } 13286 13287 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13288 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13289 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 13290 VD->dropAttr<UsedAttr>(); 13291 } 13292 } 13293 13294 const DeclContext *DC = VD->getDeclContext(); 13295 // If there's a #pragma GCC visibility in scope, and this isn't a class 13296 // member, set the visibility of this variable. 13297 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13298 AddPushedVisibilityAttribute(VD); 13299 13300 // FIXME: Warn on unused var template partial specializations. 13301 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13302 MarkUnusedFileScopedDecl(VD); 13303 13304 // Now we have parsed the initializer and can update the table of magic 13305 // tag values. 13306 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13307 !VD->getType()->isIntegralOrEnumerationType()) 13308 return; 13309 13310 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13311 const Expr *MagicValueExpr = VD->getInit(); 13312 if (!MagicValueExpr) { 13313 continue; 13314 } 13315 Optional<llvm::APSInt> MagicValueInt; 13316 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13317 Diag(I->getRange().getBegin(), 13318 diag::err_type_tag_for_datatype_not_ice) 13319 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13320 continue; 13321 } 13322 if (MagicValueInt->getActiveBits() > 64) { 13323 Diag(I->getRange().getBegin(), 13324 diag::err_type_tag_for_datatype_too_large) 13325 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13326 continue; 13327 } 13328 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13329 RegisterTypeTagForDatatype(I->getArgumentKind(), 13330 MagicValue, 13331 I->getMatchingCType(), 13332 I->getLayoutCompatible(), 13333 I->getMustBeNull()); 13334 } 13335 } 13336 13337 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13338 auto *VD = dyn_cast<VarDecl>(DD); 13339 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13340 } 13341 13342 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13343 ArrayRef<Decl *> Group) { 13344 SmallVector<Decl*, 8> Decls; 13345 13346 if (DS.isTypeSpecOwned()) 13347 Decls.push_back(DS.getRepAsDecl()); 13348 13349 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13350 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13351 bool DiagnosedMultipleDecomps = false; 13352 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13353 bool DiagnosedNonDeducedAuto = false; 13354 13355 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13356 if (Decl *D = Group[i]) { 13357 // For declarators, there are some additional syntactic-ish checks we need 13358 // to perform. 13359 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13360 if (!FirstDeclaratorInGroup) 13361 FirstDeclaratorInGroup = DD; 13362 if (!FirstDecompDeclaratorInGroup) 13363 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13364 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13365 !hasDeducedAuto(DD)) 13366 FirstNonDeducedAutoInGroup = DD; 13367 13368 if (FirstDeclaratorInGroup != DD) { 13369 // A decomposition declaration cannot be combined with any other 13370 // declaration in the same group. 13371 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13372 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13373 diag::err_decomp_decl_not_alone) 13374 << FirstDeclaratorInGroup->getSourceRange() 13375 << DD->getSourceRange(); 13376 DiagnosedMultipleDecomps = true; 13377 } 13378 13379 // A declarator that uses 'auto' in any way other than to declare a 13380 // variable with a deduced type cannot be combined with any other 13381 // declarator in the same group. 13382 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13383 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13384 diag::err_auto_non_deduced_not_alone) 13385 << FirstNonDeducedAutoInGroup->getType() 13386 ->hasAutoForTrailingReturnType() 13387 << FirstDeclaratorInGroup->getSourceRange() 13388 << DD->getSourceRange(); 13389 DiagnosedNonDeducedAuto = true; 13390 } 13391 } 13392 } 13393 13394 Decls.push_back(D); 13395 } 13396 } 13397 13398 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13399 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13400 handleTagNumbering(Tag, S); 13401 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13402 getLangOpts().CPlusPlus) 13403 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13404 } 13405 } 13406 13407 return BuildDeclaratorGroup(Decls); 13408 } 13409 13410 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13411 /// group, performing any necessary semantic checking. 13412 Sema::DeclGroupPtrTy 13413 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13414 // C++14 [dcl.spec.auto]p7: (DR1347) 13415 // If the type that replaces the placeholder type is not the same in each 13416 // deduction, the program is ill-formed. 13417 if (Group.size() > 1) { 13418 QualType Deduced; 13419 VarDecl *DeducedDecl = nullptr; 13420 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13421 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13422 if (!D || D->isInvalidDecl()) 13423 break; 13424 DeducedType *DT = D->getType()->getContainedDeducedType(); 13425 if (!DT || DT->getDeducedType().isNull()) 13426 continue; 13427 if (Deduced.isNull()) { 13428 Deduced = DT->getDeducedType(); 13429 DeducedDecl = D; 13430 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13431 auto *AT = dyn_cast<AutoType>(DT); 13432 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13433 diag::err_auto_different_deductions) 13434 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13435 << DeducedDecl->getDeclName() << DT->getDeducedType() 13436 << D->getDeclName(); 13437 if (DeducedDecl->hasInit()) 13438 Dia << DeducedDecl->getInit()->getSourceRange(); 13439 if (D->getInit()) 13440 Dia << D->getInit()->getSourceRange(); 13441 D->setInvalidDecl(); 13442 break; 13443 } 13444 } 13445 } 13446 13447 ActOnDocumentableDecls(Group); 13448 13449 return DeclGroupPtrTy::make( 13450 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13451 } 13452 13453 void Sema::ActOnDocumentableDecl(Decl *D) { 13454 ActOnDocumentableDecls(D); 13455 } 13456 13457 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13458 // Don't parse the comment if Doxygen diagnostics are ignored. 13459 if (Group.empty() || !Group[0]) 13460 return; 13461 13462 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13463 Group[0]->getLocation()) && 13464 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13465 Group[0]->getLocation())) 13466 return; 13467 13468 if (Group.size() >= 2) { 13469 // This is a decl group. Normally it will contain only declarations 13470 // produced from declarator list. But in case we have any definitions or 13471 // additional declaration references: 13472 // 'typedef struct S {} S;' 13473 // 'typedef struct S *S;' 13474 // 'struct S *pS;' 13475 // FinalizeDeclaratorGroup adds these as separate declarations. 13476 Decl *MaybeTagDecl = Group[0]; 13477 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13478 Group = Group.slice(1); 13479 } 13480 } 13481 13482 // FIMXE: We assume every Decl in the group is in the same file. 13483 // This is false when preprocessor constructs the group from decls in 13484 // different files (e. g. macros or #include). 13485 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13486 } 13487 13488 /// Common checks for a parameter-declaration that should apply to both function 13489 /// parameters and non-type template parameters. 13490 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13491 // Check that there are no default arguments inside the type of this 13492 // parameter. 13493 if (getLangOpts().CPlusPlus) 13494 CheckExtraCXXDefaultArguments(D); 13495 13496 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13497 if (D.getCXXScopeSpec().isSet()) { 13498 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13499 << D.getCXXScopeSpec().getRange(); 13500 } 13501 13502 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13503 // simple identifier except [...irrelevant cases...]. 13504 switch (D.getName().getKind()) { 13505 case UnqualifiedIdKind::IK_Identifier: 13506 break; 13507 13508 case UnqualifiedIdKind::IK_OperatorFunctionId: 13509 case UnqualifiedIdKind::IK_ConversionFunctionId: 13510 case UnqualifiedIdKind::IK_LiteralOperatorId: 13511 case UnqualifiedIdKind::IK_ConstructorName: 13512 case UnqualifiedIdKind::IK_DestructorName: 13513 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13514 case UnqualifiedIdKind::IK_DeductionGuideName: 13515 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13516 << GetNameForDeclarator(D).getName(); 13517 break; 13518 13519 case UnqualifiedIdKind::IK_TemplateId: 13520 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13521 // GetNameForDeclarator would not produce a useful name in this case. 13522 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13523 break; 13524 } 13525 } 13526 13527 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13528 /// to introduce parameters into function prototype scope. 13529 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13530 const DeclSpec &DS = D.getDeclSpec(); 13531 13532 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13533 13534 // C++03 [dcl.stc]p2 also permits 'auto'. 13535 StorageClass SC = SC_None; 13536 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13537 SC = SC_Register; 13538 // In C++11, the 'register' storage class specifier is deprecated. 13539 // In C++17, it is not allowed, but we tolerate it as an extension. 13540 if (getLangOpts().CPlusPlus11) { 13541 Diag(DS.getStorageClassSpecLoc(), 13542 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13543 : diag::warn_deprecated_register) 13544 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13545 } 13546 } else if (getLangOpts().CPlusPlus && 13547 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13548 SC = SC_Auto; 13549 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13550 Diag(DS.getStorageClassSpecLoc(), 13551 diag::err_invalid_storage_class_in_func_decl); 13552 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13553 } 13554 13555 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13556 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13557 << DeclSpec::getSpecifierName(TSCS); 13558 if (DS.isInlineSpecified()) 13559 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13560 << getLangOpts().CPlusPlus17; 13561 if (DS.hasConstexprSpecifier()) 13562 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13563 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 13564 13565 DiagnoseFunctionSpecifiers(DS); 13566 13567 CheckFunctionOrTemplateParamDeclarator(S, D); 13568 13569 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13570 QualType parmDeclType = TInfo->getType(); 13571 13572 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13573 IdentifierInfo *II = D.getIdentifier(); 13574 if (II) { 13575 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13576 ForVisibleRedeclaration); 13577 LookupName(R, S); 13578 if (R.isSingleResult()) { 13579 NamedDecl *PrevDecl = R.getFoundDecl(); 13580 if (PrevDecl->isTemplateParameter()) { 13581 // Maybe we will complain about the shadowed template parameter. 13582 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13583 // Just pretend that we didn't see the previous declaration. 13584 PrevDecl = nullptr; 13585 } else if (S->isDeclScope(PrevDecl)) { 13586 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13587 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13588 13589 // Recover by removing the name 13590 II = nullptr; 13591 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13592 D.setInvalidType(true); 13593 } 13594 } 13595 } 13596 13597 // Temporarily put parameter variables in the translation unit, not 13598 // the enclosing context. This prevents them from accidentally 13599 // looking like class members in C++. 13600 ParmVarDecl *New = 13601 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13602 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13603 13604 if (D.isInvalidType()) 13605 New->setInvalidDecl(); 13606 13607 assert(S->isFunctionPrototypeScope()); 13608 assert(S->getFunctionPrototypeDepth() >= 1); 13609 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13610 S->getNextFunctionPrototypeIndex()); 13611 13612 // Add the parameter declaration into this scope. 13613 S->AddDecl(New); 13614 if (II) 13615 IdResolver.AddDecl(New); 13616 13617 ProcessDeclAttributes(S, New, D); 13618 13619 if (D.getDeclSpec().isModulePrivateSpecified()) 13620 Diag(New->getLocation(), diag::err_module_private_local) 13621 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13622 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13623 13624 if (New->hasAttr<BlocksAttr>()) { 13625 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13626 } 13627 13628 if (getLangOpts().OpenCL) 13629 deduceOpenCLAddressSpace(New); 13630 13631 return New; 13632 } 13633 13634 /// Synthesizes a variable for a parameter arising from a 13635 /// typedef. 13636 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13637 SourceLocation Loc, 13638 QualType T) { 13639 /* FIXME: setting StartLoc == Loc. 13640 Would it be worth to modify callers so as to provide proper source 13641 location for the unnamed parameters, embedding the parameter's type? */ 13642 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13643 T, Context.getTrivialTypeSourceInfo(T, Loc), 13644 SC_None, nullptr); 13645 Param->setImplicit(); 13646 return Param; 13647 } 13648 13649 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13650 // Don't diagnose unused-parameter errors in template instantiations; we 13651 // will already have done so in the template itself. 13652 if (inTemplateInstantiation()) 13653 return; 13654 13655 for (const ParmVarDecl *Parameter : Parameters) { 13656 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13657 !Parameter->hasAttr<UnusedAttr>()) { 13658 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13659 << Parameter->getDeclName(); 13660 } 13661 } 13662 } 13663 13664 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13665 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13666 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13667 return; 13668 13669 // Warn if the return value is pass-by-value and larger than the specified 13670 // threshold. 13671 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13672 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13673 if (Size > LangOpts.NumLargeByValueCopy) 13674 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 13675 } 13676 13677 // Warn if any parameter is pass-by-value and larger than the specified 13678 // threshold. 13679 for (const ParmVarDecl *Parameter : Parameters) { 13680 QualType T = Parameter->getType(); 13681 if (T->isDependentType() || !T.isPODType(Context)) 13682 continue; 13683 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13684 if (Size > LangOpts.NumLargeByValueCopy) 13685 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13686 << Parameter << Size; 13687 } 13688 } 13689 13690 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13691 SourceLocation NameLoc, IdentifierInfo *Name, 13692 QualType T, TypeSourceInfo *TSInfo, 13693 StorageClass SC) { 13694 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13695 if (getLangOpts().ObjCAutoRefCount && 13696 T.getObjCLifetime() == Qualifiers::OCL_None && 13697 T->isObjCLifetimeType()) { 13698 13699 Qualifiers::ObjCLifetime lifetime; 13700 13701 // Special cases for arrays: 13702 // - if it's const, use __unsafe_unretained 13703 // - otherwise, it's an error 13704 if (T->isArrayType()) { 13705 if (!T.isConstQualified()) { 13706 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13707 DelayedDiagnostics.add( 13708 sema::DelayedDiagnostic::makeForbiddenType( 13709 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13710 else 13711 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13712 << TSInfo->getTypeLoc().getSourceRange(); 13713 } 13714 lifetime = Qualifiers::OCL_ExplicitNone; 13715 } else { 13716 lifetime = T->getObjCARCImplicitLifetime(); 13717 } 13718 T = Context.getLifetimeQualifiedType(T, lifetime); 13719 } 13720 13721 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13722 Context.getAdjustedParameterType(T), 13723 TSInfo, SC, nullptr); 13724 13725 // Make a note if we created a new pack in the scope of a lambda, so that 13726 // we know that references to that pack must also be expanded within the 13727 // lambda scope. 13728 if (New->isParameterPack()) 13729 if (auto *LSI = getEnclosingLambda()) 13730 LSI->LocalPacks.push_back(New); 13731 13732 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13733 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13734 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13735 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13736 13737 // Parameters can not be abstract class types. 13738 // For record types, this is done by the AbstractClassUsageDiagnoser once 13739 // the class has been completely parsed. 13740 if (!CurContext->isRecord() && 13741 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13742 AbstractParamType)) 13743 New->setInvalidDecl(); 13744 13745 // Parameter declarators cannot be interface types. All ObjC objects are 13746 // passed by reference. 13747 if (T->isObjCObjectType()) { 13748 SourceLocation TypeEndLoc = 13749 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13750 Diag(NameLoc, 13751 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13752 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13753 T = Context.getObjCObjectPointerType(T); 13754 New->setType(T); 13755 } 13756 13757 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13758 // duration shall not be qualified by an address-space qualifier." 13759 // Since all parameters have automatic store duration, they can not have 13760 // an address space. 13761 if (T.getAddressSpace() != LangAS::Default && 13762 // OpenCL allows function arguments declared to be an array of a type 13763 // to be qualified with an address space. 13764 !(getLangOpts().OpenCL && 13765 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13766 Diag(NameLoc, diag::err_arg_with_address_space); 13767 New->setInvalidDecl(); 13768 } 13769 13770 // PPC MMA non-pointer types are not allowed as function argument types. 13771 if (Context.getTargetInfo().getTriple().isPPC64() && 13772 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 13773 New->setInvalidDecl(); 13774 } 13775 13776 return New; 13777 } 13778 13779 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13780 SourceLocation LocAfterDecls) { 13781 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13782 13783 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13784 // for a K&R function. 13785 if (!FTI.hasPrototype) { 13786 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13787 --i; 13788 if (FTI.Params[i].Param == nullptr) { 13789 SmallString<256> Code; 13790 llvm::raw_svector_ostream(Code) 13791 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13792 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13793 << FTI.Params[i].Ident 13794 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13795 13796 // Implicitly declare the argument as type 'int' for lack of a better 13797 // type. 13798 AttributeFactory attrs; 13799 DeclSpec DS(attrs); 13800 const char* PrevSpec; // unused 13801 unsigned DiagID; // unused 13802 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13803 DiagID, Context.getPrintingPolicy()); 13804 // Use the identifier location for the type source range. 13805 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13806 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13807 Declarator ParamD(DS, DeclaratorContext::KNRTypeList); 13808 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13809 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13810 } 13811 } 13812 } 13813 } 13814 13815 Decl * 13816 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13817 MultiTemplateParamsArg TemplateParameterLists, 13818 SkipBodyInfo *SkipBody) { 13819 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13820 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13821 Scope *ParentScope = FnBodyScope->getParent(); 13822 13823 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 13824 // we define a non-templated function definition, we will create a declaration 13825 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 13826 // The base function declaration will have the equivalent of an `omp declare 13827 // variant` annotation which specifies the mangled definition as a 13828 // specialization function under the OpenMP context defined as part of the 13829 // `omp begin declare variant`. 13830 SmallVector<FunctionDecl *, 4> Bases; 13831 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 13832 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 13833 ParentScope, D, TemplateParameterLists, Bases); 13834 13835 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 13836 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13837 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13838 13839 if (!Bases.empty()) 13840 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 13841 13842 return Dcl; 13843 } 13844 13845 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13846 Consumer.HandleInlineFunctionDefinition(D); 13847 } 13848 13849 static bool 13850 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13851 const FunctionDecl *&PossiblePrototype) { 13852 // Don't warn about invalid declarations. 13853 if (FD->isInvalidDecl()) 13854 return false; 13855 13856 // Or declarations that aren't global. 13857 if (!FD->isGlobal()) 13858 return false; 13859 13860 // Don't warn about C++ member functions. 13861 if (isa<CXXMethodDecl>(FD)) 13862 return false; 13863 13864 // Don't warn about 'main'. 13865 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13866 if (IdentifierInfo *II = FD->getIdentifier()) 13867 if (II->isStr("main")) 13868 return false; 13869 13870 // Don't warn about inline functions. 13871 if (FD->isInlined()) 13872 return false; 13873 13874 // Don't warn about function templates. 13875 if (FD->getDescribedFunctionTemplate()) 13876 return false; 13877 13878 // Don't warn about function template specializations. 13879 if (FD->isFunctionTemplateSpecialization()) 13880 return false; 13881 13882 // Don't warn for OpenCL kernels. 13883 if (FD->hasAttr<OpenCLKernelAttr>()) 13884 return false; 13885 13886 // Don't warn on explicitly deleted functions. 13887 if (FD->isDeleted()) 13888 return false; 13889 13890 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13891 Prev; Prev = Prev->getPreviousDecl()) { 13892 // Ignore any declarations that occur in function or method 13893 // scope, because they aren't visible from the header. 13894 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13895 continue; 13896 13897 PossiblePrototype = Prev; 13898 return Prev->getType()->isFunctionNoProtoType(); 13899 } 13900 13901 return true; 13902 } 13903 13904 void 13905 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13906 const FunctionDecl *EffectiveDefinition, 13907 SkipBodyInfo *SkipBody) { 13908 const FunctionDecl *Definition = EffectiveDefinition; 13909 if (!Definition && 13910 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 13911 return; 13912 13913 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 13914 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 13915 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13916 // A merged copy of the same function, instantiated as a member of 13917 // the same class, is OK. 13918 if (declaresSameEntity(OrigFD, OrigDef) && 13919 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 13920 cast<Decl>(FD->getLexicalDeclContext()))) 13921 return; 13922 } 13923 } 13924 } 13925 13926 if (canRedefineFunction(Definition, getLangOpts())) 13927 return; 13928 13929 // Don't emit an error when this is redefinition of a typo-corrected 13930 // definition. 13931 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13932 return; 13933 13934 // If we don't have a visible definition of the function, and it's inline or 13935 // a template, skip the new definition. 13936 if (SkipBody && !hasVisibleDefinition(Definition) && 13937 (Definition->getFormalLinkage() == InternalLinkage || 13938 Definition->isInlined() || 13939 Definition->getDescribedFunctionTemplate() || 13940 Definition->getNumTemplateParameterLists())) { 13941 SkipBody->ShouldSkip = true; 13942 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 13943 if (auto *TD = Definition->getDescribedFunctionTemplate()) 13944 makeMergedDefinitionVisible(TD); 13945 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 13946 return; 13947 } 13948 13949 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 13950 Definition->getStorageClass() == SC_Extern) 13951 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 13952 << FD << getLangOpts().CPlusPlus; 13953 else 13954 Diag(FD->getLocation(), diag::err_redefinition) << FD; 13955 13956 Diag(Definition->getLocation(), diag::note_previous_definition); 13957 FD->setInvalidDecl(); 13958 } 13959 13960 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 13961 Sema &S) { 13962 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 13963 13964 LambdaScopeInfo *LSI = S.PushLambdaScope(); 13965 LSI->CallOperator = CallOperator; 13966 LSI->Lambda = LambdaClass; 13967 LSI->ReturnType = CallOperator->getReturnType(); 13968 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 13969 13970 if (LCD == LCD_None) 13971 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 13972 else if (LCD == LCD_ByCopy) 13973 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 13974 else if (LCD == LCD_ByRef) 13975 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 13976 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 13977 13978 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 13979 LSI->Mutable = !CallOperator->isConst(); 13980 13981 // Add the captures to the LSI so they can be noted as already 13982 // captured within tryCaptureVar. 13983 auto I = LambdaClass->field_begin(); 13984 for (const auto &C : LambdaClass->captures()) { 13985 if (C.capturesVariable()) { 13986 VarDecl *VD = C.getCapturedVar(); 13987 if (VD->isInitCapture()) 13988 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 13989 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 13990 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 13991 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 13992 /*EllipsisLoc*/C.isPackExpansion() 13993 ? C.getEllipsisLoc() : SourceLocation(), 13994 I->getType(), /*Invalid*/false); 13995 13996 } else if (C.capturesThis()) { 13997 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 13998 C.getCaptureKind() == LCK_StarThis); 13999 } else { 14000 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14001 I->getType()); 14002 } 14003 ++I; 14004 } 14005 } 14006 14007 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14008 SkipBodyInfo *SkipBody) { 14009 if (!D) { 14010 // Parsing the function declaration failed in some way. Push on a fake scope 14011 // anyway so we can try to parse the function body. 14012 PushFunctionScope(); 14013 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14014 return D; 14015 } 14016 14017 FunctionDecl *FD = nullptr; 14018 14019 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14020 FD = FunTmpl->getTemplatedDecl(); 14021 else 14022 FD = cast<FunctionDecl>(D); 14023 14024 // Do not push if it is a lambda because one is already pushed when building 14025 // the lambda in ActOnStartOfLambdaDefinition(). 14026 if (!isLambdaCallOperator(FD)) 14027 PushExpressionEvaluationContext( 14028 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14029 : ExprEvalContexts.back().Context); 14030 14031 // Check for defining attributes before the check for redefinition. 14032 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14033 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14034 FD->dropAttr<AliasAttr>(); 14035 FD->setInvalidDecl(); 14036 } 14037 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14038 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14039 FD->dropAttr<IFuncAttr>(); 14040 FD->setInvalidDecl(); 14041 } 14042 14043 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14044 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14045 Ctor->isDefaultConstructor() && 14046 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14047 // If this is an MS ABI dllexport default constructor, instantiate any 14048 // default arguments. 14049 InstantiateDefaultCtorDefaultArgs(Ctor); 14050 } 14051 } 14052 14053 // See if this is a redefinition. If 'will have body' (or similar) is already 14054 // set, then these checks were already performed when it was set. 14055 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14056 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14057 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14058 14059 // If we're skipping the body, we're done. Don't enter the scope. 14060 if (SkipBody && SkipBody->ShouldSkip) 14061 return D; 14062 } 14063 14064 // Mark this function as "will have a body eventually". This lets users to 14065 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14066 // this function. 14067 FD->setWillHaveBody(); 14068 14069 // If we are instantiating a generic lambda call operator, push 14070 // a LambdaScopeInfo onto the function stack. But use the information 14071 // that's already been calculated (ActOnLambdaExpr) to prime the current 14072 // LambdaScopeInfo. 14073 // When the template operator is being specialized, the LambdaScopeInfo, 14074 // has to be properly restored so that tryCaptureVariable doesn't try 14075 // and capture any new variables. In addition when calculating potential 14076 // captures during transformation of nested lambdas, it is necessary to 14077 // have the LSI properly restored. 14078 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14079 assert(inTemplateInstantiation() && 14080 "There should be an active template instantiation on the stack " 14081 "when instantiating a generic lambda!"); 14082 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14083 } else { 14084 // Enter a new function scope 14085 PushFunctionScope(); 14086 } 14087 14088 // Builtin functions cannot be defined. 14089 if (unsigned BuiltinID = FD->getBuiltinID()) { 14090 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14091 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14092 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14093 FD->setInvalidDecl(); 14094 } 14095 } 14096 14097 // The return type of a function definition must be complete 14098 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14099 QualType ResultType = FD->getReturnType(); 14100 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14101 !FD->isInvalidDecl() && 14102 RequireCompleteType(FD->getLocation(), ResultType, 14103 diag::err_func_def_incomplete_result)) 14104 FD->setInvalidDecl(); 14105 14106 if (FnBodyScope) 14107 PushDeclContext(FnBodyScope, FD); 14108 14109 // Check the validity of our function parameters 14110 CheckParmsForFunctionDef(FD->parameters(), 14111 /*CheckParameterNames=*/true); 14112 14113 // Add non-parameter declarations already in the function to the current 14114 // scope. 14115 if (FnBodyScope) { 14116 for (Decl *NPD : FD->decls()) { 14117 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14118 if (!NonParmDecl) 14119 continue; 14120 assert(!isa<ParmVarDecl>(NonParmDecl) && 14121 "parameters should not be in newly created FD yet"); 14122 14123 // If the decl has a name, make it accessible in the current scope. 14124 if (NonParmDecl->getDeclName()) 14125 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14126 14127 // Similarly, dive into enums and fish their constants out, making them 14128 // accessible in this scope. 14129 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14130 for (auto *EI : ED->enumerators()) 14131 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14132 } 14133 } 14134 } 14135 14136 // Introduce our parameters into the function scope 14137 for (auto Param : FD->parameters()) { 14138 Param->setOwningFunction(FD); 14139 14140 // If this has an identifier, add it to the scope stack. 14141 if (Param->getIdentifier() && FnBodyScope) { 14142 CheckShadow(FnBodyScope, Param); 14143 14144 PushOnScopeChains(Param, FnBodyScope); 14145 } 14146 } 14147 14148 // Ensure that the function's exception specification is instantiated. 14149 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14150 ResolveExceptionSpec(D->getLocation(), FPT); 14151 14152 // dllimport cannot be applied to non-inline function definitions. 14153 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14154 !FD->isTemplateInstantiation()) { 14155 assert(!FD->hasAttr<DLLExportAttr>()); 14156 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14157 FD->setInvalidDecl(); 14158 return D; 14159 } 14160 // We want to attach documentation to original Decl (which might be 14161 // a function template). 14162 ActOnDocumentableDecl(D); 14163 if (getCurLexicalContext()->isObjCContainer() && 14164 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14165 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14166 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14167 14168 return D; 14169 } 14170 14171 /// Given the set of return statements within a function body, 14172 /// compute the variables that are subject to the named return value 14173 /// optimization. 14174 /// 14175 /// Each of the variables that is subject to the named return value 14176 /// optimization will be marked as NRVO variables in the AST, and any 14177 /// return statement that has a marked NRVO variable as its NRVO candidate can 14178 /// use the named return value optimization. 14179 /// 14180 /// This function applies a very simplistic algorithm for NRVO: if every return 14181 /// statement in the scope of a variable has the same NRVO candidate, that 14182 /// candidate is an NRVO variable. 14183 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14184 ReturnStmt **Returns = Scope->Returns.data(); 14185 14186 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14187 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14188 if (!NRVOCandidate->isNRVOVariable()) 14189 Returns[I]->setNRVOCandidate(nullptr); 14190 } 14191 } 14192 } 14193 14194 bool Sema::canDelayFunctionBody(const Declarator &D) { 14195 // We can't delay parsing the body of a constexpr function template (yet). 14196 if (D.getDeclSpec().hasConstexprSpecifier()) 14197 return false; 14198 14199 // We can't delay parsing the body of a function template with a deduced 14200 // return type (yet). 14201 if (D.getDeclSpec().hasAutoTypeSpec()) { 14202 // If the placeholder introduces a non-deduced trailing return type, 14203 // we can still delay parsing it. 14204 if (D.getNumTypeObjects()) { 14205 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14206 if (Outer.Kind == DeclaratorChunk::Function && 14207 Outer.Fun.hasTrailingReturnType()) { 14208 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14209 return Ty.isNull() || !Ty->isUndeducedType(); 14210 } 14211 } 14212 return false; 14213 } 14214 14215 return true; 14216 } 14217 14218 bool Sema::canSkipFunctionBody(Decl *D) { 14219 // We cannot skip the body of a function (or function template) which is 14220 // constexpr, since we may need to evaluate its body in order to parse the 14221 // rest of the file. 14222 // We cannot skip the body of a function with an undeduced return type, 14223 // because any callers of that function need to know the type. 14224 if (const FunctionDecl *FD = D->getAsFunction()) { 14225 if (FD->isConstexpr()) 14226 return false; 14227 // We can't simply call Type::isUndeducedType here, because inside template 14228 // auto can be deduced to a dependent type, which is not considered 14229 // "undeduced". 14230 if (FD->getReturnType()->getContainedDeducedType()) 14231 return false; 14232 } 14233 return Consumer.shouldSkipFunctionBody(D); 14234 } 14235 14236 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14237 if (!Decl) 14238 return nullptr; 14239 if (FunctionDecl *FD = Decl->getAsFunction()) 14240 FD->setHasSkippedBody(); 14241 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14242 MD->setHasSkippedBody(); 14243 return Decl; 14244 } 14245 14246 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14247 return ActOnFinishFunctionBody(D, BodyArg, false); 14248 } 14249 14250 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14251 /// body. 14252 class ExitFunctionBodyRAII { 14253 public: 14254 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14255 ~ExitFunctionBodyRAII() { 14256 if (!IsLambda) 14257 S.PopExpressionEvaluationContext(); 14258 } 14259 14260 private: 14261 Sema &S; 14262 bool IsLambda = false; 14263 }; 14264 14265 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14266 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14267 14268 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14269 if (EscapeInfo.count(BD)) 14270 return EscapeInfo[BD]; 14271 14272 bool R = false; 14273 const BlockDecl *CurBD = BD; 14274 14275 do { 14276 R = !CurBD->doesNotEscape(); 14277 if (R) 14278 break; 14279 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14280 } while (CurBD); 14281 14282 return EscapeInfo[BD] = R; 14283 }; 14284 14285 // If the location where 'self' is implicitly retained is inside a escaping 14286 // block, emit a diagnostic. 14287 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14288 S.ImplicitlyRetainedSelfLocs) 14289 if (IsOrNestedInEscapingBlock(P.second)) 14290 S.Diag(P.first, diag::warn_implicitly_retains_self) 14291 << FixItHint::CreateInsertion(P.first, "self->"); 14292 } 14293 14294 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14295 bool IsInstantiation) { 14296 FunctionScopeInfo *FSI = getCurFunction(); 14297 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14298 14299 if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>()) 14300 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14301 14302 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14303 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14304 14305 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14306 CheckCompletedCoroutineBody(FD, Body); 14307 14308 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14309 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14310 // meant to pop the context added in ActOnStartOfFunctionDef(). 14311 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14312 14313 if (FD) { 14314 FD->setBody(Body); 14315 FD->setWillHaveBody(false); 14316 14317 if (getLangOpts().CPlusPlus14) { 14318 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14319 FD->getReturnType()->isUndeducedType()) { 14320 // If the function has a deduced result type but contains no 'return' 14321 // statements, the result type as written must be exactly 'auto', and 14322 // the deduced result type is 'void'. 14323 if (!FD->getReturnType()->getAs<AutoType>()) { 14324 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14325 << FD->getReturnType(); 14326 FD->setInvalidDecl(); 14327 } else { 14328 // Substitute 'void' for the 'auto' in the type. 14329 TypeLoc ResultType = getReturnTypeLoc(FD); 14330 Context.adjustDeducedFunctionResultType( 14331 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14332 } 14333 } 14334 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14335 // In C++11, we don't use 'auto' deduction rules for lambda call 14336 // operators because we don't support return type deduction. 14337 auto *LSI = getCurLambda(); 14338 if (LSI->HasImplicitReturnType) { 14339 deduceClosureReturnType(*LSI); 14340 14341 // C++11 [expr.prim.lambda]p4: 14342 // [...] if there are no return statements in the compound-statement 14343 // [the deduced type is] the type void 14344 QualType RetType = 14345 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14346 14347 // Update the return type to the deduced type. 14348 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14349 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14350 Proto->getExtProtoInfo())); 14351 } 14352 } 14353 14354 // If the function implicitly returns zero (like 'main') or is naked, 14355 // don't complain about missing return statements. 14356 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14357 WP.disableCheckFallThrough(); 14358 14359 // MSVC permits the use of pure specifier (=0) on function definition, 14360 // defined at class scope, warn about this non-standard construct. 14361 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14362 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14363 14364 if (!FD->isInvalidDecl()) { 14365 // Don't diagnose unused parameters of defaulted or deleted functions. 14366 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14367 DiagnoseUnusedParameters(FD->parameters()); 14368 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14369 FD->getReturnType(), FD); 14370 14371 // If this is a structor, we need a vtable. 14372 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14373 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14374 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14375 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14376 14377 // Try to apply the named return value optimization. We have to check 14378 // if we can do this here because lambdas keep return statements around 14379 // to deduce an implicit return type. 14380 if (FD->getReturnType()->isRecordType() && 14381 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14382 computeNRVO(Body, FSI); 14383 } 14384 14385 // GNU warning -Wmissing-prototypes: 14386 // Warn if a global function is defined without a previous 14387 // prototype declaration. This warning is issued even if the 14388 // definition itself provides a prototype. The aim is to detect 14389 // global functions that fail to be declared in header files. 14390 const FunctionDecl *PossiblePrototype = nullptr; 14391 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14392 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14393 14394 if (PossiblePrototype) { 14395 // We found a declaration that is not a prototype, 14396 // but that could be a zero-parameter prototype 14397 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14398 TypeLoc TL = TI->getTypeLoc(); 14399 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14400 Diag(PossiblePrototype->getLocation(), 14401 diag::note_declaration_not_a_prototype) 14402 << (FD->getNumParams() != 0) 14403 << (FD->getNumParams() == 0 14404 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14405 : FixItHint{}); 14406 } 14407 } else { 14408 // Returns true if the token beginning at this Loc is `const`. 14409 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14410 const LangOptions &LangOpts) { 14411 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14412 if (LocInfo.first.isInvalid()) 14413 return false; 14414 14415 bool Invalid = false; 14416 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14417 if (Invalid) 14418 return false; 14419 14420 if (LocInfo.second > Buffer.size()) 14421 return false; 14422 14423 const char *LexStart = Buffer.data() + LocInfo.second; 14424 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14425 14426 return StartTok.consume_front("const") && 14427 (StartTok.empty() || isWhitespace(StartTok[0]) || 14428 StartTok.startswith("/*") || StartTok.startswith("//")); 14429 }; 14430 14431 auto findBeginLoc = [&]() { 14432 // If the return type has `const` qualifier, we want to insert 14433 // `static` before `const` (and not before the typename). 14434 if ((FD->getReturnType()->isAnyPointerType() && 14435 FD->getReturnType()->getPointeeType().isConstQualified()) || 14436 FD->getReturnType().isConstQualified()) { 14437 // But only do this if we can determine where the `const` is. 14438 14439 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14440 getLangOpts())) 14441 14442 return FD->getBeginLoc(); 14443 } 14444 return FD->getTypeSpecStartLoc(); 14445 }; 14446 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14447 << /* function */ 1 14448 << (FD->getStorageClass() == SC_None 14449 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14450 : FixItHint{}); 14451 } 14452 14453 // GNU warning -Wstrict-prototypes 14454 // Warn if K&R function is defined without a previous declaration. 14455 // This warning is issued only if the definition itself does not provide 14456 // a prototype. Only K&R definitions do not provide a prototype. 14457 if (!FD->hasWrittenPrototype()) { 14458 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14459 TypeLoc TL = TI->getTypeLoc(); 14460 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14461 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14462 } 14463 } 14464 14465 // Warn on CPUDispatch with an actual body. 14466 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14467 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14468 if (!CmpndBody->body_empty()) 14469 Diag(CmpndBody->body_front()->getBeginLoc(), 14470 diag::warn_dispatch_body_ignored); 14471 14472 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14473 const CXXMethodDecl *KeyFunction; 14474 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14475 MD->isVirtual() && 14476 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14477 MD == KeyFunction->getCanonicalDecl()) { 14478 // Update the key-function state if necessary for this ABI. 14479 if (FD->isInlined() && 14480 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14481 Context.setNonKeyFunction(MD); 14482 14483 // If the newly-chosen key function is already defined, then we 14484 // need to mark the vtable as used retroactively. 14485 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14486 const FunctionDecl *Definition; 14487 if (KeyFunction && KeyFunction->isDefined(Definition)) 14488 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14489 } else { 14490 // We just defined they key function; mark the vtable as used. 14491 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14492 } 14493 } 14494 } 14495 14496 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14497 "Function parsing confused"); 14498 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14499 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14500 MD->setBody(Body); 14501 if (!MD->isInvalidDecl()) { 14502 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14503 MD->getReturnType(), MD); 14504 14505 if (Body) 14506 computeNRVO(Body, FSI); 14507 } 14508 if (FSI->ObjCShouldCallSuper) { 14509 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14510 << MD->getSelector().getAsString(); 14511 FSI->ObjCShouldCallSuper = false; 14512 } 14513 if (FSI->ObjCWarnForNoDesignatedInitChain) { 14514 const ObjCMethodDecl *InitMethod = nullptr; 14515 bool isDesignated = 14516 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14517 assert(isDesignated && InitMethod); 14518 (void)isDesignated; 14519 14520 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14521 auto IFace = MD->getClassInterface(); 14522 if (!IFace) 14523 return false; 14524 auto SuperD = IFace->getSuperClass(); 14525 if (!SuperD) 14526 return false; 14527 return SuperD->getIdentifier() == 14528 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14529 }; 14530 // Don't issue this warning for unavailable inits or direct subclasses 14531 // of NSObject. 14532 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14533 Diag(MD->getLocation(), 14534 diag::warn_objc_designated_init_missing_super_call); 14535 Diag(InitMethod->getLocation(), 14536 diag::note_objc_designated_init_marked_here); 14537 } 14538 FSI->ObjCWarnForNoDesignatedInitChain = false; 14539 } 14540 if (FSI->ObjCWarnForNoInitDelegation) { 14541 // Don't issue this warning for unavaialable inits. 14542 if (!MD->isUnavailable()) 14543 Diag(MD->getLocation(), 14544 diag::warn_objc_secondary_init_missing_init_call); 14545 FSI->ObjCWarnForNoInitDelegation = false; 14546 } 14547 14548 diagnoseImplicitlyRetainedSelf(*this); 14549 } else { 14550 // Parsing the function declaration failed in some way. Pop the fake scope 14551 // we pushed on. 14552 PopFunctionScopeInfo(ActivePolicy, dcl); 14553 return nullptr; 14554 } 14555 14556 if (Body && FSI->HasPotentialAvailabilityViolations) 14557 DiagnoseUnguardedAvailabilityViolations(dcl); 14558 14559 assert(!FSI->ObjCShouldCallSuper && 14560 "This should only be set for ObjC methods, which should have been " 14561 "handled in the block above."); 14562 14563 // Verify and clean out per-function state. 14564 if (Body && (!FD || !FD->isDefaulted())) { 14565 // C++ constructors that have function-try-blocks can't have return 14566 // statements in the handlers of that block. (C++ [except.handle]p14) 14567 // Verify this. 14568 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14569 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14570 14571 // Verify that gotos and switch cases don't jump into scopes illegally. 14572 if (FSI->NeedsScopeChecking() && 14573 !PP.isCodeCompletionEnabled()) 14574 DiagnoseInvalidJumps(Body); 14575 14576 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14577 if (!Destructor->getParent()->isDependentType()) 14578 CheckDestructor(Destructor); 14579 14580 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14581 Destructor->getParent()); 14582 } 14583 14584 // If any errors have occurred, clear out any temporaries that may have 14585 // been leftover. This ensures that these temporaries won't be picked up for 14586 // deletion in some later function. 14587 if (hasUncompilableErrorOccurred() || 14588 getDiagnostics().getSuppressAllDiagnostics()) { 14589 DiscardCleanupsInEvaluationContext(); 14590 } 14591 if (!hasUncompilableErrorOccurred() && 14592 !isa<FunctionTemplateDecl>(dcl)) { 14593 // Since the body is valid, issue any analysis-based warnings that are 14594 // enabled. 14595 ActivePolicy = &WP; 14596 } 14597 14598 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14599 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14600 FD->setInvalidDecl(); 14601 14602 if (FD && FD->hasAttr<NakedAttr>()) { 14603 for (const Stmt *S : Body->children()) { 14604 // Allow local register variables without initializer as they don't 14605 // require prologue. 14606 bool RegisterVariables = false; 14607 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14608 for (const auto *Decl : DS->decls()) { 14609 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14610 RegisterVariables = 14611 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14612 if (!RegisterVariables) 14613 break; 14614 } 14615 } 14616 } 14617 if (RegisterVariables) 14618 continue; 14619 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14620 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14621 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14622 FD->setInvalidDecl(); 14623 break; 14624 } 14625 } 14626 } 14627 14628 assert(ExprCleanupObjects.size() == 14629 ExprEvalContexts.back().NumCleanupObjects && 14630 "Leftover temporaries in function"); 14631 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14632 assert(MaybeODRUseExprs.empty() && 14633 "Leftover expressions for odr-use checking"); 14634 } 14635 14636 if (!IsInstantiation) 14637 PopDeclContext(); 14638 14639 PopFunctionScopeInfo(ActivePolicy, dcl); 14640 // If any errors have occurred, clear out any temporaries that may have 14641 // been leftover. This ensures that these temporaries won't be picked up for 14642 // deletion in some later function. 14643 if (hasUncompilableErrorOccurred()) { 14644 DiscardCleanupsInEvaluationContext(); 14645 } 14646 14647 if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 14648 auto ES = getEmissionStatus(FD); 14649 if (ES == Sema::FunctionEmissionStatus::Emitted || 14650 ES == Sema::FunctionEmissionStatus::Unknown) 14651 DeclsToCheckForDeferredDiags.push_back(FD); 14652 } 14653 14654 return dcl; 14655 } 14656 14657 /// When we finish delayed parsing of an attribute, we must attach it to the 14658 /// relevant Decl. 14659 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14660 ParsedAttributes &Attrs) { 14661 // Always attach attributes to the underlying decl. 14662 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14663 D = TD->getTemplatedDecl(); 14664 ProcessDeclAttributeList(S, D, Attrs); 14665 14666 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14667 if (Method->isStatic()) 14668 checkThisInStaticMemberFunctionAttributes(Method); 14669 } 14670 14671 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14672 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14673 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14674 IdentifierInfo &II, Scope *S) { 14675 // Find the scope in which the identifier is injected and the corresponding 14676 // DeclContext. 14677 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14678 // In that case, we inject the declaration into the translation unit scope 14679 // instead. 14680 Scope *BlockScope = S; 14681 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14682 BlockScope = BlockScope->getParent(); 14683 14684 Scope *ContextScope = BlockScope; 14685 while (!ContextScope->getEntity()) 14686 ContextScope = ContextScope->getParent(); 14687 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14688 14689 // Before we produce a declaration for an implicitly defined 14690 // function, see whether there was a locally-scoped declaration of 14691 // this name as a function or variable. If so, use that 14692 // (non-visible) declaration, and complain about it. 14693 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14694 if (ExternCPrev) { 14695 // We still need to inject the function into the enclosing block scope so 14696 // that later (non-call) uses can see it. 14697 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14698 14699 // C89 footnote 38: 14700 // If in fact it is not defined as having type "function returning int", 14701 // the behavior is undefined. 14702 if (!isa<FunctionDecl>(ExternCPrev) || 14703 !Context.typesAreCompatible( 14704 cast<FunctionDecl>(ExternCPrev)->getType(), 14705 Context.getFunctionNoProtoType(Context.IntTy))) { 14706 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14707 << ExternCPrev << !getLangOpts().C99; 14708 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14709 return ExternCPrev; 14710 } 14711 } 14712 14713 // Extension in C99. Legal in C90, but warn about it. 14714 unsigned diag_id; 14715 if (II.getName().startswith("__builtin_")) 14716 diag_id = diag::warn_builtin_unknown; 14717 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14718 else if (getLangOpts().OpenCL) 14719 diag_id = diag::err_opencl_implicit_function_decl; 14720 else if (getLangOpts().C99) 14721 diag_id = diag::ext_implicit_function_decl; 14722 else 14723 diag_id = diag::warn_implicit_function_decl; 14724 Diag(Loc, diag_id) << &II; 14725 14726 // If we found a prior declaration of this function, don't bother building 14727 // another one. We've already pushed that one into scope, so there's nothing 14728 // more to do. 14729 if (ExternCPrev) 14730 return ExternCPrev; 14731 14732 // Because typo correction is expensive, only do it if the implicit 14733 // function declaration is going to be treated as an error. 14734 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14735 TypoCorrection Corrected; 14736 DeclFilterCCC<FunctionDecl> CCC{}; 14737 if (S && (Corrected = 14738 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14739 S, nullptr, CCC, CTK_NonError))) 14740 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14741 /*ErrorRecovery*/false); 14742 } 14743 14744 // Set a Declarator for the implicit definition: int foo(); 14745 const char *Dummy; 14746 AttributeFactory attrFactory; 14747 DeclSpec DS(attrFactory); 14748 unsigned DiagID; 14749 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14750 Context.getPrintingPolicy()); 14751 (void)Error; // Silence warning. 14752 assert(!Error && "Error setting up implicit decl!"); 14753 SourceLocation NoLoc; 14754 Declarator D(DS, DeclaratorContext::Block); 14755 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14756 /*IsAmbiguous=*/false, 14757 /*LParenLoc=*/NoLoc, 14758 /*Params=*/nullptr, 14759 /*NumParams=*/0, 14760 /*EllipsisLoc=*/NoLoc, 14761 /*RParenLoc=*/NoLoc, 14762 /*RefQualifierIsLvalueRef=*/true, 14763 /*RefQualifierLoc=*/NoLoc, 14764 /*MutableLoc=*/NoLoc, EST_None, 14765 /*ESpecRange=*/SourceRange(), 14766 /*Exceptions=*/nullptr, 14767 /*ExceptionRanges=*/nullptr, 14768 /*NumExceptions=*/0, 14769 /*NoexceptExpr=*/nullptr, 14770 /*ExceptionSpecTokens=*/nullptr, 14771 /*DeclsInPrototype=*/None, Loc, 14772 Loc, D), 14773 std::move(DS.getAttributes()), SourceLocation()); 14774 D.SetIdentifier(&II, Loc); 14775 14776 // Insert this function into the enclosing block scope. 14777 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14778 FD->setImplicit(); 14779 14780 AddKnownFunctionAttributes(FD); 14781 14782 return FD; 14783 } 14784 14785 /// If this function is a C++ replaceable global allocation function 14786 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14787 /// adds any function attributes that we know a priori based on the standard. 14788 /// 14789 /// We need to check for duplicate attributes both here and where user-written 14790 /// attributes are applied to declarations. 14791 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14792 FunctionDecl *FD) { 14793 if (FD->isInvalidDecl()) 14794 return; 14795 14796 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14797 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14798 return; 14799 14800 Optional<unsigned> AlignmentParam; 14801 bool IsNothrow = false; 14802 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14803 return; 14804 14805 // C++2a [basic.stc.dynamic.allocation]p4: 14806 // An allocation function that has a non-throwing exception specification 14807 // indicates failure by returning a null pointer value. Any other allocation 14808 // function never returns a null pointer value and indicates failure only by 14809 // throwing an exception [...] 14810 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14811 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14812 14813 // C++2a [basic.stc.dynamic.allocation]p2: 14814 // An allocation function attempts to allocate the requested amount of 14815 // storage. [...] If the request succeeds, the value returned by a 14816 // replaceable allocation function is a [...] pointer value p0 different 14817 // from any previously returned value p1 [...] 14818 // 14819 // However, this particular information is being added in codegen, 14820 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14821 14822 // C++2a [basic.stc.dynamic.allocation]p2: 14823 // An allocation function attempts to allocate the requested amount of 14824 // storage. If it is successful, it returns the address of the start of a 14825 // block of storage whose length in bytes is at least as large as the 14826 // requested size. 14827 if (!FD->hasAttr<AllocSizeAttr>()) { 14828 FD->addAttr(AllocSizeAttr::CreateImplicit( 14829 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14830 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14831 } 14832 14833 // C++2a [basic.stc.dynamic.allocation]p3: 14834 // For an allocation function [...], the pointer returned on a successful 14835 // call shall represent the address of storage that is aligned as follows: 14836 // (3.1) If the allocation function takes an argument of type 14837 // std::align_val_t, the storage will have the alignment 14838 // specified by the value of this argument. 14839 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14840 FD->addAttr(AllocAlignAttr::CreateImplicit( 14841 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14842 } 14843 14844 // FIXME: 14845 // C++2a [basic.stc.dynamic.allocation]p3: 14846 // For an allocation function [...], the pointer returned on a successful 14847 // call shall represent the address of storage that is aligned as follows: 14848 // (3.2) Otherwise, if the allocation function is named operator new[], 14849 // the storage is aligned for any object that does not have 14850 // new-extended alignment ([basic.align]) and is no larger than the 14851 // requested size. 14852 // (3.3) Otherwise, the storage is aligned for any object that does not 14853 // have new-extended alignment and is of the requested size. 14854 } 14855 14856 /// Adds any function attributes that we know a priori based on 14857 /// the declaration of this function. 14858 /// 14859 /// These attributes can apply both to implicitly-declared builtins 14860 /// (like __builtin___printf_chk) or to library-declared functions 14861 /// like NSLog or printf. 14862 /// 14863 /// We need to check for duplicate attributes both here and where user-written 14864 /// attributes are applied to declarations. 14865 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14866 if (FD->isInvalidDecl()) 14867 return; 14868 14869 // If this is a built-in function, map its builtin attributes to 14870 // actual attributes. 14871 if (unsigned BuiltinID = FD->getBuiltinID()) { 14872 // Handle printf-formatting attributes. 14873 unsigned FormatIdx; 14874 bool HasVAListArg; 14875 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14876 if (!FD->hasAttr<FormatAttr>()) { 14877 const char *fmt = "printf"; 14878 unsigned int NumParams = FD->getNumParams(); 14879 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14880 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14881 fmt = "NSString"; 14882 FD->addAttr(FormatAttr::CreateImplicit(Context, 14883 &Context.Idents.get(fmt), 14884 FormatIdx+1, 14885 HasVAListArg ? 0 : FormatIdx+2, 14886 FD->getLocation())); 14887 } 14888 } 14889 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14890 HasVAListArg)) { 14891 if (!FD->hasAttr<FormatAttr>()) 14892 FD->addAttr(FormatAttr::CreateImplicit(Context, 14893 &Context.Idents.get("scanf"), 14894 FormatIdx+1, 14895 HasVAListArg ? 0 : FormatIdx+2, 14896 FD->getLocation())); 14897 } 14898 14899 // Handle automatically recognized callbacks. 14900 SmallVector<int, 4> Encoding; 14901 if (!FD->hasAttr<CallbackAttr>() && 14902 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14903 FD->addAttr(CallbackAttr::CreateImplicit( 14904 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14905 14906 // Mark const if we don't care about errno and that is the only thing 14907 // preventing the function from being const. This allows IRgen to use LLVM 14908 // intrinsics for such functions. 14909 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14910 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14911 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14912 14913 // We make "fma" on some platforms const because we know it does not set 14914 // errno in those environments even though it could set errno based on the 14915 // C standard. 14916 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14917 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14918 !FD->hasAttr<ConstAttr>()) { 14919 switch (BuiltinID) { 14920 case Builtin::BI__builtin_fma: 14921 case Builtin::BI__builtin_fmaf: 14922 case Builtin::BI__builtin_fmal: 14923 case Builtin::BIfma: 14924 case Builtin::BIfmaf: 14925 case Builtin::BIfmal: 14926 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14927 break; 14928 default: 14929 break; 14930 } 14931 } 14932 14933 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14934 !FD->hasAttr<ReturnsTwiceAttr>()) 14935 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 14936 FD->getLocation())); 14937 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 14938 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14939 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 14940 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 14941 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 14942 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14943 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 14944 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 14945 // Add the appropriate attribute, depending on the CUDA compilation mode 14946 // and which target the builtin belongs to. For example, during host 14947 // compilation, aux builtins are __device__, while the rest are __host__. 14948 if (getLangOpts().CUDAIsDevice != 14949 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 14950 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 14951 else 14952 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 14953 } 14954 } 14955 14956 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 14957 14958 // If C++ exceptions are enabled but we are told extern "C" functions cannot 14959 // throw, add an implicit nothrow attribute to any extern "C" function we come 14960 // across. 14961 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 14962 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 14963 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 14964 if (!FPT || FPT->getExceptionSpecType() == EST_None) 14965 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14966 } 14967 14968 IdentifierInfo *Name = FD->getIdentifier(); 14969 if (!Name) 14970 return; 14971 if ((!getLangOpts().CPlusPlus && 14972 FD->getDeclContext()->isTranslationUnit()) || 14973 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 14974 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 14975 LinkageSpecDecl::lang_c)) { 14976 // Okay: this could be a libc/libm/Objective-C function we know 14977 // about. 14978 } else 14979 return; 14980 14981 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 14982 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 14983 // target-specific builtins, perhaps? 14984 if (!FD->hasAttr<FormatAttr>()) 14985 FD->addAttr(FormatAttr::CreateImplicit(Context, 14986 &Context.Idents.get("printf"), 2, 14987 Name->isStr("vasprintf") ? 0 : 3, 14988 FD->getLocation())); 14989 } 14990 14991 if (Name->isStr("__CFStringMakeConstantString")) { 14992 // We already have a __builtin___CFStringMakeConstantString, 14993 // but builds that use -fno-constant-cfstrings don't go through that. 14994 if (!FD->hasAttr<FormatArgAttr>()) 14995 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 14996 FD->getLocation())); 14997 } 14998 } 14999 15000 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15001 TypeSourceInfo *TInfo) { 15002 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 15003 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15004 15005 if (!TInfo) { 15006 assert(D.isInvalidType() && "no declarator info for valid type"); 15007 TInfo = Context.getTrivialTypeSourceInfo(T); 15008 } 15009 15010 // Scope manipulation handled by caller. 15011 TypedefDecl *NewTD = 15012 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15013 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15014 15015 // Bail out immediately if we have an invalid declaration. 15016 if (D.isInvalidType()) { 15017 NewTD->setInvalidDecl(); 15018 return NewTD; 15019 } 15020 15021 if (D.getDeclSpec().isModulePrivateSpecified()) { 15022 if (CurContext->isFunctionOrMethod()) 15023 Diag(NewTD->getLocation(), diag::err_module_private_local) 15024 << 2 << NewTD 15025 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15026 << FixItHint::CreateRemoval( 15027 D.getDeclSpec().getModulePrivateSpecLoc()); 15028 else 15029 NewTD->setModulePrivate(); 15030 } 15031 15032 // C++ [dcl.typedef]p8: 15033 // If the typedef declaration defines an unnamed class (or 15034 // enum), the first typedef-name declared by the declaration 15035 // to be that class type (or enum type) is used to denote the 15036 // class type (or enum type) for linkage purposes only. 15037 // We need to check whether the type was declared in the declaration. 15038 switch (D.getDeclSpec().getTypeSpecType()) { 15039 case TST_enum: 15040 case TST_struct: 15041 case TST_interface: 15042 case TST_union: 15043 case TST_class: { 15044 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15045 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15046 break; 15047 } 15048 15049 default: 15050 break; 15051 } 15052 15053 return NewTD; 15054 } 15055 15056 /// Check that this is a valid underlying type for an enum declaration. 15057 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15058 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15059 QualType T = TI->getType(); 15060 15061 if (T->isDependentType()) 15062 return false; 15063 15064 // This doesn't use 'isIntegralType' despite the error message mentioning 15065 // integral type because isIntegralType would also allow enum types in C. 15066 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15067 if (BT->isInteger()) 15068 return false; 15069 15070 if (T->isExtIntType()) 15071 return false; 15072 15073 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15074 } 15075 15076 /// Check whether this is a valid redeclaration of a previous enumeration. 15077 /// \return true if the redeclaration was invalid. 15078 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15079 QualType EnumUnderlyingTy, bool IsFixed, 15080 const EnumDecl *Prev) { 15081 if (IsScoped != Prev->isScoped()) { 15082 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15083 << Prev->isScoped(); 15084 Diag(Prev->getLocation(), diag::note_previous_declaration); 15085 return true; 15086 } 15087 15088 if (IsFixed && Prev->isFixed()) { 15089 if (!EnumUnderlyingTy->isDependentType() && 15090 !Prev->getIntegerType()->isDependentType() && 15091 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15092 Prev->getIntegerType())) { 15093 // TODO: Highlight the underlying type of the redeclaration. 15094 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15095 << EnumUnderlyingTy << Prev->getIntegerType(); 15096 Diag(Prev->getLocation(), diag::note_previous_declaration) 15097 << Prev->getIntegerTypeRange(); 15098 return true; 15099 } 15100 } else if (IsFixed != Prev->isFixed()) { 15101 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15102 << Prev->isFixed(); 15103 Diag(Prev->getLocation(), diag::note_previous_declaration); 15104 return true; 15105 } 15106 15107 return false; 15108 } 15109 15110 /// Get diagnostic %select index for tag kind for 15111 /// redeclaration diagnostic message. 15112 /// WARNING: Indexes apply to particular diagnostics only! 15113 /// 15114 /// \returns diagnostic %select index. 15115 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15116 switch (Tag) { 15117 case TTK_Struct: return 0; 15118 case TTK_Interface: return 1; 15119 case TTK_Class: return 2; 15120 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15121 } 15122 } 15123 15124 /// Determine if tag kind is a class-key compatible with 15125 /// class for redeclaration (class, struct, or __interface). 15126 /// 15127 /// \returns true iff the tag kind is compatible. 15128 static bool isClassCompatTagKind(TagTypeKind Tag) 15129 { 15130 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15131 } 15132 15133 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15134 TagTypeKind TTK) { 15135 if (isa<TypedefDecl>(PrevDecl)) 15136 return NTK_Typedef; 15137 else if (isa<TypeAliasDecl>(PrevDecl)) 15138 return NTK_TypeAlias; 15139 else if (isa<ClassTemplateDecl>(PrevDecl)) 15140 return NTK_Template; 15141 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15142 return NTK_TypeAliasTemplate; 15143 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15144 return NTK_TemplateTemplateArgument; 15145 switch (TTK) { 15146 case TTK_Struct: 15147 case TTK_Interface: 15148 case TTK_Class: 15149 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15150 case TTK_Union: 15151 return NTK_NonUnion; 15152 case TTK_Enum: 15153 return NTK_NonEnum; 15154 } 15155 llvm_unreachable("invalid TTK"); 15156 } 15157 15158 /// Determine whether a tag with a given kind is acceptable 15159 /// as a redeclaration of the given tag declaration. 15160 /// 15161 /// \returns true if the new tag kind is acceptable, false otherwise. 15162 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15163 TagTypeKind NewTag, bool isDefinition, 15164 SourceLocation NewTagLoc, 15165 const IdentifierInfo *Name) { 15166 // C++ [dcl.type.elab]p3: 15167 // The class-key or enum keyword present in the 15168 // elaborated-type-specifier shall agree in kind with the 15169 // declaration to which the name in the elaborated-type-specifier 15170 // refers. This rule also applies to the form of 15171 // elaborated-type-specifier that declares a class-name or 15172 // friend class since it can be construed as referring to the 15173 // definition of the class. Thus, in any 15174 // elaborated-type-specifier, the enum keyword shall be used to 15175 // refer to an enumeration (7.2), the union class-key shall be 15176 // used to refer to a union (clause 9), and either the class or 15177 // struct class-key shall be used to refer to a class (clause 9) 15178 // declared using the class or struct class-key. 15179 TagTypeKind OldTag = Previous->getTagKind(); 15180 if (OldTag != NewTag && 15181 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15182 return false; 15183 15184 // Tags are compatible, but we might still want to warn on mismatched tags. 15185 // Non-class tags can't be mismatched at this point. 15186 if (!isClassCompatTagKind(NewTag)) 15187 return true; 15188 15189 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15190 // by our warning analysis. We don't want to warn about mismatches with (eg) 15191 // declarations in system headers that are designed to be specialized, but if 15192 // a user asks us to warn, we should warn if their code contains mismatched 15193 // declarations. 15194 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15195 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15196 Loc); 15197 }; 15198 if (IsIgnoredLoc(NewTagLoc)) 15199 return true; 15200 15201 auto IsIgnored = [&](const TagDecl *Tag) { 15202 return IsIgnoredLoc(Tag->getLocation()); 15203 }; 15204 while (IsIgnored(Previous)) { 15205 Previous = Previous->getPreviousDecl(); 15206 if (!Previous) 15207 return true; 15208 OldTag = Previous->getTagKind(); 15209 } 15210 15211 bool isTemplate = false; 15212 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15213 isTemplate = Record->getDescribedClassTemplate(); 15214 15215 if (inTemplateInstantiation()) { 15216 if (OldTag != NewTag) { 15217 // In a template instantiation, do not offer fix-its for tag mismatches 15218 // since they usually mess up the template instead of fixing the problem. 15219 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15220 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15221 << getRedeclDiagFromTagKind(OldTag); 15222 // FIXME: Note previous location? 15223 } 15224 return true; 15225 } 15226 15227 if (isDefinition) { 15228 // On definitions, check all previous tags and issue a fix-it for each 15229 // one that doesn't match the current tag. 15230 if (Previous->getDefinition()) { 15231 // Don't suggest fix-its for redefinitions. 15232 return true; 15233 } 15234 15235 bool previousMismatch = false; 15236 for (const TagDecl *I : Previous->redecls()) { 15237 if (I->getTagKind() != NewTag) { 15238 // Ignore previous declarations for which the warning was disabled. 15239 if (IsIgnored(I)) 15240 continue; 15241 15242 if (!previousMismatch) { 15243 previousMismatch = true; 15244 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15245 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15246 << getRedeclDiagFromTagKind(I->getTagKind()); 15247 } 15248 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15249 << getRedeclDiagFromTagKind(NewTag) 15250 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15251 TypeWithKeyword::getTagTypeKindName(NewTag)); 15252 } 15253 } 15254 return true; 15255 } 15256 15257 // Identify the prevailing tag kind: this is the kind of the definition (if 15258 // there is a non-ignored definition), or otherwise the kind of the prior 15259 // (non-ignored) declaration. 15260 const TagDecl *PrevDef = Previous->getDefinition(); 15261 if (PrevDef && IsIgnored(PrevDef)) 15262 PrevDef = nullptr; 15263 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15264 if (Redecl->getTagKind() != NewTag) { 15265 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15266 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15267 << getRedeclDiagFromTagKind(OldTag); 15268 Diag(Redecl->getLocation(), diag::note_previous_use); 15269 15270 // If there is a previous definition, suggest a fix-it. 15271 if (PrevDef) { 15272 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15273 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15274 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15275 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15276 } 15277 } 15278 15279 return true; 15280 } 15281 15282 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15283 /// from an outer enclosing namespace or file scope inside a friend declaration. 15284 /// This should provide the commented out code in the following snippet: 15285 /// namespace N { 15286 /// struct X; 15287 /// namespace M { 15288 /// struct Y { friend struct /*N::*/ X; }; 15289 /// } 15290 /// } 15291 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15292 SourceLocation NameLoc) { 15293 // While the decl is in a namespace, do repeated lookup of that name and see 15294 // if we get the same namespace back. If we do not, continue until 15295 // translation unit scope, at which point we have a fully qualified NNS. 15296 SmallVector<IdentifierInfo *, 4> Namespaces; 15297 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15298 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15299 // This tag should be declared in a namespace, which can only be enclosed by 15300 // other namespaces. Bail if there's an anonymous namespace in the chain. 15301 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15302 if (!Namespace || Namespace->isAnonymousNamespace()) 15303 return FixItHint(); 15304 IdentifierInfo *II = Namespace->getIdentifier(); 15305 Namespaces.push_back(II); 15306 NamedDecl *Lookup = SemaRef.LookupSingleName( 15307 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15308 if (Lookup == Namespace) 15309 break; 15310 } 15311 15312 // Once we have all the namespaces, reverse them to go outermost first, and 15313 // build an NNS. 15314 SmallString<64> Insertion; 15315 llvm::raw_svector_ostream OS(Insertion); 15316 if (DC->isTranslationUnit()) 15317 OS << "::"; 15318 std::reverse(Namespaces.begin(), Namespaces.end()); 15319 for (auto *II : Namespaces) 15320 OS << II->getName() << "::"; 15321 return FixItHint::CreateInsertion(NameLoc, Insertion); 15322 } 15323 15324 /// Determine whether a tag originally declared in context \p OldDC can 15325 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15326 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15327 /// using-declaration). 15328 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15329 DeclContext *NewDC) { 15330 OldDC = OldDC->getRedeclContext(); 15331 NewDC = NewDC->getRedeclContext(); 15332 15333 if (OldDC->Equals(NewDC)) 15334 return true; 15335 15336 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15337 // encloses the other). 15338 if (S.getLangOpts().MSVCCompat && 15339 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15340 return true; 15341 15342 return false; 15343 } 15344 15345 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15346 /// former case, Name will be non-null. In the later case, Name will be null. 15347 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15348 /// reference/declaration/definition of a tag. 15349 /// 15350 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15351 /// trailing-type-specifier) other than one in an alias-declaration. 15352 /// 15353 /// \param SkipBody If non-null, will be set to indicate if the caller should 15354 /// skip the definition of this tag and treat it as if it were a declaration. 15355 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15356 SourceLocation KWLoc, CXXScopeSpec &SS, 15357 IdentifierInfo *Name, SourceLocation NameLoc, 15358 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15359 SourceLocation ModulePrivateLoc, 15360 MultiTemplateParamsArg TemplateParameterLists, 15361 bool &OwnedDecl, bool &IsDependent, 15362 SourceLocation ScopedEnumKWLoc, 15363 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15364 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15365 SkipBodyInfo *SkipBody) { 15366 // If this is not a definition, it must have a name. 15367 IdentifierInfo *OrigName = Name; 15368 assert((Name != nullptr || TUK == TUK_Definition) && 15369 "Nameless record must be a definition!"); 15370 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15371 15372 OwnedDecl = false; 15373 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15374 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15375 15376 // FIXME: Check member specializations more carefully. 15377 bool isMemberSpecialization = false; 15378 bool Invalid = false; 15379 15380 // We only need to do this matching if we have template parameters 15381 // or a scope specifier, which also conveniently avoids this work 15382 // for non-C++ cases. 15383 if (TemplateParameterLists.size() > 0 || 15384 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15385 if (TemplateParameterList *TemplateParams = 15386 MatchTemplateParametersToScopeSpecifier( 15387 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15388 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15389 if (Kind == TTK_Enum) { 15390 Diag(KWLoc, diag::err_enum_template); 15391 return nullptr; 15392 } 15393 15394 if (TemplateParams->size() > 0) { 15395 // This is a declaration or definition of a class template (which may 15396 // be a member of another template). 15397 15398 if (Invalid) 15399 return nullptr; 15400 15401 OwnedDecl = false; 15402 DeclResult Result = CheckClassTemplate( 15403 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15404 AS, ModulePrivateLoc, 15405 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15406 TemplateParameterLists.data(), SkipBody); 15407 return Result.get(); 15408 } else { 15409 // The "template<>" header is extraneous. 15410 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15411 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15412 isMemberSpecialization = true; 15413 } 15414 } 15415 15416 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15417 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15418 return nullptr; 15419 } 15420 15421 // Figure out the underlying type if this a enum declaration. We need to do 15422 // this early, because it's needed to detect if this is an incompatible 15423 // redeclaration. 15424 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15425 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15426 15427 if (Kind == TTK_Enum) { 15428 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15429 // No underlying type explicitly specified, or we failed to parse the 15430 // type, default to int. 15431 EnumUnderlying = Context.IntTy.getTypePtr(); 15432 } else if (UnderlyingType.get()) { 15433 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15434 // integral type; any cv-qualification is ignored. 15435 TypeSourceInfo *TI = nullptr; 15436 GetTypeFromParser(UnderlyingType.get(), &TI); 15437 EnumUnderlying = TI; 15438 15439 if (CheckEnumUnderlyingType(TI)) 15440 // Recover by falling back to int. 15441 EnumUnderlying = Context.IntTy.getTypePtr(); 15442 15443 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15444 UPPC_FixedUnderlyingType)) 15445 EnumUnderlying = Context.IntTy.getTypePtr(); 15446 15447 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15448 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15449 // of 'int'. However, if this is an unfixed forward declaration, don't set 15450 // the underlying type unless the user enables -fms-compatibility. This 15451 // makes unfixed forward declared enums incomplete and is more conforming. 15452 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15453 EnumUnderlying = Context.IntTy.getTypePtr(); 15454 } 15455 } 15456 15457 DeclContext *SearchDC = CurContext; 15458 DeclContext *DC = CurContext; 15459 bool isStdBadAlloc = false; 15460 bool isStdAlignValT = false; 15461 15462 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15463 if (TUK == TUK_Friend || TUK == TUK_Reference) 15464 Redecl = NotForRedeclaration; 15465 15466 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15467 /// implemented asks for structural equivalence checking, the returned decl 15468 /// here is passed back to the parser, allowing the tag body to be parsed. 15469 auto createTagFromNewDecl = [&]() -> TagDecl * { 15470 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15471 // If there is an identifier, use the location of the identifier as the 15472 // location of the decl, otherwise use the location of the struct/union 15473 // keyword. 15474 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15475 TagDecl *New = nullptr; 15476 15477 if (Kind == TTK_Enum) { 15478 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15479 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15480 // If this is an undefined enum, bail. 15481 if (TUK != TUK_Definition && !Invalid) 15482 return nullptr; 15483 if (EnumUnderlying) { 15484 EnumDecl *ED = cast<EnumDecl>(New); 15485 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15486 ED->setIntegerTypeSourceInfo(TI); 15487 else 15488 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15489 ED->setPromotionType(ED->getIntegerType()); 15490 } 15491 } else { // struct/union 15492 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15493 nullptr); 15494 } 15495 15496 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15497 // Add alignment attributes if necessary; these attributes are checked 15498 // when the ASTContext lays out the structure. 15499 // 15500 // It is important for implementing the correct semantics that this 15501 // happen here (in ActOnTag). The #pragma pack stack is 15502 // maintained as a result of parser callbacks which can occur at 15503 // many points during the parsing of a struct declaration (because 15504 // the #pragma tokens are effectively skipped over during the 15505 // parsing of the struct). 15506 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15507 AddAlignmentAttributesForRecord(RD); 15508 AddMsStructLayoutForRecord(RD); 15509 } 15510 } 15511 New->setLexicalDeclContext(CurContext); 15512 return New; 15513 }; 15514 15515 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15516 if (Name && SS.isNotEmpty()) { 15517 // We have a nested-name tag ('struct foo::bar'). 15518 15519 // Check for invalid 'foo::'. 15520 if (SS.isInvalid()) { 15521 Name = nullptr; 15522 goto CreateNewDecl; 15523 } 15524 15525 // If this is a friend or a reference to a class in a dependent 15526 // context, don't try to make a decl for it. 15527 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15528 DC = computeDeclContext(SS, false); 15529 if (!DC) { 15530 IsDependent = true; 15531 return nullptr; 15532 } 15533 } else { 15534 DC = computeDeclContext(SS, true); 15535 if (!DC) { 15536 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15537 << SS.getRange(); 15538 return nullptr; 15539 } 15540 } 15541 15542 if (RequireCompleteDeclContext(SS, DC)) 15543 return nullptr; 15544 15545 SearchDC = DC; 15546 // Look-up name inside 'foo::'. 15547 LookupQualifiedName(Previous, DC); 15548 15549 if (Previous.isAmbiguous()) 15550 return nullptr; 15551 15552 if (Previous.empty()) { 15553 // Name lookup did not find anything. However, if the 15554 // nested-name-specifier refers to the current instantiation, 15555 // and that current instantiation has any dependent base 15556 // classes, we might find something at instantiation time: treat 15557 // this as a dependent elaborated-type-specifier. 15558 // But this only makes any sense for reference-like lookups. 15559 if (Previous.wasNotFoundInCurrentInstantiation() && 15560 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15561 IsDependent = true; 15562 return nullptr; 15563 } 15564 15565 // A tag 'foo::bar' must already exist. 15566 Diag(NameLoc, diag::err_not_tag_in_scope) 15567 << Kind << Name << DC << SS.getRange(); 15568 Name = nullptr; 15569 Invalid = true; 15570 goto CreateNewDecl; 15571 } 15572 } else if (Name) { 15573 // C++14 [class.mem]p14: 15574 // If T is the name of a class, then each of the following shall have a 15575 // name different from T: 15576 // -- every member of class T that is itself a type 15577 if (TUK != TUK_Reference && TUK != TUK_Friend && 15578 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15579 return nullptr; 15580 15581 // If this is a named struct, check to see if there was a previous forward 15582 // declaration or definition. 15583 // FIXME: We're looking into outer scopes here, even when we 15584 // shouldn't be. Doing so can result in ambiguities that we 15585 // shouldn't be diagnosing. 15586 LookupName(Previous, S); 15587 15588 // When declaring or defining a tag, ignore ambiguities introduced 15589 // by types using'ed into this scope. 15590 if (Previous.isAmbiguous() && 15591 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15592 LookupResult::Filter F = Previous.makeFilter(); 15593 while (F.hasNext()) { 15594 NamedDecl *ND = F.next(); 15595 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15596 SearchDC->getRedeclContext())) 15597 F.erase(); 15598 } 15599 F.done(); 15600 } 15601 15602 // C++11 [namespace.memdef]p3: 15603 // If the name in a friend declaration is neither qualified nor 15604 // a template-id and the declaration is a function or an 15605 // elaborated-type-specifier, the lookup to determine whether 15606 // the entity has been previously declared shall not consider 15607 // any scopes outside the innermost enclosing namespace. 15608 // 15609 // MSVC doesn't implement the above rule for types, so a friend tag 15610 // declaration may be a redeclaration of a type declared in an enclosing 15611 // scope. They do implement this rule for friend functions. 15612 // 15613 // Does it matter that this should be by scope instead of by 15614 // semantic context? 15615 if (!Previous.empty() && TUK == TUK_Friend) { 15616 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15617 LookupResult::Filter F = Previous.makeFilter(); 15618 bool FriendSawTagOutsideEnclosingNamespace = false; 15619 while (F.hasNext()) { 15620 NamedDecl *ND = F.next(); 15621 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15622 if (DC->isFileContext() && 15623 !EnclosingNS->Encloses(ND->getDeclContext())) { 15624 if (getLangOpts().MSVCCompat) 15625 FriendSawTagOutsideEnclosingNamespace = true; 15626 else 15627 F.erase(); 15628 } 15629 } 15630 F.done(); 15631 15632 // Diagnose this MSVC extension in the easy case where lookup would have 15633 // unambiguously found something outside the enclosing namespace. 15634 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15635 NamedDecl *ND = Previous.getFoundDecl(); 15636 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15637 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15638 } 15639 } 15640 15641 // Note: there used to be some attempt at recovery here. 15642 if (Previous.isAmbiguous()) 15643 return nullptr; 15644 15645 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15646 // FIXME: This makes sure that we ignore the contexts associated 15647 // with C structs, unions, and enums when looking for a matching 15648 // tag declaration or definition. See the similar lookup tweak 15649 // in Sema::LookupName; is there a better way to deal with this? 15650 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15651 SearchDC = SearchDC->getParent(); 15652 } 15653 } 15654 15655 if (Previous.isSingleResult() && 15656 Previous.getFoundDecl()->isTemplateParameter()) { 15657 // Maybe we will complain about the shadowed template parameter. 15658 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15659 // Just pretend that we didn't see the previous declaration. 15660 Previous.clear(); 15661 } 15662 15663 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15664 DC->Equals(getStdNamespace())) { 15665 if (Name->isStr("bad_alloc")) { 15666 // This is a declaration of or a reference to "std::bad_alloc". 15667 isStdBadAlloc = true; 15668 15669 // If std::bad_alloc has been implicitly declared (but made invisible to 15670 // name lookup), fill in this implicit declaration as the previous 15671 // declaration, so that the declarations get chained appropriately. 15672 if (Previous.empty() && StdBadAlloc) 15673 Previous.addDecl(getStdBadAlloc()); 15674 } else if (Name->isStr("align_val_t")) { 15675 isStdAlignValT = true; 15676 if (Previous.empty() && StdAlignValT) 15677 Previous.addDecl(getStdAlignValT()); 15678 } 15679 } 15680 15681 // If we didn't find a previous declaration, and this is a reference 15682 // (or friend reference), move to the correct scope. In C++, we 15683 // also need to do a redeclaration lookup there, just in case 15684 // there's a shadow friend decl. 15685 if (Name && Previous.empty() && 15686 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15687 if (Invalid) goto CreateNewDecl; 15688 assert(SS.isEmpty()); 15689 15690 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15691 // C++ [basic.scope.pdecl]p5: 15692 // -- for an elaborated-type-specifier of the form 15693 // 15694 // class-key identifier 15695 // 15696 // if the elaborated-type-specifier is used in the 15697 // decl-specifier-seq or parameter-declaration-clause of a 15698 // function defined in namespace scope, the identifier is 15699 // declared as a class-name in the namespace that contains 15700 // the declaration; otherwise, except as a friend 15701 // declaration, the identifier is declared in the smallest 15702 // non-class, non-function-prototype scope that contains the 15703 // declaration. 15704 // 15705 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15706 // C structs and unions. 15707 // 15708 // It is an error in C++ to declare (rather than define) an enum 15709 // type, including via an elaborated type specifier. We'll 15710 // diagnose that later; for now, declare the enum in the same 15711 // scope as we would have picked for any other tag type. 15712 // 15713 // GNU C also supports this behavior as part of its incomplete 15714 // enum types extension, while GNU C++ does not. 15715 // 15716 // Find the context where we'll be declaring the tag. 15717 // FIXME: We would like to maintain the current DeclContext as the 15718 // lexical context, 15719 SearchDC = getTagInjectionContext(SearchDC); 15720 15721 // Find the scope where we'll be declaring the tag. 15722 S = getTagInjectionScope(S, getLangOpts()); 15723 } else { 15724 assert(TUK == TUK_Friend); 15725 // C++ [namespace.memdef]p3: 15726 // If a friend declaration in a non-local class first declares a 15727 // class or function, the friend class or function is a member of 15728 // the innermost enclosing namespace. 15729 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15730 } 15731 15732 // In C++, we need to do a redeclaration lookup to properly 15733 // diagnose some problems. 15734 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15735 // hidden declaration so that we don't get ambiguity errors when using a 15736 // type declared by an elaborated-type-specifier. In C that is not correct 15737 // and we should instead merge compatible types found by lookup. 15738 if (getLangOpts().CPlusPlus) { 15739 // FIXME: This can perform qualified lookups into function contexts, 15740 // which are meaningless. 15741 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15742 LookupQualifiedName(Previous, SearchDC); 15743 } else { 15744 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15745 LookupName(Previous, S); 15746 } 15747 } 15748 15749 // If we have a known previous declaration to use, then use it. 15750 if (Previous.empty() && SkipBody && SkipBody->Previous) 15751 Previous.addDecl(SkipBody->Previous); 15752 15753 if (!Previous.empty()) { 15754 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15755 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15756 15757 // It's okay to have a tag decl in the same scope as a typedef 15758 // which hides a tag decl in the same scope. Finding this 15759 // insanity with a redeclaration lookup can only actually happen 15760 // in C++. 15761 // 15762 // This is also okay for elaborated-type-specifiers, which is 15763 // technically forbidden by the current standard but which is 15764 // okay according to the likely resolution of an open issue; 15765 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15766 if (getLangOpts().CPlusPlus) { 15767 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15768 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15769 TagDecl *Tag = TT->getDecl(); 15770 if (Tag->getDeclName() == Name && 15771 Tag->getDeclContext()->getRedeclContext() 15772 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15773 PrevDecl = Tag; 15774 Previous.clear(); 15775 Previous.addDecl(Tag); 15776 Previous.resolveKind(); 15777 } 15778 } 15779 } 15780 } 15781 15782 // If this is a redeclaration of a using shadow declaration, it must 15783 // declare a tag in the same context. In MSVC mode, we allow a 15784 // redefinition if either context is within the other. 15785 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15786 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15787 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15788 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15789 !(OldTag && isAcceptableTagRedeclContext( 15790 *this, OldTag->getDeclContext(), SearchDC))) { 15791 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15792 Diag(Shadow->getTargetDecl()->getLocation(), 15793 diag::note_using_decl_target); 15794 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15795 << 0; 15796 // Recover by ignoring the old declaration. 15797 Previous.clear(); 15798 goto CreateNewDecl; 15799 } 15800 } 15801 15802 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15803 // If this is a use of a previous tag, or if the tag is already declared 15804 // in the same scope (so that the definition/declaration completes or 15805 // rementions the tag), reuse the decl. 15806 if (TUK == TUK_Reference || TUK == TUK_Friend || 15807 isDeclInScope(DirectPrevDecl, SearchDC, S, 15808 SS.isNotEmpty() || isMemberSpecialization)) { 15809 // Make sure that this wasn't declared as an enum and now used as a 15810 // struct or something similar. 15811 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15812 TUK == TUK_Definition, KWLoc, 15813 Name)) { 15814 bool SafeToContinue 15815 = (PrevTagDecl->getTagKind() != TTK_Enum && 15816 Kind != TTK_Enum); 15817 if (SafeToContinue) 15818 Diag(KWLoc, diag::err_use_with_wrong_tag) 15819 << Name 15820 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15821 PrevTagDecl->getKindName()); 15822 else 15823 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15824 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15825 15826 if (SafeToContinue) 15827 Kind = PrevTagDecl->getTagKind(); 15828 else { 15829 // Recover by making this an anonymous redefinition. 15830 Name = nullptr; 15831 Previous.clear(); 15832 Invalid = true; 15833 } 15834 } 15835 15836 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15837 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15838 if (TUK == TUK_Reference || TUK == TUK_Friend) 15839 return PrevTagDecl; 15840 15841 QualType EnumUnderlyingTy; 15842 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15843 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15844 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15845 EnumUnderlyingTy = QualType(T, 0); 15846 15847 // All conflicts with previous declarations are recovered by 15848 // returning the previous declaration, unless this is a definition, 15849 // in which case we want the caller to bail out. 15850 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15851 ScopedEnum, EnumUnderlyingTy, 15852 IsFixed, PrevEnum)) 15853 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15854 } 15855 15856 // C++11 [class.mem]p1: 15857 // A member shall not be declared twice in the member-specification, 15858 // except that a nested class or member class template can be declared 15859 // and then later defined. 15860 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15861 S->isDeclScope(PrevDecl)) { 15862 Diag(NameLoc, diag::ext_member_redeclared); 15863 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15864 } 15865 15866 if (!Invalid) { 15867 // If this is a use, just return the declaration we found, unless 15868 // we have attributes. 15869 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15870 if (!Attrs.empty()) { 15871 // FIXME: Diagnose these attributes. For now, we create a new 15872 // declaration to hold them. 15873 } else if (TUK == TUK_Reference && 15874 (PrevTagDecl->getFriendObjectKind() == 15875 Decl::FOK_Undeclared || 15876 PrevDecl->getOwningModule() != getCurrentModule()) && 15877 SS.isEmpty()) { 15878 // This declaration is a reference to an existing entity, but 15879 // has different visibility from that entity: it either makes 15880 // a friend visible or it makes a type visible in a new module. 15881 // In either case, create a new declaration. We only do this if 15882 // the declaration would have meant the same thing if no prior 15883 // declaration were found, that is, if it was found in the same 15884 // scope where we would have injected a declaration. 15885 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15886 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15887 return PrevTagDecl; 15888 // This is in the injected scope, create a new declaration in 15889 // that scope. 15890 S = getTagInjectionScope(S, getLangOpts()); 15891 } else { 15892 return PrevTagDecl; 15893 } 15894 } 15895 15896 // Diagnose attempts to redefine a tag. 15897 if (TUK == TUK_Definition) { 15898 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15899 // If we're defining a specialization and the previous definition 15900 // is from an implicit instantiation, don't emit an error 15901 // here; we'll catch this in the general case below. 15902 bool IsExplicitSpecializationAfterInstantiation = false; 15903 if (isMemberSpecialization) { 15904 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15905 IsExplicitSpecializationAfterInstantiation = 15906 RD->getTemplateSpecializationKind() != 15907 TSK_ExplicitSpecialization; 15908 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15909 IsExplicitSpecializationAfterInstantiation = 15910 ED->getTemplateSpecializationKind() != 15911 TSK_ExplicitSpecialization; 15912 } 15913 15914 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15915 // not keep more that one definition around (merge them). However, 15916 // ensure the decl passes the structural compatibility check in 15917 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15918 NamedDecl *Hidden = nullptr; 15919 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15920 // There is a definition of this tag, but it is not visible. We 15921 // explicitly make use of C++'s one definition rule here, and 15922 // assume that this definition is identical to the hidden one 15923 // we already have. Make the existing definition visible and 15924 // use it in place of this one. 15925 if (!getLangOpts().CPlusPlus) { 15926 // Postpone making the old definition visible until after we 15927 // complete parsing the new one and do the structural 15928 // comparison. 15929 SkipBody->CheckSameAsPrevious = true; 15930 SkipBody->New = createTagFromNewDecl(); 15931 SkipBody->Previous = Def; 15932 return Def; 15933 } else { 15934 SkipBody->ShouldSkip = true; 15935 SkipBody->Previous = Def; 15936 makeMergedDefinitionVisible(Hidden); 15937 // Carry on and handle it like a normal definition. We'll 15938 // skip starting the definitiion later. 15939 } 15940 } else if (!IsExplicitSpecializationAfterInstantiation) { 15941 // A redeclaration in function prototype scope in C isn't 15942 // visible elsewhere, so merely issue a warning. 15943 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 15944 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 15945 else 15946 Diag(NameLoc, diag::err_redefinition) << Name; 15947 notePreviousDefinition(Def, 15948 NameLoc.isValid() ? NameLoc : KWLoc); 15949 // If this is a redefinition, recover by making this 15950 // struct be anonymous, which will make any later 15951 // references get the previous definition. 15952 Name = nullptr; 15953 Previous.clear(); 15954 Invalid = true; 15955 } 15956 } else { 15957 // If the type is currently being defined, complain 15958 // about a nested redefinition. 15959 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 15960 if (TD->isBeingDefined()) { 15961 Diag(NameLoc, diag::err_nested_redefinition) << Name; 15962 Diag(PrevTagDecl->getLocation(), 15963 diag::note_previous_definition); 15964 Name = nullptr; 15965 Previous.clear(); 15966 Invalid = true; 15967 } 15968 } 15969 15970 // Okay, this is definition of a previously declared or referenced 15971 // tag. We're going to create a new Decl for it. 15972 } 15973 15974 // Okay, we're going to make a redeclaration. If this is some kind 15975 // of reference, make sure we build the redeclaration in the same DC 15976 // as the original, and ignore the current access specifier. 15977 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15978 SearchDC = PrevTagDecl->getDeclContext(); 15979 AS = AS_none; 15980 } 15981 } 15982 // If we get here we have (another) forward declaration or we 15983 // have a definition. Just create a new decl. 15984 15985 } else { 15986 // If we get here, this is a definition of a new tag type in a nested 15987 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 15988 // new decl/type. We set PrevDecl to NULL so that the entities 15989 // have distinct types. 15990 Previous.clear(); 15991 } 15992 // If we get here, we're going to create a new Decl. If PrevDecl 15993 // is non-NULL, it's a definition of the tag declared by 15994 // PrevDecl. If it's NULL, we have a new definition. 15995 15996 // Otherwise, PrevDecl is not a tag, but was found with tag 15997 // lookup. This is only actually possible in C++, where a few 15998 // things like templates still live in the tag namespace. 15999 } else { 16000 // Use a better diagnostic if an elaborated-type-specifier 16001 // found the wrong kind of type on the first 16002 // (non-redeclaration) lookup. 16003 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16004 !Previous.isForRedeclaration()) { 16005 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16006 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16007 << Kind; 16008 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16009 Invalid = true; 16010 16011 // Otherwise, only diagnose if the declaration is in scope. 16012 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16013 SS.isNotEmpty() || isMemberSpecialization)) { 16014 // do nothing 16015 16016 // Diagnose implicit declarations introduced by elaborated types. 16017 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16018 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16019 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16020 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16021 Invalid = true; 16022 16023 // Otherwise it's a declaration. Call out a particularly common 16024 // case here. 16025 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16026 unsigned Kind = 0; 16027 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16028 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16029 << Name << Kind << TND->getUnderlyingType(); 16030 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16031 Invalid = true; 16032 16033 // Otherwise, diagnose. 16034 } else { 16035 // The tag name clashes with something else in the target scope, 16036 // issue an error and recover by making this tag be anonymous. 16037 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16038 notePreviousDefinition(PrevDecl, NameLoc); 16039 Name = nullptr; 16040 Invalid = true; 16041 } 16042 16043 // The existing declaration isn't relevant to us; we're in a 16044 // new scope, so clear out the previous declaration. 16045 Previous.clear(); 16046 } 16047 } 16048 16049 CreateNewDecl: 16050 16051 TagDecl *PrevDecl = nullptr; 16052 if (Previous.isSingleResult()) 16053 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16054 16055 // If there is an identifier, use the location of the identifier as the 16056 // location of the decl, otherwise use the location of the struct/union 16057 // keyword. 16058 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16059 16060 // Otherwise, create a new declaration. If there is a previous 16061 // declaration of the same entity, the two will be linked via 16062 // PrevDecl. 16063 TagDecl *New; 16064 16065 if (Kind == TTK_Enum) { 16066 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16067 // enum X { A, B, C } D; D should chain to X. 16068 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16069 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16070 ScopedEnumUsesClassTag, IsFixed); 16071 16072 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16073 StdAlignValT = cast<EnumDecl>(New); 16074 16075 // If this is an undefined enum, warn. 16076 if (TUK != TUK_Definition && !Invalid) { 16077 TagDecl *Def; 16078 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16079 // C++0x: 7.2p2: opaque-enum-declaration. 16080 // Conflicts are diagnosed above. Do nothing. 16081 } 16082 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16083 Diag(Loc, diag::ext_forward_ref_enum_def) 16084 << New; 16085 Diag(Def->getLocation(), diag::note_previous_definition); 16086 } else { 16087 unsigned DiagID = diag::ext_forward_ref_enum; 16088 if (getLangOpts().MSVCCompat) 16089 DiagID = diag::ext_ms_forward_ref_enum; 16090 else if (getLangOpts().CPlusPlus) 16091 DiagID = diag::err_forward_ref_enum; 16092 Diag(Loc, DiagID); 16093 } 16094 } 16095 16096 if (EnumUnderlying) { 16097 EnumDecl *ED = cast<EnumDecl>(New); 16098 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16099 ED->setIntegerTypeSourceInfo(TI); 16100 else 16101 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16102 ED->setPromotionType(ED->getIntegerType()); 16103 assert(ED->isComplete() && "enum with type should be complete"); 16104 } 16105 } else { 16106 // struct/union/class 16107 16108 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16109 // struct X { int A; } D; D should chain to X. 16110 if (getLangOpts().CPlusPlus) { 16111 // FIXME: Look for a way to use RecordDecl for simple structs. 16112 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16113 cast_or_null<CXXRecordDecl>(PrevDecl)); 16114 16115 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16116 StdBadAlloc = cast<CXXRecordDecl>(New); 16117 } else 16118 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16119 cast_or_null<RecordDecl>(PrevDecl)); 16120 } 16121 16122 // C++11 [dcl.type]p3: 16123 // A type-specifier-seq shall not define a class or enumeration [...]. 16124 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16125 TUK == TUK_Definition) { 16126 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16127 << Context.getTagDeclType(New); 16128 Invalid = true; 16129 } 16130 16131 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16132 DC->getDeclKind() == Decl::Enum) { 16133 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16134 << Context.getTagDeclType(New); 16135 Invalid = true; 16136 } 16137 16138 // Maybe add qualifier info. 16139 if (SS.isNotEmpty()) { 16140 if (SS.isSet()) { 16141 // If this is either a declaration or a definition, check the 16142 // nested-name-specifier against the current context. 16143 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16144 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16145 isMemberSpecialization)) 16146 Invalid = true; 16147 16148 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16149 if (TemplateParameterLists.size() > 0) { 16150 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16151 } 16152 } 16153 else 16154 Invalid = true; 16155 } 16156 16157 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16158 // Add alignment attributes if necessary; these attributes are checked when 16159 // the ASTContext lays out the structure. 16160 // 16161 // It is important for implementing the correct semantics that this 16162 // happen here (in ActOnTag). The #pragma pack stack is 16163 // maintained as a result of parser callbacks which can occur at 16164 // many points during the parsing of a struct declaration (because 16165 // the #pragma tokens are effectively skipped over during the 16166 // parsing of the struct). 16167 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16168 AddAlignmentAttributesForRecord(RD); 16169 AddMsStructLayoutForRecord(RD); 16170 } 16171 } 16172 16173 if (ModulePrivateLoc.isValid()) { 16174 if (isMemberSpecialization) 16175 Diag(New->getLocation(), diag::err_module_private_specialization) 16176 << 2 16177 << FixItHint::CreateRemoval(ModulePrivateLoc); 16178 // __module_private__ does not apply to local classes. However, we only 16179 // diagnose this as an error when the declaration specifiers are 16180 // freestanding. Here, we just ignore the __module_private__. 16181 else if (!SearchDC->isFunctionOrMethod()) 16182 New->setModulePrivate(); 16183 } 16184 16185 // If this is a specialization of a member class (of a class template), 16186 // check the specialization. 16187 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16188 Invalid = true; 16189 16190 // If we're declaring or defining a tag in function prototype scope in C, 16191 // note that this type can only be used within the function and add it to 16192 // the list of decls to inject into the function definition scope. 16193 if ((Name || Kind == TTK_Enum) && 16194 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16195 if (getLangOpts().CPlusPlus) { 16196 // C++ [dcl.fct]p6: 16197 // Types shall not be defined in return or parameter types. 16198 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16199 Diag(Loc, diag::err_type_defined_in_param_type) 16200 << Name; 16201 Invalid = true; 16202 } 16203 } else if (!PrevDecl) { 16204 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16205 } 16206 } 16207 16208 if (Invalid) 16209 New->setInvalidDecl(); 16210 16211 // Set the lexical context. If the tag has a C++ scope specifier, the 16212 // lexical context will be different from the semantic context. 16213 New->setLexicalDeclContext(CurContext); 16214 16215 // Mark this as a friend decl if applicable. 16216 // In Microsoft mode, a friend declaration also acts as a forward 16217 // declaration so we always pass true to setObjectOfFriendDecl to make 16218 // the tag name visible. 16219 if (TUK == TUK_Friend) 16220 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16221 16222 // Set the access specifier. 16223 if (!Invalid && SearchDC->isRecord()) 16224 SetMemberAccessSpecifier(New, PrevDecl, AS); 16225 16226 if (PrevDecl) 16227 CheckRedeclarationModuleOwnership(New, PrevDecl); 16228 16229 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16230 New->startDefinition(); 16231 16232 ProcessDeclAttributeList(S, New, Attrs); 16233 AddPragmaAttributes(S, New); 16234 16235 // If this has an identifier, add it to the scope stack. 16236 if (TUK == TUK_Friend) { 16237 // We might be replacing an existing declaration in the lookup tables; 16238 // if so, borrow its access specifier. 16239 if (PrevDecl) 16240 New->setAccess(PrevDecl->getAccess()); 16241 16242 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16243 DC->makeDeclVisibleInContext(New); 16244 if (Name) // can be null along some error paths 16245 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16246 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16247 } else if (Name) { 16248 S = getNonFieldDeclScope(S); 16249 PushOnScopeChains(New, S, true); 16250 } else { 16251 CurContext->addDecl(New); 16252 } 16253 16254 // If this is the C FILE type, notify the AST context. 16255 if (IdentifierInfo *II = New->getIdentifier()) 16256 if (!New->isInvalidDecl() && 16257 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16258 II->isStr("FILE")) 16259 Context.setFILEDecl(New); 16260 16261 if (PrevDecl) 16262 mergeDeclAttributes(New, PrevDecl); 16263 16264 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16265 inferGslOwnerPointerAttribute(CXXRD); 16266 16267 // If there's a #pragma GCC visibility in scope, set the visibility of this 16268 // record. 16269 AddPushedVisibilityAttribute(New); 16270 16271 if (isMemberSpecialization && !New->isInvalidDecl()) 16272 CompleteMemberSpecialization(New, Previous); 16273 16274 OwnedDecl = true; 16275 // In C++, don't return an invalid declaration. We can't recover well from 16276 // the cases where we make the type anonymous. 16277 if (Invalid && getLangOpts().CPlusPlus) { 16278 if (New->isBeingDefined()) 16279 if (auto RD = dyn_cast<RecordDecl>(New)) 16280 RD->completeDefinition(); 16281 return nullptr; 16282 } else if (SkipBody && SkipBody->ShouldSkip) { 16283 return SkipBody->Previous; 16284 } else { 16285 return New; 16286 } 16287 } 16288 16289 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16290 AdjustDeclIfTemplate(TagD); 16291 TagDecl *Tag = cast<TagDecl>(TagD); 16292 16293 // Enter the tag context. 16294 PushDeclContext(S, Tag); 16295 16296 ActOnDocumentableDecl(TagD); 16297 16298 // If there's a #pragma GCC visibility in scope, set the visibility of this 16299 // record. 16300 AddPushedVisibilityAttribute(Tag); 16301 } 16302 16303 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16304 SkipBodyInfo &SkipBody) { 16305 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16306 return false; 16307 16308 // Make the previous decl visible. 16309 makeMergedDefinitionVisible(SkipBody.Previous); 16310 return true; 16311 } 16312 16313 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16314 assert(isa<ObjCContainerDecl>(IDecl) && 16315 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16316 DeclContext *OCD = cast<DeclContext>(IDecl); 16317 assert(OCD->getLexicalParent() == CurContext && 16318 "The next DeclContext should be lexically contained in the current one."); 16319 CurContext = OCD; 16320 return IDecl; 16321 } 16322 16323 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16324 SourceLocation FinalLoc, 16325 bool IsFinalSpelledSealed, 16326 SourceLocation LBraceLoc) { 16327 AdjustDeclIfTemplate(TagD); 16328 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16329 16330 FieldCollector->StartClass(); 16331 16332 if (!Record->getIdentifier()) 16333 return; 16334 16335 if (FinalLoc.isValid()) 16336 Record->addAttr(FinalAttr::Create( 16337 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16338 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16339 16340 // C++ [class]p2: 16341 // [...] The class-name is also inserted into the scope of the 16342 // class itself; this is known as the injected-class-name. For 16343 // purposes of access checking, the injected-class-name is treated 16344 // as if it were a public member name. 16345 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16346 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16347 Record->getLocation(), Record->getIdentifier(), 16348 /*PrevDecl=*/nullptr, 16349 /*DelayTypeCreation=*/true); 16350 Context.getTypeDeclType(InjectedClassName, Record); 16351 InjectedClassName->setImplicit(); 16352 InjectedClassName->setAccess(AS_public); 16353 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16354 InjectedClassName->setDescribedClassTemplate(Template); 16355 PushOnScopeChains(InjectedClassName, S); 16356 assert(InjectedClassName->isInjectedClassName() && 16357 "Broken injected-class-name"); 16358 } 16359 16360 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16361 SourceRange BraceRange) { 16362 AdjustDeclIfTemplate(TagD); 16363 TagDecl *Tag = cast<TagDecl>(TagD); 16364 Tag->setBraceRange(BraceRange); 16365 16366 // Make sure we "complete" the definition even it is invalid. 16367 if (Tag->isBeingDefined()) { 16368 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16369 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16370 RD->completeDefinition(); 16371 } 16372 16373 if (isa<CXXRecordDecl>(Tag)) { 16374 FieldCollector->FinishClass(); 16375 } 16376 16377 // Exit this scope of this tag's definition. 16378 PopDeclContext(); 16379 16380 if (getCurLexicalContext()->isObjCContainer() && 16381 Tag->getDeclContext()->isFileContext()) 16382 Tag->setTopLevelDeclInObjCContainer(); 16383 16384 // Notify the consumer that we've defined a tag. 16385 if (!Tag->isInvalidDecl()) 16386 Consumer.HandleTagDeclDefinition(Tag); 16387 } 16388 16389 void Sema::ActOnObjCContainerFinishDefinition() { 16390 // Exit this scope of this interface definition. 16391 PopDeclContext(); 16392 } 16393 16394 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16395 assert(DC == CurContext && "Mismatch of container contexts"); 16396 OriginalLexicalContext = DC; 16397 ActOnObjCContainerFinishDefinition(); 16398 } 16399 16400 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16401 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16402 OriginalLexicalContext = nullptr; 16403 } 16404 16405 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16406 AdjustDeclIfTemplate(TagD); 16407 TagDecl *Tag = cast<TagDecl>(TagD); 16408 Tag->setInvalidDecl(); 16409 16410 // Make sure we "complete" the definition even it is invalid. 16411 if (Tag->isBeingDefined()) { 16412 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16413 RD->completeDefinition(); 16414 } 16415 16416 // We're undoing ActOnTagStartDefinition here, not 16417 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16418 // the FieldCollector. 16419 16420 PopDeclContext(); 16421 } 16422 16423 // Note that FieldName may be null for anonymous bitfields. 16424 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16425 IdentifierInfo *FieldName, 16426 QualType FieldTy, bool IsMsStruct, 16427 Expr *BitWidth, bool *ZeroWidth) { 16428 assert(BitWidth); 16429 if (BitWidth->containsErrors()) 16430 return ExprError(); 16431 16432 // Default to true; that shouldn't confuse checks for emptiness 16433 if (ZeroWidth) 16434 *ZeroWidth = true; 16435 16436 // C99 6.7.2.1p4 - verify the field type. 16437 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16438 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16439 // Handle incomplete and sizeless types with a specific error. 16440 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16441 diag::err_field_incomplete_or_sizeless)) 16442 return ExprError(); 16443 if (FieldName) 16444 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16445 << FieldName << FieldTy << BitWidth->getSourceRange(); 16446 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16447 << FieldTy << BitWidth->getSourceRange(); 16448 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16449 UPPC_BitFieldWidth)) 16450 return ExprError(); 16451 16452 // If the bit-width is type- or value-dependent, don't try to check 16453 // it now. 16454 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16455 return BitWidth; 16456 16457 llvm::APSInt Value; 16458 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 16459 if (ICE.isInvalid()) 16460 return ICE; 16461 BitWidth = ICE.get(); 16462 16463 if (Value != 0 && ZeroWidth) 16464 *ZeroWidth = false; 16465 16466 // Zero-width bitfield is ok for anonymous field. 16467 if (Value == 0 && FieldName) 16468 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16469 16470 if (Value.isSigned() && Value.isNegative()) { 16471 if (FieldName) 16472 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16473 << FieldName << Value.toString(10); 16474 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16475 << Value.toString(10); 16476 } 16477 16478 // The size of the bit-field must not exceed our maximum permitted object 16479 // size. 16480 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 16481 return Diag(FieldLoc, diag::err_bitfield_too_wide) 16482 << !FieldName << FieldName << Value.toString(10); 16483 } 16484 16485 if (!FieldTy->isDependentType()) { 16486 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16487 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16488 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16489 16490 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16491 // ABI. 16492 bool CStdConstraintViolation = 16493 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16494 bool MSBitfieldViolation = 16495 Value.ugt(TypeStorageSize) && 16496 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16497 if (CStdConstraintViolation || MSBitfieldViolation) { 16498 unsigned DiagWidth = 16499 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16500 if (FieldName) 16501 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16502 << FieldName << Value.toString(10) 16503 << !CStdConstraintViolation << DiagWidth; 16504 16505 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16506 << Value.toString(10) << !CStdConstraintViolation 16507 << DiagWidth; 16508 } 16509 16510 // Warn on types where the user might conceivably expect to get all 16511 // specified bits as value bits: that's all integral types other than 16512 // 'bool'. 16513 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 16514 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16515 << FieldName << Value.toString(10) 16516 << (unsigned)TypeWidth; 16517 } 16518 } 16519 16520 return BitWidth; 16521 } 16522 16523 /// ActOnField - Each field of a C struct/union is passed into this in order 16524 /// to create a FieldDecl object for it. 16525 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16526 Declarator &D, Expr *BitfieldWidth) { 16527 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16528 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16529 /*InitStyle=*/ICIS_NoInit, AS_public); 16530 return Res; 16531 } 16532 16533 /// HandleField - Analyze a field of a C struct or a C++ data member. 16534 /// 16535 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16536 SourceLocation DeclStart, 16537 Declarator &D, Expr *BitWidth, 16538 InClassInitStyle InitStyle, 16539 AccessSpecifier AS) { 16540 if (D.isDecompositionDeclarator()) { 16541 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16542 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16543 << Decomp.getSourceRange(); 16544 return nullptr; 16545 } 16546 16547 IdentifierInfo *II = D.getIdentifier(); 16548 SourceLocation Loc = DeclStart; 16549 if (II) Loc = D.getIdentifierLoc(); 16550 16551 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16552 QualType T = TInfo->getType(); 16553 if (getLangOpts().CPlusPlus) { 16554 CheckExtraCXXDefaultArguments(D); 16555 16556 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16557 UPPC_DataMemberType)) { 16558 D.setInvalidType(); 16559 T = Context.IntTy; 16560 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16561 } 16562 } 16563 16564 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16565 16566 if (D.getDeclSpec().isInlineSpecified()) 16567 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16568 << getLangOpts().CPlusPlus17; 16569 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16570 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16571 diag::err_invalid_thread) 16572 << DeclSpec::getSpecifierName(TSCS); 16573 16574 // Check to see if this name was declared as a member previously 16575 NamedDecl *PrevDecl = nullptr; 16576 LookupResult Previous(*this, II, Loc, LookupMemberName, 16577 ForVisibleRedeclaration); 16578 LookupName(Previous, S); 16579 switch (Previous.getResultKind()) { 16580 case LookupResult::Found: 16581 case LookupResult::FoundUnresolvedValue: 16582 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16583 break; 16584 16585 case LookupResult::FoundOverloaded: 16586 PrevDecl = Previous.getRepresentativeDecl(); 16587 break; 16588 16589 case LookupResult::NotFound: 16590 case LookupResult::NotFoundInCurrentInstantiation: 16591 case LookupResult::Ambiguous: 16592 break; 16593 } 16594 Previous.suppressDiagnostics(); 16595 16596 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16597 // Maybe we will complain about the shadowed template parameter. 16598 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16599 // Just pretend that we didn't see the previous declaration. 16600 PrevDecl = nullptr; 16601 } 16602 16603 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16604 PrevDecl = nullptr; 16605 16606 bool Mutable 16607 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16608 SourceLocation TSSL = D.getBeginLoc(); 16609 FieldDecl *NewFD 16610 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16611 TSSL, AS, PrevDecl, &D); 16612 16613 if (NewFD->isInvalidDecl()) 16614 Record->setInvalidDecl(); 16615 16616 if (D.getDeclSpec().isModulePrivateSpecified()) 16617 NewFD->setModulePrivate(); 16618 16619 if (NewFD->isInvalidDecl() && PrevDecl) { 16620 // Don't introduce NewFD into scope; there's already something 16621 // with the same name in the same scope. 16622 } else if (II) { 16623 PushOnScopeChains(NewFD, S); 16624 } else 16625 Record->addDecl(NewFD); 16626 16627 return NewFD; 16628 } 16629 16630 /// Build a new FieldDecl and check its well-formedness. 16631 /// 16632 /// This routine builds a new FieldDecl given the fields name, type, 16633 /// record, etc. \p PrevDecl should refer to any previous declaration 16634 /// with the same name and in the same scope as the field to be 16635 /// created. 16636 /// 16637 /// \returns a new FieldDecl. 16638 /// 16639 /// \todo The Declarator argument is a hack. It will be removed once 16640 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16641 TypeSourceInfo *TInfo, 16642 RecordDecl *Record, SourceLocation Loc, 16643 bool Mutable, Expr *BitWidth, 16644 InClassInitStyle InitStyle, 16645 SourceLocation TSSL, 16646 AccessSpecifier AS, NamedDecl *PrevDecl, 16647 Declarator *D) { 16648 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16649 bool InvalidDecl = false; 16650 if (D) InvalidDecl = D->isInvalidType(); 16651 16652 // If we receive a broken type, recover by assuming 'int' and 16653 // marking this declaration as invalid. 16654 if (T.isNull() || T->containsErrors()) { 16655 InvalidDecl = true; 16656 T = Context.IntTy; 16657 } 16658 16659 QualType EltTy = Context.getBaseElementType(T); 16660 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16661 if (RequireCompleteSizedType(Loc, EltTy, 16662 diag::err_field_incomplete_or_sizeless)) { 16663 // Fields of incomplete type force their record to be invalid. 16664 Record->setInvalidDecl(); 16665 InvalidDecl = true; 16666 } else { 16667 NamedDecl *Def; 16668 EltTy->isIncompleteType(&Def); 16669 if (Def && Def->isInvalidDecl()) { 16670 Record->setInvalidDecl(); 16671 InvalidDecl = true; 16672 } 16673 } 16674 } 16675 16676 // TR 18037 does not allow fields to be declared with address space 16677 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16678 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16679 Diag(Loc, diag::err_field_with_address_space); 16680 Record->setInvalidDecl(); 16681 InvalidDecl = true; 16682 } 16683 16684 if (LangOpts.OpenCL) { 16685 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16686 // used as structure or union field: image, sampler, event or block types. 16687 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16688 T->isBlockPointerType()) { 16689 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16690 Record->setInvalidDecl(); 16691 InvalidDecl = true; 16692 } 16693 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16694 if (BitWidth) { 16695 Diag(Loc, diag::err_opencl_bitfields); 16696 InvalidDecl = true; 16697 } 16698 } 16699 16700 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16701 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16702 T.hasQualifiers()) { 16703 InvalidDecl = true; 16704 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16705 } 16706 16707 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16708 // than a variably modified type. 16709 if (!InvalidDecl && T->isVariablyModifiedType()) { 16710 if (!tryToFixVariablyModifiedVarType( 16711 *this, TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 16712 InvalidDecl = true; 16713 } 16714 16715 // Fields can not have abstract class types 16716 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16717 diag::err_abstract_type_in_decl, 16718 AbstractFieldType)) 16719 InvalidDecl = true; 16720 16721 bool ZeroWidth = false; 16722 if (InvalidDecl) 16723 BitWidth = nullptr; 16724 // If this is declared as a bit-field, check the bit-field. 16725 if (BitWidth) { 16726 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16727 &ZeroWidth).get(); 16728 if (!BitWidth) { 16729 InvalidDecl = true; 16730 BitWidth = nullptr; 16731 ZeroWidth = false; 16732 } 16733 } 16734 16735 // Check that 'mutable' is consistent with the type of the declaration. 16736 if (!InvalidDecl && Mutable) { 16737 unsigned DiagID = 0; 16738 if (T->isReferenceType()) 16739 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16740 : diag::err_mutable_reference; 16741 else if (T.isConstQualified()) 16742 DiagID = diag::err_mutable_const; 16743 16744 if (DiagID) { 16745 SourceLocation ErrLoc = Loc; 16746 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16747 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16748 Diag(ErrLoc, DiagID); 16749 if (DiagID != diag::ext_mutable_reference) { 16750 Mutable = false; 16751 InvalidDecl = true; 16752 } 16753 } 16754 } 16755 16756 // C++11 [class.union]p8 (DR1460): 16757 // At most one variant member of a union may have a 16758 // brace-or-equal-initializer. 16759 if (InitStyle != ICIS_NoInit) 16760 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16761 16762 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16763 BitWidth, Mutable, InitStyle); 16764 if (InvalidDecl) 16765 NewFD->setInvalidDecl(); 16766 16767 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16768 Diag(Loc, diag::err_duplicate_member) << II; 16769 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16770 NewFD->setInvalidDecl(); 16771 } 16772 16773 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16774 if (Record->isUnion()) { 16775 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16776 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16777 if (RDecl->getDefinition()) { 16778 // C++ [class.union]p1: An object of a class with a non-trivial 16779 // constructor, a non-trivial copy constructor, a non-trivial 16780 // destructor, or a non-trivial copy assignment operator 16781 // cannot be a member of a union, nor can an array of such 16782 // objects. 16783 if (CheckNontrivialField(NewFD)) 16784 NewFD->setInvalidDecl(); 16785 } 16786 } 16787 16788 // C++ [class.union]p1: If a union contains a member of reference type, 16789 // the program is ill-formed, except when compiling with MSVC extensions 16790 // enabled. 16791 if (EltTy->isReferenceType()) { 16792 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16793 diag::ext_union_member_of_reference_type : 16794 diag::err_union_member_of_reference_type) 16795 << NewFD->getDeclName() << EltTy; 16796 if (!getLangOpts().MicrosoftExt) 16797 NewFD->setInvalidDecl(); 16798 } 16799 } 16800 } 16801 16802 // FIXME: We need to pass in the attributes given an AST 16803 // representation, not a parser representation. 16804 if (D) { 16805 // FIXME: The current scope is almost... but not entirely... correct here. 16806 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16807 16808 if (NewFD->hasAttrs()) 16809 CheckAlignasUnderalignment(NewFD); 16810 } 16811 16812 // In auto-retain/release, infer strong retension for fields of 16813 // retainable type. 16814 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16815 NewFD->setInvalidDecl(); 16816 16817 if (T.isObjCGCWeak()) 16818 Diag(Loc, diag::warn_attribute_weak_on_field); 16819 16820 // PPC MMA non-pointer types are not allowed as field types. 16821 if (Context.getTargetInfo().getTriple().isPPC64() && 16822 CheckPPCMMAType(T, NewFD->getLocation())) 16823 NewFD->setInvalidDecl(); 16824 16825 NewFD->setAccess(AS); 16826 return NewFD; 16827 } 16828 16829 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16830 assert(FD); 16831 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16832 16833 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16834 return false; 16835 16836 QualType EltTy = Context.getBaseElementType(FD->getType()); 16837 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16838 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16839 if (RDecl->getDefinition()) { 16840 // We check for copy constructors before constructors 16841 // because otherwise we'll never get complaints about 16842 // copy constructors. 16843 16844 CXXSpecialMember member = CXXInvalid; 16845 // We're required to check for any non-trivial constructors. Since the 16846 // implicit default constructor is suppressed if there are any 16847 // user-declared constructors, we just need to check that there is a 16848 // trivial default constructor and a trivial copy constructor. (We don't 16849 // worry about move constructors here, since this is a C++98 check.) 16850 if (RDecl->hasNonTrivialCopyConstructor()) 16851 member = CXXCopyConstructor; 16852 else if (!RDecl->hasTrivialDefaultConstructor()) 16853 member = CXXDefaultConstructor; 16854 else if (RDecl->hasNonTrivialCopyAssignment()) 16855 member = CXXCopyAssignment; 16856 else if (RDecl->hasNonTrivialDestructor()) 16857 member = CXXDestructor; 16858 16859 if (member != CXXInvalid) { 16860 if (!getLangOpts().CPlusPlus11 && 16861 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16862 // Objective-C++ ARC: it is an error to have a non-trivial field of 16863 // a union. However, system headers in Objective-C programs 16864 // occasionally have Objective-C lifetime objects within unions, 16865 // and rather than cause the program to fail, we make those 16866 // members unavailable. 16867 SourceLocation Loc = FD->getLocation(); 16868 if (getSourceManager().isInSystemHeader(Loc)) { 16869 if (!FD->hasAttr<UnavailableAttr>()) 16870 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16871 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16872 return false; 16873 } 16874 } 16875 16876 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16877 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16878 diag::err_illegal_union_or_anon_struct_member) 16879 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16880 DiagnoseNontrivial(RDecl, member); 16881 return !getLangOpts().CPlusPlus11; 16882 } 16883 } 16884 } 16885 16886 return false; 16887 } 16888 16889 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16890 /// AST enum value. 16891 static ObjCIvarDecl::AccessControl 16892 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16893 switch (ivarVisibility) { 16894 default: llvm_unreachable("Unknown visitibility kind"); 16895 case tok::objc_private: return ObjCIvarDecl::Private; 16896 case tok::objc_public: return ObjCIvarDecl::Public; 16897 case tok::objc_protected: return ObjCIvarDecl::Protected; 16898 case tok::objc_package: return ObjCIvarDecl::Package; 16899 } 16900 } 16901 16902 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16903 /// in order to create an IvarDecl object for it. 16904 Decl *Sema::ActOnIvar(Scope *S, 16905 SourceLocation DeclStart, 16906 Declarator &D, Expr *BitfieldWidth, 16907 tok::ObjCKeywordKind Visibility) { 16908 16909 IdentifierInfo *II = D.getIdentifier(); 16910 Expr *BitWidth = (Expr*)BitfieldWidth; 16911 SourceLocation Loc = DeclStart; 16912 if (II) Loc = D.getIdentifierLoc(); 16913 16914 // FIXME: Unnamed fields can be handled in various different ways, for 16915 // example, unnamed unions inject all members into the struct namespace! 16916 16917 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16918 QualType T = TInfo->getType(); 16919 16920 if (BitWidth) { 16921 // 6.7.2.1p3, 6.7.2.1p4 16922 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16923 if (!BitWidth) 16924 D.setInvalidType(); 16925 } else { 16926 // Not a bitfield. 16927 16928 // validate II. 16929 16930 } 16931 if (T->isReferenceType()) { 16932 Diag(Loc, diag::err_ivar_reference_type); 16933 D.setInvalidType(); 16934 } 16935 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16936 // than a variably modified type. 16937 else if (T->isVariablyModifiedType()) { 16938 if (!tryToFixVariablyModifiedVarType( 16939 *this, TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 16940 D.setInvalidType(); 16941 } 16942 16943 // Get the visibility (access control) for this ivar. 16944 ObjCIvarDecl::AccessControl ac = 16945 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 16946 : ObjCIvarDecl::None; 16947 // Must set ivar's DeclContext to its enclosing interface. 16948 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 16949 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 16950 return nullptr; 16951 ObjCContainerDecl *EnclosingContext; 16952 if (ObjCImplementationDecl *IMPDecl = 16953 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16954 if (LangOpts.ObjCRuntime.isFragile()) { 16955 // Case of ivar declared in an implementation. Context is that of its class. 16956 EnclosingContext = IMPDecl->getClassInterface(); 16957 assert(EnclosingContext && "Implementation has no class interface!"); 16958 } 16959 else 16960 EnclosingContext = EnclosingDecl; 16961 } else { 16962 if (ObjCCategoryDecl *CDecl = 16963 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16964 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 16965 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 16966 return nullptr; 16967 } 16968 } 16969 EnclosingContext = EnclosingDecl; 16970 } 16971 16972 // Construct the decl. 16973 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 16974 DeclStart, Loc, II, T, 16975 TInfo, ac, (Expr *)BitfieldWidth); 16976 16977 if (II) { 16978 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 16979 ForVisibleRedeclaration); 16980 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 16981 && !isa<TagDecl>(PrevDecl)) { 16982 Diag(Loc, diag::err_duplicate_member) << II; 16983 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16984 NewID->setInvalidDecl(); 16985 } 16986 } 16987 16988 // Process attributes attached to the ivar. 16989 ProcessDeclAttributes(S, NewID, D); 16990 16991 if (D.isInvalidType()) 16992 NewID->setInvalidDecl(); 16993 16994 // In ARC, infer 'retaining' for ivars of retainable type. 16995 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 16996 NewID->setInvalidDecl(); 16997 16998 if (D.getDeclSpec().isModulePrivateSpecified()) 16999 NewID->setModulePrivate(); 17000 17001 if (II) { 17002 // FIXME: When interfaces are DeclContexts, we'll need to add 17003 // these to the interface. 17004 S->AddDecl(NewID); 17005 IdResolver.AddDecl(NewID); 17006 } 17007 17008 if (LangOpts.ObjCRuntime.isNonFragile() && 17009 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17010 Diag(Loc, diag::warn_ivars_in_interface); 17011 17012 return NewID; 17013 } 17014 17015 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17016 /// class and class extensions. For every class \@interface and class 17017 /// extension \@interface, if the last ivar is a bitfield of any type, 17018 /// then add an implicit `char :0` ivar to the end of that interface. 17019 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17020 SmallVectorImpl<Decl *> &AllIvarDecls) { 17021 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17022 return; 17023 17024 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17025 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17026 17027 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17028 return; 17029 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17030 if (!ID) { 17031 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17032 if (!CD->IsClassExtension()) 17033 return; 17034 } 17035 // No need to add this to end of @implementation. 17036 else 17037 return; 17038 } 17039 // All conditions are met. Add a new bitfield to the tail end of ivars. 17040 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17041 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17042 17043 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17044 DeclLoc, DeclLoc, nullptr, 17045 Context.CharTy, 17046 Context.getTrivialTypeSourceInfo(Context.CharTy, 17047 DeclLoc), 17048 ObjCIvarDecl::Private, BW, 17049 true); 17050 AllIvarDecls.push_back(Ivar); 17051 } 17052 17053 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17054 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17055 SourceLocation RBrac, 17056 const ParsedAttributesView &Attrs) { 17057 assert(EnclosingDecl && "missing record or interface decl"); 17058 17059 // If this is an Objective-C @implementation or category and we have 17060 // new fields here we should reset the layout of the interface since 17061 // it will now change. 17062 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17063 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17064 switch (DC->getKind()) { 17065 default: break; 17066 case Decl::ObjCCategory: 17067 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17068 break; 17069 case Decl::ObjCImplementation: 17070 Context. 17071 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17072 break; 17073 } 17074 } 17075 17076 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17077 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17078 17079 // Start counting up the number of named members; make sure to include 17080 // members of anonymous structs and unions in the total. 17081 unsigned NumNamedMembers = 0; 17082 if (Record) { 17083 for (const auto *I : Record->decls()) { 17084 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17085 if (IFD->getDeclName()) 17086 ++NumNamedMembers; 17087 } 17088 } 17089 17090 // Verify that all the fields are okay. 17091 SmallVector<FieldDecl*, 32> RecFields; 17092 17093 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17094 i != end; ++i) { 17095 FieldDecl *FD = cast<FieldDecl>(*i); 17096 17097 // Get the type for the field. 17098 const Type *FDTy = FD->getType().getTypePtr(); 17099 17100 if (!FD->isAnonymousStructOrUnion()) { 17101 // Remember all fields written by the user. 17102 RecFields.push_back(FD); 17103 } 17104 17105 // If the field is already invalid for some reason, don't emit more 17106 // diagnostics about it. 17107 if (FD->isInvalidDecl()) { 17108 EnclosingDecl->setInvalidDecl(); 17109 continue; 17110 } 17111 17112 // C99 6.7.2.1p2: 17113 // A structure or union shall not contain a member with 17114 // incomplete or function type (hence, a structure shall not 17115 // contain an instance of itself, but may contain a pointer to 17116 // an instance of itself), except that the last member of a 17117 // structure with more than one named member may have incomplete 17118 // array type; such a structure (and any union containing, 17119 // possibly recursively, a member that is such a structure) 17120 // shall not be a member of a structure or an element of an 17121 // array. 17122 bool IsLastField = (i + 1 == Fields.end()); 17123 if (FDTy->isFunctionType()) { 17124 // Field declared as a function. 17125 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17126 << FD->getDeclName(); 17127 FD->setInvalidDecl(); 17128 EnclosingDecl->setInvalidDecl(); 17129 continue; 17130 } else if (FDTy->isIncompleteArrayType() && 17131 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17132 if (Record) { 17133 // Flexible array member. 17134 // Microsoft and g++ is more permissive regarding flexible array. 17135 // It will accept flexible array in union and also 17136 // as the sole element of a struct/class. 17137 unsigned DiagID = 0; 17138 if (!Record->isUnion() && !IsLastField) { 17139 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17140 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17141 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17142 FD->setInvalidDecl(); 17143 EnclosingDecl->setInvalidDecl(); 17144 continue; 17145 } else if (Record->isUnion()) 17146 DiagID = getLangOpts().MicrosoftExt 17147 ? diag::ext_flexible_array_union_ms 17148 : getLangOpts().CPlusPlus 17149 ? diag::ext_flexible_array_union_gnu 17150 : diag::err_flexible_array_union; 17151 else if (NumNamedMembers < 1) 17152 DiagID = getLangOpts().MicrosoftExt 17153 ? diag::ext_flexible_array_empty_aggregate_ms 17154 : getLangOpts().CPlusPlus 17155 ? diag::ext_flexible_array_empty_aggregate_gnu 17156 : diag::err_flexible_array_empty_aggregate; 17157 17158 if (DiagID) 17159 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17160 << Record->getTagKind(); 17161 // While the layout of types that contain virtual bases is not specified 17162 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17163 // virtual bases after the derived members. This would make a flexible 17164 // array member declared at the end of an object not adjacent to the end 17165 // of the type. 17166 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17167 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17168 << FD->getDeclName() << Record->getTagKind(); 17169 if (!getLangOpts().C99) 17170 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17171 << FD->getDeclName() << Record->getTagKind(); 17172 17173 // If the element type has a non-trivial destructor, we would not 17174 // implicitly destroy the elements, so disallow it for now. 17175 // 17176 // FIXME: GCC allows this. We should probably either implicitly delete 17177 // the destructor of the containing class, or just allow this. 17178 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17179 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17180 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17181 << FD->getDeclName() << FD->getType(); 17182 FD->setInvalidDecl(); 17183 EnclosingDecl->setInvalidDecl(); 17184 continue; 17185 } 17186 // Okay, we have a legal flexible array member at the end of the struct. 17187 Record->setHasFlexibleArrayMember(true); 17188 } else { 17189 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17190 // unless they are followed by another ivar. That check is done 17191 // elsewhere, after synthesized ivars are known. 17192 } 17193 } else if (!FDTy->isDependentType() && 17194 RequireCompleteSizedType( 17195 FD->getLocation(), FD->getType(), 17196 diag::err_field_incomplete_or_sizeless)) { 17197 // Incomplete type 17198 FD->setInvalidDecl(); 17199 EnclosingDecl->setInvalidDecl(); 17200 continue; 17201 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17202 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17203 // A type which contains a flexible array member is considered to be a 17204 // flexible array member. 17205 Record->setHasFlexibleArrayMember(true); 17206 if (!Record->isUnion()) { 17207 // If this is a struct/class and this is not the last element, reject 17208 // it. Note that GCC supports variable sized arrays in the middle of 17209 // structures. 17210 if (!IsLastField) 17211 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17212 << FD->getDeclName() << FD->getType(); 17213 else { 17214 // We support flexible arrays at the end of structs in 17215 // other structs as an extension. 17216 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17217 << FD->getDeclName(); 17218 } 17219 } 17220 } 17221 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17222 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17223 diag::err_abstract_type_in_decl, 17224 AbstractIvarType)) { 17225 // Ivars can not have abstract class types 17226 FD->setInvalidDecl(); 17227 } 17228 if (Record && FDTTy->getDecl()->hasObjectMember()) 17229 Record->setHasObjectMember(true); 17230 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17231 Record->setHasVolatileMember(true); 17232 } else if (FDTy->isObjCObjectType()) { 17233 /// A field cannot be an Objective-c object 17234 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17235 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17236 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17237 FD->setType(T); 17238 } else if (Record && Record->isUnion() && 17239 FD->getType().hasNonTrivialObjCLifetime() && 17240 getSourceManager().isInSystemHeader(FD->getLocation()) && 17241 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17242 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17243 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17244 // For backward compatibility, fields of C unions declared in system 17245 // headers that have non-trivial ObjC ownership qualifications are marked 17246 // as unavailable unless the qualifier is explicit and __strong. This can 17247 // break ABI compatibility between programs compiled with ARC and MRR, but 17248 // is a better option than rejecting programs using those unions under 17249 // ARC. 17250 FD->addAttr(UnavailableAttr::CreateImplicit( 17251 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17252 FD->getLocation())); 17253 } else if (getLangOpts().ObjC && 17254 getLangOpts().getGC() != LangOptions::NonGC && Record && 17255 !Record->hasObjectMember()) { 17256 if (FD->getType()->isObjCObjectPointerType() || 17257 FD->getType().isObjCGCStrong()) 17258 Record->setHasObjectMember(true); 17259 else if (Context.getAsArrayType(FD->getType())) { 17260 QualType BaseType = Context.getBaseElementType(FD->getType()); 17261 if (BaseType->isRecordType() && 17262 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17263 Record->setHasObjectMember(true); 17264 else if (BaseType->isObjCObjectPointerType() || 17265 BaseType.isObjCGCStrong()) 17266 Record->setHasObjectMember(true); 17267 } 17268 } 17269 17270 if (Record && !getLangOpts().CPlusPlus && 17271 !shouldIgnoreForRecordTriviality(FD)) { 17272 QualType FT = FD->getType(); 17273 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17274 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17275 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17276 Record->isUnion()) 17277 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17278 } 17279 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17280 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17281 Record->setNonTrivialToPrimitiveCopy(true); 17282 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17283 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17284 } 17285 if (FT.isDestructedType()) { 17286 Record->setNonTrivialToPrimitiveDestroy(true); 17287 Record->setParamDestroyedInCallee(true); 17288 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17289 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17290 } 17291 17292 if (const auto *RT = FT->getAs<RecordType>()) { 17293 if (RT->getDecl()->getArgPassingRestrictions() == 17294 RecordDecl::APK_CanNeverPassInRegs) 17295 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17296 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17297 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17298 } 17299 17300 if (Record && FD->getType().isVolatileQualified()) 17301 Record->setHasVolatileMember(true); 17302 // Keep track of the number of named members. 17303 if (FD->getIdentifier()) 17304 ++NumNamedMembers; 17305 } 17306 17307 // Okay, we successfully defined 'Record'. 17308 if (Record) { 17309 bool Completed = false; 17310 if (CXXRecord) { 17311 if (!CXXRecord->isInvalidDecl()) { 17312 // Set access bits correctly on the directly-declared conversions. 17313 for (CXXRecordDecl::conversion_iterator 17314 I = CXXRecord->conversion_begin(), 17315 E = CXXRecord->conversion_end(); I != E; ++I) 17316 I.setAccess((*I)->getAccess()); 17317 } 17318 17319 // Add any implicitly-declared members to this class. 17320 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17321 17322 if (!CXXRecord->isDependentType()) { 17323 if (!CXXRecord->isInvalidDecl()) { 17324 // If we have virtual base classes, we may end up finding multiple 17325 // final overriders for a given virtual function. Check for this 17326 // problem now. 17327 if (CXXRecord->getNumVBases()) { 17328 CXXFinalOverriderMap FinalOverriders; 17329 CXXRecord->getFinalOverriders(FinalOverriders); 17330 17331 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17332 MEnd = FinalOverriders.end(); 17333 M != MEnd; ++M) { 17334 for (OverridingMethods::iterator SO = M->second.begin(), 17335 SOEnd = M->second.end(); 17336 SO != SOEnd; ++SO) { 17337 assert(SO->second.size() > 0 && 17338 "Virtual function without overriding functions?"); 17339 if (SO->second.size() == 1) 17340 continue; 17341 17342 // C++ [class.virtual]p2: 17343 // In a derived class, if a virtual member function of a base 17344 // class subobject has more than one final overrider the 17345 // program is ill-formed. 17346 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17347 << (const NamedDecl *)M->first << Record; 17348 Diag(M->first->getLocation(), 17349 diag::note_overridden_virtual_function); 17350 for (OverridingMethods::overriding_iterator 17351 OM = SO->second.begin(), 17352 OMEnd = SO->second.end(); 17353 OM != OMEnd; ++OM) 17354 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17355 << (const NamedDecl *)M->first << OM->Method->getParent(); 17356 17357 Record->setInvalidDecl(); 17358 } 17359 } 17360 CXXRecord->completeDefinition(&FinalOverriders); 17361 Completed = true; 17362 } 17363 } 17364 } 17365 } 17366 17367 if (!Completed) 17368 Record->completeDefinition(); 17369 17370 // Handle attributes before checking the layout. 17371 ProcessDeclAttributeList(S, Record, Attrs); 17372 17373 // We may have deferred checking for a deleted destructor. Check now. 17374 if (CXXRecord) { 17375 auto *Dtor = CXXRecord->getDestructor(); 17376 if (Dtor && Dtor->isImplicit() && 17377 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17378 CXXRecord->setImplicitDestructorIsDeleted(); 17379 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17380 } 17381 } 17382 17383 if (Record->hasAttrs()) { 17384 CheckAlignasUnderalignment(Record); 17385 17386 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17387 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17388 IA->getRange(), IA->getBestCase(), 17389 IA->getInheritanceModel()); 17390 } 17391 17392 // Check if the structure/union declaration is a type that can have zero 17393 // size in C. For C this is a language extension, for C++ it may cause 17394 // compatibility problems. 17395 bool CheckForZeroSize; 17396 if (!getLangOpts().CPlusPlus) { 17397 CheckForZeroSize = true; 17398 } else { 17399 // For C++ filter out types that cannot be referenced in C code. 17400 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17401 CheckForZeroSize = 17402 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17403 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 17404 CXXRecord->isCLike(); 17405 } 17406 if (CheckForZeroSize) { 17407 bool ZeroSize = true; 17408 bool IsEmpty = true; 17409 unsigned NonBitFields = 0; 17410 for (RecordDecl::field_iterator I = Record->field_begin(), 17411 E = Record->field_end(); 17412 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17413 IsEmpty = false; 17414 if (I->isUnnamedBitfield()) { 17415 if (!I->isZeroLengthBitField(Context)) 17416 ZeroSize = false; 17417 } else { 17418 ++NonBitFields; 17419 QualType FieldType = I->getType(); 17420 if (FieldType->isIncompleteType() || 17421 !Context.getTypeSizeInChars(FieldType).isZero()) 17422 ZeroSize = false; 17423 } 17424 } 17425 17426 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17427 // allowed in C++, but warn if its declaration is inside 17428 // extern "C" block. 17429 if (ZeroSize) { 17430 Diag(RecLoc, getLangOpts().CPlusPlus ? 17431 diag::warn_zero_size_struct_union_in_extern_c : 17432 diag::warn_zero_size_struct_union_compat) 17433 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17434 } 17435 17436 // Structs without named members are extension in C (C99 6.7.2.1p7), 17437 // but are accepted by GCC. 17438 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17439 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17440 diag::ext_no_named_members_in_struct_union) 17441 << Record->isUnion(); 17442 } 17443 } 17444 } else { 17445 ObjCIvarDecl **ClsFields = 17446 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17447 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17448 ID->setEndOfDefinitionLoc(RBrac); 17449 // Add ivar's to class's DeclContext. 17450 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17451 ClsFields[i]->setLexicalDeclContext(ID); 17452 ID->addDecl(ClsFields[i]); 17453 } 17454 // Must enforce the rule that ivars in the base classes may not be 17455 // duplicates. 17456 if (ID->getSuperClass()) 17457 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17458 } else if (ObjCImplementationDecl *IMPDecl = 17459 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17460 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17461 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17462 // Ivar declared in @implementation never belongs to the implementation. 17463 // Only it is in implementation's lexical context. 17464 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17465 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17466 IMPDecl->setIvarLBraceLoc(LBrac); 17467 IMPDecl->setIvarRBraceLoc(RBrac); 17468 } else if (ObjCCategoryDecl *CDecl = 17469 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17470 // case of ivars in class extension; all other cases have been 17471 // reported as errors elsewhere. 17472 // FIXME. Class extension does not have a LocEnd field. 17473 // CDecl->setLocEnd(RBrac); 17474 // Add ivar's to class extension's DeclContext. 17475 // Diagnose redeclaration of private ivars. 17476 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17477 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17478 if (IDecl) { 17479 if (const ObjCIvarDecl *ClsIvar = 17480 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17481 Diag(ClsFields[i]->getLocation(), 17482 diag::err_duplicate_ivar_declaration); 17483 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17484 continue; 17485 } 17486 for (const auto *Ext : IDecl->known_extensions()) { 17487 if (const ObjCIvarDecl *ClsExtIvar 17488 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17489 Diag(ClsFields[i]->getLocation(), 17490 diag::err_duplicate_ivar_declaration); 17491 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17492 continue; 17493 } 17494 } 17495 } 17496 ClsFields[i]->setLexicalDeclContext(CDecl); 17497 CDecl->addDecl(ClsFields[i]); 17498 } 17499 CDecl->setIvarLBraceLoc(LBrac); 17500 CDecl->setIvarRBraceLoc(RBrac); 17501 } 17502 } 17503 } 17504 17505 /// Determine whether the given integral value is representable within 17506 /// the given type T. 17507 static bool isRepresentableIntegerValue(ASTContext &Context, 17508 llvm::APSInt &Value, 17509 QualType T) { 17510 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17511 "Integral type required!"); 17512 unsigned BitWidth = Context.getIntWidth(T); 17513 17514 if (Value.isUnsigned() || Value.isNonNegative()) { 17515 if (T->isSignedIntegerOrEnumerationType()) 17516 --BitWidth; 17517 return Value.getActiveBits() <= BitWidth; 17518 } 17519 return Value.getMinSignedBits() <= BitWidth; 17520 } 17521 17522 // Given an integral type, return the next larger integral type 17523 // (or a NULL type of no such type exists). 17524 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17525 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17526 // enum checking below. 17527 assert((T->isIntegralType(Context) || 17528 T->isEnumeralType()) && "Integral type required!"); 17529 const unsigned NumTypes = 4; 17530 QualType SignedIntegralTypes[NumTypes] = { 17531 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17532 }; 17533 QualType UnsignedIntegralTypes[NumTypes] = { 17534 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17535 Context.UnsignedLongLongTy 17536 }; 17537 17538 unsigned BitWidth = Context.getTypeSize(T); 17539 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17540 : UnsignedIntegralTypes; 17541 for (unsigned I = 0; I != NumTypes; ++I) 17542 if (Context.getTypeSize(Types[I]) > BitWidth) 17543 return Types[I]; 17544 17545 return QualType(); 17546 } 17547 17548 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17549 EnumConstantDecl *LastEnumConst, 17550 SourceLocation IdLoc, 17551 IdentifierInfo *Id, 17552 Expr *Val) { 17553 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17554 llvm::APSInt EnumVal(IntWidth); 17555 QualType EltTy; 17556 17557 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17558 Val = nullptr; 17559 17560 if (Val) 17561 Val = DefaultLvalueConversion(Val).get(); 17562 17563 if (Val) { 17564 if (Enum->isDependentType() || Val->isTypeDependent()) 17565 EltTy = Context.DependentTy; 17566 else { 17567 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 17568 // underlying type, but do allow it in all other contexts. 17569 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17570 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17571 // constant-expression in the enumerator-definition shall be a converted 17572 // constant expression of the underlying type. 17573 EltTy = Enum->getIntegerType(); 17574 ExprResult Converted = 17575 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17576 CCEK_Enumerator); 17577 if (Converted.isInvalid()) 17578 Val = nullptr; 17579 else 17580 Val = Converted.get(); 17581 } else if (!Val->isValueDependent() && 17582 !(Val = 17583 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 17584 .get())) { 17585 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17586 } else { 17587 if (Enum->isComplete()) { 17588 EltTy = Enum->getIntegerType(); 17589 17590 // In Obj-C and Microsoft mode, require the enumeration value to be 17591 // representable in the underlying type of the enumeration. In C++11, 17592 // we perform a non-narrowing conversion as part of converted constant 17593 // expression checking. 17594 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17595 if (Context.getTargetInfo() 17596 .getTriple() 17597 .isWindowsMSVCEnvironment()) { 17598 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17599 } else { 17600 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17601 } 17602 } 17603 17604 // Cast to the underlying type. 17605 Val = ImpCastExprToType(Val, EltTy, 17606 EltTy->isBooleanType() ? CK_IntegralToBoolean 17607 : CK_IntegralCast) 17608 .get(); 17609 } else if (getLangOpts().CPlusPlus) { 17610 // C++11 [dcl.enum]p5: 17611 // If the underlying type is not fixed, the type of each enumerator 17612 // is the type of its initializing value: 17613 // - If an initializer is specified for an enumerator, the 17614 // initializing value has the same type as the expression. 17615 EltTy = Val->getType(); 17616 } else { 17617 // C99 6.7.2.2p2: 17618 // The expression that defines the value of an enumeration constant 17619 // shall be an integer constant expression that has a value 17620 // representable as an int. 17621 17622 // Complain if the value is not representable in an int. 17623 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17624 Diag(IdLoc, diag::ext_enum_value_not_int) 17625 << EnumVal.toString(10) << Val->getSourceRange() 17626 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17627 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17628 // Force the type of the expression to 'int'. 17629 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17630 } 17631 EltTy = Val->getType(); 17632 } 17633 } 17634 } 17635 } 17636 17637 if (!Val) { 17638 if (Enum->isDependentType()) 17639 EltTy = Context.DependentTy; 17640 else if (!LastEnumConst) { 17641 // C++0x [dcl.enum]p5: 17642 // If the underlying type is not fixed, the type of each enumerator 17643 // is the type of its initializing value: 17644 // - If no initializer is specified for the first enumerator, the 17645 // initializing value has an unspecified integral type. 17646 // 17647 // GCC uses 'int' for its unspecified integral type, as does 17648 // C99 6.7.2.2p3. 17649 if (Enum->isFixed()) { 17650 EltTy = Enum->getIntegerType(); 17651 } 17652 else { 17653 EltTy = Context.IntTy; 17654 } 17655 } else { 17656 // Assign the last value + 1. 17657 EnumVal = LastEnumConst->getInitVal(); 17658 ++EnumVal; 17659 EltTy = LastEnumConst->getType(); 17660 17661 // Check for overflow on increment. 17662 if (EnumVal < LastEnumConst->getInitVal()) { 17663 // C++0x [dcl.enum]p5: 17664 // If the underlying type is not fixed, the type of each enumerator 17665 // is the type of its initializing value: 17666 // 17667 // - Otherwise the type of the initializing value is the same as 17668 // the type of the initializing value of the preceding enumerator 17669 // unless the incremented value is not representable in that type, 17670 // in which case the type is an unspecified integral type 17671 // sufficient to contain the incremented value. If no such type 17672 // exists, the program is ill-formed. 17673 QualType T = getNextLargerIntegralType(Context, EltTy); 17674 if (T.isNull() || Enum->isFixed()) { 17675 // There is no integral type larger enough to represent this 17676 // value. Complain, then allow the value to wrap around. 17677 EnumVal = LastEnumConst->getInitVal(); 17678 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17679 ++EnumVal; 17680 if (Enum->isFixed()) 17681 // When the underlying type is fixed, this is ill-formed. 17682 Diag(IdLoc, diag::err_enumerator_wrapped) 17683 << EnumVal.toString(10) 17684 << EltTy; 17685 else 17686 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17687 << EnumVal.toString(10); 17688 } else { 17689 EltTy = T; 17690 } 17691 17692 // Retrieve the last enumerator's value, extent that type to the 17693 // type that is supposed to be large enough to represent the incremented 17694 // value, then increment. 17695 EnumVal = LastEnumConst->getInitVal(); 17696 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17697 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17698 ++EnumVal; 17699 17700 // If we're not in C++, diagnose the overflow of enumerator values, 17701 // which in C99 means that the enumerator value is not representable in 17702 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17703 // permits enumerator values that are representable in some larger 17704 // integral type. 17705 if (!getLangOpts().CPlusPlus && !T.isNull()) 17706 Diag(IdLoc, diag::warn_enum_value_overflow); 17707 } else if (!getLangOpts().CPlusPlus && 17708 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17709 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17710 Diag(IdLoc, diag::ext_enum_value_not_int) 17711 << EnumVal.toString(10) << 1; 17712 } 17713 } 17714 } 17715 17716 if (!EltTy->isDependentType()) { 17717 // Make the enumerator value match the signedness and size of the 17718 // enumerator's type. 17719 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17720 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17721 } 17722 17723 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17724 Val, EnumVal); 17725 } 17726 17727 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17728 SourceLocation IILoc) { 17729 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17730 !getLangOpts().CPlusPlus) 17731 return SkipBodyInfo(); 17732 17733 // We have an anonymous enum definition. Look up the first enumerator to 17734 // determine if we should merge the definition with an existing one and 17735 // skip the body. 17736 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17737 forRedeclarationInCurContext()); 17738 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17739 if (!PrevECD) 17740 return SkipBodyInfo(); 17741 17742 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17743 NamedDecl *Hidden; 17744 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17745 SkipBodyInfo Skip; 17746 Skip.Previous = Hidden; 17747 return Skip; 17748 } 17749 17750 return SkipBodyInfo(); 17751 } 17752 17753 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17754 SourceLocation IdLoc, IdentifierInfo *Id, 17755 const ParsedAttributesView &Attrs, 17756 SourceLocation EqualLoc, Expr *Val) { 17757 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17758 EnumConstantDecl *LastEnumConst = 17759 cast_or_null<EnumConstantDecl>(lastEnumConst); 17760 17761 // The scope passed in may not be a decl scope. Zip up the scope tree until 17762 // we find one that is. 17763 S = getNonFieldDeclScope(S); 17764 17765 // Verify that there isn't already something declared with this name in this 17766 // scope. 17767 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17768 LookupName(R, S); 17769 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17770 17771 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17772 // Maybe we will complain about the shadowed template parameter. 17773 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17774 // Just pretend that we didn't see the previous declaration. 17775 PrevDecl = nullptr; 17776 } 17777 17778 // C++ [class.mem]p15: 17779 // If T is the name of a class, then each of the following shall have a name 17780 // different from T: 17781 // - every enumerator of every member of class T that is an unscoped 17782 // enumerated type 17783 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17784 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17785 DeclarationNameInfo(Id, IdLoc)); 17786 17787 EnumConstantDecl *New = 17788 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17789 if (!New) 17790 return nullptr; 17791 17792 if (PrevDecl) { 17793 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17794 // Check for other kinds of shadowing not already handled. 17795 CheckShadow(New, PrevDecl, R); 17796 } 17797 17798 // When in C++, we may get a TagDecl with the same name; in this case the 17799 // enum constant will 'hide' the tag. 17800 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17801 "Received TagDecl when not in C++!"); 17802 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17803 if (isa<EnumConstantDecl>(PrevDecl)) 17804 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17805 else 17806 Diag(IdLoc, diag::err_redefinition) << Id; 17807 notePreviousDefinition(PrevDecl, IdLoc); 17808 return nullptr; 17809 } 17810 } 17811 17812 // Process attributes. 17813 ProcessDeclAttributeList(S, New, Attrs); 17814 AddPragmaAttributes(S, New); 17815 17816 // Register this decl in the current scope stack. 17817 New->setAccess(TheEnumDecl->getAccess()); 17818 PushOnScopeChains(New, S); 17819 17820 ActOnDocumentableDecl(New); 17821 17822 return New; 17823 } 17824 17825 // Returns true when the enum initial expression does not trigger the 17826 // duplicate enum warning. A few common cases are exempted as follows: 17827 // Element2 = Element1 17828 // Element2 = Element1 + 1 17829 // Element2 = Element1 - 1 17830 // Where Element2 and Element1 are from the same enum. 17831 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17832 Expr *InitExpr = ECD->getInitExpr(); 17833 if (!InitExpr) 17834 return true; 17835 InitExpr = InitExpr->IgnoreImpCasts(); 17836 17837 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17838 if (!BO->isAdditiveOp()) 17839 return true; 17840 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17841 if (!IL) 17842 return true; 17843 if (IL->getValue() != 1) 17844 return true; 17845 17846 InitExpr = BO->getLHS(); 17847 } 17848 17849 // This checks if the elements are from the same enum. 17850 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17851 if (!DRE) 17852 return true; 17853 17854 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17855 if (!EnumConstant) 17856 return true; 17857 17858 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17859 Enum) 17860 return true; 17861 17862 return false; 17863 } 17864 17865 // Emits a warning when an element is implicitly set a value that 17866 // a previous element has already been set to. 17867 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17868 EnumDecl *Enum, QualType EnumType) { 17869 // Avoid anonymous enums 17870 if (!Enum->getIdentifier()) 17871 return; 17872 17873 // Only check for small enums. 17874 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17875 return; 17876 17877 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17878 return; 17879 17880 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17881 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17882 17883 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17884 17885 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 17886 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17887 17888 // Use int64_t as a key to avoid needing special handling for map keys. 17889 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17890 llvm::APSInt Val = D->getInitVal(); 17891 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17892 }; 17893 17894 DuplicatesVector DupVector; 17895 ValueToVectorMap EnumMap; 17896 17897 // Populate the EnumMap with all values represented by enum constants without 17898 // an initializer. 17899 for (auto *Element : Elements) { 17900 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17901 17902 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17903 // this constant. Skip this enum since it may be ill-formed. 17904 if (!ECD) { 17905 return; 17906 } 17907 17908 // Constants with initalizers are handled in the next loop. 17909 if (ECD->getInitExpr()) 17910 continue; 17911 17912 // Duplicate values are handled in the next loop. 17913 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17914 } 17915 17916 if (EnumMap.size() == 0) 17917 return; 17918 17919 // Create vectors for any values that has duplicates. 17920 for (auto *Element : Elements) { 17921 // The last loop returned if any constant was null. 17922 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17923 if (!ValidDuplicateEnum(ECD, Enum)) 17924 continue; 17925 17926 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17927 if (Iter == EnumMap.end()) 17928 continue; 17929 17930 DeclOrVector& Entry = Iter->second; 17931 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17932 // Ensure constants are different. 17933 if (D == ECD) 17934 continue; 17935 17936 // Create new vector and push values onto it. 17937 auto Vec = std::make_unique<ECDVector>(); 17938 Vec->push_back(D); 17939 Vec->push_back(ECD); 17940 17941 // Update entry to point to the duplicates vector. 17942 Entry = Vec.get(); 17943 17944 // Store the vector somewhere we can consult later for quick emission of 17945 // diagnostics. 17946 DupVector.emplace_back(std::move(Vec)); 17947 continue; 17948 } 17949 17950 ECDVector *Vec = Entry.get<ECDVector*>(); 17951 // Make sure constants are not added more than once. 17952 if (*Vec->begin() == ECD) 17953 continue; 17954 17955 Vec->push_back(ECD); 17956 } 17957 17958 // Emit diagnostics. 17959 for (const auto &Vec : DupVector) { 17960 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 17961 17962 // Emit warning for one enum constant. 17963 auto *FirstECD = Vec->front(); 17964 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 17965 << FirstECD << FirstECD->getInitVal().toString(10) 17966 << FirstECD->getSourceRange(); 17967 17968 // Emit one note for each of the remaining enum constants with 17969 // the same value. 17970 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 17971 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 17972 << ECD << ECD->getInitVal().toString(10) 17973 << ECD->getSourceRange(); 17974 } 17975 } 17976 17977 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 17978 bool AllowMask) const { 17979 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 17980 assert(ED->isCompleteDefinition() && "expected enum definition"); 17981 17982 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 17983 llvm::APInt &FlagBits = R.first->second; 17984 17985 if (R.second) { 17986 for (auto *E : ED->enumerators()) { 17987 const auto &EVal = E->getInitVal(); 17988 // Only single-bit enumerators introduce new flag values. 17989 if (EVal.isPowerOf2()) 17990 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 17991 } 17992 } 17993 17994 // A value is in a flag enum if either its bits are a subset of the enum's 17995 // flag bits (the first condition) or we are allowing masks and the same is 17996 // true of its complement (the second condition). When masks are allowed, we 17997 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 17998 // 17999 // While it's true that any value could be used as a mask, the assumption is 18000 // that a mask will have all of the insignificant bits set. Anything else is 18001 // likely a logic error. 18002 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18003 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18004 } 18005 18006 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18007 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18008 const ParsedAttributesView &Attrs) { 18009 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18010 QualType EnumType = Context.getTypeDeclType(Enum); 18011 18012 ProcessDeclAttributeList(S, Enum, Attrs); 18013 18014 if (Enum->isDependentType()) { 18015 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18016 EnumConstantDecl *ECD = 18017 cast_or_null<EnumConstantDecl>(Elements[i]); 18018 if (!ECD) continue; 18019 18020 ECD->setType(EnumType); 18021 } 18022 18023 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18024 return; 18025 } 18026 18027 // TODO: If the result value doesn't fit in an int, it must be a long or long 18028 // long value. ISO C does not support this, but GCC does as an extension, 18029 // emit a warning. 18030 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18031 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18032 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18033 18034 // Verify that all the values are okay, compute the size of the values, and 18035 // reverse the list. 18036 unsigned NumNegativeBits = 0; 18037 unsigned NumPositiveBits = 0; 18038 18039 // Keep track of whether all elements have type int. 18040 bool AllElementsInt = true; 18041 18042 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18043 EnumConstantDecl *ECD = 18044 cast_or_null<EnumConstantDecl>(Elements[i]); 18045 if (!ECD) continue; // Already issued a diagnostic. 18046 18047 const llvm::APSInt &InitVal = ECD->getInitVal(); 18048 18049 // Keep track of the size of positive and negative values. 18050 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18051 NumPositiveBits = std::max(NumPositiveBits, 18052 (unsigned)InitVal.getActiveBits()); 18053 else 18054 NumNegativeBits = std::max(NumNegativeBits, 18055 (unsigned)InitVal.getMinSignedBits()); 18056 18057 // Keep track of whether every enum element has type int (very common). 18058 if (AllElementsInt) 18059 AllElementsInt = ECD->getType() == Context.IntTy; 18060 } 18061 18062 // Figure out the type that should be used for this enum. 18063 QualType BestType; 18064 unsigned BestWidth; 18065 18066 // C++0x N3000 [conv.prom]p3: 18067 // An rvalue of an unscoped enumeration type whose underlying 18068 // type is not fixed can be converted to an rvalue of the first 18069 // of the following types that can represent all the values of 18070 // the enumeration: int, unsigned int, long int, unsigned long 18071 // int, long long int, or unsigned long long int. 18072 // C99 6.4.4.3p2: 18073 // An identifier declared as an enumeration constant has type int. 18074 // The C99 rule is modified by a gcc extension 18075 QualType BestPromotionType; 18076 18077 bool Packed = Enum->hasAttr<PackedAttr>(); 18078 // -fshort-enums is the equivalent to specifying the packed attribute on all 18079 // enum definitions. 18080 if (LangOpts.ShortEnums) 18081 Packed = true; 18082 18083 // If the enum already has a type because it is fixed or dictated by the 18084 // target, promote that type instead of analyzing the enumerators. 18085 if (Enum->isComplete()) { 18086 BestType = Enum->getIntegerType(); 18087 if (BestType->isPromotableIntegerType()) 18088 BestPromotionType = Context.getPromotedIntegerType(BestType); 18089 else 18090 BestPromotionType = BestType; 18091 18092 BestWidth = Context.getIntWidth(BestType); 18093 } 18094 else if (NumNegativeBits) { 18095 // If there is a negative value, figure out the smallest integer type (of 18096 // int/long/longlong) that fits. 18097 // If it's packed, check also if it fits a char or a short. 18098 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18099 BestType = Context.SignedCharTy; 18100 BestWidth = CharWidth; 18101 } else if (Packed && NumNegativeBits <= ShortWidth && 18102 NumPositiveBits < ShortWidth) { 18103 BestType = Context.ShortTy; 18104 BestWidth = ShortWidth; 18105 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18106 BestType = Context.IntTy; 18107 BestWidth = IntWidth; 18108 } else { 18109 BestWidth = Context.getTargetInfo().getLongWidth(); 18110 18111 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18112 BestType = Context.LongTy; 18113 } else { 18114 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18115 18116 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18117 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18118 BestType = Context.LongLongTy; 18119 } 18120 } 18121 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18122 } else { 18123 // If there is no negative value, figure out the smallest type that fits 18124 // all of the enumerator values. 18125 // If it's packed, check also if it fits a char or a short. 18126 if (Packed && NumPositiveBits <= CharWidth) { 18127 BestType = Context.UnsignedCharTy; 18128 BestPromotionType = Context.IntTy; 18129 BestWidth = CharWidth; 18130 } else if (Packed && NumPositiveBits <= ShortWidth) { 18131 BestType = Context.UnsignedShortTy; 18132 BestPromotionType = Context.IntTy; 18133 BestWidth = ShortWidth; 18134 } else if (NumPositiveBits <= IntWidth) { 18135 BestType = Context.UnsignedIntTy; 18136 BestWidth = IntWidth; 18137 BestPromotionType 18138 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18139 ? Context.UnsignedIntTy : Context.IntTy; 18140 } else if (NumPositiveBits <= 18141 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18142 BestType = Context.UnsignedLongTy; 18143 BestPromotionType 18144 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18145 ? Context.UnsignedLongTy : Context.LongTy; 18146 } else { 18147 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18148 assert(NumPositiveBits <= BestWidth && 18149 "How could an initializer get larger than ULL?"); 18150 BestType = Context.UnsignedLongLongTy; 18151 BestPromotionType 18152 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18153 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18154 } 18155 } 18156 18157 // Loop over all of the enumerator constants, changing their types to match 18158 // the type of the enum if needed. 18159 for (auto *D : Elements) { 18160 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18161 if (!ECD) continue; // Already issued a diagnostic. 18162 18163 // Standard C says the enumerators have int type, but we allow, as an 18164 // extension, the enumerators to be larger than int size. If each 18165 // enumerator value fits in an int, type it as an int, otherwise type it the 18166 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18167 // that X has type 'int', not 'unsigned'. 18168 18169 // Determine whether the value fits into an int. 18170 llvm::APSInt InitVal = ECD->getInitVal(); 18171 18172 // If it fits into an integer type, force it. Otherwise force it to match 18173 // the enum decl type. 18174 QualType NewTy; 18175 unsigned NewWidth; 18176 bool NewSign; 18177 if (!getLangOpts().CPlusPlus && 18178 !Enum->isFixed() && 18179 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18180 NewTy = Context.IntTy; 18181 NewWidth = IntWidth; 18182 NewSign = true; 18183 } else if (ECD->getType() == BestType) { 18184 // Already the right type! 18185 if (getLangOpts().CPlusPlus) 18186 // C++ [dcl.enum]p4: Following the closing brace of an 18187 // enum-specifier, each enumerator has the type of its 18188 // enumeration. 18189 ECD->setType(EnumType); 18190 continue; 18191 } else { 18192 NewTy = BestType; 18193 NewWidth = BestWidth; 18194 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18195 } 18196 18197 // Adjust the APSInt value. 18198 InitVal = InitVal.extOrTrunc(NewWidth); 18199 InitVal.setIsSigned(NewSign); 18200 ECD->setInitVal(InitVal); 18201 18202 // Adjust the Expr initializer and type. 18203 if (ECD->getInitExpr() && 18204 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18205 ECD->setInitExpr(ImplicitCastExpr::Create( 18206 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18207 /*base paths*/ nullptr, VK_RValue, FPOptionsOverride())); 18208 if (getLangOpts().CPlusPlus) 18209 // C++ [dcl.enum]p4: Following the closing brace of an 18210 // enum-specifier, each enumerator has the type of its 18211 // enumeration. 18212 ECD->setType(EnumType); 18213 else 18214 ECD->setType(NewTy); 18215 } 18216 18217 Enum->completeDefinition(BestType, BestPromotionType, 18218 NumPositiveBits, NumNegativeBits); 18219 18220 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18221 18222 if (Enum->isClosedFlag()) { 18223 for (Decl *D : Elements) { 18224 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18225 if (!ECD) continue; // Already issued a diagnostic. 18226 18227 llvm::APSInt InitVal = ECD->getInitVal(); 18228 if (InitVal != 0 && !InitVal.isPowerOf2() && 18229 !IsValueInFlagEnum(Enum, InitVal, true)) 18230 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18231 << ECD << Enum; 18232 } 18233 } 18234 18235 // Now that the enum type is defined, ensure it's not been underaligned. 18236 if (Enum->hasAttrs()) 18237 CheckAlignasUnderalignment(Enum); 18238 } 18239 18240 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18241 SourceLocation StartLoc, 18242 SourceLocation EndLoc) { 18243 StringLiteral *AsmString = cast<StringLiteral>(expr); 18244 18245 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18246 AsmString, StartLoc, 18247 EndLoc); 18248 CurContext->addDecl(New); 18249 return New; 18250 } 18251 18252 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18253 IdentifierInfo* AliasName, 18254 SourceLocation PragmaLoc, 18255 SourceLocation NameLoc, 18256 SourceLocation AliasNameLoc) { 18257 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18258 LookupOrdinaryName); 18259 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18260 AttributeCommonInfo::AS_Pragma); 18261 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18262 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18263 18264 // If a declaration that: 18265 // 1) declares a function or a variable 18266 // 2) has external linkage 18267 // already exists, add a label attribute to it. 18268 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18269 if (isDeclExternC(PrevDecl)) 18270 PrevDecl->addAttr(Attr); 18271 else 18272 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18273 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18274 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18275 } else 18276 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18277 } 18278 18279 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18280 SourceLocation PragmaLoc, 18281 SourceLocation NameLoc) { 18282 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18283 18284 if (PrevDecl) { 18285 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18286 } else { 18287 (void)WeakUndeclaredIdentifiers.insert( 18288 std::pair<IdentifierInfo*,WeakInfo> 18289 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18290 } 18291 } 18292 18293 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18294 IdentifierInfo* AliasName, 18295 SourceLocation PragmaLoc, 18296 SourceLocation NameLoc, 18297 SourceLocation AliasNameLoc) { 18298 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18299 LookupOrdinaryName); 18300 WeakInfo W = WeakInfo(Name, NameLoc); 18301 18302 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18303 if (!PrevDecl->hasAttr<AliasAttr>()) 18304 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18305 DeclApplyPragmaWeak(TUScope, ND, W); 18306 } else { 18307 (void)WeakUndeclaredIdentifiers.insert( 18308 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18309 } 18310 } 18311 18312 Decl *Sema::getObjCDeclContext() const { 18313 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18314 } 18315 18316 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18317 bool Final) { 18318 // SYCL functions can be template, so we check if they have appropriate 18319 // attribute prior to checking if it is a template. 18320 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18321 return FunctionEmissionStatus::Emitted; 18322 18323 // Templates are emitted when they're instantiated. 18324 if (FD->isDependentContext()) 18325 return FunctionEmissionStatus::TemplateDiscarded; 18326 18327 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; 18328 if (LangOpts.OpenMPIsDevice) { 18329 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18330 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18331 if (DevTy.hasValue()) { 18332 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18333 OMPES = FunctionEmissionStatus::OMPDiscarded; 18334 else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost || 18335 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) { 18336 OMPES = FunctionEmissionStatus::Emitted; 18337 } 18338 } 18339 } else if (LangOpts.OpenMP) { 18340 // In OpenMP 4.5 all the functions are host functions. 18341 if (LangOpts.OpenMP <= 45) { 18342 OMPES = FunctionEmissionStatus::Emitted; 18343 } else { 18344 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18345 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18346 // In OpenMP 5.0 or above, DevTy may be changed later by 18347 // #pragma omp declare target to(*) device_type(*). Therefore DevTy 18348 // having no value does not imply host. The emission status will be 18349 // checked again at the end of compilation unit. 18350 if (DevTy.hasValue()) { 18351 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 18352 OMPES = FunctionEmissionStatus::OMPDiscarded; 18353 } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host || 18354 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) 18355 OMPES = FunctionEmissionStatus::Emitted; 18356 } else if (Final) 18357 OMPES = FunctionEmissionStatus::Emitted; 18358 } 18359 } 18360 if (OMPES == FunctionEmissionStatus::OMPDiscarded || 18361 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) 18362 return OMPES; 18363 18364 if (LangOpts.CUDA) { 18365 // When compiling for device, host functions are never emitted. Similarly, 18366 // when compiling for host, device and global functions are never emitted. 18367 // (Technically, we do emit a host-side stub for global functions, but this 18368 // doesn't count for our purposes here.) 18369 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18370 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18371 return FunctionEmissionStatus::CUDADiscarded; 18372 if (!LangOpts.CUDAIsDevice && 18373 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18374 return FunctionEmissionStatus::CUDADiscarded; 18375 18376 // Check whether this function is externally visible -- if so, it's 18377 // known-emitted. 18378 // 18379 // We have to check the GVA linkage of the function's *definition* -- if we 18380 // only have a declaration, we don't know whether or not the function will 18381 // be emitted, because (say) the definition could include "inline". 18382 FunctionDecl *Def = FD->getDefinition(); 18383 18384 if (Def && 18385 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) 18386 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) 18387 return FunctionEmissionStatus::Emitted; 18388 } 18389 18390 // Otherwise, the function is known-emitted if it's in our set of 18391 // known-emitted functions. 18392 return FunctionEmissionStatus::Unknown; 18393 } 18394 18395 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18396 // Host-side references to a __global__ function refer to the stub, so the 18397 // function itself is never emitted and therefore should not be marked. 18398 // If we have host fn calls kernel fn calls host+device, the HD function 18399 // does not get instantiated on the host. We model this by omitting at the 18400 // call to the kernel from the callgraph. This ensures that, when compiling 18401 // for host, only HD functions actually called from the host get marked as 18402 // known-emitted. 18403 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18404 IdentifyCUDATarget(Callee) == CFT_Global; 18405 } 18406