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 warnOnReservedIdentifier(D); 1520 } 1521 1522 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1523 bool AllowInlineNamespace) { 1524 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1525 } 1526 1527 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1528 DeclContext *TargetDC = DC->getPrimaryContext(); 1529 do { 1530 if (DeclContext *ScopeDC = S->getEntity()) 1531 if (ScopeDC->getPrimaryContext() == TargetDC) 1532 return S; 1533 } while ((S = S->getParent())); 1534 1535 return nullptr; 1536 } 1537 1538 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1539 DeclContext*, 1540 ASTContext&); 1541 1542 /// Filters out lookup results that don't fall within the given scope 1543 /// as determined by isDeclInScope. 1544 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1545 bool ConsiderLinkage, 1546 bool AllowInlineNamespace) { 1547 LookupResult::Filter F = R.makeFilter(); 1548 while (F.hasNext()) { 1549 NamedDecl *D = F.next(); 1550 1551 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1552 continue; 1553 1554 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1555 continue; 1556 1557 F.erase(); 1558 } 1559 1560 F.done(); 1561 } 1562 1563 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1564 /// have compatible owning modules. 1565 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1566 // FIXME: The Modules TS is not clear about how friend declarations are 1567 // to be treated. It's not meaningful to have different owning modules for 1568 // linkage in redeclarations of the same entity, so for now allow the 1569 // redeclaration and change the owning modules to match. 1570 if (New->getFriendObjectKind() && 1571 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1572 New->setLocalOwningModule(Old->getOwningModule()); 1573 makeMergedDefinitionVisible(New); 1574 return false; 1575 } 1576 1577 Module *NewM = New->getOwningModule(); 1578 Module *OldM = Old->getOwningModule(); 1579 1580 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1581 NewM = NewM->Parent; 1582 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1583 OldM = OldM->Parent; 1584 1585 if (NewM == OldM) 1586 return false; 1587 1588 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1589 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1590 if (NewIsModuleInterface || OldIsModuleInterface) { 1591 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1592 // if a declaration of D [...] appears in the purview of a module, all 1593 // other such declarations shall appear in the purview of the same module 1594 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1595 << New 1596 << NewIsModuleInterface 1597 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1598 << OldIsModuleInterface 1599 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1600 Diag(Old->getLocation(), diag::note_previous_declaration); 1601 New->setInvalidDecl(); 1602 return true; 1603 } 1604 1605 return false; 1606 } 1607 1608 static bool isUsingDecl(NamedDecl *D) { 1609 return isa<UsingShadowDecl>(D) || 1610 isa<UnresolvedUsingTypenameDecl>(D) || 1611 isa<UnresolvedUsingValueDecl>(D); 1612 } 1613 1614 /// Removes using shadow declarations from the lookup results. 1615 static void RemoveUsingDecls(LookupResult &R) { 1616 LookupResult::Filter F = R.makeFilter(); 1617 while (F.hasNext()) 1618 if (isUsingDecl(F.next())) 1619 F.erase(); 1620 1621 F.done(); 1622 } 1623 1624 /// Check for this common pattern: 1625 /// @code 1626 /// class S { 1627 /// S(const S&); // DO NOT IMPLEMENT 1628 /// void operator=(const S&); // DO NOT IMPLEMENT 1629 /// }; 1630 /// @endcode 1631 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1632 // FIXME: Should check for private access too but access is set after we get 1633 // the decl here. 1634 if (D->doesThisDeclarationHaveABody()) 1635 return false; 1636 1637 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1638 return CD->isCopyConstructor(); 1639 return D->isCopyAssignmentOperator(); 1640 } 1641 1642 // We need this to handle 1643 // 1644 // typedef struct { 1645 // void *foo() { return 0; } 1646 // } A; 1647 // 1648 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1649 // for example. If 'A', foo will have external linkage. If we have '*A', 1650 // foo will have no linkage. Since we can't know until we get to the end 1651 // of the typedef, this function finds out if D might have non-external linkage. 1652 // Callers should verify at the end of the TU if it D has external linkage or 1653 // not. 1654 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1655 const DeclContext *DC = D->getDeclContext(); 1656 while (!DC->isTranslationUnit()) { 1657 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1658 if (!RD->hasNameForLinkage()) 1659 return true; 1660 } 1661 DC = DC->getParent(); 1662 } 1663 1664 return !D->isExternallyVisible(); 1665 } 1666 1667 // FIXME: This needs to be refactored; some other isInMainFile users want 1668 // these semantics. 1669 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1670 if (S.TUKind != TU_Complete) 1671 return false; 1672 return S.SourceMgr.isInMainFile(Loc); 1673 } 1674 1675 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1676 assert(D); 1677 1678 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1679 return false; 1680 1681 // Ignore all entities declared within templates, and out-of-line definitions 1682 // of members of class templates. 1683 if (D->getDeclContext()->isDependentContext() || 1684 D->getLexicalDeclContext()->isDependentContext()) 1685 return false; 1686 1687 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1688 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1689 return false; 1690 // A non-out-of-line declaration of a member specialization was implicitly 1691 // instantiated; it's the out-of-line declaration that we're interested in. 1692 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1693 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1694 return false; 1695 1696 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1697 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1698 return false; 1699 } else { 1700 // 'static inline' functions are defined in headers; don't warn. 1701 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1702 return false; 1703 } 1704 1705 if (FD->doesThisDeclarationHaveABody() && 1706 Context.DeclMustBeEmitted(FD)) 1707 return false; 1708 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1709 // Constants and utility variables are defined in headers with internal 1710 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1711 // like "inline".) 1712 if (!isMainFileLoc(*this, VD->getLocation())) 1713 return false; 1714 1715 if (Context.DeclMustBeEmitted(VD)) 1716 return false; 1717 1718 if (VD->isStaticDataMember() && 1719 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1720 return false; 1721 if (VD->isStaticDataMember() && 1722 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1723 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1724 return false; 1725 1726 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1727 return false; 1728 } else { 1729 return false; 1730 } 1731 1732 // Only warn for unused decls internal to the translation unit. 1733 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1734 // for inline functions defined in the main source file, for instance. 1735 return mightHaveNonExternalLinkage(D); 1736 } 1737 1738 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1739 if (!D) 1740 return; 1741 1742 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1743 const FunctionDecl *First = FD->getFirstDecl(); 1744 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1745 return; // First should already be in the vector. 1746 } 1747 1748 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1749 const VarDecl *First = VD->getFirstDecl(); 1750 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1751 return; // First should already be in the vector. 1752 } 1753 1754 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1755 UnusedFileScopedDecls.push_back(D); 1756 } 1757 1758 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1759 if (D->isInvalidDecl()) 1760 return false; 1761 1762 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1763 // For a decomposition declaration, warn if none of the bindings are 1764 // referenced, instead of if the variable itself is referenced (which 1765 // it is, by the bindings' expressions). 1766 for (auto *BD : DD->bindings()) 1767 if (BD->isReferenced()) 1768 return false; 1769 } else if (!D->getDeclName()) { 1770 return false; 1771 } else if (D->isReferenced() || D->isUsed()) { 1772 return false; 1773 } 1774 1775 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) 1776 return false; 1777 1778 if (isa<LabelDecl>(D)) 1779 return true; 1780 1781 // Except for labels, we only care about unused decls that are local to 1782 // functions. 1783 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1784 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1785 // For dependent types, the diagnostic is deferred. 1786 WithinFunction = 1787 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1788 if (!WithinFunction) 1789 return false; 1790 1791 if (isa<TypedefNameDecl>(D)) 1792 return true; 1793 1794 // White-list anything that isn't a local variable. 1795 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1796 return false; 1797 1798 // Types of valid local variables should be complete, so this should succeed. 1799 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1800 1801 // White-list anything with an __attribute__((unused)) type. 1802 const auto *Ty = VD->getType().getTypePtr(); 1803 1804 // Only look at the outermost level of typedef. 1805 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1806 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1807 return false; 1808 } 1809 1810 // If we failed to complete the type for some reason, or if the type is 1811 // dependent, don't diagnose the variable. 1812 if (Ty->isIncompleteType() || Ty->isDependentType()) 1813 return false; 1814 1815 // Look at the element type to ensure that the warning behaviour is 1816 // consistent for both scalars and arrays. 1817 Ty = Ty->getBaseElementTypeUnsafe(); 1818 1819 if (const TagType *TT = Ty->getAs<TagType>()) { 1820 const TagDecl *Tag = TT->getDecl(); 1821 if (Tag->hasAttr<UnusedAttr>()) 1822 return false; 1823 1824 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1825 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1826 return false; 1827 1828 if (const Expr *Init = VD->getInit()) { 1829 if (const ExprWithCleanups *Cleanups = 1830 dyn_cast<ExprWithCleanups>(Init)) 1831 Init = Cleanups->getSubExpr(); 1832 const CXXConstructExpr *Construct = 1833 dyn_cast<CXXConstructExpr>(Init); 1834 if (Construct && !Construct->isElidable()) { 1835 CXXConstructorDecl *CD = Construct->getConstructor(); 1836 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1837 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1838 return false; 1839 } 1840 1841 // Suppress the warning if we don't know how this is constructed, and 1842 // it could possibly be non-trivial constructor. 1843 if (Init->isTypeDependent()) 1844 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1845 if (!Ctor->isTrivial()) 1846 return false; 1847 } 1848 } 1849 } 1850 1851 // TODO: __attribute__((unused)) templates? 1852 } 1853 1854 return true; 1855 } 1856 1857 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1858 FixItHint &Hint) { 1859 if (isa<LabelDecl>(D)) { 1860 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1861 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1862 true); 1863 if (AfterColon.isInvalid()) 1864 return; 1865 Hint = FixItHint::CreateRemoval( 1866 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1867 } 1868 } 1869 1870 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1871 if (D->getTypeForDecl()->isDependentType()) 1872 return; 1873 1874 for (auto *TmpD : D->decls()) { 1875 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1876 DiagnoseUnusedDecl(T); 1877 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1878 DiagnoseUnusedNestedTypedefs(R); 1879 } 1880 } 1881 1882 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1883 /// unless they are marked attr(unused). 1884 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1885 if (!ShouldDiagnoseUnusedDecl(D)) 1886 return; 1887 1888 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1889 // typedefs can be referenced later on, so the diagnostics are emitted 1890 // at end-of-translation-unit. 1891 UnusedLocalTypedefNameCandidates.insert(TD); 1892 return; 1893 } 1894 1895 FixItHint Hint; 1896 GenerateFixForUnusedDecl(D, Context, Hint); 1897 1898 unsigned DiagID; 1899 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1900 DiagID = diag::warn_unused_exception_param; 1901 else if (isa<LabelDecl>(D)) 1902 DiagID = diag::warn_unused_label; 1903 else 1904 DiagID = diag::warn_unused_variable; 1905 1906 Diag(D->getLocation(), DiagID) << D << Hint; 1907 } 1908 1909 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1910 // Verify that we have no forward references left. If so, there was a goto 1911 // or address of a label taken, but no definition of it. Label fwd 1912 // definitions are indicated with a null substmt which is also not a resolved 1913 // MS inline assembly label name. 1914 bool Diagnose = false; 1915 if (L->isMSAsmLabel()) 1916 Diagnose = !L->isResolvedMSAsmLabel(); 1917 else 1918 Diagnose = L->getStmt() == nullptr; 1919 if (Diagnose) 1920 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; 1921 } 1922 1923 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1924 S->mergeNRVOIntoParent(); 1925 1926 if (S->decl_empty()) return; 1927 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1928 "Scope shouldn't contain decls!"); 1929 1930 for (auto *TmpD : S->decls()) { 1931 assert(TmpD && "This decl didn't get pushed??"); 1932 1933 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1934 NamedDecl *D = cast<NamedDecl>(TmpD); 1935 1936 // Diagnose unused variables in this scope. 1937 if (!S->hasUnrecoverableErrorOccurred()) { 1938 DiagnoseUnusedDecl(D); 1939 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1940 DiagnoseUnusedNestedTypedefs(RD); 1941 } 1942 1943 if (!D->getDeclName()) continue; 1944 1945 // If this was a forward reference to a label, verify it was defined. 1946 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1947 CheckPoppedLabel(LD, *this); 1948 1949 // Remove this name from our lexical scope, and warn on it if we haven't 1950 // already. 1951 IdResolver.RemoveDecl(D); 1952 auto ShadowI = ShadowingDecls.find(D); 1953 if (ShadowI != ShadowingDecls.end()) { 1954 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1955 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1956 << D << FD << FD->getParent(); 1957 Diag(FD->getLocation(), diag::note_previous_declaration); 1958 } 1959 ShadowingDecls.erase(ShadowI); 1960 } 1961 } 1962 } 1963 1964 /// Look for an Objective-C class in the translation unit. 1965 /// 1966 /// \param Id The name of the Objective-C class we're looking for. If 1967 /// typo-correction fixes this name, the Id will be updated 1968 /// to the fixed name. 1969 /// 1970 /// \param IdLoc The location of the name in the translation unit. 1971 /// 1972 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1973 /// if there is no class with the given name. 1974 /// 1975 /// \returns The declaration of the named Objective-C class, or NULL if the 1976 /// class could not be found. 1977 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1978 SourceLocation IdLoc, 1979 bool DoTypoCorrection) { 1980 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1981 // creation from this context. 1982 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1983 1984 if (!IDecl && DoTypoCorrection) { 1985 // Perform typo correction at the given location, but only if we 1986 // find an Objective-C class name. 1987 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1988 if (TypoCorrection C = 1989 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1990 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1991 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1992 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1993 Id = IDecl->getIdentifier(); 1994 } 1995 } 1996 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1997 // This routine must always return a class definition, if any. 1998 if (Def && Def->getDefinition()) 1999 Def = Def->getDefinition(); 2000 return Def; 2001 } 2002 2003 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2004 /// from S, where a non-field would be declared. This routine copes 2005 /// with the difference between C and C++ scoping rules in structs and 2006 /// unions. For example, the following code is well-formed in C but 2007 /// ill-formed in C++: 2008 /// @code 2009 /// struct S6 { 2010 /// enum { BAR } e; 2011 /// }; 2012 /// 2013 /// void test_S6() { 2014 /// struct S6 a; 2015 /// a.e = BAR; 2016 /// } 2017 /// @endcode 2018 /// For the declaration of BAR, this routine will return a different 2019 /// scope. The scope S will be the scope of the unnamed enumeration 2020 /// within S6. In C++, this routine will return the scope associated 2021 /// with S6, because the enumeration's scope is a transparent 2022 /// context but structures can contain non-field names. In C, this 2023 /// routine will return the translation unit scope, since the 2024 /// enumeration's scope is a transparent context and structures cannot 2025 /// contain non-field names. 2026 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2027 while (((S->getFlags() & Scope::DeclScope) == 0) || 2028 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2029 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2030 S = S->getParent(); 2031 return S; 2032 } 2033 2034 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2035 ASTContext::GetBuiltinTypeError Error) { 2036 switch (Error) { 2037 case ASTContext::GE_None: 2038 return ""; 2039 case ASTContext::GE_Missing_type: 2040 return BuiltinInfo.getHeaderName(ID); 2041 case ASTContext::GE_Missing_stdio: 2042 return "stdio.h"; 2043 case ASTContext::GE_Missing_setjmp: 2044 return "setjmp.h"; 2045 case ASTContext::GE_Missing_ucontext: 2046 return "ucontext.h"; 2047 } 2048 llvm_unreachable("unhandled error kind"); 2049 } 2050 2051 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2052 unsigned ID, SourceLocation Loc) { 2053 DeclContext *Parent = Context.getTranslationUnitDecl(); 2054 2055 if (getLangOpts().CPlusPlus) { 2056 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2057 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); 2058 CLinkageDecl->setImplicit(); 2059 Parent->addDecl(CLinkageDecl); 2060 Parent = CLinkageDecl; 2061 } 2062 2063 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2064 /*TInfo=*/nullptr, SC_Extern, false, 2065 Type->isFunctionProtoType()); 2066 New->setImplicit(); 2067 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2068 2069 // Create Decl objects for each parameter, adding them to the 2070 // FunctionDecl. 2071 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2072 SmallVector<ParmVarDecl *, 16> Params; 2073 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2074 ParmVarDecl *parm = ParmVarDecl::Create( 2075 Context, New, SourceLocation(), SourceLocation(), nullptr, 2076 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2077 parm->setScopeInfo(0, i); 2078 Params.push_back(parm); 2079 } 2080 New->setParams(Params); 2081 } 2082 2083 AddKnownFunctionAttributes(New); 2084 return New; 2085 } 2086 2087 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2088 /// file scope. lazily create a decl for it. ForRedeclaration is true 2089 /// if we're creating this built-in in anticipation of redeclaring the 2090 /// built-in. 2091 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2092 Scope *S, bool ForRedeclaration, 2093 SourceLocation Loc) { 2094 LookupNecessaryTypesForBuiltin(S, ID); 2095 2096 ASTContext::GetBuiltinTypeError Error; 2097 QualType R = Context.GetBuiltinType(ID, Error); 2098 if (Error) { 2099 if (!ForRedeclaration) 2100 return nullptr; 2101 2102 // If we have a builtin without an associated type we should not emit a 2103 // warning when we were not able to find a type for it. 2104 if (Error == ASTContext::GE_Missing_type || 2105 Context.BuiltinInfo.allowTypeMismatch(ID)) 2106 return nullptr; 2107 2108 // If we could not find a type for setjmp it is because the jmp_buf type was 2109 // not defined prior to the setjmp declaration. 2110 if (Error == ASTContext::GE_Missing_setjmp) { 2111 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2112 << Context.BuiltinInfo.getName(ID); 2113 return nullptr; 2114 } 2115 2116 // Generally, we emit a warning that the declaration requires the 2117 // appropriate header. 2118 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2119 << getHeaderName(Context.BuiltinInfo, ID, Error) 2120 << Context.BuiltinInfo.getName(ID); 2121 return nullptr; 2122 } 2123 2124 if (!ForRedeclaration && 2125 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2126 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2127 Diag(Loc, diag::ext_implicit_lib_function_decl) 2128 << Context.BuiltinInfo.getName(ID) << R; 2129 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2130 Diag(Loc, diag::note_include_header_or_declare) 2131 << Header << Context.BuiltinInfo.getName(ID); 2132 } 2133 2134 if (R.isNull()) 2135 return nullptr; 2136 2137 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2138 RegisterLocallyScopedExternCDecl(New, S); 2139 2140 // TUScope is the translation-unit scope to insert this function into. 2141 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2142 // relate Scopes to DeclContexts, and probably eliminate CurContext 2143 // entirely, but we're not there yet. 2144 DeclContext *SavedContext = CurContext; 2145 CurContext = New->getDeclContext(); 2146 PushOnScopeChains(New, TUScope); 2147 CurContext = SavedContext; 2148 return New; 2149 } 2150 2151 /// Typedef declarations don't have linkage, but they still denote the same 2152 /// entity if their types are the same. 2153 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2154 /// isSameEntity. 2155 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2156 TypedefNameDecl *Decl, 2157 LookupResult &Previous) { 2158 // This is only interesting when modules are enabled. 2159 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2160 return; 2161 2162 // Empty sets are uninteresting. 2163 if (Previous.empty()) 2164 return; 2165 2166 LookupResult::Filter Filter = Previous.makeFilter(); 2167 while (Filter.hasNext()) { 2168 NamedDecl *Old = Filter.next(); 2169 2170 // Non-hidden declarations are never ignored. 2171 if (S.isVisible(Old)) 2172 continue; 2173 2174 // Declarations of the same entity are not ignored, even if they have 2175 // different linkages. 2176 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2177 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2178 Decl->getUnderlyingType())) 2179 continue; 2180 2181 // If both declarations give a tag declaration a typedef name for linkage 2182 // purposes, then they declare the same entity. 2183 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2184 Decl->getAnonDeclWithTypedefName()) 2185 continue; 2186 } 2187 2188 Filter.erase(); 2189 } 2190 2191 Filter.done(); 2192 } 2193 2194 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2195 QualType OldType; 2196 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2197 OldType = OldTypedef->getUnderlyingType(); 2198 else 2199 OldType = Context.getTypeDeclType(Old); 2200 QualType NewType = New->getUnderlyingType(); 2201 2202 if (NewType->isVariablyModifiedType()) { 2203 // Must not redefine a typedef with a variably-modified type. 2204 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2205 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2206 << Kind << NewType; 2207 if (Old->getLocation().isValid()) 2208 notePreviousDefinition(Old, New->getLocation()); 2209 New->setInvalidDecl(); 2210 return true; 2211 } 2212 2213 if (OldType != NewType && 2214 !OldType->isDependentType() && 2215 !NewType->isDependentType() && 2216 !Context.hasSameType(OldType, NewType)) { 2217 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2218 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2219 << Kind << NewType << OldType; 2220 if (Old->getLocation().isValid()) 2221 notePreviousDefinition(Old, New->getLocation()); 2222 New->setInvalidDecl(); 2223 return true; 2224 } 2225 return false; 2226 } 2227 2228 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2229 /// same name and scope as a previous declaration 'Old'. Figure out 2230 /// how to resolve this situation, merging decls or emitting 2231 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2232 /// 2233 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2234 LookupResult &OldDecls) { 2235 // If the new decl is known invalid already, don't bother doing any 2236 // merging checks. 2237 if (New->isInvalidDecl()) return; 2238 2239 // Allow multiple definitions for ObjC built-in typedefs. 2240 // FIXME: Verify the underlying types are equivalent! 2241 if (getLangOpts().ObjC) { 2242 const IdentifierInfo *TypeID = New->getIdentifier(); 2243 switch (TypeID->getLength()) { 2244 default: break; 2245 case 2: 2246 { 2247 if (!TypeID->isStr("id")) 2248 break; 2249 QualType T = New->getUnderlyingType(); 2250 if (!T->isPointerType()) 2251 break; 2252 if (!T->isVoidPointerType()) { 2253 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2254 if (!PT->isStructureType()) 2255 break; 2256 } 2257 Context.setObjCIdRedefinitionType(T); 2258 // Install the built-in type for 'id', ignoring the current definition. 2259 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2260 return; 2261 } 2262 case 5: 2263 if (!TypeID->isStr("Class")) 2264 break; 2265 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2266 // Install the built-in type for 'Class', ignoring the current definition. 2267 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2268 return; 2269 case 3: 2270 if (!TypeID->isStr("SEL")) 2271 break; 2272 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2273 // Install the built-in type for 'SEL', ignoring the current definition. 2274 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2275 return; 2276 } 2277 // Fall through - the typedef name was not a builtin type. 2278 } 2279 2280 // Verify the old decl was also a type. 2281 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2282 if (!Old) { 2283 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2284 << New->getDeclName(); 2285 2286 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2287 if (OldD->getLocation().isValid()) 2288 notePreviousDefinition(OldD, New->getLocation()); 2289 2290 return New->setInvalidDecl(); 2291 } 2292 2293 // If the old declaration is invalid, just give up here. 2294 if (Old->isInvalidDecl()) 2295 return New->setInvalidDecl(); 2296 2297 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2298 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2299 auto *NewTag = New->getAnonDeclWithTypedefName(); 2300 NamedDecl *Hidden = nullptr; 2301 if (OldTag && NewTag && 2302 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2303 !hasVisibleDefinition(OldTag, &Hidden)) { 2304 // There is a definition of this tag, but it is not visible. Use it 2305 // instead of our tag. 2306 New->setTypeForDecl(OldTD->getTypeForDecl()); 2307 if (OldTD->isModed()) 2308 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2309 OldTD->getUnderlyingType()); 2310 else 2311 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2312 2313 // Make the old tag definition visible. 2314 makeMergedDefinitionVisible(Hidden); 2315 2316 // If this was an unscoped enumeration, yank all of its enumerators 2317 // out of the scope. 2318 if (isa<EnumDecl>(NewTag)) { 2319 Scope *EnumScope = getNonFieldDeclScope(S); 2320 for (auto *D : NewTag->decls()) { 2321 auto *ED = cast<EnumConstantDecl>(D); 2322 assert(EnumScope->isDeclScope(ED)); 2323 EnumScope->RemoveDecl(ED); 2324 IdResolver.RemoveDecl(ED); 2325 ED->getLexicalDeclContext()->removeDecl(ED); 2326 } 2327 } 2328 } 2329 } 2330 2331 // If the typedef types are not identical, reject them in all languages and 2332 // with any extensions enabled. 2333 if (isIncompatibleTypedef(Old, New)) 2334 return; 2335 2336 // The types match. Link up the redeclaration chain and merge attributes if 2337 // the old declaration was a typedef. 2338 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2339 New->setPreviousDecl(Typedef); 2340 mergeDeclAttributes(New, Old); 2341 } 2342 2343 if (getLangOpts().MicrosoftExt) 2344 return; 2345 2346 if (getLangOpts().CPlusPlus) { 2347 // C++ [dcl.typedef]p2: 2348 // In a given non-class scope, a typedef specifier can be used to 2349 // redefine the name of any type declared in that scope to refer 2350 // to the type to which it already refers. 2351 if (!isa<CXXRecordDecl>(CurContext)) 2352 return; 2353 2354 // C++0x [dcl.typedef]p4: 2355 // In a given class scope, a typedef specifier can be used to redefine 2356 // any class-name declared in that scope that is not also a typedef-name 2357 // to refer to the type to which it already refers. 2358 // 2359 // This wording came in via DR424, which was a correction to the 2360 // wording in DR56, which accidentally banned code like: 2361 // 2362 // struct S { 2363 // typedef struct A { } A; 2364 // }; 2365 // 2366 // in the C++03 standard. We implement the C++0x semantics, which 2367 // allow the above but disallow 2368 // 2369 // struct S { 2370 // typedef int I; 2371 // typedef int I; 2372 // }; 2373 // 2374 // since that was the intent of DR56. 2375 if (!isa<TypedefNameDecl>(Old)) 2376 return; 2377 2378 Diag(New->getLocation(), diag::err_redefinition) 2379 << New->getDeclName(); 2380 notePreviousDefinition(Old, New->getLocation()); 2381 return New->setInvalidDecl(); 2382 } 2383 2384 // Modules always permit redefinition of typedefs, as does C11. 2385 if (getLangOpts().Modules || getLangOpts().C11) 2386 return; 2387 2388 // If we have a redefinition of a typedef in C, emit a warning. This warning 2389 // is normally mapped to an error, but can be controlled with 2390 // -Wtypedef-redefinition. If either the original or the redefinition is 2391 // in a system header, don't emit this for compatibility with GCC. 2392 if (getDiagnostics().getSuppressSystemWarnings() && 2393 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2394 (Old->isImplicit() || 2395 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2396 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2397 return; 2398 2399 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2400 << New->getDeclName(); 2401 notePreviousDefinition(Old, New->getLocation()); 2402 } 2403 2404 /// DeclhasAttr - returns true if decl Declaration already has the target 2405 /// attribute. 2406 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2407 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2408 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2409 for (const auto *i : D->attrs()) 2410 if (i->getKind() == A->getKind()) { 2411 if (Ann) { 2412 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2413 return true; 2414 continue; 2415 } 2416 // FIXME: Don't hardcode this check 2417 if (OA && isa<OwnershipAttr>(i)) 2418 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2419 return true; 2420 } 2421 2422 return false; 2423 } 2424 2425 static bool isAttributeTargetADefinition(Decl *D) { 2426 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2427 return VD->isThisDeclarationADefinition(); 2428 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2429 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2430 return true; 2431 } 2432 2433 /// Merge alignment attributes from \p Old to \p New, taking into account the 2434 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2435 /// 2436 /// \return \c true if any attributes were added to \p New. 2437 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2438 // Look for alignas attributes on Old, and pick out whichever attribute 2439 // specifies the strictest alignment requirement. 2440 AlignedAttr *OldAlignasAttr = nullptr; 2441 AlignedAttr *OldStrictestAlignAttr = nullptr; 2442 unsigned OldAlign = 0; 2443 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2444 // FIXME: We have no way of representing inherited dependent alignments 2445 // in a case like: 2446 // template<int A, int B> struct alignas(A) X; 2447 // template<int A, int B> struct alignas(B) X {}; 2448 // For now, we just ignore any alignas attributes which are not on the 2449 // definition in such a case. 2450 if (I->isAlignmentDependent()) 2451 return false; 2452 2453 if (I->isAlignas()) 2454 OldAlignasAttr = I; 2455 2456 unsigned Align = I->getAlignment(S.Context); 2457 if (Align > OldAlign) { 2458 OldAlign = Align; 2459 OldStrictestAlignAttr = I; 2460 } 2461 } 2462 2463 // Look for alignas attributes on New. 2464 AlignedAttr *NewAlignasAttr = nullptr; 2465 unsigned NewAlign = 0; 2466 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2467 if (I->isAlignmentDependent()) 2468 return false; 2469 2470 if (I->isAlignas()) 2471 NewAlignasAttr = I; 2472 2473 unsigned Align = I->getAlignment(S.Context); 2474 if (Align > NewAlign) 2475 NewAlign = Align; 2476 } 2477 2478 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2479 // Both declarations have 'alignas' attributes. We require them to match. 2480 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2481 // fall short. (If two declarations both have alignas, they must both match 2482 // every definition, and so must match each other if there is a definition.) 2483 2484 // If either declaration only contains 'alignas(0)' specifiers, then it 2485 // specifies the natural alignment for the type. 2486 if (OldAlign == 0 || NewAlign == 0) { 2487 QualType Ty; 2488 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2489 Ty = VD->getType(); 2490 else 2491 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2492 2493 if (OldAlign == 0) 2494 OldAlign = S.Context.getTypeAlign(Ty); 2495 if (NewAlign == 0) 2496 NewAlign = S.Context.getTypeAlign(Ty); 2497 } 2498 2499 if (OldAlign != NewAlign) { 2500 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2501 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2502 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2503 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2504 } 2505 } 2506 2507 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2508 // C++11 [dcl.align]p6: 2509 // if any declaration of an entity has an alignment-specifier, 2510 // every defining declaration of that entity shall specify an 2511 // equivalent alignment. 2512 // C11 6.7.5/7: 2513 // If the definition of an object does not have an alignment 2514 // specifier, any other declaration of that object shall also 2515 // have no alignment specifier. 2516 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2517 << OldAlignasAttr; 2518 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2519 << OldAlignasAttr; 2520 } 2521 2522 bool AnyAdded = false; 2523 2524 // Ensure we have an attribute representing the strictest alignment. 2525 if (OldAlign > NewAlign) { 2526 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2527 Clone->setInherited(true); 2528 New->addAttr(Clone); 2529 AnyAdded = true; 2530 } 2531 2532 // Ensure we have an alignas attribute if the old declaration had one. 2533 if (OldAlignasAttr && !NewAlignasAttr && 2534 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2535 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2536 Clone->setInherited(true); 2537 New->addAttr(Clone); 2538 AnyAdded = true; 2539 } 2540 2541 return AnyAdded; 2542 } 2543 2544 #define WANT_DECL_MERGE_LOGIC 2545 #include "clang/Sema/AttrParsedAttrImpl.inc" 2546 #undef WANT_DECL_MERGE_LOGIC 2547 2548 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2549 const InheritableAttr *Attr, 2550 Sema::AvailabilityMergeKind AMK) { 2551 // Diagnose any mutual exclusions between the attribute that we want to add 2552 // and attributes that already exist on the declaration. 2553 if (!DiagnoseMutualExclusions(S, D, Attr)) 2554 return false; 2555 2556 // This function copies an attribute Attr from a previous declaration to the 2557 // new declaration D if the new declaration doesn't itself have that attribute 2558 // yet or if that attribute allows duplicates. 2559 // If you're adding a new attribute that requires logic different from 2560 // "use explicit attribute on decl if present, else use attribute from 2561 // previous decl", for example if the attribute needs to be consistent 2562 // between redeclarations, you need to call a custom merge function here. 2563 InheritableAttr *NewAttr = nullptr; 2564 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2565 NewAttr = S.mergeAvailabilityAttr( 2566 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2567 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2568 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2569 AA->getPriority()); 2570 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2571 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2572 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2573 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2574 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2575 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2576 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2577 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2578 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2579 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2580 FA->getFirstArg()); 2581 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2582 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2583 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2584 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2585 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2586 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2587 IA->getInheritanceModel()); 2588 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2589 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2590 &S.Context.Idents.get(AA->getSpelling())); 2591 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2592 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2593 isa<CUDAGlobalAttr>(Attr))) { 2594 // CUDA target attributes are part of function signature for 2595 // overloading purposes and must not be merged. 2596 return false; 2597 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2598 NewAttr = S.mergeMinSizeAttr(D, *MA); 2599 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2600 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2601 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2602 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2603 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2604 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2605 else if (isa<AlignedAttr>(Attr)) 2606 // AlignedAttrs are handled separately, because we need to handle all 2607 // such attributes on a declaration at the same time. 2608 NewAttr = nullptr; 2609 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2610 (AMK == Sema::AMK_Override || 2611 AMK == Sema::AMK_ProtocolImplementation || 2612 AMK == Sema::AMK_OptionalProtocolImplementation)) 2613 NewAttr = nullptr; 2614 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2615 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2616 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2617 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2618 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2619 NewAttr = S.mergeImportNameAttr(D, *INA); 2620 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 2621 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 2622 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 2623 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 2624 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2625 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2626 2627 if (NewAttr) { 2628 NewAttr->setInherited(true); 2629 D->addAttr(NewAttr); 2630 if (isa<MSInheritanceAttr>(NewAttr)) 2631 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2632 return true; 2633 } 2634 2635 return false; 2636 } 2637 2638 static const NamedDecl *getDefinition(const Decl *D) { 2639 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2640 return TD->getDefinition(); 2641 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2642 const VarDecl *Def = VD->getDefinition(); 2643 if (Def) 2644 return Def; 2645 return VD->getActingDefinition(); 2646 } 2647 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2648 const FunctionDecl *Def = nullptr; 2649 if (FD->isDefined(Def, true)) 2650 return Def; 2651 } 2652 return nullptr; 2653 } 2654 2655 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2656 for (const auto *Attribute : D->attrs()) 2657 if (Attribute->getKind() == Kind) 2658 return true; 2659 return false; 2660 } 2661 2662 /// checkNewAttributesAfterDef - If we already have a definition, check that 2663 /// there are no new attributes in this declaration. 2664 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2665 if (!New->hasAttrs()) 2666 return; 2667 2668 const NamedDecl *Def = getDefinition(Old); 2669 if (!Def || Def == New) 2670 return; 2671 2672 AttrVec &NewAttributes = New->getAttrs(); 2673 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2674 const Attr *NewAttribute = NewAttributes[I]; 2675 2676 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2677 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2678 Sema::SkipBodyInfo SkipBody; 2679 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2680 2681 // If we're skipping this definition, drop the "alias" attribute. 2682 if (SkipBody.ShouldSkip) { 2683 NewAttributes.erase(NewAttributes.begin() + I); 2684 --E; 2685 continue; 2686 } 2687 } else { 2688 VarDecl *VD = cast<VarDecl>(New); 2689 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2690 VarDecl::TentativeDefinition 2691 ? diag::err_alias_after_tentative 2692 : diag::err_redefinition; 2693 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2694 if (Diag == diag::err_redefinition) 2695 S.notePreviousDefinition(Def, VD->getLocation()); 2696 else 2697 S.Diag(Def->getLocation(), diag::note_previous_definition); 2698 VD->setInvalidDecl(); 2699 } 2700 ++I; 2701 continue; 2702 } 2703 2704 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2705 // Tentative definitions are only interesting for the alias check above. 2706 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2707 ++I; 2708 continue; 2709 } 2710 } 2711 2712 if (hasAttribute(Def, NewAttribute->getKind())) { 2713 ++I; 2714 continue; // regular attr merging will take care of validating this. 2715 } 2716 2717 if (isa<C11NoReturnAttr>(NewAttribute)) { 2718 // C's _Noreturn is allowed to be added to a function after it is defined. 2719 ++I; 2720 continue; 2721 } else if (isa<UuidAttr>(NewAttribute)) { 2722 // msvc will allow a subsequent definition to add an uuid to a class 2723 ++I; 2724 continue; 2725 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2726 if (AA->isAlignas()) { 2727 // C++11 [dcl.align]p6: 2728 // if any declaration of an entity has an alignment-specifier, 2729 // every defining declaration of that entity shall specify an 2730 // equivalent alignment. 2731 // C11 6.7.5/7: 2732 // If the definition of an object does not have an alignment 2733 // specifier, any other declaration of that object shall also 2734 // have no alignment specifier. 2735 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2736 << AA; 2737 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2738 << AA; 2739 NewAttributes.erase(NewAttributes.begin() + I); 2740 --E; 2741 continue; 2742 } 2743 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2744 // If there is a C definition followed by a redeclaration with this 2745 // attribute then there are two different definitions. In C++, prefer the 2746 // standard diagnostics. 2747 if (!S.getLangOpts().CPlusPlus) { 2748 S.Diag(NewAttribute->getLocation(), 2749 diag::err_loader_uninitialized_redeclaration); 2750 S.Diag(Def->getLocation(), diag::note_previous_definition); 2751 NewAttributes.erase(NewAttributes.begin() + I); 2752 --E; 2753 continue; 2754 } 2755 } else if (isa<SelectAnyAttr>(NewAttribute) && 2756 cast<VarDecl>(New)->isInline() && 2757 !cast<VarDecl>(New)->isInlineSpecified()) { 2758 // Don't warn about applying selectany to implicitly inline variables. 2759 // Older compilers and language modes would require the use of selectany 2760 // to make such variables inline, and it would have no effect if we 2761 // honored it. 2762 ++I; 2763 continue; 2764 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2765 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2766 // declarations after defintions. 2767 ++I; 2768 continue; 2769 } 2770 2771 S.Diag(NewAttribute->getLocation(), 2772 diag::warn_attribute_precede_definition); 2773 S.Diag(Def->getLocation(), diag::note_previous_definition); 2774 NewAttributes.erase(NewAttributes.begin() + I); 2775 --E; 2776 } 2777 } 2778 2779 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2780 const ConstInitAttr *CIAttr, 2781 bool AttrBeforeInit) { 2782 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2783 2784 // Figure out a good way to write this specifier on the old declaration. 2785 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2786 // enough of the attribute list spelling information to extract that without 2787 // heroics. 2788 std::string SuitableSpelling; 2789 if (S.getLangOpts().CPlusPlus20) 2790 SuitableSpelling = std::string( 2791 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2792 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2793 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2794 InsertLoc, {tok::l_square, tok::l_square, 2795 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2796 S.PP.getIdentifierInfo("require_constant_initialization"), 2797 tok::r_square, tok::r_square})); 2798 if (SuitableSpelling.empty()) 2799 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2800 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2801 S.PP.getIdentifierInfo("require_constant_initialization"), 2802 tok::r_paren, tok::r_paren})); 2803 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2804 SuitableSpelling = "constinit"; 2805 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2806 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2807 if (SuitableSpelling.empty()) 2808 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2809 SuitableSpelling += " "; 2810 2811 if (AttrBeforeInit) { 2812 // extern constinit int a; 2813 // int a = 0; // error (missing 'constinit'), accepted as extension 2814 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2815 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2816 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2817 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2818 } else { 2819 // int a = 0; 2820 // constinit extern int a; // error (missing 'constinit') 2821 S.Diag(CIAttr->getLocation(), 2822 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2823 : diag::warn_require_const_init_added_too_late) 2824 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2825 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2826 << CIAttr->isConstinit() 2827 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2828 } 2829 } 2830 2831 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2832 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2833 AvailabilityMergeKind AMK) { 2834 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2835 UsedAttr *NewAttr = OldAttr->clone(Context); 2836 NewAttr->setInherited(true); 2837 New->addAttr(NewAttr); 2838 } 2839 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { 2840 RetainAttr *NewAttr = OldAttr->clone(Context); 2841 NewAttr->setInherited(true); 2842 New->addAttr(NewAttr); 2843 } 2844 2845 if (!Old->hasAttrs() && !New->hasAttrs()) 2846 return; 2847 2848 // [dcl.constinit]p1: 2849 // If the [constinit] specifier is applied to any declaration of a 2850 // variable, it shall be applied to the initializing declaration. 2851 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2852 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2853 if (bool(OldConstInit) != bool(NewConstInit)) { 2854 const auto *OldVD = cast<VarDecl>(Old); 2855 auto *NewVD = cast<VarDecl>(New); 2856 2857 // Find the initializing declaration. Note that we might not have linked 2858 // the new declaration into the redeclaration chain yet. 2859 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2860 if (!InitDecl && 2861 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2862 InitDecl = NewVD; 2863 2864 if (InitDecl == NewVD) { 2865 // This is the initializing declaration. If it would inherit 'constinit', 2866 // that's ill-formed. (Note that we do not apply this to the attribute 2867 // form). 2868 if (OldConstInit && OldConstInit->isConstinit()) 2869 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2870 /*AttrBeforeInit=*/true); 2871 } else if (NewConstInit) { 2872 // This is the first time we've been told that this declaration should 2873 // have a constant initializer. If we already saw the initializing 2874 // declaration, this is too late. 2875 if (InitDecl && InitDecl != NewVD) { 2876 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2877 /*AttrBeforeInit=*/false); 2878 NewVD->dropAttr<ConstInitAttr>(); 2879 } 2880 } 2881 } 2882 2883 // Attributes declared post-definition are currently ignored. 2884 checkNewAttributesAfterDef(*this, New, Old); 2885 2886 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2887 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2888 if (!OldA->isEquivalent(NewA)) { 2889 // This redeclaration changes __asm__ label. 2890 Diag(New->getLocation(), diag::err_different_asm_label); 2891 Diag(OldA->getLocation(), diag::note_previous_declaration); 2892 } 2893 } else if (Old->isUsed()) { 2894 // This redeclaration adds an __asm__ label to a declaration that has 2895 // already been ODR-used. 2896 Diag(New->getLocation(), diag::err_late_asm_label_name) 2897 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2898 } 2899 } 2900 2901 // Re-declaration cannot add abi_tag's. 2902 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2903 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2904 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2905 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2906 NewTag) == OldAbiTagAttr->tags_end()) { 2907 Diag(NewAbiTagAttr->getLocation(), 2908 diag::err_new_abi_tag_on_redeclaration) 2909 << NewTag; 2910 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2911 } 2912 } 2913 } else { 2914 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2915 Diag(Old->getLocation(), diag::note_previous_declaration); 2916 } 2917 } 2918 2919 // This redeclaration adds a section attribute. 2920 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2921 if (auto *VD = dyn_cast<VarDecl>(New)) { 2922 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2923 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2924 Diag(Old->getLocation(), diag::note_previous_declaration); 2925 } 2926 } 2927 } 2928 2929 // Redeclaration adds code-seg attribute. 2930 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2931 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2932 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2933 Diag(New->getLocation(), diag::warn_mismatched_section) 2934 << 0 /*codeseg*/; 2935 Diag(Old->getLocation(), diag::note_previous_declaration); 2936 } 2937 2938 if (!Old->hasAttrs()) 2939 return; 2940 2941 bool foundAny = New->hasAttrs(); 2942 2943 // Ensure that any moving of objects within the allocated map is done before 2944 // we process them. 2945 if (!foundAny) New->setAttrs(AttrVec()); 2946 2947 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2948 // Ignore deprecated/unavailable/availability attributes if requested. 2949 AvailabilityMergeKind LocalAMK = AMK_None; 2950 if (isa<DeprecatedAttr>(I) || 2951 isa<UnavailableAttr>(I) || 2952 isa<AvailabilityAttr>(I)) { 2953 switch (AMK) { 2954 case AMK_None: 2955 continue; 2956 2957 case AMK_Redeclaration: 2958 case AMK_Override: 2959 case AMK_ProtocolImplementation: 2960 case AMK_OptionalProtocolImplementation: 2961 LocalAMK = AMK; 2962 break; 2963 } 2964 } 2965 2966 // Already handled. 2967 if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) 2968 continue; 2969 2970 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2971 foundAny = true; 2972 } 2973 2974 if (mergeAlignedAttrs(*this, New, Old)) 2975 foundAny = true; 2976 2977 if (!foundAny) New->dropAttrs(); 2978 } 2979 2980 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2981 /// to the new one. 2982 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2983 const ParmVarDecl *oldDecl, 2984 Sema &S) { 2985 // C++11 [dcl.attr.depend]p2: 2986 // The first declaration of a function shall specify the 2987 // carries_dependency attribute for its declarator-id if any declaration 2988 // of the function specifies the carries_dependency attribute. 2989 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2990 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2991 S.Diag(CDA->getLocation(), 2992 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2993 // Find the first declaration of the parameter. 2994 // FIXME: Should we build redeclaration chains for function parameters? 2995 const FunctionDecl *FirstFD = 2996 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2997 const ParmVarDecl *FirstVD = 2998 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2999 S.Diag(FirstVD->getLocation(), 3000 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 3001 } 3002 3003 if (!oldDecl->hasAttrs()) 3004 return; 3005 3006 bool foundAny = newDecl->hasAttrs(); 3007 3008 // Ensure that any moving of objects within the allocated map is 3009 // done before we process them. 3010 if (!foundAny) newDecl->setAttrs(AttrVec()); 3011 3012 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3013 if (!DeclHasAttr(newDecl, I)) { 3014 InheritableAttr *newAttr = 3015 cast<InheritableParamAttr>(I->clone(S.Context)); 3016 newAttr->setInherited(true); 3017 newDecl->addAttr(newAttr); 3018 foundAny = true; 3019 } 3020 } 3021 3022 if (!foundAny) newDecl->dropAttrs(); 3023 } 3024 3025 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3026 const ParmVarDecl *OldParam, 3027 Sema &S) { 3028 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3029 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3030 if (*Oldnullability != *Newnullability) { 3031 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3032 << DiagNullabilityKind( 3033 *Newnullability, 3034 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3035 != 0)) 3036 << DiagNullabilityKind( 3037 *Oldnullability, 3038 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3039 != 0)); 3040 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3041 } 3042 } else { 3043 QualType NewT = NewParam->getType(); 3044 NewT = S.Context.getAttributedType( 3045 AttributedType::getNullabilityAttrKind(*Oldnullability), 3046 NewT, NewT); 3047 NewParam->setType(NewT); 3048 } 3049 } 3050 } 3051 3052 namespace { 3053 3054 /// Used in MergeFunctionDecl to keep track of function parameters in 3055 /// C. 3056 struct GNUCompatibleParamWarning { 3057 ParmVarDecl *OldParm; 3058 ParmVarDecl *NewParm; 3059 QualType PromotedType; 3060 }; 3061 3062 } // end anonymous namespace 3063 3064 // Determine whether the previous declaration was a definition, implicit 3065 // declaration, or a declaration. 3066 template <typename T> 3067 static std::pair<diag::kind, SourceLocation> 3068 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3069 diag::kind PrevDiag; 3070 SourceLocation OldLocation = Old->getLocation(); 3071 if (Old->isThisDeclarationADefinition()) 3072 PrevDiag = diag::note_previous_definition; 3073 else if (Old->isImplicit()) { 3074 PrevDiag = diag::note_previous_implicit_declaration; 3075 if (OldLocation.isInvalid()) 3076 OldLocation = New->getLocation(); 3077 } else 3078 PrevDiag = diag::note_previous_declaration; 3079 return std::make_pair(PrevDiag, OldLocation); 3080 } 3081 3082 /// canRedefineFunction - checks if a function can be redefined. Currently, 3083 /// only extern inline functions can be redefined, and even then only in 3084 /// GNU89 mode. 3085 static bool canRedefineFunction(const FunctionDecl *FD, 3086 const LangOptions& LangOpts) { 3087 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3088 !LangOpts.CPlusPlus && 3089 FD->isInlineSpecified() && 3090 FD->getStorageClass() == SC_Extern); 3091 } 3092 3093 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3094 const AttributedType *AT = T->getAs<AttributedType>(); 3095 while (AT && !AT->isCallingConv()) 3096 AT = AT->getModifiedType()->getAs<AttributedType>(); 3097 return AT; 3098 } 3099 3100 template <typename T> 3101 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3102 const DeclContext *DC = Old->getDeclContext(); 3103 if (DC->isRecord()) 3104 return false; 3105 3106 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3107 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3108 return true; 3109 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3110 return true; 3111 return false; 3112 } 3113 3114 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3115 static bool isExternC(VarTemplateDecl *) { return false; } 3116 3117 /// Check whether a redeclaration of an entity introduced by a 3118 /// using-declaration is valid, given that we know it's not an overload 3119 /// (nor a hidden tag declaration). 3120 template<typename ExpectedDecl> 3121 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3122 ExpectedDecl *New) { 3123 // C++11 [basic.scope.declarative]p4: 3124 // Given a set of declarations in a single declarative region, each of 3125 // which specifies the same unqualified name, 3126 // -- they shall all refer to the same entity, or all refer to functions 3127 // and function templates; or 3128 // -- exactly one declaration shall declare a class name or enumeration 3129 // name that is not a typedef name and the other declarations shall all 3130 // refer to the same variable or enumerator, or all refer to functions 3131 // and function templates; in this case the class name or enumeration 3132 // name is hidden (3.3.10). 3133 3134 // C++11 [namespace.udecl]p14: 3135 // If a function declaration in namespace scope or block scope has the 3136 // same name and the same parameter-type-list as a function introduced 3137 // by a using-declaration, and the declarations do not declare the same 3138 // function, the program is ill-formed. 3139 3140 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3141 if (Old && 3142 !Old->getDeclContext()->getRedeclContext()->Equals( 3143 New->getDeclContext()->getRedeclContext()) && 3144 !(isExternC(Old) && isExternC(New))) 3145 Old = nullptr; 3146 3147 if (!Old) { 3148 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3149 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3150 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3151 return true; 3152 } 3153 return false; 3154 } 3155 3156 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3157 const FunctionDecl *B) { 3158 assert(A->getNumParams() == B->getNumParams()); 3159 3160 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3161 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3162 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3163 if (AttrA == AttrB) 3164 return true; 3165 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3166 AttrA->isDynamic() == AttrB->isDynamic(); 3167 }; 3168 3169 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3170 } 3171 3172 /// If necessary, adjust the semantic declaration context for a qualified 3173 /// declaration to name the correct inline namespace within the qualifier. 3174 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3175 DeclaratorDecl *OldD) { 3176 // The only case where we need to update the DeclContext is when 3177 // redeclaration lookup for a qualified name finds a declaration 3178 // in an inline namespace within the context named by the qualifier: 3179 // 3180 // inline namespace N { int f(); } 3181 // int ::f(); // Sema DC needs adjusting from :: to N::. 3182 // 3183 // For unqualified declarations, the semantic context *can* change 3184 // along the redeclaration chain (for local extern declarations, 3185 // extern "C" declarations, and friend declarations in particular). 3186 if (!NewD->getQualifier()) 3187 return; 3188 3189 // NewD is probably already in the right context. 3190 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3191 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3192 if (NamedDC->Equals(SemaDC)) 3193 return; 3194 3195 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3196 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3197 "unexpected context for redeclaration"); 3198 3199 auto *LexDC = NewD->getLexicalDeclContext(); 3200 auto FixSemaDC = [=](NamedDecl *D) { 3201 if (!D) 3202 return; 3203 D->setDeclContext(SemaDC); 3204 D->setLexicalDeclContext(LexDC); 3205 }; 3206 3207 FixSemaDC(NewD); 3208 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3209 FixSemaDC(FD->getDescribedFunctionTemplate()); 3210 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3211 FixSemaDC(VD->getDescribedVarTemplate()); 3212 } 3213 3214 /// MergeFunctionDecl - We just parsed a function 'New' from 3215 /// declarator D which has the same name and scope as a previous 3216 /// declaration 'Old'. Figure out how to resolve this situation, 3217 /// merging decls or emitting diagnostics as appropriate. 3218 /// 3219 /// In C++, New and Old must be declarations that are not 3220 /// overloaded. Use IsOverload to determine whether New and Old are 3221 /// overloaded, and to select the Old declaration that New should be 3222 /// merged with. 3223 /// 3224 /// Returns true if there was an error, false otherwise. 3225 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3226 Scope *S, bool MergeTypeWithOld) { 3227 // Verify the old decl was also a function. 3228 FunctionDecl *Old = OldD->getAsFunction(); 3229 if (!Old) { 3230 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3231 if (New->getFriendObjectKind()) { 3232 Diag(New->getLocation(), diag::err_using_decl_friend); 3233 Diag(Shadow->getTargetDecl()->getLocation(), 3234 diag::note_using_decl_target); 3235 Diag(Shadow->getUsingDecl()->getLocation(), 3236 diag::note_using_decl) << 0; 3237 return true; 3238 } 3239 3240 // Check whether the two declarations might declare the same function. 3241 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3242 return true; 3243 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3244 } else { 3245 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3246 << New->getDeclName(); 3247 notePreviousDefinition(OldD, New->getLocation()); 3248 return true; 3249 } 3250 } 3251 3252 // If the old declaration was found in an inline namespace and the new 3253 // declaration was qualified, update the DeclContext to match. 3254 adjustDeclContextForDeclaratorDecl(New, Old); 3255 3256 // If the old declaration is invalid, just give up here. 3257 if (Old->isInvalidDecl()) 3258 return true; 3259 3260 // Disallow redeclaration of some builtins. 3261 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3262 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3263 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3264 << Old << Old->getType(); 3265 return true; 3266 } 3267 3268 diag::kind PrevDiag; 3269 SourceLocation OldLocation; 3270 std::tie(PrevDiag, OldLocation) = 3271 getNoteDiagForInvalidRedeclaration(Old, New); 3272 3273 // Don't complain about this if we're in GNU89 mode and the old function 3274 // is an extern inline function. 3275 // Don't complain about specializations. They are not supposed to have 3276 // storage classes. 3277 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3278 New->getStorageClass() == SC_Static && 3279 Old->hasExternalFormalLinkage() && 3280 !New->getTemplateSpecializationInfo() && 3281 !canRedefineFunction(Old, getLangOpts())) { 3282 if (getLangOpts().MicrosoftExt) { 3283 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3284 Diag(OldLocation, PrevDiag); 3285 } else { 3286 Diag(New->getLocation(), diag::err_static_non_static) << New; 3287 Diag(OldLocation, PrevDiag); 3288 return true; 3289 } 3290 } 3291 3292 if (New->hasAttr<InternalLinkageAttr>() && 3293 !Old->hasAttr<InternalLinkageAttr>()) { 3294 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3295 << New->getDeclName(); 3296 notePreviousDefinition(Old, New->getLocation()); 3297 New->dropAttr<InternalLinkageAttr>(); 3298 } 3299 3300 if (CheckRedeclarationModuleOwnership(New, Old)) 3301 return true; 3302 3303 if (!getLangOpts().CPlusPlus) { 3304 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3305 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3306 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3307 << New << OldOvl; 3308 3309 // Try our best to find a decl that actually has the overloadable 3310 // attribute for the note. In most cases (e.g. programs with only one 3311 // broken declaration/definition), this won't matter. 3312 // 3313 // FIXME: We could do this if we juggled some extra state in 3314 // OverloadableAttr, rather than just removing it. 3315 const Decl *DiagOld = Old; 3316 if (OldOvl) { 3317 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3318 const auto *A = D->getAttr<OverloadableAttr>(); 3319 return A && !A->isImplicit(); 3320 }); 3321 // If we've implicitly added *all* of the overloadable attrs to this 3322 // chain, emitting a "previous redecl" note is pointless. 3323 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3324 } 3325 3326 if (DiagOld) 3327 Diag(DiagOld->getLocation(), 3328 diag::note_attribute_overloadable_prev_overload) 3329 << OldOvl; 3330 3331 if (OldOvl) 3332 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3333 else 3334 New->dropAttr<OverloadableAttr>(); 3335 } 3336 } 3337 3338 // If a function is first declared with a calling convention, but is later 3339 // declared or defined without one, all following decls assume the calling 3340 // convention of the first. 3341 // 3342 // It's OK if a function is first declared without a calling convention, 3343 // but is later declared or defined with the default calling convention. 3344 // 3345 // To test if either decl has an explicit calling convention, we look for 3346 // AttributedType sugar nodes on the type as written. If they are missing or 3347 // were canonicalized away, we assume the calling convention was implicit. 3348 // 3349 // Note also that we DO NOT return at this point, because we still have 3350 // other tests to run. 3351 QualType OldQType = Context.getCanonicalType(Old->getType()); 3352 QualType NewQType = Context.getCanonicalType(New->getType()); 3353 const FunctionType *OldType = cast<FunctionType>(OldQType); 3354 const FunctionType *NewType = cast<FunctionType>(NewQType); 3355 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3356 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3357 bool RequiresAdjustment = false; 3358 3359 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3360 FunctionDecl *First = Old->getFirstDecl(); 3361 const FunctionType *FT = 3362 First->getType().getCanonicalType()->castAs<FunctionType>(); 3363 FunctionType::ExtInfo FI = FT->getExtInfo(); 3364 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3365 if (!NewCCExplicit) { 3366 // Inherit the CC from the previous declaration if it was specified 3367 // there but not here. 3368 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3369 RequiresAdjustment = true; 3370 } else if (Old->getBuiltinID()) { 3371 // Builtin attribute isn't propagated to the new one yet at this point, 3372 // so we check if the old one is a builtin. 3373 3374 // Calling Conventions on a Builtin aren't really useful and setting a 3375 // default calling convention and cdecl'ing some builtin redeclarations is 3376 // common, so warn and ignore the calling convention on the redeclaration. 3377 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3378 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3379 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3380 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3381 RequiresAdjustment = true; 3382 } else { 3383 // Calling conventions aren't compatible, so complain. 3384 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3385 Diag(New->getLocation(), diag::err_cconv_change) 3386 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3387 << !FirstCCExplicit 3388 << (!FirstCCExplicit ? "" : 3389 FunctionType::getNameForCallConv(FI.getCC())); 3390 3391 // Put the note on the first decl, since it is the one that matters. 3392 Diag(First->getLocation(), diag::note_previous_declaration); 3393 return true; 3394 } 3395 } 3396 3397 // FIXME: diagnose the other way around? 3398 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3399 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3400 RequiresAdjustment = true; 3401 } 3402 3403 // Merge regparm attribute. 3404 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3405 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3406 if (NewTypeInfo.getHasRegParm()) { 3407 Diag(New->getLocation(), diag::err_regparm_mismatch) 3408 << NewType->getRegParmType() 3409 << OldType->getRegParmType(); 3410 Diag(OldLocation, diag::note_previous_declaration); 3411 return true; 3412 } 3413 3414 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3415 RequiresAdjustment = true; 3416 } 3417 3418 // Merge ns_returns_retained attribute. 3419 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3420 if (NewTypeInfo.getProducesResult()) { 3421 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3422 << "'ns_returns_retained'"; 3423 Diag(OldLocation, diag::note_previous_declaration); 3424 return true; 3425 } 3426 3427 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3428 RequiresAdjustment = true; 3429 } 3430 3431 if (OldTypeInfo.getNoCallerSavedRegs() != 3432 NewTypeInfo.getNoCallerSavedRegs()) { 3433 if (NewTypeInfo.getNoCallerSavedRegs()) { 3434 AnyX86NoCallerSavedRegistersAttr *Attr = 3435 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3436 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3437 Diag(OldLocation, diag::note_previous_declaration); 3438 return true; 3439 } 3440 3441 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3442 RequiresAdjustment = true; 3443 } 3444 3445 if (RequiresAdjustment) { 3446 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3447 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3448 New->setType(QualType(AdjustedType, 0)); 3449 NewQType = Context.getCanonicalType(New->getType()); 3450 } 3451 3452 // If this redeclaration makes the function inline, we may need to add it to 3453 // UndefinedButUsed. 3454 if (!Old->isInlined() && New->isInlined() && 3455 !New->hasAttr<GNUInlineAttr>() && 3456 !getLangOpts().GNUInline && 3457 Old->isUsed(false) && 3458 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3459 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3460 SourceLocation())); 3461 3462 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3463 // about it. 3464 if (New->hasAttr<GNUInlineAttr>() && 3465 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3466 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3467 } 3468 3469 // If pass_object_size params don't match up perfectly, this isn't a valid 3470 // redeclaration. 3471 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3472 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3473 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3474 << New->getDeclName(); 3475 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3476 return true; 3477 } 3478 3479 if (getLangOpts().CPlusPlus) { 3480 // C++1z [over.load]p2 3481 // Certain function declarations cannot be overloaded: 3482 // -- Function declarations that differ only in the return type, 3483 // the exception specification, or both cannot be overloaded. 3484 3485 // Check the exception specifications match. This may recompute the type of 3486 // both Old and New if it resolved exception specifications, so grab the 3487 // types again after this. Because this updates the type, we do this before 3488 // any of the other checks below, which may update the "de facto" NewQType 3489 // but do not necessarily update the type of New. 3490 if (CheckEquivalentExceptionSpec(Old, New)) 3491 return true; 3492 OldQType = Context.getCanonicalType(Old->getType()); 3493 NewQType = Context.getCanonicalType(New->getType()); 3494 3495 // Go back to the type source info to compare the declared return types, 3496 // per C++1y [dcl.type.auto]p13: 3497 // Redeclarations or specializations of a function or function template 3498 // with a declared return type that uses a placeholder type shall also 3499 // use that placeholder, not a deduced type. 3500 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3501 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3502 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3503 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3504 OldDeclaredReturnType)) { 3505 QualType ResQT; 3506 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3507 OldDeclaredReturnType->isObjCObjectPointerType()) 3508 // FIXME: This does the wrong thing for a deduced return type. 3509 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3510 if (ResQT.isNull()) { 3511 if (New->isCXXClassMember() && New->isOutOfLine()) 3512 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3513 << New << New->getReturnTypeSourceRange(); 3514 else 3515 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3516 << New->getReturnTypeSourceRange(); 3517 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3518 << Old->getReturnTypeSourceRange(); 3519 return true; 3520 } 3521 else 3522 NewQType = ResQT; 3523 } 3524 3525 QualType OldReturnType = OldType->getReturnType(); 3526 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3527 if (OldReturnType != NewReturnType) { 3528 // If this function has a deduced return type and has already been 3529 // defined, copy the deduced value from the old declaration. 3530 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3531 if (OldAT && OldAT->isDeduced()) { 3532 New->setType( 3533 SubstAutoType(New->getType(), 3534 OldAT->isDependentType() ? Context.DependentTy 3535 : OldAT->getDeducedType())); 3536 NewQType = Context.getCanonicalType( 3537 SubstAutoType(NewQType, 3538 OldAT->isDependentType() ? Context.DependentTy 3539 : OldAT->getDeducedType())); 3540 } 3541 } 3542 3543 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3544 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3545 if (OldMethod && NewMethod) { 3546 // Preserve triviality. 3547 NewMethod->setTrivial(OldMethod->isTrivial()); 3548 3549 // MSVC allows explicit template specialization at class scope: 3550 // 2 CXXMethodDecls referring to the same function will be injected. 3551 // We don't want a redeclaration error. 3552 bool IsClassScopeExplicitSpecialization = 3553 OldMethod->isFunctionTemplateSpecialization() && 3554 NewMethod->isFunctionTemplateSpecialization(); 3555 bool isFriend = NewMethod->getFriendObjectKind(); 3556 3557 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3558 !IsClassScopeExplicitSpecialization) { 3559 // -- Member function declarations with the same name and the 3560 // same parameter types cannot be overloaded if any of them 3561 // is a static member function declaration. 3562 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3563 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3564 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3565 return true; 3566 } 3567 3568 // C++ [class.mem]p1: 3569 // [...] A member shall not be declared twice in the 3570 // member-specification, except that a nested class or member 3571 // class template can be declared and then later defined. 3572 if (!inTemplateInstantiation()) { 3573 unsigned NewDiag; 3574 if (isa<CXXConstructorDecl>(OldMethod)) 3575 NewDiag = diag::err_constructor_redeclared; 3576 else if (isa<CXXDestructorDecl>(NewMethod)) 3577 NewDiag = diag::err_destructor_redeclared; 3578 else if (isa<CXXConversionDecl>(NewMethod)) 3579 NewDiag = diag::err_conv_function_redeclared; 3580 else 3581 NewDiag = diag::err_member_redeclared; 3582 3583 Diag(New->getLocation(), NewDiag); 3584 } else { 3585 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3586 << New << New->getType(); 3587 } 3588 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3589 return true; 3590 3591 // Complain if this is an explicit declaration of a special 3592 // member that was initially declared implicitly. 3593 // 3594 // As an exception, it's okay to befriend such methods in order 3595 // to permit the implicit constructor/destructor/operator calls. 3596 } else if (OldMethod->isImplicit()) { 3597 if (isFriend) { 3598 NewMethod->setImplicit(); 3599 } else { 3600 Diag(NewMethod->getLocation(), 3601 diag::err_definition_of_implicitly_declared_member) 3602 << New << getSpecialMember(OldMethod); 3603 return true; 3604 } 3605 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3606 Diag(NewMethod->getLocation(), 3607 diag::err_definition_of_explicitly_defaulted_member) 3608 << getSpecialMember(OldMethod); 3609 return true; 3610 } 3611 } 3612 3613 // C++11 [dcl.attr.noreturn]p1: 3614 // The first declaration of a function shall specify the noreturn 3615 // attribute if any declaration of that function specifies the noreturn 3616 // attribute. 3617 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3618 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3619 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3620 Diag(Old->getFirstDecl()->getLocation(), 3621 diag::note_noreturn_missing_first_decl); 3622 } 3623 3624 // C++11 [dcl.attr.depend]p2: 3625 // The first declaration of a function shall specify the 3626 // carries_dependency attribute for its declarator-id if any declaration 3627 // of the function specifies the carries_dependency attribute. 3628 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3629 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3630 Diag(CDA->getLocation(), 3631 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3632 Diag(Old->getFirstDecl()->getLocation(), 3633 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3634 } 3635 3636 // (C++98 8.3.5p3): 3637 // All declarations for a function shall agree exactly in both the 3638 // return type and the parameter-type-list. 3639 // We also want to respect all the extended bits except noreturn. 3640 3641 // noreturn should now match unless the old type info didn't have it. 3642 QualType OldQTypeForComparison = OldQType; 3643 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3644 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3645 const FunctionType *OldTypeForComparison 3646 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3647 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3648 assert(OldQTypeForComparison.isCanonical()); 3649 } 3650 3651 if (haveIncompatibleLanguageLinkages(Old, New)) { 3652 // As a special case, retain the language linkage from previous 3653 // declarations of a friend function as an extension. 3654 // 3655 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3656 // and is useful because there's otherwise no way to specify language 3657 // linkage within class scope. 3658 // 3659 // Check cautiously as the friend object kind isn't yet complete. 3660 if (New->getFriendObjectKind() != Decl::FOK_None) { 3661 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3662 Diag(OldLocation, PrevDiag); 3663 } else { 3664 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3665 Diag(OldLocation, PrevDiag); 3666 return true; 3667 } 3668 } 3669 3670 // If the function types are compatible, merge the declarations. Ignore the 3671 // exception specifier because it was already checked above in 3672 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3673 // about incompatible types under -fms-compatibility. 3674 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3675 NewQType)) 3676 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3677 3678 // If the types are imprecise (due to dependent constructs in friends or 3679 // local extern declarations), it's OK if they differ. We'll check again 3680 // during instantiation. 3681 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3682 return false; 3683 3684 // Fall through for conflicting redeclarations and redefinitions. 3685 } 3686 3687 // C: Function types need to be compatible, not identical. This handles 3688 // duplicate function decls like "void f(int); void f(enum X);" properly. 3689 if (!getLangOpts().CPlusPlus && 3690 Context.typesAreCompatible(OldQType, NewQType)) { 3691 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3692 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3693 const FunctionProtoType *OldProto = nullptr; 3694 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3695 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3696 // The old declaration provided a function prototype, but the 3697 // new declaration does not. Merge in the prototype. 3698 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3699 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3700 NewQType = 3701 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3702 OldProto->getExtProtoInfo()); 3703 New->setType(NewQType); 3704 New->setHasInheritedPrototype(); 3705 3706 // Synthesize parameters with the same types. 3707 SmallVector<ParmVarDecl*, 16> Params; 3708 for (const auto &ParamType : OldProto->param_types()) { 3709 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3710 SourceLocation(), nullptr, 3711 ParamType, /*TInfo=*/nullptr, 3712 SC_None, nullptr); 3713 Param->setScopeInfo(0, Params.size()); 3714 Param->setImplicit(); 3715 Params.push_back(Param); 3716 } 3717 3718 New->setParams(Params); 3719 } 3720 3721 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3722 } 3723 3724 // Check if the function types are compatible when pointer size address 3725 // spaces are ignored. 3726 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3727 return false; 3728 3729 // GNU C permits a K&R definition to follow a prototype declaration 3730 // if the declared types of the parameters in the K&R definition 3731 // match the types in the prototype declaration, even when the 3732 // promoted types of the parameters from the K&R definition differ 3733 // from the types in the prototype. GCC then keeps the types from 3734 // the prototype. 3735 // 3736 // If a variadic prototype is followed by a non-variadic K&R definition, 3737 // the K&R definition becomes variadic. This is sort of an edge case, but 3738 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3739 // C99 6.9.1p8. 3740 if (!getLangOpts().CPlusPlus && 3741 Old->hasPrototype() && !New->hasPrototype() && 3742 New->getType()->getAs<FunctionProtoType>() && 3743 Old->getNumParams() == New->getNumParams()) { 3744 SmallVector<QualType, 16> ArgTypes; 3745 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3746 const FunctionProtoType *OldProto 3747 = Old->getType()->getAs<FunctionProtoType>(); 3748 const FunctionProtoType *NewProto 3749 = New->getType()->getAs<FunctionProtoType>(); 3750 3751 // Determine whether this is the GNU C extension. 3752 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3753 NewProto->getReturnType()); 3754 bool LooseCompatible = !MergedReturn.isNull(); 3755 for (unsigned Idx = 0, End = Old->getNumParams(); 3756 LooseCompatible && Idx != End; ++Idx) { 3757 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3758 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3759 if (Context.typesAreCompatible(OldParm->getType(), 3760 NewProto->getParamType(Idx))) { 3761 ArgTypes.push_back(NewParm->getType()); 3762 } else if (Context.typesAreCompatible(OldParm->getType(), 3763 NewParm->getType(), 3764 /*CompareUnqualified=*/true)) { 3765 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3766 NewProto->getParamType(Idx) }; 3767 Warnings.push_back(Warn); 3768 ArgTypes.push_back(NewParm->getType()); 3769 } else 3770 LooseCompatible = false; 3771 } 3772 3773 if (LooseCompatible) { 3774 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3775 Diag(Warnings[Warn].NewParm->getLocation(), 3776 diag::ext_param_promoted_not_compatible_with_prototype) 3777 << Warnings[Warn].PromotedType 3778 << Warnings[Warn].OldParm->getType(); 3779 if (Warnings[Warn].OldParm->getLocation().isValid()) 3780 Diag(Warnings[Warn].OldParm->getLocation(), 3781 diag::note_previous_declaration); 3782 } 3783 3784 if (MergeTypeWithOld) 3785 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3786 OldProto->getExtProtoInfo())); 3787 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3788 } 3789 3790 // Fall through to diagnose conflicting types. 3791 } 3792 3793 // A function that has already been declared has been redeclared or 3794 // defined with a different type; show an appropriate diagnostic. 3795 3796 // If the previous declaration was an implicitly-generated builtin 3797 // declaration, then at the very least we should use a specialized note. 3798 unsigned BuiltinID; 3799 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3800 // If it's actually a library-defined builtin function like 'malloc' 3801 // or 'printf', just warn about the incompatible redeclaration. 3802 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3803 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3804 Diag(OldLocation, diag::note_previous_builtin_declaration) 3805 << Old << Old->getType(); 3806 return false; 3807 } 3808 3809 PrevDiag = diag::note_previous_builtin_declaration; 3810 } 3811 3812 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3813 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3814 return true; 3815 } 3816 3817 /// Completes the merge of two function declarations that are 3818 /// known to be compatible. 3819 /// 3820 /// This routine handles the merging of attributes and other 3821 /// properties of function declarations from the old declaration to 3822 /// the new declaration, once we know that New is in fact a 3823 /// redeclaration of Old. 3824 /// 3825 /// \returns false 3826 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3827 Scope *S, bool MergeTypeWithOld) { 3828 // Merge the attributes 3829 mergeDeclAttributes(New, Old); 3830 3831 // Merge "pure" flag. 3832 if (Old->isPure()) 3833 New->setPure(); 3834 3835 // Merge "used" flag. 3836 if (Old->getMostRecentDecl()->isUsed(false)) 3837 New->setIsUsed(); 3838 3839 // Merge attributes from the parameters. These can mismatch with K&R 3840 // declarations. 3841 if (New->getNumParams() == Old->getNumParams()) 3842 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3843 ParmVarDecl *NewParam = New->getParamDecl(i); 3844 ParmVarDecl *OldParam = Old->getParamDecl(i); 3845 mergeParamDeclAttributes(NewParam, OldParam, *this); 3846 mergeParamDeclTypes(NewParam, OldParam, *this); 3847 } 3848 3849 if (getLangOpts().CPlusPlus) 3850 return MergeCXXFunctionDecl(New, Old, S); 3851 3852 // Merge the function types so the we get the composite types for the return 3853 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3854 // was visible. 3855 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3856 if (!Merged.isNull() && MergeTypeWithOld) 3857 New->setType(Merged); 3858 3859 return false; 3860 } 3861 3862 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3863 ObjCMethodDecl *oldMethod) { 3864 // Merge the attributes, including deprecated/unavailable 3865 AvailabilityMergeKind MergeKind = 3866 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3867 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation 3868 : AMK_ProtocolImplementation) 3869 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3870 : AMK_Override; 3871 3872 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3873 3874 // Merge attributes from the parameters. 3875 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3876 oe = oldMethod->param_end(); 3877 for (ObjCMethodDecl::param_iterator 3878 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3879 ni != ne && oi != oe; ++ni, ++oi) 3880 mergeParamDeclAttributes(*ni, *oi, *this); 3881 3882 CheckObjCMethodOverride(newMethod, oldMethod); 3883 } 3884 3885 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3886 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3887 3888 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3889 ? diag::err_redefinition_different_type 3890 : diag::err_redeclaration_different_type) 3891 << New->getDeclName() << New->getType() << Old->getType(); 3892 3893 diag::kind PrevDiag; 3894 SourceLocation OldLocation; 3895 std::tie(PrevDiag, OldLocation) 3896 = getNoteDiagForInvalidRedeclaration(Old, New); 3897 S.Diag(OldLocation, PrevDiag); 3898 New->setInvalidDecl(); 3899 } 3900 3901 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3902 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3903 /// emitting diagnostics as appropriate. 3904 /// 3905 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3906 /// to here in AddInitializerToDecl. We can't check them before the initializer 3907 /// is attached. 3908 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3909 bool MergeTypeWithOld) { 3910 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3911 return; 3912 3913 QualType MergedT; 3914 if (getLangOpts().CPlusPlus) { 3915 if (New->getType()->isUndeducedType()) { 3916 // We don't know what the new type is until the initializer is attached. 3917 return; 3918 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3919 // These could still be something that needs exception specs checked. 3920 return MergeVarDeclExceptionSpecs(New, Old); 3921 } 3922 // C++ [basic.link]p10: 3923 // [...] the types specified by all declarations referring to a given 3924 // object or function shall be identical, except that declarations for an 3925 // array object can specify array types that differ by the presence or 3926 // absence of a major array bound (8.3.4). 3927 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3928 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3929 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3930 3931 // We are merging a variable declaration New into Old. If it has an array 3932 // bound, and that bound differs from Old's bound, we should diagnose the 3933 // mismatch. 3934 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3935 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3936 PrevVD = PrevVD->getPreviousDecl()) { 3937 QualType PrevVDTy = PrevVD->getType(); 3938 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3939 continue; 3940 3941 if (!Context.hasSameType(New->getType(), PrevVDTy)) 3942 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3943 } 3944 } 3945 3946 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3947 if (Context.hasSameType(OldArray->getElementType(), 3948 NewArray->getElementType())) 3949 MergedT = New->getType(); 3950 } 3951 // FIXME: Check visibility. New is hidden but has a complete type. If New 3952 // has no array bound, it should not inherit one from Old, if Old is not 3953 // visible. 3954 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3955 if (Context.hasSameType(OldArray->getElementType(), 3956 NewArray->getElementType())) 3957 MergedT = Old->getType(); 3958 } 3959 } 3960 else if (New->getType()->isObjCObjectPointerType() && 3961 Old->getType()->isObjCObjectPointerType()) { 3962 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3963 Old->getType()); 3964 } 3965 } else { 3966 // C 6.2.7p2: 3967 // All declarations that refer to the same object or function shall have 3968 // compatible type. 3969 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3970 } 3971 if (MergedT.isNull()) { 3972 // It's OK if we couldn't merge types if either type is dependent, for a 3973 // block-scope variable. In other cases (static data members of class 3974 // templates, variable templates, ...), we require the types to be 3975 // equivalent. 3976 // FIXME: The C++ standard doesn't say anything about this. 3977 if ((New->getType()->isDependentType() || 3978 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3979 // If the old type was dependent, we can't merge with it, so the new type 3980 // becomes dependent for now. We'll reproduce the original type when we 3981 // instantiate the TypeSourceInfo for the variable. 3982 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3983 New->setType(Context.DependentTy); 3984 return; 3985 } 3986 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3987 } 3988 3989 // Don't actually update the type on the new declaration if the old 3990 // declaration was an extern declaration in a different scope. 3991 if (MergeTypeWithOld) 3992 New->setType(MergedT); 3993 } 3994 3995 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3996 LookupResult &Previous) { 3997 // C11 6.2.7p4: 3998 // For an identifier with internal or external linkage declared 3999 // in a scope in which a prior declaration of that identifier is 4000 // visible, if the prior declaration specifies internal or 4001 // external linkage, the type of the identifier at the later 4002 // declaration becomes the composite type. 4003 // 4004 // If the variable isn't visible, we do not merge with its type. 4005 if (Previous.isShadowed()) 4006 return false; 4007 4008 if (S.getLangOpts().CPlusPlus) { 4009 // C++11 [dcl.array]p3: 4010 // If there is a preceding declaration of the entity in the same 4011 // scope in which the bound was specified, an omitted array bound 4012 // is taken to be the same as in that earlier declaration. 4013 return NewVD->isPreviousDeclInSameBlockScope() || 4014 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4015 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4016 } else { 4017 // If the old declaration was function-local, don't merge with its 4018 // type unless we're in the same function. 4019 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4020 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4021 } 4022 } 4023 4024 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4025 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4026 /// situation, merging decls or emitting diagnostics as appropriate. 4027 /// 4028 /// Tentative definition rules (C99 6.9.2p2) are checked by 4029 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4030 /// definitions here, since the initializer hasn't been attached. 4031 /// 4032 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4033 // If the new decl is already invalid, don't do any other checking. 4034 if (New->isInvalidDecl()) 4035 return; 4036 4037 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4038 return; 4039 4040 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4041 4042 // Verify the old decl was also a variable or variable template. 4043 VarDecl *Old = nullptr; 4044 VarTemplateDecl *OldTemplate = nullptr; 4045 if (Previous.isSingleResult()) { 4046 if (NewTemplate) { 4047 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4048 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4049 4050 if (auto *Shadow = 4051 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4052 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4053 return New->setInvalidDecl(); 4054 } else { 4055 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4056 4057 if (auto *Shadow = 4058 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4059 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4060 return New->setInvalidDecl(); 4061 } 4062 } 4063 if (!Old) { 4064 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4065 << New->getDeclName(); 4066 notePreviousDefinition(Previous.getRepresentativeDecl(), 4067 New->getLocation()); 4068 return New->setInvalidDecl(); 4069 } 4070 4071 // If the old declaration was found in an inline namespace and the new 4072 // declaration was qualified, update the DeclContext to match. 4073 adjustDeclContextForDeclaratorDecl(New, Old); 4074 4075 // Ensure the template parameters are compatible. 4076 if (NewTemplate && 4077 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4078 OldTemplate->getTemplateParameters(), 4079 /*Complain=*/true, TPL_TemplateMatch)) 4080 return New->setInvalidDecl(); 4081 4082 // C++ [class.mem]p1: 4083 // A member shall not be declared twice in the member-specification [...] 4084 // 4085 // Here, we need only consider static data members. 4086 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4087 Diag(New->getLocation(), diag::err_duplicate_member) 4088 << New->getIdentifier(); 4089 Diag(Old->getLocation(), diag::note_previous_declaration); 4090 New->setInvalidDecl(); 4091 } 4092 4093 mergeDeclAttributes(New, Old); 4094 // Warn if an already-declared variable is made a weak_import in a subsequent 4095 // declaration 4096 if (New->hasAttr<WeakImportAttr>() && 4097 Old->getStorageClass() == SC_None && 4098 !Old->hasAttr<WeakImportAttr>()) { 4099 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4100 notePreviousDefinition(Old, New->getLocation()); 4101 // Remove weak_import attribute on new declaration. 4102 New->dropAttr<WeakImportAttr>(); 4103 } 4104 4105 if (New->hasAttr<InternalLinkageAttr>() && 4106 !Old->hasAttr<InternalLinkageAttr>()) { 4107 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4108 << New->getDeclName(); 4109 notePreviousDefinition(Old, New->getLocation()); 4110 New->dropAttr<InternalLinkageAttr>(); 4111 } 4112 4113 // Merge the types. 4114 VarDecl *MostRecent = Old->getMostRecentDecl(); 4115 if (MostRecent != Old) { 4116 MergeVarDeclTypes(New, MostRecent, 4117 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4118 if (New->isInvalidDecl()) 4119 return; 4120 } 4121 4122 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4123 if (New->isInvalidDecl()) 4124 return; 4125 4126 diag::kind PrevDiag; 4127 SourceLocation OldLocation; 4128 std::tie(PrevDiag, OldLocation) = 4129 getNoteDiagForInvalidRedeclaration(Old, New); 4130 4131 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4132 if (New->getStorageClass() == SC_Static && 4133 !New->isStaticDataMember() && 4134 Old->hasExternalFormalLinkage()) { 4135 if (getLangOpts().MicrosoftExt) { 4136 Diag(New->getLocation(), diag::ext_static_non_static) 4137 << New->getDeclName(); 4138 Diag(OldLocation, PrevDiag); 4139 } else { 4140 Diag(New->getLocation(), diag::err_static_non_static) 4141 << New->getDeclName(); 4142 Diag(OldLocation, PrevDiag); 4143 return New->setInvalidDecl(); 4144 } 4145 } 4146 // C99 6.2.2p4: 4147 // For an identifier declared with the storage-class specifier 4148 // extern in a scope in which a prior declaration of that 4149 // identifier is visible,23) if the prior declaration specifies 4150 // internal or external linkage, the linkage of the identifier at 4151 // the later declaration is the same as the linkage specified at 4152 // the prior declaration. If no prior declaration is visible, or 4153 // if the prior declaration specifies no linkage, then the 4154 // identifier has external linkage. 4155 if (New->hasExternalStorage() && Old->hasLinkage()) 4156 /* Okay */; 4157 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4158 !New->isStaticDataMember() && 4159 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4160 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4161 Diag(OldLocation, PrevDiag); 4162 return New->setInvalidDecl(); 4163 } 4164 4165 // Check if extern is followed by non-extern and vice-versa. 4166 if (New->hasExternalStorage() && 4167 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4168 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4169 Diag(OldLocation, PrevDiag); 4170 return New->setInvalidDecl(); 4171 } 4172 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4173 !New->hasExternalStorage()) { 4174 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4175 Diag(OldLocation, PrevDiag); 4176 return New->setInvalidDecl(); 4177 } 4178 4179 if (CheckRedeclarationModuleOwnership(New, Old)) 4180 return; 4181 4182 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4183 4184 // FIXME: The test for external storage here seems wrong? We still 4185 // need to check for mismatches. 4186 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4187 // Don't complain about out-of-line definitions of static members. 4188 !(Old->getLexicalDeclContext()->isRecord() && 4189 !New->getLexicalDeclContext()->isRecord())) { 4190 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4191 Diag(OldLocation, PrevDiag); 4192 return New->setInvalidDecl(); 4193 } 4194 4195 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4196 if (VarDecl *Def = Old->getDefinition()) { 4197 // C++1z [dcl.fcn.spec]p4: 4198 // If the definition of a variable appears in a translation unit before 4199 // its first declaration as inline, the program is ill-formed. 4200 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4201 Diag(Def->getLocation(), diag::note_previous_definition); 4202 } 4203 } 4204 4205 // If this redeclaration makes the variable inline, we may need to add it to 4206 // UndefinedButUsed. 4207 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4208 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4209 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4210 SourceLocation())); 4211 4212 if (New->getTLSKind() != Old->getTLSKind()) { 4213 if (!Old->getTLSKind()) { 4214 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4215 Diag(OldLocation, PrevDiag); 4216 } else if (!New->getTLSKind()) { 4217 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4218 Diag(OldLocation, PrevDiag); 4219 } else { 4220 // Do not allow redeclaration to change the variable between requiring 4221 // static and dynamic initialization. 4222 // FIXME: GCC allows this, but uses the TLS keyword on the first 4223 // declaration to determine the kind. Do we need to be compatible here? 4224 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4225 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4226 Diag(OldLocation, PrevDiag); 4227 } 4228 } 4229 4230 // C++ doesn't have tentative definitions, so go right ahead and check here. 4231 if (getLangOpts().CPlusPlus && 4232 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4233 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4234 Old->getCanonicalDecl()->isConstexpr()) { 4235 // This definition won't be a definition any more once it's been merged. 4236 Diag(New->getLocation(), 4237 diag::warn_deprecated_redundant_constexpr_static_def); 4238 } else if (VarDecl *Def = Old->getDefinition()) { 4239 if (checkVarDeclRedefinition(Def, New)) 4240 return; 4241 } 4242 } 4243 4244 if (haveIncompatibleLanguageLinkages(Old, New)) { 4245 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4246 Diag(OldLocation, PrevDiag); 4247 New->setInvalidDecl(); 4248 return; 4249 } 4250 4251 // Merge "used" flag. 4252 if (Old->getMostRecentDecl()->isUsed(false)) 4253 New->setIsUsed(); 4254 4255 // Keep a chain of previous declarations. 4256 New->setPreviousDecl(Old); 4257 if (NewTemplate) 4258 NewTemplate->setPreviousDecl(OldTemplate); 4259 4260 // Inherit access appropriately. 4261 New->setAccess(Old->getAccess()); 4262 if (NewTemplate) 4263 NewTemplate->setAccess(New->getAccess()); 4264 4265 if (Old->isInline()) 4266 New->setImplicitlyInline(); 4267 } 4268 4269 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4270 SourceManager &SrcMgr = getSourceManager(); 4271 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4272 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4273 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4274 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4275 auto &HSI = PP.getHeaderSearchInfo(); 4276 StringRef HdrFilename = 4277 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4278 4279 auto noteFromModuleOrInclude = [&](Module *Mod, 4280 SourceLocation IncLoc) -> bool { 4281 // Redefinition errors with modules are common with non modular mapped 4282 // headers, example: a non-modular header H in module A that also gets 4283 // included directly in a TU. Pointing twice to the same header/definition 4284 // is confusing, try to get better diagnostics when modules is on. 4285 if (IncLoc.isValid()) { 4286 if (Mod) { 4287 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4288 << HdrFilename.str() << Mod->getFullModuleName(); 4289 if (!Mod->DefinitionLoc.isInvalid()) 4290 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4291 << Mod->getFullModuleName(); 4292 } else { 4293 Diag(IncLoc, diag::note_redefinition_include_same_file) 4294 << HdrFilename.str(); 4295 } 4296 return true; 4297 } 4298 4299 return false; 4300 }; 4301 4302 // Is it the same file and same offset? Provide more information on why 4303 // this leads to a redefinition error. 4304 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4305 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4306 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4307 bool EmittedDiag = 4308 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4309 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4310 4311 // If the header has no guards, emit a note suggesting one. 4312 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4313 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4314 4315 if (EmittedDiag) 4316 return; 4317 } 4318 4319 // Redefinition coming from different files or couldn't do better above. 4320 if (Old->getLocation().isValid()) 4321 Diag(Old->getLocation(), diag::note_previous_definition); 4322 } 4323 4324 /// We've just determined that \p Old and \p New both appear to be definitions 4325 /// of the same variable. Either diagnose or fix the problem. 4326 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4327 if (!hasVisibleDefinition(Old) && 4328 (New->getFormalLinkage() == InternalLinkage || 4329 New->isInline() || 4330 New->getDescribedVarTemplate() || 4331 New->getNumTemplateParameterLists() || 4332 New->getDeclContext()->isDependentContext())) { 4333 // The previous definition is hidden, and multiple definitions are 4334 // permitted (in separate TUs). Demote this to a declaration. 4335 New->demoteThisDefinitionToDeclaration(); 4336 4337 // Make the canonical definition visible. 4338 if (auto *OldTD = Old->getDescribedVarTemplate()) 4339 makeMergedDefinitionVisible(OldTD); 4340 makeMergedDefinitionVisible(Old); 4341 return false; 4342 } else { 4343 Diag(New->getLocation(), diag::err_redefinition) << New; 4344 notePreviousDefinition(Old, New->getLocation()); 4345 New->setInvalidDecl(); 4346 return true; 4347 } 4348 } 4349 4350 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4351 /// no declarator (e.g. "struct foo;") is parsed. 4352 Decl * 4353 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4354 RecordDecl *&AnonRecord) { 4355 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4356 AnonRecord); 4357 } 4358 4359 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4360 // disambiguate entities defined in different scopes. 4361 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4362 // compatibility. 4363 // We will pick our mangling number depending on which version of MSVC is being 4364 // targeted. 4365 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4366 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4367 ? S->getMSCurManglingNumber() 4368 : S->getMSLastManglingNumber(); 4369 } 4370 4371 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4372 if (!Context.getLangOpts().CPlusPlus) 4373 return; 4374 4375 if (isa<CXXRecordDecl>(Tag->getParent())) { 4376 // If this tag is the direct child of a class, number it if 4377 // it is anonymous. 4378 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4379 return; 4380 MangleNumberingContext &MCtx = 4381 Context.getManglingNumberContext(Tag->getParent()); 4382 Context.setManglingNumber( 4383 Tag, MCtx.getManglingNumber( 4384 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4385 return; 4386 } 4387 4388 // If this tag isn't a direct child of a class, number it if it is local. 4389 MangleNumberingContext *MCtx; 4390 Decl *ManglingContextDecl; 4391 std::tie(MCtx, ManglingContextDecl) = 4392 getCurrentMangleNumberContext(Tag->getDeclContext()); 4393 if (MCtx) { 4394 Context.setManglingNumber( 4395 Tag, MCtx->getManglingNumber( 4396 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4397 } 4398 } 4399 4400 namespace { 4401 struct NonCLikeKind { 4402 enum { 4403 None, 4404 BaseClass, 4405 DefaultMemberInit, 4406 Lambda, 4407 Friend, 4408 OtherMember, 4409 Invalid, 4410 } Kind = None; 4411 SourceRange Range; 4412 4413 explicit operator bool() { return Kind != None; } 4414 }; 4415 } 4416 4417 /// Determine whether a class is C-like, according to the rules of C++ 4418 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4419 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4420 if (RD->isInvalidDecl()) 4421 return {NonCLikeKind::Invalid, {}}; 4422 4423 // C++ [dcl.typedef]p9: [P1766R1] 4424 // An unnamed class with a typedef name for linkage purposes shall not 4425 // 4426 // -- have any base classes 4427 if (RD->getNumBases()) 4428 return {NonCLikeKind::BaseClass, 4429 SourceRange(RD->bases_begin()->getBeginLoc(), 4430 RD->bases_end()[-1].getEndLoc())}; 4431 bool Invalid = false; 4432 for (Decl *D : RD->decls()) { 4433 // Don't complain about things we already diagnosed. 4434 if (D->isInvalidDecl()) { 4435 Invalid = true; 4436 continue; 4437 } 4438 4439 // -- have any [...] default member initializers 4440 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4441 if (FD->hasInClassInitializer()) { 4442 auto *Init = FD->getInClassInitializer(); 4443 return {NonCLikeKind::DefaultMemberInit, 4444 Init ? Init->getSourceRange() : D->getSourceRange()}; 4445 } 4446 continue; 4447 } 4448 4449 // FIXME: We don't allow friend declarations. This violates the wording of 4450 // P1766, but not the intent. 4451 if (isa<FriendDecl>(D)) 4452 return {NonCLikeKind::Friend, D->getSourceRange()}; 4453 4454 // -- declare any members other than non-static data members, member 4455 // enumerations, or member classes, 4456 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4457 isa<EnumDecl>(D)) 4458 continue; 4459 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4460 if (!MemberRD) { 4461 if (D->isImplicit()) 4462 continue; 4463 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4464 } 4465 4466 // -- contain a lambda-expression, 4467 if (MemberRD->isLambda()) 4468 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4469 4470 // and all member classes shall also satisfy these requirements 4471 // (recursively). 4472 if (MemberRD->isThisDeclarationADefinition()) { 4473 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4474 return Kind; 4475 } 4476 } 4477 4478 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4479 } 4480 4481 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4482 TypedefNameDecl *NewTD) { 4483 if (TagFromDeclSpec->isInvalidDecl()) 4484 return; 4485 4486 // Do nothing if the tag already has a name for linkage purposes. 4487 if (TagFromDeclSpec->hasNameForLinkage()) 4488 return; 4489 4490 // A well-formed anonymous tag must always be a TUK_Definition. 4491 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4492 4493 // The type must match the tag exactly; no qualifiers allowed. 4494 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4495 Context.getTagDeclType(TagFromDeclSpec))) { 4496 if (getLangOpts().CPlusPlus) 4497 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4498 return; 4499 } 4500 4501 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4502 // An unnamed class with a typedef name for linkage purposes shall [be 4503 // C-like]. 4504 // 4505 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4506 // shouldn't happen, but there are constructs that the language rule doesn't 4507 // disallow for which we can't reasonably avoid computing linkage early. 4508 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4509 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4510 : NonCLikeKind(); 4511 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4512 if (NonCLike || ChangesLinkage) { 4513 if (NonCLike.Kind == NonCLikeKind::Invalid) 4514 return; 4515 4516 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4517 if (ChangesLinkage) { 4518 // If the linkage changes, we can't accept this as an extension. 4519 if (NonCLike.Kind == NonCLikeKind::None) 4520 DiagID = diag::err_typedef_changes_linkage; 4521 else 4522 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4523 } 4524 4525 SourceLocation FixitLoc = 4526 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4527 llvm::SmallString<40> TextToInsert; 4528 TextToInsert += ' '; 4529 TextToInsert += NewTD->getIdentifier()->getName(); 4530 4531 Diag(FixitLoc, DiagID) 4532 << isa<TypeAliasDecl>(NewTD) 4533 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4534 if (NonCLike.Kind != NonCLikeKind::None) { 4535 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4536 << NonCLike.Kind - 1 << NonCLike.Range; 4537 } 4538 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4539 << NewTD << isa<TypeAliasDecl>(NewTD); 4540 4541 if (ChangesLinkage) 4542 return; 4543 } 4544 4545 // Otherwise, set this as the anon-decl typedef for the tag. 4546 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4547 } 4548 4549 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4550 switch (T) { 4551 case DeclSpec::TST_class: 4552 return 0; 4553 case DeclSpec::TST_struct: 4554 return 1; 4555 case DeclSpec::TST_interface: 4556 return 2; 4557 case DeclSpec::TST_union: 4558 return 3; 4559 case DeclSpec::TST_enum: 4560 return 4; 4561 default: 4562 llvm_unreachable("unexpected type specifier"); 4563 } 4564 } 4565 4566 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4567 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4568 /// parameters to cope with template friend declarations. 4569 Decl * 4570 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4571 MultiTemplateParamsArg TemplateParams, 4572 bool IsExplicitInstantiation, 4573 RecordDecl *&AnonRecord) { 4574 Decl *TagD = nullptr; 4575 TagDecl *Tag = nullptr; 4576 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4577 DS.getTypeSpecType() == DeclSpec::TST_struct || 4578 DS.getTypeSpecType() == DeclSpec::TST_interface || 4579 DS.getTypeSpecType() == DeclSpec::TST_union || 4580 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4581 TagD = DS.getRepAsDecl(); 4582 4583 if (!TagD) // We probably had an error 4584 return nullptr; 4585 4586 // Note that the above type specs guarantee that the 4587 // type rep is a Decl, whereas in many of the others 4588 // it's a Type. 4589 if (isa<TagDecl>(TagD)) 4590 Tag = cast<TagDecl>(TagD); 4591 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4592 Tag = CTD->getTemplatedDecl(); 4593 } 4594 4595 if (Tag) { 4596 handleTagNumbering(Tag, S); 4597 Tag->setFreeStanding(); 4598 if (Tag->isInvalidDecl()) 4599 return Tag; 4600 } 4601 4602 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4603 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4604 // or incomplete types shall not be restrict-qualified." 4605 if (TypeQuals & DeclSpec::TQ_restrict) 4606 Diag(DS.getRestrictSpecLoc(), 4607 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4608 << DS.getSourceRange(); 4609 } 4610 4611 if (DS.isInlineSpecified()) 4612 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4613 << getLangOpts().CPlusPlus17; 4614 4615 if (DS.hasConstexprSpecifier()) { 4616 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4617 // and definitions of functions and variables. 4618 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4619 // the declaration of a function or function template 4620 if (Tag) 4621 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4622 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4623 << static_cast<int>(DS.getConstexprSpecifier()); 4624 else 4625 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4626 << static_cast<int>(DS.getConstexprSpecifier()); 4627 // Don't emit warnings after this error. 4628 return TagD; 4629 } 4630 4631 DiagnoseFunctionSpecifiers(DS); 4632 4633 if (DS.isFriendSpecified()) { 4634 // If we're dealing with a decl but not a TagDecl, assume that 4635 // whatever routines created it handled the friendship aspect. 4636 if (TagD && !Tag) 4637 return nullptr; 4638 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4639 } 4640 4641 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4642 bool IsExplicitSpecialization = 4643 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4644 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4645 !IsExplicitInstantiation && !IsExplicitSpecialization && 4646 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4647 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4648 // nested-name-specifier unless it is an explicit instantiation 4649 // or an explicit specialization. 4650 // 4651 // FIXME: We allow class template partial specializations here too, per the 4652 // obvious intent of DR1819. 4653 // 4654 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4655 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4656 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4657 return nullptr; 4658 } 4659 4660 // Track whether this decl-specifier declares anything. 4661 bool DeclaresAnything = true; 4662 4663 // Handle anonymous struct definitions. 4664 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4665 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4666 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4667 if (getLangOpts().CPlusPlus || 4668 Record->getDeclContext()->isRecord()) { 4669 // If CurContext is a DeclContext that can contain statements, 4670 // RecursiveASTVisitor won't visit the decls that 4671 // BuildAnonymousStructOrUnion() will put into CurContext. 4672 // Also store them here so that they can be part of the 4673 // DeclStmt that gets created in this case. 4674 // FIXME: Also return the IndirectFieldDecls created by 4675 // BuildAnonymousStructOr union, for the same reason? 4676 if (CurContext->isFunctionOrMethod()) 4677 AnonRecord = Record; 4678 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4679 Context.getPrintingPolicy()); 4680 } 4681 4682 DeclaresAnything = false; 4683 } 4684 } 4685 4686 // C11 6.7.2.1p2: 4687 // A struct-declaration that does not declare an anonymous structure or 4688 // anonymous union shall contain a struct-declarator-list. 4689 // 4690 // This rule also existed in C89 and C99; the grammar for struct-declaration 4691 // did not permit a struct-declaration without a struct-declarator-list. 4692 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4693 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4694 // Check for Microsoft C extension: anonymous struct/union member. 4695 // Handle 2 kinds of anonymous struct/union: 4696 // struct STRUCT; 4697 // union UNION; 4698 // and 4699 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4700 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4701 if ((Tag && Tag->getDeclName()) || 4702 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4703 RecordDecl *Record = nullptr; 4704 if (Tag) 4705 Record = dyn_cast<RecordDecl>(Tag); 4706 else if (const RecordType *RT = 4707 DS.getRepAsType().get()->getAsStructureType()) 4708 Record = RT->getDecl(); 4709 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4710 Record = UT->getDecl(); 4711 4712 if (Record && getLangOpts().MicrosoftExt) { 4713 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4714 << Record->isUnion() << DS.getSourceRange(); 4715 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4716 } 4717 4718 DeclaresAnything = false; 4719 } 4720 } 4721 4722 // Skip all the checks below if we have a type error. 4723 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4724 (TagD && TagD->isInvalidDecl())) 4725 return TagD; 4726 4727 if (getLangOpts().CPlusPlus && 4728 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4729 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4730 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4731 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4732 DeclaresAnything = false; 4733 4734 if (!DS.isMissingDeclaratorOk()) { 4735 // Customize diagnostic for a typedef missing a name. 4736 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4737 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4738 << DS.getSourceRange(); 4739 else 4740 DeclaresAnything = false; 4741 } 4742 4743 if (DS.isModulePrivateSpecified() && 4744 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4745 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4746 << Tag->getTagKind() 4747 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4748 4749 ActOnDocumentableDecl(TagD); 4750 4751 // C 6.7/2: 4752 // A declaration [...] shall declare at least a declarator [...], a tag, 4753 // or the members of an enumeration. 4754 // C++ [dcl.dcl]p3: 4755 // [If there are no declarators], and except for the declaration of an 4756 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4757 // names into the program, or shall redeclare a name introduced by a 4758 // previous declaration. 4759 if (!DeclaresAnything) { 4760 // In C, we allow this as a (popular) extension / bug. Don't bother 4761 // producing further diagnostics for redundant qualifiers after this. 4762 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 4763 ? diag::err_no_declarators 4764 : diag::ext_no_declarators) 4765 << DS.getSourceRange(); 4766 return TagD; 4767 } 4768 4769 // C++ [dcl.stc]p1: 4770 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4771 // init-declarator-list of the declaration shall not be empty. 4772 // C++ [dcl.fct.spec]p1: 4773 // If a cv-qualifier appears in a decl-specifier-seq, the 4774 // init-declarator-list of the declaration shall not be empty. 4775 // 4776 // Spurious qualifiers here appear to be valid in C. 4777 unsigned DiagID = diag::warn_standalone_specifier; 4778 if (getLangOpts().CPlusPlus) 4779 DiagID = diag::ext_standalone_specifier; 4780 4781 // Note that a linkage-specification sets a storage class, but 4782 // 'extern "C" struct foo;' is actually valid and not theoretically 4783 // useless. 4784 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4785 if (SCS == DeclSpec::SCS_mutable) 4786 // Since mutable is not a viable storage class specifier in C, there is 4787 // no reason to treat it as an extension. Instead, diagnose as an error. 4788 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4789 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4790 Diag(DS.getStorageClassSpecLoc(), DiagID) 4791 << DeclSpec::getSpecifierName(SCS); 4792 } 4793 4794 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4795 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4796 << DeclSpec::getSpecifierName(TSCS); 4797 if (DS.getTypeQualifiers()) { 4798 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4799 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4800 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4801 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4802 // Restrict is covered above. 4803 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4804 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4805 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4806 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4807 } 4808 4809 // Warn about ignored type attributes, for example: 4810 // __attribute__((aligned)) struct A; 4811 // Attributes should be placed after tag to apply to type declaration. 4812 if (!DS.getAttributes().empty()) { 4813 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4814 if (TypeSpecType == DeclSpec::TST_class || 4815 TypeSpecType == DeclSpec::TST_struct || 4816 TypeSpecType == DeclSpec::TST_interface || 4817 TypeSpecType == DeclSpec::TST_union || 4818 TypeSpecType == DeclSpec::TST_enum) { 4819 for (const ParsedAttr &AL : DS.getAttributes()) 4820 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4821 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4822 } 4823 } 4824 4825 return TagD; 4826 } 4827 4828 /// We are trying to inject an anonymous member into the given scope; 4829 /// check if there's an existing declaration that can't be overloaded. 4830 /// 4831 /// \return true if this is a forbidden redeclaration 4832 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4833 Scope *S, 4834 DeclContext *Owner, 4835 DeclarationName Name, 4836 SourceLocation NameLoc, 4837 bool IsUnion) { 4838 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4839 Sema::ForVisibleRedeclaration); 4840 if (!SemaRef.LookupName(R, S)) return false; 4841 4842 // Pick a representative declaration. 4843 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4844 assert(PrevDecl && "Expected a non-null Decl"); 4845 4846 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4847 return false; 4848 4849 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4850 << IsUnion << Name; 4851 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4852 4853 return true; 4854 } 4855 4856 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4857 /// anonymous struct or union AnonRecord into the owning context Owner 4858 /// and scope S. This routine will be invoked just after we realize 4859 /// that an unnamed union or struct is actually an anonymous union or 4860 /// struct, e.g., 4861 /// 4862 /// @code 4863 /// union { 4864 /// int i; 4865 /// float f; 4866 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4867 /// // f into the surrounding scope.x 4868 /// @endcode 4869 /// 4870 /// This routine is recursive, injecting the names of nested anonymous 4871 /// structs/unions into the owning context and scope as well. 4872 static bool 4873 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4874 RecordDecl *AnonRecord, AccessSpecifier AS, 4875 SmallVectorImpl<NamedDecl *> &Chaining) { 4876 bool Invalid = false; 4877 4878 // Look every FieldDecl and IndirectFieldDecl with a name. 4879 for (auto *D : AnonRecord->decls()) { 4880 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4881 cast<NamedDecl>(D)->getDeclName()) { 4882 ValueDecl *VD = cast<ValueDecl>(D); 4883 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4884 VD->getLocation(), 4885 AnonRecord->isUnion())) { 4886 // C++ [class.union]p2: 4887 // The names of the members of an anonymous union shall be 4888 // distinct from the names of any other entity in the 4889 // scope in which the anonymous union is declared. 4890 Invalid = true; 4891 } else { 4892 // C++ [class.union]p2: 4893 // For the purpose of name lookup, after the anonymous union 4894 // definition, the members of the anonymous union are 4895 // considered to have been defined in the scope in which the 4896 // anonymous union is declared. 4897 unsigned OldChainingSize = Chaining.size(); 4898 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4899 Chaining.append(IF->chain_begin(), IF->chain_end()); 4900 else 4901 Chaining.push_back(VD); 4902 4903 assert(Chaining.size() >= 2); 4904 NamedDecl **NamedChain = 4905 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4906 for (unsigned i = 0; i < Chaining.size(); i++) 4907 NamedChain[i] = Chaining[i]; 4908 4909 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4910 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4911 VD->getType(), {NamedChain, Chaining.size()}); 4912 4913 for (const auto *Attr : VD->attrs()) 4914 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4915 4916 IndirectField->setAccess(AS); 4917 IndirectField->setImplicit(); 4918 SemaRef.PushOnScopeChains(IndirectField, S); 4919 4920 // That includes picking up the appropriate access specifier. 4921 if (AS != AS_none) IndirectField->setAccess(AS); 4922 4923 Chaining.resize(OldChainingSize); 4924 } 4925 } 4926 } 4927 4928 return Invalid; 4929 } 4930 4931 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4932 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4933 /// illegal input values are mapped to SC_None. 4934 static StorageClass 4935 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4936 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4937 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4938 "Parser allowed 'typedef' as storage class VarDecl."); 4939 switch (StorageClassSpec) { 4940 case DeclSpec::SCS_unspecified: return SC_None; 4941 case DeclSpec::SCS_extern: 4942 if (DS.isExternInLinkageSpec()) 4943 return SC_None; 4944 return SC_Extern; 4945 case DeclSpec::SCS_static: return SC_Static; 4946 case DeclSpec::SCS_auto: return SC_Auto; 4947 case DeclSpec::SCS_register: return SC_Register; 4948 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4949 // Illegal SCSs map to None: error reporting is up to the caller. 4950 case DeclSpec::SCS_mutable: // Fall through. 4951 case DeclSpec::SCS_typedef: return SC_None; 4952 } 4953 llvm_unreachable("unknown storage class specifier"); 4954 } 4955 4956 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4957 assert(Record->hasInClassInitializer()); 4958 4959 for (const auto *I : Record->decls()) { 4960 const auto *FD = dyn_cast<FieldDecl>(I); 4961 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4962 FD = IFD->getAnonField(); 4963 if (FD && FD->hasInClassInitializer()) 4964 return FD->getLocation(); 4965 } 4966 4967 llvm_unreachable("couldn't find in-class initializer"); 4968 } 4969 4970 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4971 SourceLocation DefaultInitLoc) { 4972 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4973 return; 4974 4975 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4976 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4977 } 4978 4979 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4980 CXXRecordDecl *AnonUnion) { 4981 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4982 return; 4983 4984 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4985 } 4986 4987 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4988 /// anonymous structure or union. Anonymous unions are a C++ feature 4989 /// (C++ [class.union]) and a C11 feature; anonymous structures 4990 /// are a C11 feature and GNU C++ extension. 4991 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4992 AccessSpecifier AS, 4993 RecordDecl *Record, 4994 const PrintingPolicy &Policy) { 4995 DeclContext *Owner = Record->getDeclContext(); 4996 4997 // Diagnose whether this anonymous struct/union is an extension. 4998 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4999 Diag(Record->getLocation(), diag::ext_anonymous_union); 5000 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 5001 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 5002 else if (!Record->isUnion() && !getLangOpts().C11) 5003 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 5004 5005 // C and C++ require different kinds of checks for anonymous 5006 // structs/unions. 5007 bool Invalid = false; 5008 if (getLangOpts().CPlusPlus) { 5009 const char *PrevSpec = nullptr; 5010 if (Record->isUnion()) { 5011 // C++ [class.union]p6: 5012 // C++17 [class.union.anon]p2: 5013 // Anonymous unions declared in a named namespace or in the 5014 // global namespace shall be declared static. 5015 unsigned DiagID; 5016 DeclContext *OwnerScope = Owner->getRedeclContext(); 5017 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5018 (OwnerScope->isTranslationUnit() || 5019 (OwnerScope->isNamespace() && 5020 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5021 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5022 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5023 5024 // Recover by adding 'static'. 5025 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5026 PrevSpec, DiagID, Policy); 5027 } 5028 // C++ [class.union]p6: 5029 // A storage class is not allowed in a declaration of an 5030 // anonymous union in a class scope. 5031 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5032 isa<RecordDecl>(Owner)) { 5033 Diag(DS.getStorageClassSpecLoc(), 5034 diag::err_anonymous_union_with_storage_spec) 5035 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5036 5037 // Recover by removing the storage specifier. 5038 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5039 SourceLocation(), 5040 PrevSpec, DiagID, Context.getPrintingPolicy()); 5041 } 5042 } 5043 5044 // Ignore const/volatile/restrict qualifiers. 5045 if (DS.getTypeQualifiers()) { 5046 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5047 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5048 << Record->isUnion() << "const" 5049 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5050 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5051 Diag(DS.getVolatileSpecLoc(), 5052 diag::ext_anonymous_struct_union_qualified) 5053 << Record->isUnion() << "volatile" 5054 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5055 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5056 Diag(DS.getRestrictSpecLoc(), 5057 diag::ext_anonymous_struct_union_qualified) 5058 << Record->isUnion() << "restrict" 5059 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5060 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5061 Diag(DS.getAtomicSpecLoc(), 5062 diag::ext_anonymous_struct_union_qualified) 5063 << Record->isUnion() << "_Atomic" 5064 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5065 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5066 Diag(DS.getUnalignedSpecLoc(), 5067 diag::ext_anonymous_struct_union_qualified) 5068 << Record->isUnion() << "__unaligned" 5069 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5070 5071 DS.ClearTypeQualifiers(); 5072 } 5073 5074 // C++ [class.union]p2: 5075 // The member-specification of an anonymous union shall only 5076 // define non-static data members. [Note: nested types and 5077 // functions cannot be declared within an anonymous union. ] 5078 for (auto *Mem : Record->decls()) { 5079 // Ignore invalid declarations; we already diagnosed them. 5080 if (Mem->isInvalidDecl()) 5081 continue; 5082 5083 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5084 // C++ [class.union]p3: 5085 // An anonymous union shall not have private or protected 5086 // members (clause 11). 5087 assert(FD->getAccess() != AS_none); 5088 if (FD->getAccess() != AS_public) { 5089 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5090 << Record->isUnion() << (FD->getAccess() == AS_protected); 5091 Invalid = true; 5092 } 5093 5094 // C++ [class.union]p1 5095 // An object of a class with a non-trivial constructor, a non-trivial 5096 // copy constructor, a non-trivial destructor, or a non-trivial copy 5097 // assignment operator cannot be a member of a union, nor can an 5098 // array of such objects. 5099 if (CheckNontrivialField(FD)) 5100 Invalid = true; 5101 } else if (Mem->isImplicit()) { 5102 // Any implicit members are fine. 5103 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5104 // This is a type that showed up in an 5105 // elaborated-type-specifier inside the anonymous struct or 5106 // union, but which actually declares a type outside of the 5107 // anonymous struct or union. It's okay. 5108 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5109 if (!MemRecord->isAnonymousStructOrUnion() && 5110 MemRecord->getDeclName()) { 5111 // Visual C++ allows type definition in anonymous struct or union. 5112 if (getLangOpts().MicrosoftExt) 5113 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5114 << Record->isUnion(); 5115 else { 5116 // This is a nested type declaration. 5117 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5118 << Record->isUnion(); 5119 Invalid = true; 5120 } 5121 } else { 5122 // This is an anonymous type definition within another anonymous type. 5123 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5124 // not part of standard C++. 5125 Diag(MemRecord->getLocation(), 5126 diag::ext_anonymous_record_with_anonymous_type) 5127 << Record->isUnion(); 5128 } 5129 } else if (isa<AccessSpecDecl>(Mem)) { 5130 // Any access specifier is fine. 5131 } else if (isa<StaticAssertDecl>(Mem)) { 5132 // In C++1z, static_assert declarations are also fine. 5133 } else { 5134 // We have something that isn't a non-static data 5135 // member. Complain about it. 5136 unsigned DK = diag::err_anonymous_record_bad_member; 5137 if (isa<TypeDecl>(Mem)) 5138 DK = diag::err_anonymous_record_with_type; 5139 else if (isa<FunctionDecl>(Mem)) 5140 DK = diag::err_anonymous_record_with_function; 5141 else if (isa<VarDecl>(Mem)) 5142 DK = diag::err_anonymous_record_with_static; 5143 5144 // Visual C++ allows type definition in anonymous struct or union. 5145 if (getLangOpts().MicrosoftExt && 5146 DK == diag::err_anonymous_record_with_type) 5147 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5148 << Record->isUnion(); 5149 else { 5150 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5151 Invalid = true; 5152 } 5153 } 5154 } 5155 5156 // C++11 [class.union]p8 (DR1460): 5157 // At most one variant member of a union may have a 5158 // brace-or-equal-initializer. 5159 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5160 Owner->isRecord()) 5161 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5162 cast<CXXRecordDecl>(Record)); 5163 } 5164 5165 if (!Record->isUnion() && !Owner->isRecord()) { 5166 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5167 << getLangOpts().CPlusPlus; 5168 Invalid = true; 5169 } 5170 5171 // C++ [dcl.dcl]p3: 5172 // [If there are no declarators], and except for the declaration of an 5173 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5174 // names into the program 5175 // C++ [class.mem]p2: 5176 // each such member-declaration shall either declare at least one member 5177 // name of the class or declare at least one unnamed bit-field 5178 // 5179 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5180 if (getLangOpts().CPlusPlus && Record->field_empty()) 5181 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5182 5183 // Mock up a declarator. 5184 Declarator Dc(DS, DeclaratorContext::Member); 5185 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5186 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5187 5188 // Create a declaration for this anonymous struct/union. 5189 NamedDecl *Anon = nullptr; 5190 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5191 Anon = FieldDecl::Create( 5192 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5193 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5194 /*BitWidth=*/nullptr, /*Mutable=*/false, 5195 /*InitStyle=*/ICIS_NoInit); 5196 Anon->setAccess(AS); 5197 ProcessDeclAttributes(S, Anon, Dc); 5198 5199 if (getLangOpts().CPlusPlus) 5200 FieldCollector->Add(cast<FieldDecl>(Anon)); 5201 } else { 5202 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5203 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5204 if (SCSpec == DeclSpec::SCS_mutable) { 5205 // mutable can only appear on non-static class members, so it's always 5206 // an error here 5207 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5208 Invalid = true; 5209 SC = SC_None; 5210 } 5211 5212 assert(DS.getAttributes().empty() && "No attribute expected"); 5213 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5214 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5215 Context.getTypeDeclType(Record), TInfo, SC); 5216 5217 // Default-initialize the implicit variable. This initialization will be 5218 // trivial in almost all cases, except if a union member has an in-class 5219 // initializer: 5220 // union { int n = 0; }; 5221 if (!Invalid) 5222 ActOnUninitializedDecl(Anon); 5223 } 5224 Anon->setImplicit(); 5225 5226 // Mark this as an anonymous struct/union type. 5227 Record->setAnonymousStructOrUnion(true); 5228 5229 // Add the anonymous struct/union object to the current 5230 // context. We'll be referencing this object when we refer to one of 5231 // its members. 5232 Owner->addDecl(Anon); 5233 5234 // Inject the members of the anonymous struct/union into the owning 5235 // context and into the identifier resolver chain for name lookup 5236 // purposes. 5237 SmallVector<NamedDecl*, 2> Chain; 5238 Chain.push_back(Anon); 5239 5240 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5241 Invalid = true; 5242 5243 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5244 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5245 MangleNumberingContext *MCtx; 5246 Decl *ManglingContextDecl; 5247 std::tie(MCtx, ManglingContextDecl) = 5248 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5249 if (MCtx) { 5250 Context.setManglingNumber( 5251 NewVD, MCtx->getManglingNumber( 5252 NewVD, getMSManglingNumber(getLangOpts(), S))); 5253 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5254 } 5255 } 5256 } 5257 5258 if (Invalid) 5259 Anon->setInvalidDecl(); 5260 5261 return Anon; 5262 } 5263 5264 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5265 /// Microsoft C anonymous structure. 5266 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5267 /// Example: 5268 /// 5269 /// struct A { int a; }; 5270 /// struct B { struct A; int b; }; 5271 /// 5272 /// void foo() { 5273 /// B var; 5274 /// var.a = 3; 5275 /// } 5276 /// 5277 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5278 RecordDecl *Record) { 5279 assert(Record && "expected a record!"); 5280 5281 // Mock up a declarator. 5282 Declarator Dc(DS, DeclaratorContext::TypeName); 5283 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5284 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5285 5286 auto *ParentDecl = cast<RecordDecl>(CurContext); 5287 QualType RecTy = Context.getTypeDeclType(Record); 5288 5289 // Create a declaration for this anonymous struct. 5290 NamedDecl *Anon = 5291 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5292 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5293 /*BitWidth=*/nullptr, /*Mutable=*/false, 5294 /*InitStyle=*/ICIS_NoInit); 5295 Anon->setImplicit(); 5296 5297 // Add the anonymous struct object to the current context. 5298 CurContext->addDecl(Anon); 5299 5300 // Inject the members of the anonymous struct into the current 5301 // context and into the identifier resolver chain for name lookup 5302 // purposes. 5303 SmallVector<NamedDecl*, 2> Chain; 5304 Chain.push_back(Anon); 5305 5306 RecordDecl *RecordDef = Record->getDefinition(); 5307 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5308 diag::err_field_incomplete_or_sizeless) || 5309 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5310 AS_none, Chain)) { 5311 Anon->setInvalidDecl(); 5312 ParentDecl->setInvalidDecl(); 5313 } 5314 5315 return Anon; 5316 } 5317 5318 /// GetNameForDeclarator - Determine the full declaration name for the 5319 /// given Declarator. 5320 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5321 return GetNameFromUnqualifiedId(D.getName()); 5322 } 5323 5324 /// Retrieves the declaration name from a parsed unqualified-id. 5325 DeclarationNameInfo 5326 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5327 DeclarationNameInfo NameInfo; 5328 NameInfo.setLoc(Name.StartLocation); 5329 5330 switch (Name.getKind()) { 5331 5332 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5333 case UnqualifiedIdKind::IK_Identifier: 5334 NameInfo.setName(Name.Identifier); 5335 return NameInfo; 5336 5337 case UnqualifiedIdKind::IK_DeductionGuideName: { 5338 // C++ [temp.deduct.guide]p3: 5339 // The simple-template-id shall name a class template specialization. 5340 // The template-name shall be the same identifier as the template-name 5341 // of the simple-template-id. 5342 // These together intend to imply that the template-name shall name a 5343 // class template. 5344 // FIXME: template<typename T> struct X {}; 5345 // template<typename T> using Y = X<T>; 5346 // Y(int) -> Y<int>; 5347 // satisfies these rules but does not name a class template. 5348 TemplateName TN = Name.TemplateName.get().get(); 5349 auto *Template = TN.getAsTemplateDecl(); 5350 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5351 Diag(Name.StartLocation, 5352 diag::err_deduction_guide_name_not_class_template) 5353 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5354 if (Template) 5355 Diag(Template->getLocation(), diag::note_template_decl_here); 5356 return DeclarationNameInfo(); 5357 } 5358 5359 NameInfo.setName( 5360 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5361 return NameInfo; 5362 } 5363 5364 case UnqualifiedIdKind::IK_OperatorFunctionId: 5365 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5366 Name.OperatorFunctionId.Operator)); 5367 NameInfo.setCXXOperatorNameRange(SourceRange( 5368 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5369 return NameInfo; 5370 5371 case UnqualifiedIdKind::IK_LiteralOperatorId: 5372 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5373 Name.Identifier)); 5374 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5375 return NameInfo; 5376 5377 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5378 TypeSourceInfo *TInfo; 5379 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5380 if (Ty.isNull()) 5381 return DeclarationNameInfo(); 5382 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5383 Context.getCanonicalType(Ty))); 5384 NameInfo.setNamedTypeInfo(TInfo); 5385 return NameInfo; 5386 } 5387 5388 case UnqualifiedIdKind::IK_ConstructorName: { 5389 TypeSourceInfo *TInfo; 5390 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5391 if (Ty.isNull()) 5392 return DeclarationNameInfo(); 5393 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5394 Context.getCanonicalType(Ty))); 5395 NameInfo.setNamedTypeInfo(TInfo); 5396 return NameInfo; 5397 } 5398 5399 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5400 // In well-formed code, we can only have a constructor 5401 // template-id that refers to the current context, so go there 5402 // to find the actual type being constructed. 5403 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5404 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5405 return DeclarationNameInfo(); 5406 5407 // Determine the type of the class being constructed. 5408 QualType CurClassType = Context.getTypeDeclType(CurClass); 5409 5410 // FIXME: Check two things: that the template-id names the same type as 5411 // CurClassType, and that the template-id does not occur when the name 5412 // was qualified. 5413 5414 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5415 Context.getCanonicalType(CurClassType))); 5416 // FIXME: should we retrieve TypeSourceInfo? 5417 NameInfo.setNamedTypeInfo(nullptr); 5418 return NameInfo; 5419 } 5420 5421 case UnqualifiedIdKind::IK_DestructorName: { 5422 TypeSourceInfo *TInfo; 5423 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5424 if (Ty.isNull()) 5425 return DeclarationNameInfo(); 5426 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5427 Context.getCanonicalType(Ty))); 5428 NameInfo.setNamedTypeInfo(TInfo); 5429 return NameInfo; 5430 } 5431 5432 case UnqualifiedIdKind::IK_TemplateId: { 5433 TemplateName TName = Name.TemplateId->Template.get(); 5434 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5435 return Context.getNameForTemplate(TName, TNameLoc); 5436 } 5437 5438 } // switch (Name.getKind()) 5439 5440 llvm_unreachable("Unknown name kind"); 5441 } 5442 5443 static QualType getCoreType(QualType Ty) { 5444 do { 5445 if (Ty->isPointerType() || Ty->isReferenceType()) 5446 Ty = Ty->getPointeeType(); 5447 else if (Ty->isArrayType()) 5448 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5449 else 5450 return Ty.withoutLocalFastQualifiers(); 5451 } while (true); 5452 } 5453 5454 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5455 /// and Definition have "nearly" matching parameters. This heuristic is 5456 /// used to improve diagnostics in the case where an out-of-line function 5457 /// definition doesn't match any declaration within the class or namespace. 5458 /// Also sets Params to the list of indices to the parameters that differ 5459 /// between the declaration and the definition. If hasSimilarParameters 5460 /// returns true and Params is empty, then all of the parameters match. 5461 static bool hasSimilarParameters(ASTContext &Context, 5462 FunctionDecl *Declaration, 5463 FunctionDecl *Definition, 5464 SmallVectorImpl<unsigned> &Params) { 5465 Params.clear(); 5466 if (Declaration->param_size() != Definition->param_size()) 5467 return false; 5468 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5469 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5470 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5471 5472 // The parameter types are identical 5473 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5474 continue; 5475 5476 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5477 QualType DefParamBaseTy = getCoreType(DefParamTy); 5478 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5479 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5480 5481 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5482 (DeclTyName && DeclTyName == DefTyName)) 5483 Params.push_back(Idx); 5484 else // The two parameters aren't even close 5485 return false; 5486 } 5487 5488 return true; 5489 } 5490 5491 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5492 /// declarator needs to be rebuilt in the current instantiation. 5493 /// Any bits of declarator which appear before the name are valid for 5494 /// consideration here. That's specifically the type in the decl spec 5495 /// and the base type in any member-pointer chunks. 5496 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5497 DeclarationName Name) { 5498 // The types we specifically need to rebuild are: 5499 // - typenames, typeofs, and decltypes 5500 // - types which will become injected class names 5501 // Of course, we also need to rebuild any type referencing such a 5502 // type. It's safest to just say "dependent", but we call out a 5503 // few cases here. 5504 5505 DeclSpec &DS = D.getMutableDeclSpec(); 5506 switch (DS.getTypeSpecType()) { 5507 case DeclSpec::TST_typename: 5508 case DeclSpec::TST_typeofType: 5509 case DeclSpec::TST_underlyingType: 5510 case DeclSpec::TST_atomic: { 5511 // Grab the type from the parser. 5512 TypeSourceInfo *TSI = nullptr; 5513 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5514 if (T.isNull() || !T->isInstantiationDependentType()) break; 5515 5516 // Make sure there's a type source info. This isn't really much 5517 // of a waste; most dependent types should have type source info 5518 // attached already. 5519 if (!TSI) 5520 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5521 5522 // Rebuild the type in the current instantiation. 5523 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5524 if (!TSI) return true; 5525 5526 // Store the new type back in the decl spec. 5527 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5528 DS.UpdateTypeRep(LocType); 5529 break; 5530 } 5531 5532 case DeclSpec::TST_decltype: 5533 case DeclSpec::TST_typeofExpr: { 5534 Expr *E = DS.getRepAsExpr(); 5535 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5536 if (Result.isInvalid()) return true; 5537 DS.UpdateExprRep(Result.get()); 5538 break; 5539 } 5540 5541 default: 5542 // Nothing to do for these decl specs. 5543 break; 5544 } 5545 5546 // It doesn't matter what order we do this in. 5547 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5548 DeclaratorChunk &Chunk = D.getTypeObject(I); 5549 5550 // The only type information in the declarator which can come 5551 // before the declaration name is the base type of a member 5552 // pointer. 5553 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5554 continue; 5555 5556 // Rebuild the scope specifier in-place. 5557 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5558 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5559 return true; 5560 } 5561 5562 return false; 5563 } 5564 5565 void Sema::warnOnReservedIdentifier(const NamedDecl *D) { 5566 // Avoid warning twice on the same identifier, and don't warn on redeclaration 5567 // of system decl. 5568 if (D->getPreviousDecl() || D->isImplicit()) 5569 return; 5570 ReservedIdentifierStatus Status = D->isReserved(getLangOpts()); 5571 if (Status != ReservedIdentifierStatus::NotReserved && 5572 !Context.getSourceManager().isInSystemHeader(D->getLocation())) 5573 Diag(D->getLocation(), diag::warn_reserved_extern_symbol) 5574 << D << static_cast<int>(Status); 5575 } 5576 5577 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5578 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 5579 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5580 5581 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5582 Dcl && Dcl->getDeclContext()->isFileContext()) 5583 Dcl->setTopLevelDeclInObjCContainer(); 5584 5585 return Dcl; 5586 } 5587 5588 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5589 /// If T is the name of a class, then each of the following shall have a 5590 /// name different from T: 5591 /// - every static data member of class T; 5592 /// - every member function of class T 5593 /// - every member of class T that is itself a type; 5594 /// \returns true if the declaration name violates these rules. 5595 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5596 DeclarationNameInfo NameInfo) { 5597 DeclarationName Name = NameInfo.getName(); 5598 5599 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5600 while (Record && Record->isAnonymousStructOrUnion()) 5601 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5602 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5603 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5604 return true; 5605 } 5606 5607 return false; 5608 } 5609 5610 /// Diagnose a declaration whose declarator-id has the given 5611 /// nested-name-specifier. 5612 /// 5613 /// \param SS The nested-name-specifier of the declarator-id. 5614 /// 5615 /// \param DC The declaration context to which the nested-name-specifier 5616 /// resolves. 5617 /// 5618 /// \param Name The name of the entity being declared. 5619 /// 5620 /// \param Loc The location of the name of the entity being declared. 5621 /// 5622 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5623 /// we're declaring an explicit / partial specialization / instantiation. 5624 /// 5625 /// \returns true if we cannot safely recover from this error, false otherwise. 5626 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5627 DeclarationName Name, 5628 SourceLocation Loc, bool IsTemplateId) { 5629 DeclContext *Cur = CurContext; 5630 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5631 Cur = Cur->getParent(); 5632 5633 // If the user provided a superfluous scope specifier that refers back to the 5634 // class in which the entity is already declared, diagnose and ignore it. 5635 // 5636 // class X { 5637 // void X::f(); 5638 // }; 5639 // 5640 // Note, it was once ill-formed to give redundant qualification in all 5641 // contexts, but that rule was removed by DR482. 5642 if (Cur->Equals(DC)) { 5643 if (Cur->isRecord()) { 5644 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5645 : diag::err_member_extra_qualification) 5646 << Name << FixItHint::CreateRemoval(SS.getRange()); 5647 SS.clear(); 5648 } else { 5649 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5650 } 5651 return false; 5652 } 5653 5654 // Check whether the qualifying scope encloses the scope of the original 5655 // declaration. For a template-id, we perform the checks in 5656 // CheckTemplateSpecializationScope. 5657 if (!Cur->Encloses(DC) && !IsTemplateId) { 5658 if (Cur->isRecord()) 5659 Diag(Loc, diag::err_member_qualification) 5660 << Name << SS.getRange(); 5661 else if (isa<TranslationUnitDecl>(DC)) 5662 Diag(Loc, diag::err_invalid_declarator_global_scope) 5663 << Name << SS.getRange(); 5664 else if (isa<FunctionDecl>(Cur)) 5665 Diag(Loc, diag::err_invalid_declarator_in_function) 5666 << Name << SS.getRange(); 5667 else if (isa<BlockDecl>(Cur)) 5668 Diag(Loc, diag::err_invalid_declarator_in_block) 5669 << Name << SS.getRange(); 5670 else 5671 Diag(Loc, diag::err_invalid_declarator_scope) 5672 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5673 5674 return true; 5675 } 5676 5677 if (Cur->isRecord()) { 5678 // Cannot qualify members within a class. 5679 Diag(Loc, diag::err_member_qualification) 5680 << Name << SS.getRange(); 5681 SS.clear(); 5682 5683 // C++ constructors and destructors with incorrect scopes can break 5684 // our AST invariants by having the wrong underlying types. If 5685 // that's the case, then drop this declaration entirely. 5686 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5687 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5688 !Context.hasSameType(Name.getCXXNameType(), 5689 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5690 return true; 5691 5692 return false; 5693 } 5694 5695 // C++11 [dcl.meaning]p1: 5696 // [...] "The nested-name-specifier of the qualified declarator-id shall 5697 // not begin with a decltype-specifer" 5698 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5699 while (SpecLoc.getPrefix()) 5700 SpecLoc = SpecLoc.getPrefix(); 5701 if (dyn_cast_or_null<DecltypeType>( 5702 SpecLoc.getNestedNameSpecifier()->getAsType())) 5703 Diag(Loc, diag::err_decltype_in_declarator) 5704 << SpecLoc.getTypeLoc().getSourceRange(); 5705 5706 return false; 5707 } 5708 5709 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5710 MultiTemplateParamsArg TemplateParamLists) { 5711 // TODO: consider using NameInfo for diagnostic. 5712 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5713 DeclarationName Name = NameInfo.getName(); 5714 5715 // All of these full declarators require an identifier. If it doesn't have 5716 // one, the ParsedFreeStandingDeclSpec action should be used. 5717 if (D.isDecompositionDeclarator()) { 5718 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5719 } else if (!Name) { 5720 if (!D.isInvalidType()) // Reject this if we think it is valid. 5721 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5722 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5723 return nullptr; 5724 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5725 return nullptr; 5726 5727 // The scope passed in may not be a decl scope. Zip up the scope tree until 5728 // we find one that is. 5729 while ((S->getFlags() & Scope::DeclScope) == 0 || 5730 (S->getFlags() & Scope::TemplateParamScope) != 0) 5731 S = S->getParent(); 5732 5733 DeclContext *DC = CurContext; 5734 if (D.getCXXScopeSpec().isInvalid()) 5735 D.setInvalidType(); 5736 else if (D.getCXXScopeSpec().isSet()) { 5737 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5738 UPPC_DeclarationQualifier)) 5739 return nullptr; 5740 5741 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5742 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5743 if (!DC || isa<EnumDecl>(DC)) { 5744 // If we could not compute the declaration context, it's because the 5745 // declaration context is dependent but does not refer to a class, 5746 // class template, or class template partial specialization. Complain 5747 // and return early, to avoid the coming semantic disaster. 5748 Diag(D.getIdentifierLoc(), 5749 diag::err_template_qualified_declarator_no_match) 5750 << D.getCXXScopeSpec().getScopeRep() 5751 << D.getCXXScopeSpec().getRange(); 5752 return nullptr; 5753 } 5754 bool IsDependentContext = DC->isDependentContext(); 5755 5756 if (!IsDependentContext && 5757 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5758 return nullptr; 5759 5760 // If a class is incomplete, do not parse entities inside it. 5761 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5762 Diag(D.getIdentifierLoc(), 5763 diag::err_member_def_undefined_record) 5764 << Name << DC << D.getCXXScopeSpec().getRange(); 5765 return nullptr; 5766 } 5767 if (!D.getDeclSpec().isFriendSpecified()) { 5768 if (diagnoseQualifiedDeclaration( 5769 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5770 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5771 if (DC->isRecord()) 5772 return nullptr; 5773 5774 D.setInvalidType(); 5775 } 5776 } 5777 5778 // Check whether we need to rebuild the type of the given 5779 // declaration in the current instantiation. 5780 if (EnteringContext && IsDependentContext && 5781 TemplateParamLists.size() != 0) { 5782 ContextRAII SavedContext(*this, DC); 5783 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5784 D.setInvalidType(); 5785 } 5786 } 5787 5788 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5789 QualType R = TInfo->getType(); 5790 5791 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5792 UPPC_DeclarationType)) 5793 D.setInvalidType(); 5794 5795 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5796 forRedeclarationInCurContext()); 5797 5798 // See if this is a redefinition of a variable in the same scope. 5799 if (!D.getCXXScopeSpec().isSet()) { 5800 bool IsLinkageLookup = false; 5801 bool CreateBuiltins = false; 5802 5803 // If the declaration we're planning to build will be a function 5804 // or object with linkage, then look for another declaration with 5805 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5806 // 5807 // If the declaration we're planning to build will be declared with 5808 // external linkage in the translation unit, create any builtin with 5809 // the same name. 5810 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5811 /* Do nothing*/; 5812 else if (CurContext->isFunctionOrMethod() && 5813 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5814 R->isFunctionType())) { 5815 IsLinkageLookup = true; 5816 CreateBuiltins = 5817 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5818 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5819 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5820 CreateBuiltins = true; 5821 5822 if (IsLinkageLookup) { 5823 Previous.clear(LookupRedeclarationWithLinkage); 5824 Previous.setRedeclarationKind(ForExternalRedeclaration); 5825 } 5826 5827 LookupName(Previous, S, CreateBuiltins); 5828 } else { // Something like "int foo::x;" 5829 LookupQualifiedName(Previous, DC); 5830 5831 // C++ [dcl.meaning]p1: 5832 // When the declarator-id is qualified, the declaration shall refer to a 5833 // previously declared member of the class or namespace to which the 5834 // qualifier refers (or, in the case of a namespace, of an element of the 5835 // inline namespace set of that namespace (7.3.1)) or to a specialization 5836 // thereof; [...] 5837 // 5838 // Note that we already checked the context above, and that we do not have 5839 // enough information to make sure that Previous contains the declaration 5840 // we want to match. For example, given: 5841 // 5842 // class X { 5843 // void f(); 5844 // void f(float); 5845 // }; 5846 // 5847 // void X::f(int) { } // ill-formed 5848 // 5849 // In this case, Previous will point to the overload set 5850 // containing the two f's declared in X, but neither of them 5851 // matches. 5852 5853 // C++ [dcl.meaning]p1: 5854 // [...] the member shall not merely have been introduced by a 5855 // using-declaration in the scope of the class or namespace nominated by 5856 // the nested-name-specifier of the declarator-id. 5857 RemoveUsingDecls(Previous); 5858 } 5859 5860 if (Previous.isSingleResult() && 5861 Previous.getFoundDecl()->isTemplateParameter()) { 5862 // Maybe we will complain about the shadowed template parameter. 5863 if (!D.isInvalidType()) 5864 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5865 Previous.getFoundDecl()); 5866 5867 // Just pretend that we didn't see the previous declaration. 5868 Previous.clear(); 5869 } 5870 5871 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5872 // Forget that the previous declaration is the injected-class-name. 5873 Previous.clear(); 5874 5875 // In C++, the previous declaration we find might be a tag type 5876 // (class or enum). In this case, the new declaration will hide the 5877 // tag type. Note that this applies to functions, function templates, and 5878 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5879 if (Previous.isSingleTagDecl() && 5880 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5881 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5882 Previous.clear(); 5883 5884 // Check that there are no default arguments other than in the parameters 5885 // of a function declaration (C++ only). 5886 if (getLangOpts().CPlusPlus) 5887 CheckExtraCXXDefaultArguments(D); 5888 5889 NamedDecl *New; 5890 5891 bool AddToScope = true; 5892 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5893 if (TemplateParamLists.size()) { 5894 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5895 return nullptr; 5896 } 5897 5898 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5899 } else if (R->isFunctionType()) { 5900 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5901 TemplateParamLists, 5902 AddToScope); 5903 } else { 5904 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5905 AddToScope); 5906 } 5907 5908 if (!New) 5909 return nullptr; 5910 5911 // If this has an identifier and is not a function template specialization, 5912 // add it to the scope stack. 5913 if (New->getDeclName() && AddToScope) 5914 PushOnScopeChains(New, S); 5915 5916 if (isInOpenMPDeclareTargetContext()) 5917 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5918 5919 return New; 5920 } 5921 5922 /// Helper method to turn variable array types into constant array 5923 /// types in certain situations which would otherwise be errors (for 5924 /// GCC compatibility). 5925 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5926 ASTContext &Context, 5927 bool &SizeIsNegative, 5928 llvm::APSInt &Oversized) { 5929 // This method tries to turn a variable array into a constant 5930 // array even when the size isn't an ICE. This is necessary 5931 // for compatibility with code that depends on gcc's buggy 5932 // constant expression folding, like struct {char x[(int)(char*)2];} 5933 SizeIsNegative = false; 5934 Oversized = 0; 5935 5936 if (T->isDependentType()) 5937 return QualType(); 5938 5939 QualifierCollector Qs; 5940 const Type *Ty = Qs.strip(T); 5941 5942 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5943 QualType Pointee = PTy->getPointeeType(); 5944 QualType FixedType = 5945 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5946 Oversized); 5947 if (FixedType.isNull()) return FixedType; 5948 FixedType = Context.getPointerType(FixedType); 5949 return Qs.apply(Context, FixedType); 5950 } 5951 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5952 QualType Inner = PTy->getInnerType(); 5953 QualType FixedType = 5954 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5955 Oversized); 5956 if (FixedType.isNull()) return FixedType; 5957 FixedType = Context.getParenType(FixedType); 5958 return Qs.apply(Context, FixedType); 5959 } 5960 5961 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5962 if (!VLATy) 5963 return QualType(); 5964 5965 QualType ElemTy = VLATy->getElementType(); 5966 if (ElemTy->isVariablyModifiedType()) { 5967 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 5968 SizeIsNegative, Oversized); 5969 if (ElemTy.isNull()) 5970 return QualType(); 5971 } 5972 5973 Expr::EvalResult Result; 5974 if (!VLATy->getSizeExpr() || 5975 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5976 return QualType(); 5977 5978 llvm::APSInt Res = Result.Val.getInt(); 5979 5980 // Check whether the array size is negative. 5981 if (Res.isSigned() && Res.isNegative()) { 5982 SizeIsNegative = true; 5983 return QualType(); 5984 } 5985 5986 // Check whether the array is too large to be addressed. 5987 unsigned ActiveSizeBits = 5988 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 5989 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 5990 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 5991 : Res.getActiveBits(); 5992 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5993 Oversized = Res; 5994 return QualType(); 5995 } 5996 5997 QualType FoldedArrayType = Context.getConstantArrayType( 5998 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 5999 return Qs.apply(Context, FoldedArrayType); 6000 } 6001 6002 static void 6003 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 6004 SrcTL = SrcTL.getUnqualifiedLoc(); 6005 DstTL = DstTL.getUnqualifiedLoc(); 6006 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 6007 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 6008 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 6009 DstPTL.getPointeeLoc()); 6010 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 6011 return; 6012 } 6013 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 6014 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 6015 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 6016 DstPTL.getInnerLoc()); 6017 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 6018 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 6019 return; 6020 } 6021 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6022 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6023 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6024 TypeLoc DstElemTL = DstATL.getElementLoc(); 6025 if (VariableArrayTypeLoc SrcElemATL = 6026 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6027 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6028 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6029 } else { 6030 DstElemTL.initializeFullCopy(SrcElemTL); 6031 } 6032 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6033 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6034 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6035 } 6036 6037 /// Helper method to turn variable array types into constant array 6038 /// types in certain situations which would otherwise be errors (for 6039 /// GCC compatibility). 6040 static TypeSourceInfo* 6041 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6042 ASTContext &Context, 6043 bool &SizeIsNegative, 6044 llvm::APSInt &Oversized) { 6045 QualType FixedTy 6046 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6047 SizeIsNegative, Oversized); 6048 if (FixedTy.isNull()) 6049 return nullptr; 6050 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6051 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6052 FixedTInfo->getTypeLoc()); 6053 return FixedTInfo; 6054 } 6055 6056 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6057 /// true if we were successful. 6058 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, 6059 QualType &T, SourceLocation Loc, 6060 unsigned FailedFoldDiagID) { 6061 bool SizeIsNegative; 6062 llvm::APSInt Oversized; 6063 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6064 TInfo, Context, SizeIsNegative, Oversized); 6065 if (FixedTInfo) { 6066 Diag(Loc, diag::ext_vla_folded_to_constant); 6067 TInfo = FixedTInfo; 6068 T = FixedTInfo->getType(); 6069 return true; 6070 } 6071 6072 if (SizeIsNegative) 6073 Diag(Loc, diag::err_typecheck_negative_array_size); 6074 else if (Oversized.getBoolValue()) 6075 Diag(Loc, diag::err_array_too_large) << Oversized.toString(10); 6076 else if (FailedFoldDiagID) 6077 Diag(Loc, FailedFoldDiagID); 6078 return false; 6079 } 6080 6081 /// Register the given locally-scoped extern "C" declaration so 6082 /// that it can be found later for redeclarations. We include any extern "C" 6083 /// declaration that is not visible in the translation unit here, not just 6084 /// function-scope declarations. 6085 void 6086 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6087 if (!getLangOpts().CPlusPlus && 6088 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6089 // Don't need to track declarations in the TU in C. 6090 return; 6091 6092 // Note that we have a locally-scoped external with this name. 6093 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6094 } 6095 6096 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6097 // FIXME: We can have multiple results via __attribute__((overloadable)). 6098 auto Result = Context.getExternCContextDecl()->lookup(Name); 6099 return Result.empty() ? nullptr : *Result.begin(); 6100 } 6101 6102 /// Diagnose function specifiers on a declaration of an identifier that 6103 /// does not identify a function. 6104 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6105 // FIXME: We should probably indicate the identifier in question to avoid 6106 // confusion for constructs like "virtual int a(), b;" 6107 if (DS.isVirtualSpecified()) 6108 Diag(DS.getVirtualSpecLoc(), 6109 diag::err_virtual_non_function); 6110 6111 if (DS.hasExplicitSpecifier()) 6112 Diag(DS.getExplicitSpecLoc(), 6113 diag::err_explicit_non_function); 6114 6115 if (DS.isNoreturnSpecified()) 6116 Diag(DS.getNoreturnSpecLoc(), 6117 diag::err_noreturn_non_function); 6118 } 6119 6120 NamedDecl* 6121 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6122 TypeSourceInfo *TInfo, LookupResult &Previous) { 6123 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6124 if (D.getCXXScopeSpec().isSet()) { 6125 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6126 << D.getCXXScopeSpec().getRange(); 6127 D.setInvalidType(); 6128 // Pretend we didn't see the scope specifier. 6129 DC = CurContext; 6130 Previous.clear(); 6131 } 6132 6133 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6134 6135 if (D.getDeclSpec().isInlineSpecified()) 6136 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6137 << getLangOpts().CPlusPlus17; 6138 if (D.getDeclSpec().hasConstexprSpecifier()) 6139 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6140 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6141 6142 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6143 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6144 Diag(D.getName().StartLocation, 6145 diag::err_deduction_guide_invalid_specifier) 6146 << "typedef"; 6147 else 6148 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6149 << D.getName().getSourceRange(); 6150 return nullptr; 6151 } 6152 6153 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6154 if (!NewTD) return nullptr; 6155 6156 // Handle attributes prior to checking for duplicates in MergeVarDecl 6157 ProcessDeclAttributes(S, NewTD, D); 6158 6159 CheckTypedefForVariablyModifiedType(S, NewTD); 6160 6161 bool Redeclaration = D.isRedeclaration(); 6162 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6163 D.setRedeclaration(Redeclaration); 6164 return ND; 6165 } 6166 6167 void 6168 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6169 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6170 // then it shall have block scope. 6171 // Note that variably modified types must be fixed before merging the decl so 6172 // that redeclarations will match. 6173 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6174 QualType T = TInfo->getType(); 6175 if (T->isVariablyModifiedType()) { 6176 setFunctionHasBranchProtectedScope(); 6177 6178 if (S->getFnParent() == nullptr) { 6179 bool SizeIsNegative; 6180 llvm::APSInt Oversized; 6181 TypeSourceInfo *FixedTInfo = 6182 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6183 SizeIsNegative, 6184 Oversized); 6185 if (FixedTInfo) { 6186 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6187 NewTD->setTypeSourceInfo(FixedTInfo); 6188 } else { 6189 if (SizeIsNegative) 6190 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6191 else if (T->isVariableArrayType()) 6192 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6193 else if (Oversized.getBoolValue()) 6194 Diag(NewTD->getLocation(), diag::err_array_too_large) 6195 << Oversized.toString(10); 6196 else 6197 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6198 NewTD->setInvalidDecl(); 6199 } 6200 } 6201 } 6202 } 6203 6204 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6205 /// declares a typedef-name, either using the 'typedef' type specifier or via 6206 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6207 NamedDecl* 6208 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6209 LookupResult &Previous, bool &Redeclaration) { 6210 6211 // Find the shadowed declaration before filtering for scope. 6212 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6213 6214 // Merge the decl with the existing one if appropriate. If the decl is 6215 // in an outer scope, it isn't the same thing. 6216 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6217 /*AllowInlineNamespace*/false); 6218 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6219 if (!Previous.empty()) { 6220 Redeclaration = true; 6221 MergeTypedefNameDecl(S, NewTD, Previous); 6222 } else { 6223 inferGslPointerAttribute(NewTD); 6224 } 6225 6226 if (ShadowedDecl && !Redeclaration) 6227 CheckShadow(NewTD, ShadowedDecl, Previous); 6228 6229 // If this is the C FILE type, notify the AST context. 6230 if (IdentifierInfo *II = NewTD->getIdentifier()) 6231 if (!NewTD->isInvalidDecl() && 6232 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6233 if (II->isStr("FILE")) 6234 Context.setFILEDecl(NewTD); 6235 else if (II->isStr("jmp_buf")) 6236 Context.setjmp_bufDecl(NewTD); 6237 else if (II->isStr("sigjmp_buf")) 6238 Context.setsigjmp_bufDecl(NewTD); 6239 else if (II->isStr("ucontext_t")) 6240 Context.setucontext_tDecl(NewTD); 6241 } 6242 6243 return NewTD; 6244 } 6245 6246 /// Determines whether the given declaration is an out-of-scope 6247 /// previous declaration. 6248 /// 6249 /// This routine should be invoked when name lookup has found a 6250 /// previous declaration (PrevDecl) that is not in the scope where a 6251 /// new declaration by the same name is being introduced. If the new 6252 /// declaration occurs in a local scope, previous declarations with 6253 /// linkage may still be considered previous declarations (C99 6254 /// 6.2.2p4-5, C++ [basic.link]p6). 6255 /// 6256 /// \param PrevDecl the previous declaration found by name 6257 /// lookup 6258 /// 6259 /// \param DC the context in which the new declaration is being 6260 /// declared. 6261 /// 6262 /// \returns true if PrevDecl is an out-of-scope previous declaration 6263 /// for a new delcaration with the same name. 6264 static bool 6265 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6266 ASTContext &Context) { 6267 if (!PrevDecl) 6268 return false; 6269 6270 if (!PrevDecl->hasLinkage()) 6271 return false; 6272 6273 if (Context.getLangOpts().CPlusPlus) { 6274 // C++ [basic.link]p6: 6275 // If there is a visible declaration of an entity with linkage 6276 // having the same name and type, ignoring entities declared 6277 // outside the innermost enclosing namespace scope, the block 6278 // scope declaration declares that same entity and receives the 6279 // linkage of the previous declaration. 6280 DeclContext *OuterContext = DC->getRedeclContext(); 6281 if (!OuterContext->isFunctionOrMethod()) 6282 // This rule only applies to block-scope declarations. 6283 return false; 6284 6285 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6286 if (PrevOuterContext->isRecord()) 6287 // We found a member function: ignore it. 6288 return false; 6289 6290 // Find the innermost enclosing namespace for the new and 6291 // previous declarations. 6292 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6293 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6294 6295 // The previous declaration is in a different namespace, so it 6296 // isn't the same function. 6297 if (!OuterContext->Equals(PrevOuterContext)) 6298 return false; 6299 } 6300 6301 return true; 6302 } 6303 6304 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6305 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6306 if (!SS.isSet()) return; 6307 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6308 } 6309 6310 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6311 QualType type = decl->getType(); 6312 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6313 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6314 // Various kinds of declaration aren't allowed to be __autoreleasing. 6315 unsigned kind = -1U; 6316 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6317 if (var->hasAttr<BlocksAttr>()) 6318 kind = 0; // __block 6319 else if (!var->hasLocalStorage()) 6320 kind = 1; // global 6321 } else if (isa<ObjCIvarDecl>(decl)) { 6322 kind = 3; // ivar 6323 } else if (isa<FieldDecl>(decl)) { 6324 kind = 2; // field 6325 } 6326 6327 if (kind != -1U) { 6328 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6329 << kind; 6330 } 6331 } else if (lifetime == Qualifiers::OCL_None) { 6332 // Try to infer lifetime. 6333 if (!type->isObjCLifetimeType()) 6334 return false; 6335 6336 lifetime = type->getObjCARCImplicitLifetime(); 6337 type = Context.getLifetimeQualifiedType(type, lifetime); 6338 decl->setType(type); 6339 } 6340 6341 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6342 // Thread-local variables cannot have lifetime. 6343 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6344 var->getTLSKind()) { 6345 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6346 << var->getType(); 6347 return true; 6348 } 6349 } 6350 6351 return false; 6352 } 6353 6354 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6355 if (Decl->getType().hasAddressSpace()) 6356 return; 6357 if (Decl->getType()->isDependentType()) 6358 return; 6359 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6360 QualType Type = Var->getType(); 6361 if (Type->isSamplerT() || Type->isVoidType()) 6362 return; 6363 LangAS ImplAS = LangAS::opencl_private; 6364 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6365 Var->hasGlobalStorage()) 6366 ImplAS = LangAS::opencl_global; 6367 // If the original type from a decayed type is an array type and that array 6368 // type has no address space yet, deduce it now. 6369 if (auto DT = dyn_cast<DecayedType>(Type)) { 6370 auto OrigTy = DT->getOriginalType(); 6371 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6372 // Add the address space to the original array type and then propagate 6373 // that to the element type through `getAsArrayType`. 6374 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6375 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6376 // Re-generate the decayed type. 6377 Type = Context.getDecayedType(OrigTy); 6378 } 6379 } 6380 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6381 // Apply any qualifiers (including address space) from the array type to 6382 // the element type. This implements C99 6.7.3p8: "If the specification of 6383 // an array type includes any type qualifiers, the element type is so 6384 // qualified, not the array type." 6385 if (Type->isArrayType()) 6386 Type = QualType(Context.getAsArrayType(Type), 0); 6387 Decl->setType(Type); 6388 } 6389 } 6390 6391 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6392 // Ensure that an auto decl is deduced otherwise the checks below might cache 6393 // the wrong linkage. 6394 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6395 6396 // 'weak' only applies to declarations with external linkage. 6397 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6398 if (!ND.isExternallyVisible()) { 6399 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6400 ND.dropAttr<WeakAttr>(); 6401 } 6402 } 6403 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6404 if (ND.isExternallyVisible()) { 6405 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6406 ND.dropAttr<WeakRefAttr>(); 6407 ND.dropAttr<AliasAttr>(); 6408 } 6409 } 6410 6411 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6412 if (VD->hasInit()) { 6413 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6414 assert(VD->isThisDeclarationADefinition() && 6415 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6416 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6417 VD->dropAttr<AliasAttr>(); 6418 } 6419 } 6420 } 6421 6422 // 'selectany' only applies to externally visible variable declarations. 6423 // It does not apply to functions. 6424 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6425 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6426 S.Diag(Attr->getLocation(), 6427 diag::err_attribute_selectany_non_extern_data); 6428 ND.dropAttr<SelectAnyAttr>(); 6429 } 6430 } 6431 6432 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6433 auto *VD = dyn_cast<VarDecl>(&ND); 6434 bool IsAnonymousNS = false; 6435 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6436 if (VD) { 6437 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6438 while (NS && !IsAnonymousNS) { 6439 IsAnonymousNS = NS->isAnonymousNamespace(); 6440 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6441 } 6442 } 6443 // dll attributes require external linkage. Static locals may have external 6444 // linkage but still cannot be explicitly imported or exported. 6445 // In Microsoft mode, a variable defined in anonymous namespace must have 6446 // external linkage in order to be exported. 6447 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6448 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6449 (!AnonNSInMicrosoftMode && 6450 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6451 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6452 << &ND << Attr; 6453 ND.setInvalidDecl(); 6454 } 6455 } 6456 6457 // Check the attributes on the function type, if any. 6458 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6459 // Don't declare this variable in the second operand of the for-statement; 6460 // GCC miscompiles that by ending its lifetime before evaluating the 6461 // third operand. See gcc.gnu.org/PR86769. 6462 AttributedTypeLoc ATL; 6463 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6464 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6465 TL = ATL.getModifiedLoc()) { 6466 // The [[lifetimebound]] attribute can be applied to the implicit object 6467 // parameter of a non-static member function (other than a ctor or dtor) 6468 // by applying it to the function type. 6469 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6470 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6471 if (!MD || MD->isStatic()) { 6472 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6473 << !MD << A->getRange(); 6474 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6475 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6476 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6477 } 6478 } 6479 } 6480 } 6481 } 6482 6483 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6484 NamedDecl *NewDecl, 6485 bool IsSpecialization, 6486 bool IsDefinition) { 6487 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6488 return; 6489 6490 bool IsTemplate = false; 6491 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6492 OldDecl = OldTD->getTemplatedDecl(); 6493 IsTemplate = true; 6494 if (!IsSpecialization) 6495 IsDefinition = false; 6496 } 6497 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6498 NewDecl = NewTD->getTemplatedDecl(); 6499 IsTemplate = true; 6500 } 6501 6502 if (!OldDecl || !NewDecl) 6503 return; 6504 6505 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6506 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6507 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6508 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6509 6510 // dllimport and dllexport are inheritable attributes so we have to exclude 6511 // inherited attribute instances. 6512 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6513 (NewExportAttr && !NewExportAttr->isInherited()); 6514 6515 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6516 // the only exception being explicit specializations. 6517 // Implicitly generated declarations are also excluded for now because there 6518 // is no other way to switch these to use dllimport or dllexport. 6519 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6520 6521 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6522 // Allow with a warning for free functions and global variables. 6523 bool JustWarn = false; 6524 if (!OldDecl->isCXXClassMember()) { 6525 auto *VD = dyn_cast<VarDecl>(OldDecl); 6526 if (VD && !VD->getDescribedVarTemplate()) 6527 JustWarn = true; 6528 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6529 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6530 JustWarn = true; 6531 } 6532 6533 // We cannot change a declaration that's been used because IR has already 6534 // been emitted. Dllimported functions will still work though (modulo 6535 // address equality) as they can use the thunk. 6536 if (OldDecl->isUsed()) 6537 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6538 JustWarn = false; 6539 6540 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6541 : diag::err_attribute_dll_redeclaration; 6542 S.Diag(NewDecl->getLocation(), DiagID) 6543 << NewDecl 6544 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6545 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6546 if (!JustWarn) { 6547 NewDecl->setInvalidDecl(); 6548 return; 6549 } 6550 } 6551 6552 // A redeclaration is not allowed to drop a dllimport attribute, the only 6553 // exceptions being inline function definitions (except for function 6554 // templates), local extern declarations, qualified friend declarations or 6555 // special MSVC extension: in the last case, the declaration is treated as if 6556 // it were marked dllexport. 6557 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6558 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 6559 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6560 // Ignore static data because out-of-line definitions are diagnosed 6561 // separately. 6562 IsStaticDataMember = VD->isStaticDataMember(); 6563 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6564 VarDecl::DeclarationOnly; 6565 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6566 IsInline = FD->isInlined(); 6567 IsQualifiedFriend = FD->getQualifier() && 6568 FD->getFriendObjectKind() == Decl::FOK_Declared; 6569 } 6570 6571 if (OldImportAttr && !HasNewAttr && 6572 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 6573 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6574 if (IsMicrosoftABI && IsDefinition) { 6575 S.Diag(NewDecl->getLocation(), 6576 diag::warn_redeclaration_without_import_attribute) 6577 << NewDecl; 6578 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6579 NewDecl->dropAttr<DLLImportAttr>(); 6580 NewDecl->addAttr( 6581 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6582 } else { 6583 S.Diag(NewDecl->getLocation(), 6584 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6585 << NewDecl << OldImportAttr; 6586 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6587 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6588 OldDecl->dropAttr<DLLImportAttr>(); 6589 NewDecl->dropAttr<DLLImportAttr>(); 6590 } 6591 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 6592 // In MinGW, seeing a function declared inline drops the dllimport 6593 // attribute. 6594 OldDecl->dropAttr<DLLImportAttr>(); 6595 NewDecl->dropAttr<DLLImportAttr>(); 6596 S.Diag(NewDecl->getLocation(), 6597 diag::warn_dllimport_dropped_from_inline_function) 6598 << NewDecl << OldImportAttr; 6599 } 6600 6601 // A specialization of a class template member function is processed here 6602 // since it's a redeclaration. If the parent class is dllexport, the 6603 // specialization inherits that attribute. This doesn't happen automatically 6604 // since the parent class isn't instantiated until later. 6605 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6606 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6607 !NewImportAttr && !NewExportAttr) { 6608 if (const DLLExportAttr *ParentExportAttr = 6609 MD->getParent()->getAttr<DLLExportAttr>()) { 6610 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6611 NewAttr->setInherited(true); 6612 NewDecl->addAttr(NewAttr); 6613 } 6614 } 6615 } 6616 } 6617 6618 /// Given that we are within the definition of the given function, 6619 /// will that definition behave like C99's 'inline', where the 6620 /// definition is discarded except for optimization purposes? 6621 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6622 // Try to avoid calling GetGVALinkageForFunction. 6623 6624 // All cases of this require the 'inline' keyword. 6625 if (!FD->isInlined()) return false; 6626 6627 // This is only possible in C++ with the gnu_inline attribute. 6628 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6629 return false; 6630 6631 // Okay, go ahead and call the relatively-more-expensive function. 6632 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6633 } 6634 6635 /// Determine whether a variable is extern "C" prior to attaching 6636 /// an initializer. We can't just call isExternC() here, because that 6637 /// will also compute and cache whether the declaration is externally 6638 /// visible, which might change when we attach the initializer. 6639 /// 6640 /// This can only be used if the declaration is known to not be a 6641 /// redeclaration of an internal linkage declaration. 6642 /// 6643 /// For instance: 6644 /// 6645 /// auto x = []{}; 6646 /// 6647 /// Attaching the initializer here makes this declaration not externally 6648 /// visible, because its type has internal linkage. 6649 /// 6650 /// FIXME: This is a hack. 6651 template<typename T> 6652 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6653 if (S.getLangOpts().CPlusPlus) { 6654 // In C++, the overloadable attribute negates the effects of extern "C". 6655 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6656 return false; 6657 6658 // So do CUDA's host/device attributes. 6659 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6660 D->template hasAttr<CUDAHostAttr>())) 6661 return false; 6662 } 6663 return D->isExternC(); 6664 } 6665 6666 static bool shouldConsiderLinkage(const VarDecl *VD) { 6667 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6668 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6669 isa<OMPDeclareMapperDecl>(DC)) 6670 return VD->hasExternalStorage(); 6671 if (DC->isFileContext()) 6672 return true; 6673 if (DC->isRecord()) 6674 return false; 6675 if (isa<RequiresExprBodyDecl>(DC)) 6676 return false; 6677 llvm_unreachable("Unexpected context"); 6678 } 6679 6680 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6681 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6682 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6683 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6684 return true; 6685 if (DC->isRecord()) 6686 return false; 6687 llvm_unreachable("Unexpected context"); 6688 } 6689 6690 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6691 ParsedAttr::Kind Kind) { 6692 // Check decl attributes on the DeclSpec. 6693 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6694 return true; 6695 6696 // Walk the declarator structure, checking decl attributes that were in a type 6697 // position to the decl itself. 6698 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6699 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6700 return true; 6701 } 6702 6703 // Finally, check attributes on the decl itself. 6704 return PD.getAttributes().hasAttribute(Kind); 6705 } 6706 6707 /// Adjust the \c DeclContext for a function or variable that might be a 6708 /// function-local external declaration. 6709 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6710 if (!DC->isFunctionOrMethod()) 6711 return false; 6712 6713 // If this is a local extern function or variable declared within a function 6714 // template, don't add it into the enclosing namespace scope until it is 6715 // instantiated; it might have a dependent type right now. 6716 if (DC->isDependentContext()) 6717 return true; 6718 6719 // C++11 [basic.link]p7: 6720 // When a block scope declaration of an entity with linkage is not found to 6721 // refer to some other declaration, then that entity is a member of the 6722 // innermost enclosing namespace. 6723 // 6724 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6725 // semantically-enclosing namespace, not a lexically-enclosing one. 6726 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6727 DC = DC->getParent(); 6728 return true; 6729 } 6730 6731 /// Returns true if given declaration has external C language linkage. 6732 static bool isDeclExternC(const Decl *D) { 6733 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6734 return FD->isExternC(); 6735 if (const auto *VD = dyn_cast<VarDecl>(D)) 6736 return VD->isExternC(); 6737 6738 llvm_unreachable("Unknown type of decl!"); 6739 } 6740 6741 /// Returns true if there hasn't been any invalid type diagnosed. 6742 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { 6743 DeclContext *DC = NewVD->getDeclContext(); 6744 QualType R = NewVD->getType(); 6745 6746 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6747 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6748 // argument. 6749 if (R->isImageType() || R->isPipeType()) { 6750 Se.Diag(NewVD->getLocation(), 6751 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6752 << R; 6753 NewVD->setInvalidDecl(); 6754 return false; 6755 } 6756 6757 // OpenCL v1.2 s6.9.r: 6758 // The event type cannot be used to declare a program scope variable. 6759 // OpenCL v2.0 s6.9.q: 6760 // The clk_event_t and reserve_id_t types cannot be declared in program 6761 // scope. 6762 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { 6763 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6764 Se.Diag(NewVD->getLocation(), 6765 diag::err_invalid_type_for_program_scope_var) 6766 << R; 6767 NewVD->setInvalidDecl(); 6768 return false; 6769 } 6770 } 6771 6772 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6773 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 6774 Se.getLangOpts())) { 6775 QualType NR = R.getCanonicalType(); 6776 while (NR->isPointerType() || NR->isMemberFunctionPointerType() || 6777 NR->isReferenceType()) { 6778 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || 6779 NR->isFunctionReferenceType()) { 6780 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer) 6781 << NR->isReferenceType(); 6782 NewVD->setInvalidDecl(); 6783 return false; 6784 } 6785 NR = NR->getPointeeType(); 6786 } 6787 } 6788 6789 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 6790 Se.getLangOpts())) { 6791 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6792 // half array type (unless the cl_khr_fp16 extension is enabled). 6793 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6794 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R; 6795 NewVD->setInvalidDecl(); 6796 return false; 6797 } 6798 } 6799 6800 // OpenCL v1.2 s6.9.r: 6801 // The event type cannot be used with the __local, __constant and __global 6802 // address space qualifiers. 6803 if (R->isEventT()) { 6804 if (R.getAddressSpace() != LangAS::opencl_private) { 6805 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual); 6806 NewVD->setInvalidDecl(); 6807 return false; 6808 } 6809 } 6810 6811 if (R->isSamplerT()) { 6812 // OpenCL v1.2 s6.9.b p4: 6813 // The sampler type cannot be used with the __local and __global address 6814 // space qualifiers. 6815 if (R.getAddressSpace() == LangAS::opencl_local || 6816 R.getAddressSpace() == LangAS::opencl_global) { 6817 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace); 6818 NewVD->setInvalidDecl(); 6819 } 6820 6821 // OpenCL v1.2 s6.12.14.1: 6822 // A global sampler must be declared with either the constant address 6823 // space qualifier or with the const qualifier. 6824 if (DC->isTranslationUnit() && 6825 !(R.getAddressSpace() == LangAS::opencl_constant || 6826 R.isConstQualified())) { 6827 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler); 6828 NewVD->setInvalidDecl(); 6829 } 6830 if (NewVD->isInvalidDecl()) 6831 return false; 6832 } 6833 6834 return true; 6835 } 6836 6837 template <typename AttrTy> 6838 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { 6839 const TypedefNameDecl *TND = TT->getDecl(); 6840 if (const auto *Attribute = TND->getAttr<AttrTy>()) { 6841 AttrTy *Clone = Attribute->clone(S.Context); 6842 Clone->setInherited(true); 6843 D->addAttr(Clone); 6844 } 6845 } 6846 6847 NamedDecl *Sema::ActOnVariableDeclarator( 6848 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6849 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6850 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6851 QualType R = TInfo->getType(); 6852 DeclarationName Name = GetNameForDeclarator(D).getName(); 6853 6854 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6855 6856 if (D.isDecompositionDeclarator()) { 6857 // Take the name of the first declarator as our name for diagnostic 6858 // purposes. 6859 auto &Decomp = D.getDecompositionDeclarator(); 6860 if (!Decomp.bindings().empty()) { 6861 II = Decomp.bindings()[0].Name; 6862 Name = II; 6863 } 6864 } else if (!II) { 6865 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6866 return nullptr; 6867 } 6868 6869 6870 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6871 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6872 6873 // dllimport globals without explicit storage class are treated as extern. We 6874 // have to change the storage class this early to get the right DeclContext. 6875 if (SC == SC_None && !DC->isRecord() && 6876 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6877 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6878 SC = SC_Extern; 6879 6880 DeclContext *OriginalDC = DC; 6881 bool IsLocalExternDecl = SC == SC_Extern && 6882 adjustContextForLocalExternDecl(DC); 6883 6884 if (SCSpec == DeclSpec::SCS_mutable) { 6885 // mutable can only appear on non-static class members, so it's always 6886 // an error here 6887 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6888 D.setInvalidType(); 6889 SC = SC_None; 6890 } 6891 6892 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6893 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6894 D.getDeclSpec().getStorageClassSpecLoc())) { 6895 // In C++11, the 'register' storage class specifier is deprecated. 6896 // Suppress the warning in system macros, it's used in macros in some 6897 // popular C system headers, such as in glibc's htonl() macro. 6898 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6899 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6900 : diag::warn_deprecated_register) 6901 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6902 } 6903 6904 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6905 6906 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6907 // C99 6.9p2: The storage-class specifiers auto and register shall not 6908 // appear in the declaration specifiers in an external declaration. 6909 // Global Register+Asm is a GNU extension we support. 6910 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6911 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6912 D.setInvalidType(); 6913 } 6914 } 6915 6916 // If this variable has a VLA type and an initializer, try to 6917 // fold to a constant-sized type. This is otherwise invalid. 6918 if (D.hasInitializer() && R->isVariableArrayType()) 6919 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(), 6920 /*DiagID=*/0); 6921 6922 bool IsMemberSpecialization = false; 6923 bool IsVariableTemplateSpecialization = false; 6924 bool IsPartialSpecialization = false; 6925 bool IsVariableTemplate = false; 6926 VarDecl *NewVD = nullptr; 6927 VarTemplateDecl *NewTemplate = nullptr; 6928 TemplateParameterList *TemplateParams = nullptr; 6929 if (!getLangOpts().CPlusPlus) { 6930 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6931 II, R, TInfo, SC); 6932 6933 if (R->getContainedDeducedType()) 6934 ParsingInitForAutoVars.insert(NewVD); 6935 6936 if (D.isInvalidType()) 6937 NewVD->setInvalidDecl(); 6938 6939 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6940 NewVD->hasLocalStorage()) 6941 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6942 NTCUC_AutoVar, NTCUK_Destruct); 6943 } else { 6944 bool Invalid = false; 6945 6946 if (DC->isRecord() && !CurContext->isRecord()) { 6947 // This is an out-of-line definition of a static data member. 6948 switch (SC) { 6949 case SC_None: 6950 break; 6951 case SC_Static: 6952 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6953 diag::err_static_out_of_line) 6954 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6955 break; 6956 case SC_Auto: 6957 case SC_Register: 6958 case SC_Extern: 6959 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6960 // to names of variables declared in a block or to function parameters. 6961 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6962 // of class members 6963 6964 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6965 diag::err_storage_class_for_static_member) 6966 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6967 break; 6968 case SC_PrivateExtern: 6969 llvm_unreachable("C storage class in c++!"); 6970 } 6971 } 6972 6973 if (SC == SC_Static && CurContext->isRecord()) { 6974 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6975 // Walk up the enclosing DeclContexts to check for any that are 6976 // incompatible with static data members. 6977 const DeclContext *FunctionOrMethod = nullptr; 6978 const CXXRecordDecl *AnonStruct = nullptr; 6979 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 6980 if (Ctxt->isFunctionOrMethod()) { 6981 FunctionOrMethod = Ctxt; 6982 break; 6983 } 6984 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 6985 if (ParentDecl && !ParentDecl->getDeclName()) { 6986 AnonStruct = ParentDecl; 6987 break; 6988 } 6989 } 6990 if (FunctionOrMethod) { 6991 // C++ [class.static.data]p5: A local class shall not have static data 6992 // members. 6993 Diag(D.getIdentifierLoc(), 6994 diag::err_static_data_member_not_allowed_in_local_class) 6995 << Name << RD->getDeclName() << RD->getTagKind(); 6996 } else if (AnonStruct) { 6997 // C++ [class.static.data]p4: Unnamed classes and classes contained 6998 // directly or indirectly within unnamed classes shall not contain 6999 // static data members. 7000 Diag(D.getIdentifierLoc(), 7001 diag::err_static_data_member_not_allowed_in_anon_struct) 7002 << Name << AnonStruct->getTagKind(); 7003 Invalid = true; 7004 } else if (RD->isUnion()) { 7005 // C++98 [class.union]p1: If a union contains a static data member, 7006 // the program is ill-formed. C++11 drops this restriction. 7007 Diag(D.getIdentifierLoc(), 7008 getLangOpts().CPlusPlus11 7009 ? diag::warn_cxx98_compat_static_data_member_in_union 7010 : diag::ext_static_data_member_in_union) << Name; 7011 } 7012 } 7013 } 7014 7015 // Match up the template parameter lists with the scope specifier, then 7016 // determine whether we have a template or a template specialization. 7017 bool InvalidScope = false; 7018 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7019 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7020 D.getCXXScopeSpec(), 7021 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7022 ? D.getName().TemplateId 7023 : nullptr, 7024 TemplateParamLists, 7025 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7026 Invalid |= InvalidScope; 7027 7028 if (TemplateParams) { 7029 if (!TemplateParams->size() && 7030 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7031 // There is an extraneous 'template<>' for this variable. Complain 7032 // about it, but allow the declaration of the variable. 7033 Diag(TemplateParams->getTemplateLoc(), 7034 diag::err_template_variable_noparams) 7035 << II 7036 << SourceRange(TemplateParams->getTemplateLoc(), 7037 TemplateParams->getRAngleLoc()); 7038 TemplateParams = nullptr; 7039 } else { 7040 // Check that we can declare a template here. 7041 if (CheckTemplateDeclScope(S, TemplateParams)) 7042 return nullptr; 7043 7044 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7045 // This is an explicit specialization or a partial specialization. 7046 IsVariableTemplateSpecialization = true; 7047 IsPartialSpecialization = TemplateParams->size() > 0; 7048 } else { // if (TemplateParams->size() > 0) 7049 // This is a template declaration. 7050 IsVariableTemplate = true; 7051 7052 // Only C++1y supports variable templates (N3651). 7053 Diag(D.getIdentifierLoc(), 7054 getLangOpts().CPlusPlus14 7055 ? diag::warn_cxx11_compat_variable_template 7056 : diag::ext_variable_template); 7057 } 7058 } 7059 } else { 7060 // Check that we can declare a member specialization here. 7061 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7062 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7063 return nullptr; 7064 assert((Invalid || 7065 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7066 "should have a 'template<>' for this decl"); 7067 } 7068 7069 if (IsVariableTemplateSpecialization) { 7070 SourceLocation TemplateKWLoc = 7071 TemplateParamLists.size() > 0 7072 ? TemplateParamLists[0]->getTemplateLoc() 7073 : SourceLocation(); 7074 DeclResult Res = ActOnVarTemplateSpecialization( 7075 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7076 IsPartialSpecialization); 7077 if (Res.isInvalid()) 7078 return nullptr; 7079 NewVD = cast<VarDecl>(Res.get()); 7080 AddToScope = false; 7081 } else if (D.isDecompositionDeclarator()) { 7082 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7083 D.getIdentifierLoc(), R, TInfo, SC, 7084 Bindings); 7085 } else 7086 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7087 D.getIdentifierLoc(), II, R, TInfo, SC); 7088 7089 // If this is supposed to be a variable template, create it as such. 7090 if (IsVariableTemplate) { 7091 NewTemplate = 7092 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7093 TemplateParams, NewVD); 7094 NewVD->setDescribedVarTemplate(NewTemplate); 7095 } 7096 7097 // If this decl has an auto type in need of deduction, make a note of the 7098 // Decl so we can diagnose uses of it in its own initializer. 7099 if (R->getContainedDeducedType()) 7100 ParsingInitForAutoVars.insert(NewVD); 7101 7102 if (D.isInvalidType() || Invalid) { 7103 NewVD->setInvalidDecl(); 7104 if (NewTemplate) 7105 NewTemplate->setInvalidDecl(); 7106 } 7107 7108 SetNestedNameSpecifier(*this, NewVD, D); 7109 7110 // If we have any template parameter lists that don't directly belong to 7111 // the variable (matching the scope specifier), store them. 7112 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7113 if (TemplateParamLists.size() > VDTemplateParamLists) 7114 NewVD->setTemplateParameterListsInfo( 7115 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7116 } 7117 7118 if (D.getDeclSpec().isInlineSpecified()) { 7119 if (!getLangOpts().CPlusPlus) { 7120 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7121 << 0; 7122 } else if (CurContext->isFunctionOrMethod()) { 7123 // 'inline' is not allowed on block scope variable declaration. 7124 Diag(D.getDeclSpec().getInlineSpecLoc(), 7125 diag::err_inline_declaration_block_scope) << Name 7126 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7127 } else { 7128 Diag(D.getDeclSpec().getInlineSpecLoc(), 7129 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7130 : diag::ext_inline_variable); 7131 NewVD->setInlineSpecified(); 7132 } 7133 } 7134 7135 // Set the lexical context. If the declarator has a C++ scope specifier, the 7136 // lexical context will be different from the semantic context. 7137 NewVD->setLexicalDeclContext(CurContext); 7138 if (NewTemplate) 7139 NewTemplate->setLexicalDeclContext(CurContext); 7140 7141 if (IsLocalExternDecl) { 7142 if (D.isDecompositionDeclarator()) 7143 for (auto *B : Bindings) 7144 B->setLocalExternDecl(); 7145 else 7146 NewVD->setLocalExternDecl(); 7147 } 7148 7149 bool EmitTLSUnsupportedError = false; 7150 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7151 // C++11 [dcl.stc]p4: 7152 // When thread_local is applied to a variable of block scope the 7153 // storage-class-specifier static is implied if it does not appear 7154 // explicitly. 7155 // Core issue: 'static' is not implied if the variable is declared 7156 // 'extern'. 7157 if (NewVD->hasLocalStorage() && 7158 (SCSpec != DeclSpec::SCS_unspecified || 7159 TSCS != DeclSpec::TSCS_thread_local || 7160 !DC->isFunctionOrMethod())) 7161 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7162 diag::err_thread_non_global) 7163 << DeclSpec::getSpecifierName(TSCS); 7164 else if (!Context.getTargetInfo().isTLSSupported()) { 7165 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7166 getLangOpts().SYCLIsDevice) { 7167 // Postpone error emission until we've collected attributes required to 7168 // figure out whether it's a host or device variable and whether the 7169 // error should be ignored. 7170 EmitTLSUnsupportedError = true; 7171 // We still need to mark the variable as TLS so it shows up in AST with 7172 // proper storage class for other tools to use even if we're not going 7173 // to emit any code for it. 7174 NewVD->setTSCSpec(TSCS); 7175 } else 7176 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7177 diag::err_thread_unsupported); 7178 } else 7179 NewVD->setTSCSpec(TSCS); 7180 } 7181 7182 switch (D.getDeclSpec().getConstexprSpecifier()) { 7183 case ConstexprSpecKind::Unspecified: 7184 break; 7185 7186 case ConstexprSpecKind::Consteval: 7187 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7188 diag::err_constexpr_wrong_decl_kind) 7189 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7190 LLVM_FALLTHROUGH; 7191 7192 case ConstexprSpecKind::Constexpr: 7193 NewVD->setConstexpr(true); 7194 MaybeAddCUDAConstantAttr(NewVD); 7195 // C++1z [dcl.spec.constexpr]p1: 7196 // A static data member declared with the constexpr specifier is 7197 // implicitly an inline variable. 7198 if (NewVD->isStaticDataMember() && 7199 (getLangOpts().CPlusPlus17 || 7200 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7201 NewVD->setImplicitlyInline(); 7202 break; 7203 7204 case ConstexprSpecKind::Constinit: 7205 if (!NewVD->hasGlobalStorage()) 7206 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7207 diag::err_constinit_local_variable); 7208 else 7209 NewVD->addAttr(ConstInitAttr::Create( 7210 Context, D.getDeclSpec().getConstexprSpecLoc(), 7211 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7212 break; 7213 } 7214 7215 // C99 6.7.4p3 7216 // An inline definition of a function with external linkage shall 7217 // not contain a definition of a modifiable object with static or 7218 // thread storage duration... 7219 // We only apply this when the function is required to be defined 7220 // elsewhere, i.e. when the function is not 'extern inline'. Note 7221 // that a local variable with thread storage duration still has to 7222 // be marked 'static'. Also note that it's possible to get these 7223 // semantics in C++ using __attribute__((gnu_inline)). 7224 if (SC == SC_Static && S->getFnParent() != nullptr && 7225 !NewVD->getType().isConstQualified()) { 7226 FunctionDecl *CurFD = getCurFunctionDecl(); 7227 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7228 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7229 diag::warn_static_local_in_extern_inline); 7230 MaybeSuggestAddingStaticToDecl(CurFD); 7231 } 7232 } 7233 7234 if (D.getDeclSpec().isModulePrivateSpecified()) { 7235 if (IsVariableTemplateSpecialization) 7236 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7237 << (IsPartialSpecialization ? 1 : 0) 7238 << FixItHint::CreateRemoval( 7239 D.getDeclSpec().getModulePrivateSpecLoc()); 7240 else if (IsMemberSpecialization) 7241 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7242 << 2 7243 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7244 else if (NewVD->hasLocalStorage()) 7245 Diag(NewVD->getLocation(), diag::err_module_private_local) 7246 << 0 << NewVD 7247 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7248 << FixItHint::CreateRemoval( 7249 D.getDeclSpec().getModulePrivateSpecLoc()); 7250 else { 7251 NewVD->setModulePrivate(); 7252 if (NewTemplate) 7253 NewTemplate->setModulePrivate(); 7254 for (auto *B : Bindings) 7255 B->setModulePrivate(); 7256 } 7257 } 7258 7259 if (getLangOpts().OpenCL) { 7260 deduceOpenCLAddressSpace(NewVD); 7261 7262 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 7263 if (TSC != TSCS_unspecified) { 7264 bool IsCXX = getLangOpts().OpenCLCPlusPlus; 7265 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7266 diag::err_opencl_unknown_type_specifier) 7267 << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString() 7268 << DeclSpec::getSpecifierName(TSC) << 1; 7269 NewVD->setInvalidDecl(); 7270 } 7271 } 7272 7273 // Handle attributes prior to checking for duplicates in MergeVarDecl 7274 ProcessDeclAttributes(S, NewVD, D); 7275 7276 // FIXME: This is probably the wrong location to be doing this and we should 7277 // probably be doing this for more attributes (especially for function 7278 // pointer attributes such as format, warn_unused_result, etc.). Ideally 7279 // the code to copy attributes would be generated by TableGen. 7280 if (R->isFunctionPointerType()) 7281 if (const auto *TT = R->getAs<TypedefType>()) 7282 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT); 7283 7284 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7285 getLangOpts().SYCLIsDevice) { 7286 if (EmitTLSUnsupportedError && 7287 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7288 (getLangOpts().OpenMPIsDevice && 7289 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7290 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7291 diag::err_thread_unsupported); 7292 7293 if (EmitTLSUnsupportedError && 7294 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7295 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7296 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7297 // storage [duration]." 7298 if (SC == SC_None && S->getFnParent() != nullptr && 7299 (NewVD->hasAttr<CUDASharedAttr>() || 7300 NewVD->hasAttr<CUDAConstantAttr>())) { 7301 NewVD->setStorageClass(SC_Static); 7302 } 7303 } 7304 7305 // Ensure that dllimport globals without explicit storage class are treated as 7306 // extern. The storage class is set above using parsed attributes. Now we can 7307 // check the VarDecl itself. 7308 assert(!NewVD->hasAttr<DLLImportAttr>() || 7309 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7310 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7311 7312 // In auto-retain/release, infer strong retension for variables of 7313 // retainable type. 7314 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7315 NewVD->setInvalidDecl(); 7316 7317 // Handle GNU asm-label extension (encoded as an attribute). 7318 if (Expr *E = (Expr*)D.getAsmLabel()) { 7319 // The parser guarantees this is a string. 7320 StringLiteral *SE = cast<StringLiteral>(E); 7321 StringRef Label = SE->getString(); 7322 if (S->getFnParent() != nullptr) { 7323 switch (SC) { 7324 case SC_None: 7325 case SC_Auto: 7326 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7327 break; 7328 case SC_Register: 7329 // Local Named register 7330 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7331 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7332 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7333 break; 7334 case SC_Static: 7335 case SC_Extern: 7336 case SC_PrivateExtern: 7337 break; 7338 } 7339 } else if (SC == SC_Register) { 7340 // Global Named register 7341 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7342 const auto &TI = Context.getTargetInfo(); 7343 bool HasSizeMismatch; 7344 7345 if (!TI.isValidGCCRegisterName(Label)) 7346 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7347 else if (!TI.validateGlobalRegisterVariable(Label, 7348 Context.getTypeSize(R), 7349 HasSizeMismatch)) 7350 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7351 else if (HasSizeMismatch) 7352 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7353 } 7354 7355 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7356 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7357 NewVD->setInvalidDecl(true); 7358 } 7359 } 7360 7361 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7362 /*IsLiteralLabel=*/true, 7363 SE->getStrTokenLoc(0))); 7364 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7365 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7366 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7367 if (I != ExtnameUndeclaredIdentifiers.end()) { 7368 if (isDeclExternC(NewVD)) { 7369 NewVD->addAttr(I->second); 7370 ExtnameUndeclaredIdentifiers.erase(I); 7371 } else 7372 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7373 << /*Variable*/1 << NewVD; 7374 } 7375 } 7376 7377 // Find the shadowed declaration before filtering for scope. 7378 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7379 ? getShadowedDeclaration(NewVD, Previous) 7380 : nullptr; 7381 7382 // Don't consider existing declarations that are in a different 7383 // scope and are out-of-semantic-context declarations (if the new 7384 // declaration has linkage). 7385 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7386 D.getCXXScopeSpec().isNotEmpty() || 7387 IsMemberSpecialization || 7388 IsVariableTemplateSpecialization); 7389 7390 // Check whether the previous declaration is in the same block scope. This 7391 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7392 if (getLangOpts().CPlusPlus && 7393 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7394 NewVD->setPreviousDeclInSameBlockScope( 7395 Previous.isSingleResult() && !Previous.isShadowed() && 7396 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7397 7398 if (!getLangOpts().CPlusPlus) { 7399 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7400 } else { 7401 // If this is an explicit specialization of a static data member, check it. 7402 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7403 CheckMemberSpecialization(NewVD, Previous)) 7404 NewVD->setInvalidDecl(); 7405 7406 // Merge the decl with the existing one if appropriate. 7407 if (!Previous.empty()) { 7408 if (Previous.isSingleResult() && 7409 isa<FieldDecl>(Previous.getFoundDecl()) && 7410 D.getCXXScopeSpec().isSet()) { 7411 // The user tried to define a non-static data member 7412 // out-of-line (C++ [dcl.meaning]p1). 7413 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7414 << D.getCXXScopeSpec().getRange(); 7415 Previous.clear(); 7416 NewVD->setInvalidDecl(); 7417 } 7418 } else if (D.getCXXScopeSpec().isSet()) { 7419 // No previous declaration in the qualifying scope. 7420 Diag(D.getIdentifierLoc(), diag::err_no_member) 7421 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7422 << D.getCXXScopeSpec().getRange(); 7423 NewVD->setInvalidDecl(); 7424 } 7425 7426 if (!IsVariableTemplateSpecialization) 7427 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7428 7429 if (NewTemplate) { 7430 VarTemplateDecl *PrevVarTemplate = 7431 NewVD->getPreviousDecl() 7432 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7433 : nullptr; 7434 7435 // Check the template parameter list of this declaration, possibly 7436 // merging in the template parameter list from the previous variable 7437 // template declaration. 7438 if (CheckTemplateParameterList( 7439 TemplateParams, 7440 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7441 : nullptr, 7442 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7443 DC->isDependentContext()) 7444 ? TPC_ClassTemplateMember 7445 : TPC_VarTemplate)) 7446 NewVD->setInvalidDecl(); 7447 7448 // If we are providing an explicit specialization of a static variable 7449 // template, make a note of that. 7450 if (PrevVarTemplate && 7451 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7452 PrevVarTemplate->setMemberSpecialization(); 7453 } 7454 } 7455 7456 // Diagnose shadowed variables iff this isn't a redeclaration. 7457 if (ShadowedDecl && !D.isRedeclaration()) 7458 CheckShadow(NewVD, ShadowedDecl, Previous); 7459 7460 ProcessPragmaWeak(S, NewVD); 7461 7462 // If this is the first declaration of an extern C variable, update 7463 // the map of such variables. 7464 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7465 isIncompleteDeclExternC(*this, NewVD)) 7466 RegisterLocallyScopedExternCDecl(NewVD, S); 7467 7468 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7469 MangleNumberingContext *MCtx; 7470 Decl *ManglingContextDecl; 7471 std::tie(MCtx, ManglingContextDecl) = 7472 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7473 if (MCtx) { 7474 Context.setManglingNumber( 7475 NewVD, MCtx->getManglingNumber( 7476 NewVD, getMSManglingNumber(getLangOpts(), S))); 7477 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7478 } 7479 } 7480 7481 // Special handling of variable named 'main'. 7482 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7483 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7484 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7485 7486 // C++ [basic.start.main]p3 7487 // A program that declares a variable main at global scope is ill-formed. 7488 if (getLangOpts().CPlusPlus) 7489 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7490 7491 // In C, and external-linkage variable named main results in undefined 7492 // behavior. 7493 else if (NewVD->hasExternalFormalLinkage()) 7494 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7495 } 7496 7497 if (D.isRedeclaration() && !Previous.empty()) { 7498 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7499 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7500 D.isFunctionDefinition()); 7501 } 7502 7503 if (NewTemplate) { 7504 if (NewVD->isInvalidDecl()) 7505 NewTemplate->setInvalidDecl(); 7506 ActOnDocumentableDecl(NewTemplate); 7507 return NewTemplate; 7508 } 7509 7510 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7511 CompleteMemberSpecialization(NewVD, Previous); 7512 7513 return NewVD; 7514 } 7515 7516 /// Enum describing the %select options in diag::warn_decl_shadow. 7517 enum ShadowedDeclKind { 7518 SDK_Local, 7519 SDK_Global, 7520 SDK_StaticMember, 7521 SDK_Field, 7522 SDK_Typedef, 7523 SDK_Using, 7524 SDK_StructuredBinding 7525 }; 7526 7527 /// Determine what kind of declaration we're shadowing. 7528 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7529 const DeclContext *OldDC) { 7530 if (isa<TypeAliasDecl>(ShadowedDecl)) 7531 return SDK_Using; 7532 else if (isa<TypedefDecl>(ShadowedDecl)) 7533 return SDK_Typedef; 7534 else if (isa<BindingDecl>(ShadowedDecl)) 7535 return SDK_StructuredBinding; 7536 else if (isa<RecordDecl>(OldDC)) 7537 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7538 7539 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7540 } 7541 7542 /// Return the location of the capture if the given lambda captures the given 7543 /// variable \p VD, or an invalid source location otherwise. 7544 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7545 const VarDecl *VD) { 7546 for (const Capture &Capture : LSI->Captures) { 7547 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7548 return Capture.getLocation(); 7549 } 7550 return SourceLocation(); 7551 } 7552 7553 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7554 const LookupResult &R) { 7555 // Only diagnose if we're shadowing an unambiguous field or variable. 7556 if (R.getResultKind() != LookupResult::Found) 7557 return false; 7558 7559 // Return false if warning is ignored. 7560 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7561 } 7562 7563 /// Return the declaration shadowed by the given variable \p D, or null 7564 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7565 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7566 const LookupResult &R) { 7567 if (!shouldWarnIfShadowedDecl(Diags, R)) 7568 return nullptr; 7569 7570 // Don't diagnose declarations at file scope. 7571 if (D->hasGlobalStorage()) 7572 return nullptr; 7573 7574 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7575 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7576 : nullptr; 7577 } 7578 7579 /// Return the declaration shadowed by the given typedef \p D, or null 7580 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7581 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7582 const LookupResult &R) { 7583 // Don't warn if typedef declaration is part of a class 7584 if (D->getDeclContext()->isRecord()) 7585 return nullptr; 7586 7587 if (!shouldWarnIfShadowedDecl(Diags, R)) 7588 return nullptr; 7589 7590 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7591 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7592 } 7593 7594 /// Return the declaration shadowed by the given variable \p D, or null 7595 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7596 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, 7597 const LookupResult &R) { 7598 if (!shouldWarnIfShadowedDecl(Diags, R)) 7599 return nullptr; 7600 7601 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7602 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7603 : nullptr; 7604 } 7605 7606 /// Diagnose variable or built-in function shadowing. Implements 7607 /// -Wshadow. 7608 /// 7609 /// This method is called whenever a VarDecl is added to a "useful" 7610 /// scope. 7611 /// 7612 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7613 /// \param R the lookup of the name 7614 /// 7615 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7616 const LookupResult &R) { 7617 DeclContext *NewDC = D->getDeclContext(); 7618 7619 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7620 // Fields are not shadowed by variables in C++ static methods. 7621 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7622 if (MD->isStatic()) 7623 return; 7624 7625 // Fields shadowed by constructor parameters are a special case. Usually 7626 // the constructor initializes the field with the parameter. 7627 if (isa<CXXConstructorDecl>(NewDC)) 7628 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7629 // Remember that this was shadowed so we can either warn about its 7630 // modification or its existence depending on warning settings. 7631 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7632 return; 7633 } 7634 } 7635 7636 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7637 if (shadowedVar->isExternC()) { 7638 // For shadowing external vars, make sure that we point to the global 7639 // declaration, not a locally scoped extern declaration. 7640 for (auto I : shadowedVar->redecls()) 7641 if (I->isFileVarDecl()) { 7642 ShadowedDecl = I; 7643 break; 7644 } 7645 } 7646 7647 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7648 7649 unsigned WarningDiag = diag::warn_decl_shadow; 7650 SourceLocation CaptureLoc; 7651 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7652 isa<CXXMethodDecl>(NewDC)) { 7653 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7654 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7655 if (RD->getLambdaCaptureDefault() == LCD_None) { 7656 // Try to avoid warnings for lambdas with an explicit capture list. 7657 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7658 // Warn only when the lambda captures the shadowed decl explicitly. 7659 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7660 if (CaptureLoc.isInvalid()) 7661 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7662 } else { 7663 // Remember that this was shadowed so we can avoid the warning if the 7664 // shadowed decl isn't captured and the warning settings allow it. 7665 cast<LambdaScopeInfo>(getCurFunction()) 7666 ->ShadowingDecls.push_back( 7667 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7668 return; 7669 } 7670 } 7671 7672 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7673 // A variable can't shadow a local variable in an enclosing scope, if 7674 // they are separated by a non-capturing declaration context. 7675 for (DeclContext *ParentDC = NewDC; 7676 ParentDC && !ParentDC->Equals(OldDC); 7677 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7678 // Only block literals, captured statements, and lambda expressions 7679 // can capture; other scopes don't. 7680 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7681 !isLambdaCallOperator(ParentDC)) { 7682 return; 7683 } 7684 } 7685 } 7686 } 7687 } 7688 7689 // Only warn about certain kinds of shadowing for class members. 7690 if (NewDC && NewDC->isRecord()) { 7691 // In particular, don't warn about shadowing non-class members. 7692 if (!OldDC->isRecord()) 7693 return; 7694 7695 // TODO: should we warn about static data members shadowing 7696 // static data members from base classes? 7697 7698 // TODO: don't diagnose for inaccessible shadowed members. 7699 // This is hard to do perfectly because we might friend the 7700 // shadowing context, but that's just a false negative. 7701 } 7702 7703 7704 DeclarationName Name = R.getLookupName(); 7705 7706 // Emit warning and note. 7707 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7708 return; 7709 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7710 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7711 if (!CaptureLoc.isInvalid()) 7712 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7713 << Name << /*explicitly*/ 1; 7714 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7715 } 7716 7717 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7718 /// when these variables are captured by the lambda. 7719 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7720 for (const auto &Shadow : LSI->ShadowingDecls) { 7721 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7722 // Try to avoid the warning when the shadowed decl isn't captured. 7723 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7724 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7725 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7726 ? diag::warn_decl_shadow_uncaptured_local 7727 : diag::warn_decl_shadow) 7728 << Shadow.VD->getDeclName() 7729 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7730 if (!CaptureLoc.isInvalid()) 7731 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7732 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7733 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7734 } 7735 } 7736 7737 /// Check -Wshadow without the advantage of a previous lookup. 7738 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7739 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7740 return; 7741 7742 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7743 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7744 LookupName(R, S); 7745 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7746 CheckShadow(D, ShadowedDecl, R); 7747 } 7748 7749 /// Check if 'E', which is an expression that is about to be modified, refers 7750 /// to a constructor parameter that shadows a field. 7751 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7752 // Quickly ignore expressions that can't be shadowing ctor parameters. 7753 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7754 return; 7755 E = E->IgnoreParenImpCasts(); 7756 auto *DRE = dyn_cast<DeclRefExpr>(E); 7757 if (!DRE) 7758 return; 7759 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7760 auto I = ShadowingDecls.find(D); 7761 if (I == ShadowingDecls.end()) 7762 return; 7763 const NamedDecl *ShadowedDecl = I->second; 7764 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7765 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7766 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7767 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7768 7769 // Avoid issuing multiple warnings about the same decl. 7770 ShadowingDecls.erase(I); 7771 } 7772 7773 /// Check for conflict between this global or extern "C" declaration and 7774 /// previous global or extern "C" declarations. This is only used in C++. 7775 template<typename T> 7776 static bool checkGlobalOrExternCConflict( 7777 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7778 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7779 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7780 7781 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7782 // The common case: this global doesn't conflict with any extern "C" 7783 // declaration. 7784 return false; 7785 } 7786 7787 if (Prev) { 7788 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7789 // Both the old and new declarations have C language linkage. This is a 7790 // redeclaration. 7791 Previous.clear(); 7792 Previous.addDecl(Prev); 7793 return true; 7794 } 7795 7796 // This is a global, non-extern "C" declaration, and there is a previous 7797 // non-global extern "C" declaration. Diagnose if this is a variable 7798 // declaration. 7799 if (!isa<VarDecl>(ND)) 7800 return false; 7801 } else { 7802 // The declaration is extern "C". Check for any declaration in the 7803 // translation unit which might conflict. 7804 if (IsGlobal) { 7805 // We have already performed the lookup into the translation unit. 7806 IsGlobal = false; 7807 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7808 I != E; ++I) { 7809 if (isa<VarDecl>(*I)) { 7810 Prev = *I; 7811 break; 7812 } 7813 } 7814 } else { 7815 DeclContext::lookup_result R = 7816 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7817 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7818 I != E; ++I) { 7819 if (isa<VarDecl>(*I)) { 7820 Prev = *I; 7821 break; 7822 } 7823 // FIXME: If we have any other entity with this name in global scope, 7824 // the declaration is ill-formed, but that is a defect: it breaks the 7825 // 'stat' hack, for instance. Only variables can have mangled name 7826 // clashes with extern "C" declarations, so only they deserve a 7827 // diagnostic. 7828 } 7829 } 7830 7831 if (!Prev) 7832 return false; 7833 } 7834 7835 // Use the first declaration's location to ensure we point at something which 7836 // is lexically inside an extern "C" linkage-spec. 7837 assert(Prev && "should have found a previous declaration to diagnose"); 7838 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7839 Prev = FD->getFirstDecl(); 7840 else 7841 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7842 7843 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7844 << IsGlobal << ND; 7845 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7846 << IsGlobal; 7847 return false; 7848 } 7849 7850 /// Apply special rules for handling extern "C" declarations. Returns \c true 7851 /// if we have found that this is a redeclaration of some prior entity. 7852 /// 7853 /// Per C++ [dcl.link]p6: 7854 /// Two declarations [for a function or variable] with C language linkage 7855 /// with the same name that appear in different scopes refer to the same 7856 /// [entity]. An entity with C language linkage shall not be declared with 7857 /// the same name as an entity in global scope. 7858 template<typename T> 7859 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7860 LookupResult &Previous) { 7861 if (!S.getLangOpts().CPlusPlus) { 7862 // In C, when declaring a global variable, look for a corresponding 'extern' 7863 // variable declared in function scope. We don't need this in C++, because 7864 // we find local extern decls in the surrounding file-scope DeclContext. 7865 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7866 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7867 Previous.clear(); 7868 Previous.addDecl(Prev); 7869 return true; 7870 } 7871 } 7872 return false; 7873 } 7874 7875 // A declaration in the translation unit can conflict with an extern "C" 7876 // declaration. 7877 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7878 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7879 7880 // An extern "C" declaration can conflict with a declaration in the 7881 // translation unit or can be a redeclaration of an extern "C" declaration 7882 // in another scope. 7883 if (isIncompleteDeclExternC(S,ND)) 7884 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7885 7886 // Neither global nor extern "C": nothing to do. 7887 return false; 7888 } 7889 7890 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7891 // If the decl is already known invalid, don't check it. 7892 if (NewVD->isInvalidDecl()) 7893 return; 7894 7895 QualType T = NewVD->getType(); 7896 7897 // Defer checking an 'auto' type until its initializer is attached. 7898 if (T->isUndeducedType()) 7899 return; 7900 7901 if (NewVD->hasAttrs()) 7902 CheckAlignasUnderalignment(NewVD); 7903 7904 if (T->isObjCObjectType()) { 7905 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7906 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7907 T = Context.getObjCObjectPointerType(T); 7908 NewVD->setType(T); 7909 } 7910 7911 // Emit an error if an address space was applied to decl with local storage. 7912 // This includes arrays of objects with address space qualifiers, but not 7913 // automatic variables that point to other address spaces. 7914 // ISO/IEC TR 18037 S5.1.2 7915 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7916 T.getAddressSpace() != LangAS::Default) { 7917 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7918 NewVD->setInvalidDecl(); 7919 return; 7920 } 7921 7922 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7923 // scope. 7924 if (getLangOpts().OpenCLVersion == 120 && 7925 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", 7926 getLangOpts()) && 7927 NewVD->isStaticLocal()) { 7928 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7929 NewVD->setInvalidDecl(); 7930 return; 7931 } 7932 7933 if (getLangOpts().OpenCL) { 7934 if (!diagnoseOpenCLTypes(*this, NewVD)) 7935 return; 7936 7937 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7938 if (NewVD->hasAttr<BlocksAttr>()) { 7939 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7940 return; 7941 } 7942 7943 if (T->isBlockPointerType()) { 7944 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7945 // can't use 'extern' storage class. 7946 if (!T.isConstQualified()) { 7947 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7948 << 0 /*const*/; 7949 NewVD->setInvalidDecl(); 7950 return; 7951 } 7952 if (NewVD->hasExternalStorage()) { 7953 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7954 NewVD->setInvalidDecl(); 7955 return; 7956 } 7957 } 7958 7959 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7960 // __constant address space. 7961 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7962 // variables inside a function can also be declared in the global 7963 // address space. 7964 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7965 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7966 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7967 NewVD->hasExternalStorage()) { 7968 if (!T->isSamplerT() && 7969 !T->isDependentType() && 7970 !(T.getAddressSpace() == LangAS::opencl_constant || 7971 (T.getAddressSpace() == LangAS::opencl_global && 7972 (getLangOpts().OpenCLVersion == 200 || 7973 getLangOpts().OpenCLCPlusPlus)))) { 7974 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7975 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7976 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7977 << Scope << "global or constant"; 7978 else 7979 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7980 << Scope << "constant"; 7981 NewVD->setInvalidDecl(); 7982 return; 7983 } 7984 } else { 7985 if (T.getAddressSpace() == LangAS::opencl_global) { 7986 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7987 << 1 /*is any function*/ << "global"; 7988 NewVD->setInvalidDecl(); 7989 return; 7990 } 7991 if (T.getAddressSpace() == LangAS::opencl_constant || 7992 T.getAddressSpace() == LangAS::opencl_local) { 7993 FunctionDecl *FD = getCurFunctionDecl(); 7994 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7995 // in functions. 7996 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7997 if (T.getAddressSpace() == LangAS::opencl_constant) 7998 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7999 << 0 /*non-kernel only*/ << "constant"; 8000 else 8001 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8002 << 0 /*non-kernel only*/ << "local"; 8003 NewVD->setInvalidDecl(); 8004 return; 8005 } 8006 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 8007 // in the outermost scope of a kernel function. 8008 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 8009 if (!getCurScope()->isFunctionScope()) { 8010 if (T.getAddressSpace() == LangAS::opencl_constant) 8011 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8012 << "constant"; 8013 else 8014 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8015 << "local"; 8016 NewVD->setInvalidDecl(); 8017 return; 8018 } 8019 } 8020 } else if (T.getAddressSpace() != LangAS::opencl_private && 8021 // If we are parsing a template we didn't deduce an addr 8022 // space yet. 8023 T.getAddressSpace() != LangAS::Default) { 8024 // Do not allow other address spaces on automatic variable. 8025 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 8026 NewVD->setInvalidDecl(); 8027 return; 8028 } 8029 } 8030 } 8031 8032 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 8033 && !NewVD->hasAttr<BlocksAttr>()) { 8034 if (getLangOpts().getGC() != LangOptions::NonGC) 8035 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 8036 else { 8037 assert(!getLangOpts().ObjCAutoRefCount); 8038 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 8039 } 8040 } 8041 8042 bool isVM = T->isVariablyModifiedType(); 8043 if (isVM || NewVD->hasAttr<CleanupAttr>() || 8044 NewVD->hasAttr<BlocksAttr>()) 8045 setFunctionHasBranchProtectedScope(); 8046 8047 if ((isVM && NewVD->hasLinkage()) || 8048 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8049 bool SizeIsNegative; 8050 llvm::APSInt Oversized; 8051 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8052 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8053 QualType FixedT; 8054 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8055 FixedT = FixedTInfo->getType(); 8056 else if (FixedTInfo) { 8057 // Type and type-as-written are canonically different. We need to fix up 8058 // both types separately. 8059 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8060 Oversized); 8061 } 8062 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8063 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8064 // FIXME: This won't give the correct result for 8065 // int a[10][n]; 8066 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8067 8068 if (NewVD->isFileVarDecl()) 8069 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8070 << SizeRange; 8071 else if (NewVD->isStaticLocal()) 8072 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8073 << SizeRange; 8074 else 8075 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8076 << SizeRange; 8077 NewVD->setInvalidDecl(); 8078 return; 8079 } 8080 8081 if (!FixedTInfo) { 8082 if (NewVD->isFileVarDecl()) 8083 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8084 else 8085 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8086 NewVD->setInvalidDecl(); 8087 return; 8088 } 8089 8090 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8091 NewVD->setType(FixedT); 8092 NewVD->setTypeSourceInfo(FixedTInfo); 8093 } 8094 8095 if (T->isVoidType()) { 8096 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8097 // of objects and functions. 8098 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8099 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8100 << T; 8101 NewVD->setInvalidDecl(); 8102 return; 8103 } 8104 } 8105 8106 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8107 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8108 NewVD->setInvalidDecl(); 8109 return; 8110 } 8111 8112 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8113 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8114 NewVD->setInvalidDecl(); 8115 return; 8116 } 8117 8118 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8119 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8120 NewVD->setInvalidDecl(); 8121 return; 8122 } 8123 8124 if (NewVD->isConstexpr() && !T->isDependentType() && 8125 RequireLiteralType(NewVD->getLocation(), T, 8126 diag::err_constexpr_var_non_literal)) { 8127 NewVD->setInvalidDecl(); 8128 return; 8129 } 8130 8131 // PPC MMA non-pointer types are not allowed as non-local variable types. 8132 if (Context.getTargetInfo().getTriple().isPPC64() && 8133 !NewVD->isLocalVarDecl() && 8134 CheckPPCMMAType(T, NewVD->getLocation())) { 8135 NewVD->setInvalidDecl(); 8136 return; 8137 } 8138 } 8139 8140 /// Perform semantic checking on a newly-created variable 8141 /// declaration. 8142 /// 8143 /// This routine performs all of the type-checking required for a 8144 /// variable declaration once it has been built. It is used both to 8145 /// check variables after they have been parsed and their declarators 8146 /// have been translated into a declaration, and to check variables 8147 /// that have been instantiated from a template. 8148 /// 8149 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8150 /// 8151 /// Returns true if the variable declaration is a redeclaration. 8152 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8153 CheckVariableDeclarationType(NewVD); 8154 8155 // If the decl is already known invalid, don't check it. 8156 if (NewVD->isInvalidDecl()) 8157 return false; 8158 8159 // If we did not find anything by this name, look for a non-visible 8160 // extern "C" declaration with the same name. 8161 if (Previous.empty() && 8162 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8163 Previous.setShadowed(); 8164 8165 if (!Previous.empty()) { 8166 MergeVarDecl(NewVD, Previous); 8167 return true; 8168 } 8169 return false; 8170 } 8171 8172 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8173 /// and if so, check that it's a valid override and remember it. 8174 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8175 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8176 8177 // Look for methods in base classes that this method might override. 8178 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8179 /*DetectVirtual=*/false); 8180 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8181 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8182 DeclarationName Name = MD->getDeclName(); 8183 8184 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8185 // We really want to find the base class destructor here. 8186 QualType T = Context.getTypeDeclType(BaseRecord); 8187 CanQualType CT = Context.getCanonicalType(T); 8188 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8189 } 8190 8191 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8192 CXXMethodDecl *BaseMD = 8193 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8194 if (!BaseMD || !BaseMD->isVirtual() || 8195 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8196 /*ConsiderCudaAttrs=*/true, 8197 // C++2a [class.virtual]p2 does not consider requires 8198 // clauses when overriding. 8199 /*ConsiderRequiresClauses=*/false)) 8200 continue; 8201 8202 if (Overridden.insert(BaseMD).second) { 8203 MD->addOverriddenMethod(BaseMD); 8204 CheckOverridingFunctionReturnType(MD, BaseMD); 8205 CheckOverridingFunctionAttributes(MD, BaseMD); 8206 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8207 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8208 } 8209 8210 // A method can only override one function from each base class. We 8211 // don't track indirectly overridden methods from bases of bases. 8212 return true; 8213 } 8214 8215 return false; 8216 }; 8217 8218 DC->lookupInBases(VisitBase, Paths); 8219 return !Overridden.empty(); 8220 } 8221 8222 namespace { 8223 // Struct for holding all of the extra arguments needed by 8224 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8225 struct ActOnFDArgs { 8226 Scope *S; 8227 Declarator &D; 8228 MultiTemplateParamsArg TemplateParamLists; 8229 bool AddToScope; 8230 }; 8231 } // end anonymous namespace 8232 8233 namespace { 8234 8235 // Callback to only accept typo corrections that have a non-zero edit distance. 8236 // Also only accept corrections that have the same parent decl. 8237 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8238 public: 8239 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8240 CXXRecordDecl *Parent) 8241 : Context(Context), OriginalFD(TypoFD), 8242 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8243 8244 bool ValidateCandidate(const TypoCorrection &candidate) override { 8245 if (candidate.getEditDistance() == 0) 8246 return false; 8247 8248 SmallVector<unsigned, 1> MismatchedParams; 8249 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8250 CDeclEnd = candidate.end(); 8251 CDecl != CDeclEnd; ++CDecl) { 8252 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8253 8254 if (FD && !FD->hasBody() && 8255 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8256 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8257 CXXRecordDecl *Parent = MD->getParent(); 8258 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8259 return true; 8260 } else if (!ExpectedParent) { 8261 return true; 8262 } 8263 } 8264 } 8265 8266 return false; 8267 } 8268 8269 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8270 return std::make_unique<DifferentNameValidatorCCC>(*this); 8271 } 8272 8273 private: 8274 ASTContext &Context; 8275 FunctionDecl *OriginalFD; 8276 CXXRecordDecl *ExpectedParent; 8277 }; 8278 8279 } // end anonymous namespace 8280 8281 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8282 TypoCorrectedFunctionDefinitions.insert(F); 8283 } 8284 8285 /// Generate diagnostics for an invalid function redeclaration. 8286 /// 8287 /// This routine handles generating the diagnostic messages for an invalid 8288 /// function redeclaration, including finding possible similar declarations 8289 /// or performing typo correction if there are no previous declarations with 8290 /// the same name. 8291 /// 8292 /// Returns a NamedDecl iff typo correction was performed and substituting in 8293 /// the new declaration name does not cause new errors. 8294 static NamedDecl *DiagnoseInvalidRedeclaration( 8295 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8296 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8297 DeclarationName Name = NewFD->getDeclName(); 8298 DeclContext *NewDC = NewFD->getDeclContext(); 8299 SmallVector<unsigned, 1> MismatchedParams; 8300 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8301 TypoCorrection Correction; 8302 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8303 unsigned DiagMsg = 8304 IsLocalFriend ? diag::err_no_matching_local_friend : 8305 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8306 diag::err_member_decl_does_not_match; 8307 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8308 IsLocalFriend ? Sema::LookupLocalFriendName 8309 : Sema::LookupOrdinaryName, 8310 Sema::ForVisibleRedeclaration); 8311 8312 NewFD->setInvalidDecl(); 8313 if (IsLocalFriend) 8314 SemaRef.LookupName(Prev, S); 8315 else 8316 SemaRef.LookupQualifiedName(Prev, NewDC); 8317 assert(!Prev.isAmbiguous() && 8318 "Cannot have an ambiguity in previous-declaration lookup"); 8319 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8320 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8321 MD ? MD->getParent() : nullptr); 8322 if (!Prev.empty()) { 8323 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8324 Func != FuncEnd; ++Func) { 8325 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8326 if (FD && 8327 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8328 // Add 1 to the index so that 0 can mean the mismatch didn't 8329 // involve a parameter 8330 unsigned ParamNum = 8331 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8332 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8333 } 8334 } 8335 // If the qualified name lookup yielded nothing, try typo correction 8336 } else if ((Correction = SemaRef.CorrectTypo( 8337 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8338 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8339 IsLocalFriend ? nullptr : NewDC))) { 8340 // Set up everything for the call to ActOnFunctionDeclarator 8341 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8342 ExtraArgs.D.getIdentifierLoc()); 8343 Previous.clear(); 8344 Previous.setLookupName(Correction.getCorrection()); 8345 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8346 CDeclEnd = Correction.end(); 8347 CDecl != CDeclEnd; ++CDecl) { 8348 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8349 if (FD && !FD->hasBody() && 8350 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8351 Previous.addDecl(FD); 8352 } 8353 } 8354 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8355 8356 NamedDecl *Result; 8357 // Retry building the function declaration with the new previous 8358 // declarations, and with errors suppressed. 8359 { 8360 // Trap errors. 8361 Sema::SFINAETrap Trap(SemaRef); 8362 8363 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8364 // pieces need to verify the typo-corrected C++ declaration and hopefully 8365 // eliminate the need for the parameter pack ExtraArgs. 8366 Result = SemaRef.ActOnFunctionDeclarator( 8367 ExtraArgs.S, ExtraArgs.D, 8368 Correction.getCorrectionDecl()->getDeclContext(), 8369 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8370 ExtraArgs.AddToScope); 8371 8372 if (Trap.hasErrorOccurred()) 8373 Result = nullptr; 8374 } 8375 8376 if (Result) { 8377 // Determine which correction we picked. 8378 Decl *Canonical = Result->getCanonicalDecl(); 8379 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8380 I != E; ++I) 8381 if ((*I)->getCanonicalDecl() == Canonical) 8382 Correction.setCorrectionDecl(*I); 8383 8384 // Let Sema know about the correction. 8385 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8386 SemaRef.diagnoseTypo( 8387 Correction, 8388 SemaRef.PDiag(IsLocalFriend 8389 ? diag::err_no_matching_local_friend_suggest 8390 : diag::err_member_decl_does_not_match_suggest) 8391 << Name << NewDC << IsDefinition); 8392 return Result; 8393 } 8394 8395 // Pretend the typo correction never occurred 8396 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8397 ExtraArgs.D.getIdentifierLoc()); 8398 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8399 Previous.clear(); 8400 Previous.setLookupName(Name); 8401 } 8402 8403 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8404 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8405 8406 bool NewFDisConst = false; 8407 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8408 NewFDisConst = NewMD->isConst(); 8409 8410 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8411 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8412 NearMatch != NearMatchEnd; ++NearMatch) { 8413 FunctionDecl *FD = NearMatch->first; 8414 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8415 bool FDisConst = MD && MD->isConst(); 8416 bool IsMember = MD || !IsLocalFriend; 8417 8418 // FIXME: These notes are poorly worded for the local friend case. 8419 if (unsigned Idx = NearMatch->second) { 8420 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8421 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8422 if (Loc.isInvalid()) Loc = FD->getLocation(); 8423 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8424 : diag::note_local_decl_close_param_match) 8425 << Idx << FDParam->getType() 8426 << NewFD->getParamDecl(Idx - 1)->getType(); 8427 } else if (FDisConst != NewFDisConst) { 8428 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8429 << NewFDisConst << FD->getSourceRange().getEnd(); 8430 } else 8431 SemaRef.Diag(FD->getLocation(), 8432 IsMember ? diag::note_member_def_close_match 8433 : diag::note_local_decl_close_match); 8434 } 8435 return nullptr; 8436 } 8437 8438 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8439 switch (D.getDeclSpec().getStorageClassSpec()) { 8440 default: llvm_unreachable("Unknown storage class!"); 8441 case DeclSpec::SCS_auto: 8442 case DeclSpec::SCS_register: 8443 case DeclSpec::SCS_mutable: 8444 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8445 diag::err_typecheck_sclass_func); 8446 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8447 D.setInvalidType(); 8448 break; 8449 case DeclSpec::SCS_unspecified: break; 8450 case DeclSpec::SCS_extern: 8451 if (D.getDeclSpec().isExternInLinkageSpec()) 8452 return SC_None; 8453 return SC_Extern; 8454 case DeclSpec::SCS_static: { 8455 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8456 // C99 6.7.1p5: 8457 // The declaration of an identifier for a function that has 8458 // block scope shall have no explicit storage-class specifier 8459 // other than extern 8460 // See also (C++ [dcl.stc]p4). 8461 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8462 diag::err_static_block_func); 8463 break; 8464 } else 8465 return SC_Static; 8466 } 8467 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8468 } 8469 8470 // No explicit storage class has already been returned 8471 return SC_None; 8472 } 8473 8474 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8475 DeclContext *DC, QualType &R, 8476 TypeSourceInfo *TInfo, 8477 StorageClass SC, 8478 bool &IsVirtualOkay) { 8479 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8480 DeclarationName Name = NameInfo.getName(); 8481 8482 FunctionDecl *NewFD = nullptr; 8483 bool isInline = D.getDeclSpec().isInlineSpecified(); 8484 8485 if (!SemaRef.getLangOpts().CPlusPlus) { 8486 // Determine whether the function was written with a 8487 // prototype. This true when: 8488 // - there is a prototype in the declarator, or 8489 // - the type R of the function is some kind of typedef or other non- 8490 // attributed reference to a type name (which eventually refers to a 8491 // function type). 8492 bool HasPrototype = 8493 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8494 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8495 8496 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8497 R, TInfo, SC, isInline, HasPrototype, 8498 ConstexprSpecKind::Unspecified, 8499 /*TrailingRequiresClause=*/nullptr); 8500 if (D.isInvalidType()) 8501 NewFD->setInvalidDecl(); 8502 8503 return NewFD; 8504 } 8505 8506 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8507 8508 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8509 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8510 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8511 diag::err_constexpr_wrong_decl_kind) 8512 << static_cast<int>(ConstexprKind); 8513 ConstexprKind = ConstexprSpecKind::Unspecified; 8514 D.getMutableDeclSpec().ClearConstexprSpec(); 8515 } 8516 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8517 8518 // Check that the return type is not an abstract class type. 8519 // For record types, this is done by the AbstractClassUsageDiagnoser once 8520 // the class has been completely parsed. 8521 if (!DC->isRecord() && 8522 SemaRef.RequireNonAbstractType( 8523 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8524 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8525 D.setInvalidType(); 8526 8527 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8528 // This is a C++ constructor declaration. 8529 assert(DC->isRecord() && 8530 "Constructors can only be declared in a member context"); 8531 8532 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8533 return CXXConstructorDecl::Create( 8534 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8535 TInfo, ExplicitSpecifier, isInline, 8536 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8537 TrailingRequiresClause); 8538 8539 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8540 // This is a C++ destructor declaration. 8541 if (DC->isRecord()) { 8542 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8543 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8544 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8545 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8546 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8547 TrailingRequiresClause); 8548 8549 // If the destructor needs an implicit exception specification, set it 8550 // now. FIXME: It'd be nice to be able to create the right type to start 8551 // with, but the type needs to reference the destructor declaration. 8552 if (SemaRef.getLangOpts().CPlusPlus11) 8553 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8554 8555 IsVirtualOkay = true; 8556 return NewDD; 8557 8558 } else { 8559 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8560 D.setInvalidType(); 8561 8562 // Create a FunctionDecl to satisfy the function definition parsing 8563 // code path. 8564 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8565 D.getIdentifierLoc(), Name, R, TInfo, SC, 8566 isInline, 8567 /*hasPrototype=*/true, ConstexprKind, 8568 TrailingRequiresClause); 8569 } 8570 8571 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8572 if (!DC->isRecord()) { 8573 SemaRef.Diag(D.getIdentifierLoc(), 8574 diag::err_conv_function_not_member); 8575 return nullptr; 8576 } 8577 8578 SemaRef.CheckConversionDeclarator(D, R, SC); 8579 if (D.isInvalidType()) 8580 return nullptr; 8581 8582 IsVirtualOkay = true; 8583 return CXXConversionDecl::Create( 8584 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8585 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8586 TrailingRequiresClause); 8587 8588 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8589 if (TrailingRequiresClause) 8590 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8591 diag::err_trailing_requires_clause_on_deduction_guide) 8592 << TrailingRequiresClause->getSourceRange(); 8593 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8594 8595 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8596 ExplicitSpecifier, NameInfo, R, TInfo, 8597 D.getEndLoc()); 8598 } else if (DC->isRecord()) { 8599 // If the name of the function is the same as the name of the record, 8600 // then this must be an invalid constructor that has a return type. 8601 // (The parser checks for a return type and makes the declarator a 8602 // constructor if it has no return type). 8603 if (Name.getAsIdentifierInfo() && 8604 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8605 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8606 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8607 << SourceRange(D.getIdentifierLoc()); 8608 return nullptr; 8609 } 8610 8611 // This is a C++ method declaration. 8612 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8613 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8614 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8615 TrailingRequiresClause); 8616 IsVirtualOkay = !Ret->isStatic(); 8617 return Ret; 8618 } else { 8619 bool isFriend = 8620 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8621 if (!isFriend && SemaRef.CurContext->isRecord()) 8622 return nullptr; 8623 8624 // Determine whether the function was written with a 8625 // prototype. This true when: 8626 // - we're in C++ (where every function has a prototype), 8627 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8628 R, TInfo, SC, isInline, true /*HasPrototype*/, 8629 ConstexprKind, TrailingRequiresClause); 8630 } 8631 } 8632 8633 enum OpenCLParamType { 8634 ValidKernelParam, 8635 PtrPtrKernelParam, 8636 PtrKernelParam, 8637 InvalidAddrSpacePtrKernelParam, 8638 InvalidKernelParam, 8639 RecordKernelParam 8640 }; 8641 8642 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8643 // Size dependent types are just typedefs to normal integer types 8644 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8645 // integers other than by their names. 8646 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8647 8648 // Remove typedefs one by one until we reach a typedef 8649 // for a size dependent type. 8650 QualType DesugaredTy = Ty; 8651 do { 8652 ArrayRef<StringRef> Names(SizeTypeNames); 8653 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8654 if (Names.end() != Match) 8655 return true; 8656 8657 Ty = DesugaredTy; 8658 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8659 } while (DesugaredTy != Ty); 8660 8661 return false; 8662 } 8663 8664 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8665 if (PT->isDependentType()) 8666 return InvalidKernelParam; 8667 8668 if (PT->isPointerType() || PT->isReferenceType()) { 8669 QualType PointeeType = PT->getPointeeType(); 8670 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8671 PointeeType.getAddressSpace() == LangAS::opencl_private || 8672 PointeeType.getAddressSpace() == LangAS::Default) 8673 return InvalidAddrSpacePtrKernelParam; 8674 8675 if (PointeeType->isPointerType()) { 8676 // This is a pointer to pointer parameter. 8677 // Recursively check inner type. 8678 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 8679 if (ParamKind == InvalidAddrSpacePtrKernelParam || 8680 ParamKind == InvalidKernelParam) 8681 return ParamKind; 8682 8683 return PtrPtrKernelParam; 8684 } 8685 8686 // C++ for OpenCL v1.0 s2.4: 8687 // Moreover the types used in parameters of the kernel functions must be: 8688 // Standard layout types for pointer parameters. The same applies to 8689 // reference if an implementation supports them in kernel parameters. 8690 if (S.getLangOpts().OpenCLCPlusPlus && 8691 !S.getOpenCLOptions().isAvailableOption( 8692 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 8693 !PointeeType->isAtomicType() && !PointeeType->isVoidType() && 8694 !PointeeType->isStandardLayoutType()) 8695 return InvalidKernelParam; 8696 8697 return PtrKernelParam; 8698 } 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 one 8704 // of these built-in scalar types. 8705 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8706 return InvalidKernelParam; 8707 8708 if (PT->isImageType()) 8709 return PtrKernelParam; 8710 8711 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8712 return InvalidKernelParam; 8713 8714 // OpenCL extension spec v1.2 s9.5: 8715 // This extension adds support for half scalar and vector types as built-in 8716 // types that can be used for arithmetic operations, conversions etc. 8717 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 8718 PT->isHalfType()) 8719 return InvalidKernelParam; 8720 8721 // Look into an array argument to check if it has a forbidden type. 8722 if (PT->isArrayType()) { 8723 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8724 // Call ourself to check an underlying type of an array. Since the 8725 // getPointeeOrArrayElementType returns an innermost type which is not an 8726 // array, this recursive call only happens once. 8727 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8728 } 8729 8730 // C++ for OpenCL v1.0 s2.4: 8731 // Moreover the types used in parameters of the kernel functions must be: 8732 // Trivial and standard-layout types C++17 [basic.types] (plain old data 8733 // types) for parameters passed by value; 8734 if (S.getLangOpts().OpenCLCPlusPlus && 8735 !S.getOpenCLOptions().isAvailableOption( 8736 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 8737 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context)) 8738 return InvalidKernelParam; 8739 8740 if (PT->isRecordType()) 8741 return RecordKernelParam; 8742 8743 return ValidKernelParam; 8744 } 8745 8746 static void checkIsValidOpenCLKernelParameter( 8747 Sema &S, 8748 Declarator &D, 8749 ParmVarDecl *Param, 8750 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8751 QualType PT = Param->getType(); 8752 8753 // Cache the valid types we encounter to avoid rechecking structs that are 8754 // used again 8755 if (ValidTypes.count(PT.getTypePtr())) 8756 return; 8757 8758 switch (getOpenCLKernelParameterType(S, PT)) { 8759 case PtrPtrKernelParam: 8760 // OpenCL v3.0 s6.11.a: 8761 // A kernel function argument cannot be declared as a pointer to a pointer 8762 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 8763 if (S.getLangOpts().OpenCLVersion < 120 && 8764 !S.getLangOpts().OpenCLCPlusPlus) { 8765 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8766 D.setInvalidType(); 8767 return; 8768 } 8769 8770 ValidTypes.insert(PT.getTypePtr()); 8771 return; 8772 8773 case InvalidAddrSpacePtrKernelParam: 8774 // OpenCL v1.0 s6.5: 8775 // __kernel function arguments declared to be a pointer of a type can point 8776 // to one of the following address spaces only : __global, __local or 8777 // __constant. 8778 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8779 D.setInvalidType(); 8780 return; 8781 8782 // OpenCL v1.2 s6.9.k: 8783 // Arguments to kernel functions in a program cannot be declared with the 8784 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8785 // uintptr_t or a struct and/or union that contain fields declared to be 8786 // one of these built-in scalar types. 8787 8788 case InvalidKernelParam: 8789 // OpenCL v1.2 s6.8 n: 8790 // A kernel function argument cannot be declared 8791 // of event_t type. 8792 // Do not diagnose half type since it is diagnosed as invalid argument 8793 // type for any function elsewhere. 8794 if (!PT->isHalfType()) { 8795 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8796 8797 // Explain what typedefs are involved. 8798 const TypedefType *Typedef = nullptr; 8799 while ((Typedef = PT->getAs<TypedefType>())) { 8800 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8801 // SourceLocation may be invalid for a built-in type. 8802 if (Loc.isValid()) 8803 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8804 PT = Typedef->desugar(); 8805 } 8806 } 8807 8808 D.setInvalidType(); 8809 return; 8810 8811 case PtrKernelParam: 8812 case ValidKernelParam: 8813 ValidTypes.insert(PT.getTypePtr()); 8814 return; 8815 8816 case RecordKernelParam: 8817 break; 8818 } 8819 8820 // Track nested structs we will inspect 8821 SmallVector<const Decl *, 4> VisitStack; 8822 8823 // Track where we are in the nested structs. Items will migrate from 8824 // VisitStack to HistoryStack as we do the DFS for bad field. 8825 SmallVector<const FieldDecl *, 4> HistoryStack; 8826 HistoryStack.push_back(nullptr); 8827 8828 // At this point we already handled everything except of a RecordType or 8829 // an ArrayType of a RecordType. 8830 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8831 const RecordType *RecTy = 8832 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8833 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8834 8835 VisitStack.push_back(RecTy->getDecl()); 8836 assert(VisitStack.back() && "First decl null?"); 8837 8838 do { 8839 const Decl *Next = VisitStack.pop_back_val(); 8840 if (!Next) { 8841 assert(!HistoryStack.empty()); 8842 // Found a marker, we have gone up a level 8843 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8844 ValidTypes.insert(Hist->getType().getTypePtr()); 8845 8846 continue; 8847 } 8848 8849 // Adds everything except the original parameter declaration (which is not a 8850 // field itself) to the history stack. 8851 const RecordDecl *RD; 8852 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8853 HistoryStack.push_back(Field); 8854 8855 QualType FieldTy = Field->getType(); 8856 // Other field types (known to be valid or invalid) are handled while we 8857 // walk around RecordDecl::fields(). 8858 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8859 "Unexpected type."); 8860 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8861 8862 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8863 } else { 8864 RD = cast<RecordDecl>(Next); 8865 } 8866 8867 // Add a null marker so we know when we've gone back up a level 8868 VisitStack.push_back(nullptr); 8869 8870 for (const auto *FD : RD->fields()) { 8871 QualType QT = FD->getType(); 8872 8873 if (ValidTypes.count(QT.getTypePtr())) 8874 continue; 8875 8876 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8877 if (ParamType == ValidKernelParam) 8878 continue; 8879 8880 if (ParamType == RecordKernelParam) { 8881 VisitStack.push_back(FD); 8882 continue; 8883 } 8884 8885 // OpenCL v1.2 s6.9.p: 8886 // Arguments to kernel functions that are declared to be a struct or union 8887 // do not allow OpenCL objects to be passed as elements of the struct or 8888 // union. 8889 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8890 ParamType == InvalidAddrSpacePtrKernelParam) { 8891 S.Diag(Param->getLocation(), 8892 diag::err_record_with_pointers_kernel_param) 8893 << PT->isUnionType() 8894 << PT; 8895 } else { 8896 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8897 } 8898 8899 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8900 << OrigRecDecl->getDeclName(); 8901 8902 // We have an error, now let's go back up through history and show where 8903 // the offending field came from 8904 for (ArrayRef<const FieldDecl *>::const_iterator 8905 I = HistoryStack.begin() + 1, 8906 E = HistoryStack.end(); 8907 I != E; ++I) { 8908 const FieldDecl *OuterField = *I; 8909 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8910 << OuterField->getType(); 8911 } 8912 8913 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8914 << QT->isPointerType() 8915 << QT; 8916 D.setInvalidType(); 8917 return; 8918 } 8919 } while (!VisitStack.empty()); 8920 } 8921 8922 /// Find the DeclContext in which a tag is implicitly declared if we see an 8923 /// elaborated type specifier in the specified context, and lookup finds 8924 /// nothing. 8925 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8926 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8927 DC = DC->getParent(); 8928 return DC; 8929 } 8930 8931 /// Find the Scope in which a tag is implicitly declared if we see an 8932 /// elaborated type specifier in the specified context, and lookup finds 8933 /// nothing. 8934 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8935 while (S->isClassScope() || 8936 (LangOpts.CPlusPlus && 8937 S->isFunctionPrototypeScope()) || 8938 ((S->getFlags() & Scope::DeclScope) == 0) || 8939 (S->getEntity() && S->getEntity()->isTransparentContext())) 8940 S = S->getParent(); 8941 return S; 8942 } 8943 8944 NamedDecl* 8945 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8946 TypeSourceInfo *TInfo, LookupResult &Previous, 8947 MultiTemplateParamsArg TemplateParamListsRef, 8948 bool &AddToScope) { 8949 QualType R = TInfo->getType(); 8950 8951 assert(R->isFunctionType()); 8952 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 8953 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 8954 8955 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8956 for (TemplateParameterList *TPL : TemplateParamListsRef) 8957 TemplateParamLists.push_back(TPL); 8958 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8959 if (!TemplateParamLists.empty() && 8960 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8961 TemplateParamLists.back() = Invented; 8962 else 8963 TemplateParamLists.push_back(Invented); 8964 } 8965 8966 // TODO: consider using NameInfo for diagnostic. 8967 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8968 DeclarationName Name = NameInfo.getName(); 8969 StorageClass SC = getFunctionStorageClass(*this, D); 8970 8971 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8972 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8973 diag::err_invalid_thread) 8974 << DeclSpec::getSpecifierName(TSCS); 8975 8976 if (D.isFirstDeclarationOfMember()) 8977 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8978 D.getIdentifierLoc()); 8979 8980 bool isFriend = false; 8981 FunctionTemplateDecl *FunctionTemplate = nullptr; 8982 bool isMemberSpecialization = false; 8983 bool isFunctionTemplateSpecialization = false; 8984 8985 bool isDependentClassScopeExplicitSpecialization = false; 8986 bool HasExplicitTemplateArgs = false; 8987 TemplateArgumentListInfo TemplateArgs; 8988 8989 bool isVirtualOkay = false; 8990 8991 DeclContext *OriginalDC = DC; 8992 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8993 8994 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8995 isVirtualOkay); 8996 if (!NewFD) return nullptr; 8997 8998 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8999 NewFD->setTopLevelDeclInObjCContainer(); 9000 9001 // Set the lexical context. If this is a function-scope declaration, or has a 9002 // C++ scope specifier, or is the object of a friend declaration, the lexical 9003 // context will be different from the semantic context. 9004 NewFD->setLexicalDeclContext(CurContext); 9005 9006 if (IsLocalExternDecl) 9007 NewFD->setLocalExternDecl(); 9008 9009 if (getLangOpts().CPlusPlus) { 9010 bool isInline = D.getDeclSpec().isInlineSpecified(); 9011 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9012 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 9013 isFriend = D.getDeclSpec().isFriendSpecified(); 9014 if (isFriend && !isInline && D.isFunctionDefinition()) { 9015 // C++ [class.friend]p5 9016 // A function can be defined in a friend declaration of a 9017 // class . . . . Such a function is implicitly inline. 9018 NewFD->setImplicitlyInline(); 9019 } 9020 9021 // If this is a method defined in an __interface, and is not a constructor 9022 // or an overloaded operator, then set the pure flag (isVirtual will already 9023 // return true). 9024 if (const CXXRecordDecl *Parent = 9025 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 9026 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 9027 NewFD->setPure(true); 9028 9029 // C++ [class.union]p2 9030 // A union can have member functions, but not virtual functions. 9031 if (isVirtual && Parent->isUnion()) 9032 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 9033 } 9034 9035 SetNestedNameSpecifier(*this, NewFD, D); 9036 isMemberSpecialization = false; 9037 isFunctionTemplateSpecialization = false; 9038 if (D.isInvalidType()) 9039 NewFD->setInvalidDecl(); 9040 9041 // Match up the template parameter lists with the scope specifier, then 9042 // determine whether we have a template or a template specialization. 9043 bool Invalid = false; 9044 TemplateParameterList *TemplateParams = 9045 MatchTemplateParametersToScopeSpecifier( 9046 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 9047 D.getCXXScopeSpec(), 9048 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 9049 ? D.getName().TemplateId 9050 : nullptr, 9051 TemplateParamLists, isFriend, isMemberSpecialization, 9052 Invalid); 9053 if (TemplateParams) { 9054 // Check that we can declare a template here. 9055 if (CheckTemplateDeclScope(S, TemplateParams)) 9056 NewFD->setInvalidDecl(); 9057 9058 if (TemplateParams->size() > 0) { 9059 // This is a function template 9060 9061 // A destructor cannot be a template. 9062 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9063 Diag(NewFD->getLocation(), diag::err_destructor_template); 9064 NewFD->setInvalidDecl(); 9065 } 9066 9067 // If we're adding a template to a dependent context, we may need to 9068 // rebuilding some of the types used within the template parameter list, 9069 // now that we know what the current instantiation is. 9070 if (DC->isDependentContext()) { 9071 ContextRAII SavedContext(*this, DC); 9072 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9073 Invalid = true; 9074 } 9075 9076 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9077 NewFD->getLocation(), 9078 Name, TemplateParams, 9079 NewFD); 9080 FunctionTemplate->setLexicalDeclContext(CurContext); 9081 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9082 9083 // For source fidelity, store the other template param lists. 9084 if (TemplateParamLists.size() > 1) { 9085 NewFD->setTemplateParameterListsInfo(Context, 9086 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9087 .drop_back(1)); 9088 } 9089 } else { 9090 // This is a function template specialization. 9091 isFunctionTemplateSpecialization = true; 9092 // For source fidelity, store all the template param lists. 9093 if (TemplateParamLists.size() > 0) 9094 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9095 9096 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9097 if (isFriend) { 9098 // We want to remove the "template<>", found here. 9099 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9100 9101 // If we remove the template<> and the name is not a 9102 // template-id, we're actually silently creating a problem: 9103 // the friend declaration will refer to an untemplated decl, 9104 // and clearly the user wants a template specialization. So 9105 // we need to insert '<>' after the name. 9106 SourceLocation InsertLoc; 9107 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9108 InsertLoc = D.getName().getSourceRange().getEnd(); 9109 InsertLoc = getLocForEndOfToken(InsertLoc); 9110 } 9111 9112 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9113 << Name << RemoveRange 9114 << FixItHint::CreateRemoval(RemoveRange) 9115 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9116 } 9117 } 9118 } else { 9119 // Check that we can declare a template here. 9120 if (!TemplateParamLists.empty() && isMemberSpecialization && 9121 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9122 NewFD->setInvalidDecl(); 9123 9124 // All template param lists were matched against the scope specifier: 9125 // this is NOT (an explicit specialization of) a template. 9126 if (TemplateParamLists.size() > 0) 9127 // For source fidelity, store all the template param lists. 9128 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9129 } 9130 9131 if (Invalid) { 9132 NewFD->setInvalidDecl(); 9133 if (FunctionTemplate) 9134 FunctionTemplate->setInvalidDecl(); 9135 } 9136 9137 // C++ [dcl.fct.spec]p5: 9138 // The virtual specifier shall only be used in declarations of 9139 // nonstatic class member functions that appear within a 9140 // member-specification of a class declaration; see 10.3. 9141 // 9142 if (isVirtual && !NewFD->isInvalidDecl()) { 9143 if (!isVirtualOkay) { 9144 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9145 diag::err_virtual_non_function); 9146 } else if (!CurContext->isRecord()) { 9147 // 'virtual' was specified outside of the class. 9148 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9149 diag::err_virtual_out_of_class) 9150 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9151 } else if (NewFD->getDescribedFunctionTemplate()) { 9152 // C++ [temp.mem]p3: 9153 // A member function template shall not be virtual. 9154 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9155 diag::err_virtual_member_function_template) 9156 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9157 } else { 9158 // Okay: Add virtual to the method. 9159 NewFD->setVirtualAsWritten(true); 9160 } 9161 9162 if (getLangOpts().CPlusPlus14 && 9163 NewFD->getReturnType()->isUndeducedType()) 9164 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9165 } 9166 9167 if (getLangOpts().CPlusPlus14 && 9168 (NewFD->isDependentContext() || 9169 (isFriend && CurContext->isDependentContext())) && 9170 NewFD->getReturnType()->isUndeducedType()) { 9171 // If the function template is referenced directly (for instance, as a 9172 // member of the current instantiation), pretend it has a dependent type. 9173 // This is not really justified by the standard, but is the only sane 9174 // thing to do. 9175 // FIXME: For a friend function, we have not marked the function as being 9176 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9177 const FunctionProtoType *FPT = 9178 NewFD->getType()->castAs<FunctionProtoType>(); 9179 QualType Result = 9180 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9181 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9182 FPT->getExtProtoInfo())); 9183 } 9184 9185 // C++ [dcl.fct.spec]p3: 9186 // The inline specifier shall not appear on a block scope function 9187 // declaration. 9188 if (isInline && !NewFD->isInvalidDecl()) { 9189 if (CurContext->isFunctionOrMethod()) { 9190 // 'inline' is not allowed on block scope function declaration. 9191 Diag(D.getDeclSpec().getInlineSpecLoc(), 9192 diag::err_inline_declaration_block_scope) << Name 9193 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9194 } 9195 } 9196 9197 // C++ [dcl.fct.spec]p6: 9198 // The explicit specifier shall be used only in the declaration of a 9199 // constructor or conversion function within its class definition; 9200 // see 12.3.1 and 12.3.2. 9201 if (hasExplicit && !NewFD->isInvalidDecl() && 9202 !isa<CXXDeductionGuideDecl>(NewFD)) { 9203 if (!CurContext->isRecord()) { 9204 // 'explicit' was specified outside of the class. 9205 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9206 diag::err_explicit_out_of_class) 9207 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9208 } else if (!isa<CXXConstructorDecl>(NewFD) && 9209 !isa<CXXConversionDecl>(NewFD)) { 9210 // 'explicit' was specified on a function that wasn't a constructor 9211 // or conversion function. 9212 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9213 diag::err_explicit_non_ctor_or_conv_function) 9214 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9215 } 9216 } 9217 9218 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9219 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9220 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9221 // are implicitly inline. 9222 NewFD->setImplicitlyInline(); 9223 9224 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9225 // be either constructors or to return a literal type. Therefore, 9226 // destructors cannot be declared constexpr. 9227 if (isa<CXXDestructorDecl>(NewFD) && 9228 (!getLangOpts().CPlusPlus20 || 9229 ConstexprKind == ConstexprSpecKind::Consteval)) { 9230 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9231 << static_cast<int>(ConstexprKind); 9232 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9233 ? ConstexprSpecKind::Unspecified 9234 : ConstexprSpecKind::Constexpr); 9235 } 9236 // C++20 [dcl.constexpr]p2: An allocation function, or a 9237 // deallocation function shall not be declared with the consteval 9238 // specifier. 9239 if (ConstexprKind == ConstexprSpecKind::Consteval && 9240 (NewFD->getOverloadedOperator() == OO_New || 9241 NewFD->getOverloadedOperator() == OO_Array_New || 9242 NewFD->getOverloadedOperator() == OO_Delete || 9243 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9244 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9245 diag::err_invalid_consteval_decl_kind) 9246 << NewFD; 9247 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9248 } 9249 } 9250 9251 // If __module_private__ was specified, mark the function accordingly. 9252 if (D.getDeclSpec().isModulePrivateSpecified()) { 9253 if (isFunctionTemplateSpecialization) { 9254 SourceLocation ModulePrivateLoc 9255 = D.getDeclSpec().getModulePrivateSpecLoc(); 9256 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9257 << 0 9258 << FixItHint::CreateRemoval(ModulePrivateLoc); 9259 } else { 9260 NewFD->setModulePrivate(); 9261 if (FunctionTemplate) 9262 FunctionTemplate->setModulePrivate(); 9263 } 9264 } 9265 9266 if (isFriend) { 9267 if (FunctionTemplate) { 9268 FunctionTemplate->setObjectOfFriendDecl(); 9269 FunctionTemplate->setAccess(AS_public); 9270 } 9271 NewFD->setObjectOfFriendDecl(); 9272 NewFD->setAccess(AS_public); 9273 } 9274 9275 // If a function is defined as defaulted or deleted, mark it as such now. 9276 // We'll do the relevant checks on defaulted / deleted functions later. 9277 switch (D.getFunctionDefinitionKind()) { 9278 case FunctionDefinitionKind::Declaration: 9279 case FunctionDefinitionKind::Definition: 9280 break; 9281 9282 case FunctionDefinitionKind::Defaulted: 9283 NewFD->setDefaulted(); 9284 break; 9285 9286 case FunctionDefinitionKind::Deleted: 9287 NewFD->setDeletedAsWritten(); 9288 break; 9289 } 9290 9291 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9292 D.isFunctionDefinition()) { 9293 // C++ [class.mfct]p2: 9294 // A member function may be defined (8.4) in its class definition, in 9295 // which case it is an inline member function (7.1.2) 9296 NewFD->setImplicitlyInline(); 9297 } 9298 9299 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9300 !CurContext->isRecord()) { 9301 // C++ [class.static]p1: 9302 // A data or function member of a class may be declared static 9303 // in a class definition, in which case it is a static member of 9304 // the class. 9305 9306 // Complain about the 'static' specifier if it's on an out-of-line 9307 // member function definition. 9308 9309 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9310 // member function template declaration and class member template 9311 // declaration (MSVC versions before 2015), warn about this. 9312 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9313 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9314 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9315 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9316 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9317 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9318 } 9319 9320 // C++11 [except.spec]p15: 9321 // A deallocation function with no exception-specification is treated 9322 // as if it were specified with noexcept(true). 9323 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9324 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9325 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9326 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9327 NewFD->setType(Context.getFunctionType( 9328 FPT->getReturnType(), FPT->getParamTypes(), 9329 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9330 } 9331 9332 // Filter out previous declarations that don't match the scope. 9333 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9334 D.getCXXScopeSpec().isNotEmpty() || 9335 isMemberSpecialization || 9336 isFunctionTemplateSpecialization); 9337 9338 // Handle GNU asm-label extension (encoded as an attribute). 9339 if (Expr *E = (Expr*) D.getAsmLabel()) { 9340 // The parser guarantees this is a string. 9341 StringLiteral *SE = cast<StringLiteral>(E); 9342 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9343 /*IsLiteralLabel=*/true, 9344 SE->getStrTokenLoc(0))); 9345 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9346 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9347 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9348 if (I != ExtnameUndeclaredIdentifiers.end()) { 9349 if (isDeclExternC(NewFD)) { 9350 NewFD->addAttr(I->second); 9351 ExtnameUndeclaredIdentifiers.erase(I); 9352 } else 9353 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9354 << /*Variable*/0 << NewFD; 9355 } 9356 } 9357 9358 // Copy the parameter declarations from the declarator D to the function 9359 // declaration NewFD, if they are available. First scavenge them into Params. 9360 SmallVector<ParmVarDecl*, 16> Params; 9361 unsigned FTIIdx; 9362 if (D.isFunctionDeclarator(FTIIdx)) { 9363 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9364 9365 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9366 // function that takes no arguments, not a function that takes a 9367 // single void argument. 9368 // We let through "const void" here because Sema::GetTypeForDeclarator 9369 // already checks for that case. 9370 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9371 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9372 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9373 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9374 Param->setDeclContext(NewFD); 9375 Params.push_back(Param); 9376 9377 if (Param->isInvalidDecl()) 9378 NewFD->setInvalidDecl(); 9379 } 9380 } 9381 9382 if (!getLangOpts().CPlusPlus) { 9383 // In C, find all the tag declarations from the prototype and move them 9384 // into the function DeclContext. Remove them from the surrounding tag 9385 // injection context of the function, which is typically but not always 9386 // the TU. 9387 DeclContext *PrototypeTagContext = 9388 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9389 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9390 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9391 9392 // We don't want to reparent enumerators. Look at their parent enum 9393 // instead. 9394 if (!TD) { 9395 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9396 TD = cast<EnumDecl>(ECD->getDeclContext()); 9397 } 9398 if (!TD) 9399 continue; 9400 DeclContext *TagDC = TD->getLexicalDeclContext(); 9401 if (!TagDC->containsDecl(TD)) 9402 continue; 9403 TagDC->removeDecl(TD); 9404 TD->setDeclContext(NewFD); 9405 NewFD->addDecl(TD); 9406 9407 // Preserve the lexical DeclContext if it is not the surrounding tag 9408 // injection context of the FD. In this example, the semantic context of 9409 // E will be f and the lexical context will be S, while both the 9410 // semantic and lexical contexts of S will be f: 9411 // void f(struct S { enum E { a } f; } s); 9412 if (TagDC != PrototypeTagContext) 9413 TD->setLexicalDeclContext(TagDC); 9414 } 9415 } 9416 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9417 // When we're declaring a function with a typedef, typeof, etc as in the 9418 // following example, we'll need to synthesize (unnamed) 9419 // parameters for use in the declaration. 9420 // 9421 // @code 9422 // typedef void fn(int); 9423 // fn f; 9424 // @endcode 9425 9426 // Synthesize a parameter for each argument type. 9427 for (const auto &AI : FT->param_types()) { 9428 ParmVarDecl *Param = 9429 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9430 Param->setScopeInfo(0, Params.size()); 9431 Params.push_back(Param); 9432 } 9433 } else { 9434 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9435 "Should not need args for typedef of non-prototype fn"); 9436 } 9437 9438 // Finally, we know we have the right number of parameters, install them. 9439 NewFD->setParams(Params); 9440 9441 if (D.getDeclSpec().isNoreturnSpecified()) 9442 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9443 D.getDeclSpec().getNoreturnSpecLoc(), 9444 AttributeCommonInfo::AS_Keyword)); 9445 9446 // Functions returning a variably modified type violate C99 6.7.5.2p2 9447 // because all functions have linkage. 9448 if (!NewFD->isInvalidDecl() && 9449 NewFD->getReturnType()->isVariablyModifiedType()) { 9450 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9451 NewFD->setInvalidDecl(); 9452 } 9453 9454 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9455 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9456 !NewFD->hasAttr<SectionAttr>()) 9457 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9458 Context, PragmaClangTextSection.SectionName, 9459 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9460 9461 // Apply an implicit SectionAttr if #pragma code_seg is active. 9462 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9463 !NewFD->hasAttr<SectionAttr>()) { 9464 NewFD->addAttr(SectionAttr::CreateImplicit( 9465 Context, CodeSegStack.CurrentValue->getString(), 9466 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9467 SectionAttr::Declspec_allocate)); 9468 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9469 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9470 ASTContext::PSF_Read, 9471 NewFD)) 9472 NewFD->dropAttr<SectionAttr>(); 9473 } 9474 9475 // Apply an implicit CodeSegAttr from class declspec or 9476 // apply an implicit SectionAttr from #pragma code_seg if active. 9477 if (!NewFD->hasAttr<CodeSegAttr>()) { 9478 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9479 D.isFunctionDefinition())) { 9480 NewFD->addAttr(SAttr); 9481 } 9482 } 9483 9484 // Handle attributes. 9485 ProcessDeclAttributes(S, NewFD, D); 9486 9487 if (getLangOpts().OpenCL) { 9488 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9489 // type declaration will generate a compilation error. 9490 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9491 if (AddressSpace != LangAS::Default) { 9492 Diag(NewFD->getLocation(), 9493 diag::err_opencl_return_value_with_address_space); 9494 NewFD->setInvalidDecl(); 9495 } 9496 } 9497 9498 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) 9499 checkDeviceDecl(NewFD, D.getBeginLoc()); 9500 9501 if (!getLangOpts().CPlusPlus) { 9502 // Perform semantic checking on the function declaration. 9503 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9504 CheckMain(NewFD, D.getDeclSpec()); 9505 9506 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9507 CheckMSVCRTEntryPoint(NewFD); 9508 9509 if (!NewFD->isInvalidDecl()) 9510 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9511 isMemberSpecialization)); 9512 else if (!Previous.empty()) 9513 // Recover gracefully from an invalid redeclaration. 9514 D.setRedeclaration(true); 9515 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9516 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9517 "previous declaration set still overloaded"); 9518 9519 // Diagnose no-prototype function declarations with calling conventions that 9520 // don't support variadic calls. Only do this in C and do it after merging 9521 // possibly prototyped redeclarations. 9522 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9523 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9524 CallingConv CC = FT->getExtInfo().getCC(); 9525 if (!supportsVariadicCall(CC)) { 9526 // Windows system headers sometimes accidentally use stdcall without 9527 // (void) parameters, so we relax this to a warning. 9528 int DiagID = 9529 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9530 Diag(NewFD->getLocation(), DiagID) 9531 << FunctionType::getNameForCallConv(CC); 9532 } 9533 } 9534 9535 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9536 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9537 checkNonTrivialCUnion(NewFD->getReturnType(), 9538 NewFD->getReturnTypeSourceRange().getBegin(), 9539 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9540 } else { 9541 // C++11 [replacement.functions]p3: 9542 // The program's definitions shall not be specified as inline. 9543 // 9544 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9545 // 9546 // Suppress the diagnostic if the function is __attribute__((used)), since 9547 // that forces an external definition to be emitted. 9548 if (D.getDeclSpec().isInlineSpecified() && 9549 NewFD->isReplaceableGlobalAllocationFunction() && 9550 !NewFD->hasAttr<UsedAttr>()) 9551 Diag(D.getDeclSpec().getInlineSpecLoc(), 9552 diag::ext_operator_new_delete_declared_inline) 9553 << NewFD->getDeclName(); 9554 9555 // If the declarator is a template-id, translate the parser's template 9556 // argument list into our AST format. 9557 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9558 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9559 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9560 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9561 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9562 TemplateId->NumArgs); 9563 translateTemplateArguments(TemplateArgsPtr, 9564 TemplateArgs); 9565 9566 HasExplicitTemplateArgs = true; 9567 9568 if (NewFD->isInvalidDecl()) { 9569 HasExplicitTemplateArgs = false; 9570 } else if (FunctionTemplate) { 9571 // Function template with explicit template arguments. 9572 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9573 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9574 9575 HasExplicitTemplateArgs = false; 9576 } else { 9577 assert((isFunctionTemplateSpecialization || 9578 D.getDeclSpec().isFriendSpecified()) && 9579 "should have a 'template<>' for this decl"); 9580 // "friend void foo<>(int);" is an implicit specialization decl. 9581 isFunctionTemplateSpecialization = true; 9582 } 9583 } else if (isFriend && isFunctionTemplateSpecialization) { 9584 // This combination is only possible in a recovery case; the user 9585 // wrote something like: 9586 // template <> friend void foo(int); 9587 // which we're recovering from as if the user had written: 9588 // friend void foo<>(int); 9589 // Go ahead and fake up a template id. 9590 HasExplicitTemplateArgs = true; 9591 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9592 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9593 } 9594 9595 // We do not add HD attributes to specializations here because 9596 // they may have different constexpr-ness compared to their 9597 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9598 // may end up with different effective targets. Instead, a 9599 // specialization inherits its target attributes from its template 9600 // in the CheckFunctionTemplateSpecialization() call below. 9601 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9602 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9603 9604 // If it's a friend (and only if it's a friend), it's possible 9605 // that either the specialized function type or the specialized 9606 // template is dependent, and therefore matching will fail. In 9607 // this case, don't check the specialization yet. 9608 if (isFunctionTemplateSpecialization && isFriend && 9609 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9610 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 9611 TemplateArgs.arguments()))) { 9612 assert(HasExplicitTemplateArgs && 9613 "friend function specialization without template args"); 9614 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9615 Previous)) 9616 NewFD->setInvalidDecl(); 9617 } else if (isFunctionTemplateSpecialization) { 9618 if (CurContext->isDependentContext() && CurContext->isRecord() 9619 && !isFriend) { 9620 isDependentClassScopeExplicitSpecialization = true; 9621 } else if (!NewFD->isInvalidDecl() && 9622 CheckFunctionTemplateSpecialization( 9623 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9624 Previous)) 9625 NewFD->setInvalidDecl(); 9626 9627 // C++ [dcl.stc]p1: 9628 // A storage-class-specifier shall not be specified in an explicit 9629 // specialization (14.7.3) 9630 FunctionTemplateSpecializationInfo *Info = 9631 NewFD->getTemplateSpecializationInfo(); 9632 if (Info && SC != SC_None) { 9633 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9634 Diag(NewFD->getLocation(), 9635 diag::err_explicit_specialization_inconsistent_storage_class) 9636 << SC 9637 << FixItHint::CreateRemoval( 9638 D.getDeclSpec().getStorageClassSpecLoc()); 9639 9640 else 9641 Diag(NewFD->getLocation(), 9642 diag::ext_explicit_specialization_storage_class) 9643 << FixItHint::CreateRemoval( 9644 D.getDeclSpec().getStorageClassSpecLoc()); 9645 } 9646 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9647 if (CheckMemberSpecialization(NewFD, Previous)) 9648 NewFD->setInvalidDecl(); 9649 } 9650 9651 // Perform semantic checking on the function declaration. 9652 if (!isDependentClassScopeExplicitSpecialization) { 9653 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9654 CheckMain(NewFD, D.getDeclSpec()); 9655 9656 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9657 CheckMSVCRTEntryPoint(NewFD); 9658 9659 if (!NewFD->isInvalidDecl()) 9660 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9661 isMemberSpecialization)); 9662 else if (!Previous.empty()) 9663 // Recover gracefully from an invalid redeclaration. 9664 D.setRedeclaration(true); 9665 } 9666 9667 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9668 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9669 "previous declaration set still overloaded"); 9670 9671 NamedDecl *PrincipalDecl = (FunctionTemplate 9672 ? cast<NamedDecl>(FunctionTemplate) 9673 : NewFD); 9674 9675 if (isFriend && NewFD->getPreviousDecl()) { 9676 AccessSpecifier Access = AS_public; 9677 if (!NewFD->isInvalidDecl()) 9678 Access = NewFD->getPreviousDecl()->getAccess(); 9679 9680 NewFD->setAccess(Access); 9681 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9682 } 9683 9684 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9685 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9686 PrincipalDecl->setNonMemberOperator(); 9687 9688 // If we have a function template, check the template parameter 9689 // list. This will check and merge default template arguments. 9690 if (FunctionTemplate) { 9691 FunctionTemplateDecl *PrevTemplate = 9692 FunctionTemplate->getPreviousDecl(); 9693 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9694 PrevTemplate ? PrevTemplate->getTemplateParameters() 9695 : nullptr, 9696 D.getDeclSpec().isFriendSpecified() 9697 ? (D.isFunctionDefinition() 9698 ? TPC_FriendFunctionTemplateDefinition 9699 : TPC_FriendFunctionTemplate) 9700 : (D.getCXXScopeSpec().isSet() && 9701 DC && DC->isRecord() && 9702 DC->isDependentContext()) 9703 ? TPC_ClassTemplateMember 9704 : TPC_FunctionTemplate); 9705 } 9706 9707 if (NewFD->isInvalidDecl()) { 9708 // Ignore all the rest of this. 9709 } else if (!D.isRedeclaration()) { 9710 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9711 AddToScope }; 9712 // Fake up an access specifier if it's supposed to be a class member. 9713 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9714 NewFD->setAccess(AS_public); 9715 9716 // Qualified decls generally require a previous declaration. 9717 if (D.getCXXScopeSpec().isSet()) { 9718 // ...with the major exception of templated-scope or 9719 // dependent-scope friend declarations. 9720 9721 // TODO: we currently also suppress this check in dependent 9722 // contexts because (1) the parameter depth will be off when 9723 // matching friend templates and (2) we might actually be 9724 // selecting a friend based on a dependent factor. But there 9725 // are situations where these conditions don't apply and we 9726 // can actually do this check immediately. 9727 // 9728 // Unless the scope is dependent, it's always an error if qualified 9729 // redeclaration lookup found nothing at all. Diagnose that now; 9730 // nothing will diagnose that error later. 9731 if (isFriend && 9732 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9733 (!Previous.empty() && CurContext->isDependentContext()))) { 9734 // ignore these 9735 } else if (NewFD->isCPUDispatchMultiVersion() || 9736 NewFD->isCPUSpecificMultiVersion()) { 9737 // ignore this, we allow the redeclaration behavior here to create new 9738 // versions of the function. 9739 } else { 9740 // The user tried to provide an out-of-line definition for a 9741 // function that is a member of a class or namespace, but there 9742 // was no such member function declared (C++ [class.mfct]p2, 9743 // C++ [namespace.memdef]p2). For example: 9744 // 9745 // class X { 9746 // void f() const; 9747 // }; 9748 // 9749 // void X::f() { } // ill-formed 9750 // 9751 // Complain about this problem, and attempt to suggest close 9752 // matches (e.g., those that differ only in cv-qualifiers and 9753 // whether the parameter types are references). 9754 9755 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9756 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9757 AddToScope = ExtraArgs.AddToScope; 9758 return Result; 9759 } 9760 } 9761 9762 // Unqualified local friend declarations are required to resolve 9763 // to something. 9764 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9765 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9766 *this, Previous, NewFD, ExtraArgs, true, S)) { 9767 AddToScope = ExtraArgs.AddToScope; 9768 return Result; 9769 } 9770 } 9771 } else if (!D.isFunctionDefinition() && 9772 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9773 !isFriend && !isFunctionTemplateSpecialization && 9774 !isMemberSpecialization) { 9775 // An out-of-line member function declaration must also be a 9776 // definition (C++ [class.mfct]p2). 9777 // Note that this is not the case for explicit specializations of 9778 // function templates or member functions of class templates, per 9779 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9780 // extension for compatibility with old SWIG code which likes to 9781 // generate them. 9782 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9783 << D.getCXXScopeSpec().getRange(); 9784 } 9785 } 9786 9787 // If this is the first declaration of a library builtin function, add 9788 // attributes as appropriate. 9789 if (!D.isRedeclaration() && 9790 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 9791 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 9792 if (unsigned BuiltinID = II->getBuiltinID()) { 9793 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 9794 // Validate the type matches unless this builtin is specified as 9795 // matching regardless of its declared type. 9796 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 9797 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9798 } else { 9799 ASTContext::GetBuiltinTypeError Error; 9800 LookupNecessaryTypesForBuiltin(S, BuiltinID); 9801 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 9802 9803 if (!Error && !BuiltinType.isNull() && 9804 Context.hasSameFunctionTypeIgnoringExceptionSpec( 9805 NewFD->getType(), BuiltinType)) 9806 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9807 } 9808 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 9809 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9810 // FIXME: We should consider this a builtin only in the std namespace. 9811 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9812 } 9813 } 9814 } 9815 } 9816 9817 ProcessPragmaWeak(S, NewFD); 9818 checkAttributesAfterMerging(*this, *NewFD); 9819 9820 AddKnownFunctionAttributes(NewFD); 9821 9822 if (NewFD->hasAttr<OverloadableAttr>() && 9823 !NewFD->getType()->getAs<FunctionProtoType>()) { 9824 Diag(NewFD->getLocation(), 9825 diag::err_attribute_overloadable_no_prototype) 9826 << NewFD; 9827 9828 // Turn this into a variadic function with no parameters. 9829 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9830 FunctionProtoType::ExtProtoInfo EPI( 9831 Context.getDefaultCallingConvention(true, false)); 9832 EPI.Variadic = true; 9833 EPI.ExtInfo = FT->getExtInfo(); 9834 9835 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9836 NewFD->setType(R); 9837 } 9838 9839 // If there's a #pragma GCC visibility in scope, and this isn't a class 9840 // member, set the visibility of this function. 9841 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9842 AddPushedVisibilityAttribute(NewFD); 9843 9844 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9845 // marking the function. 9846 AddCFAuditedAttribute(NewFD); 9847 9848 // If this is a function definition, check if we have to apply optnone due to 9849 // a pragma. 9850 if(D.isFunctionDefinition()) 9851 AddRangeBasedOptnone(NewFD); 9852 9853 // If this is the first declaration of an extern C variable, update 9854 // the map of such variables. 9855 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9856 isIncompleteDeclExternC(*this, NewFD)) 9857 RegisterLocallyScopedExternCDecl(NewFD, S); 9858 9859 // Set this FunctionDecl's range up to the right paren. 9860 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9861 9862 if (D.isRedeclaration() && !Previous.empty()) { 9863 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9864 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9865 isMemberSpecialization || 9866 isFunctionTemplateSpecialization, 9867 D.isFunctionDefinition()); 9868 } 9869 9870 if (getLangOpts().CUDA) { 9871 IdentifierInfo *II = NewFD->getIdentifier(); 9872 if (II && II->isStr(getCudaConfigureFuncName()) && 9873 !NewFD->isInvalidDecl() && 9874 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9875 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) 9876 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9877 << getCudaConfigureFuncName(); 9878 Context.setcudaConfigureCallDecl(NewFD); 9879 } 9880 9881 // Variadic functions, other than a *declaration* of printf, are not allowed 9882 // in device-side CUDA code, unless someone passed 9883 // -fcuda-allow-variadic-functions. 9884 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9885 (NewFD->hasAttr<CUDADeviceAttr>() || 9886 NewFD->hasAttr<CUDAGlobalAttr>()) && 9887 !(II && II->isStr("printf") && NewFD->isExternC() && 9888 !D.isFunctionDefinition())) { 9889 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9890 } 9891 } 9892 9893 MarkUnusedFileScopedDecl(NewFD); 9894 9895 9896 9897 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9898 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9899 if ((getLangOpts().OpenCLVersion >= 120) 9900 && (SC == SC_Static)) { 9901 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9902 D.setInvalidType(); 9903 } 9904 9905 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9906 if (!NewFD->getReturnType()->isVoidType()) { 9907 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9908 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9909 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9910 : FixItHint()); 9911 D.setInvalidType(); 9912 } 9913 9914 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9915 for (auto Param : NewFD->parameters()) 9916 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9917 9918 if (getLangOpts().OpenCLCPlusPlus) { 9919 if (DC->isRecord()) { 9920 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9921 D.setInvalidType(); 9922 } 9923 if (FunctionTemplate) { 9924 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9925 D.setInvalidType(); 9926 } 9927 } 9928 } 9929 9930 if (getLangOpts().CPlusPlus) { 9931 if (FunctionTemplate) { 9932 if (NewFD->isInvalidDecl()) 9933 FunctionTemplate->setInvalidDecl(); 9934 return FunctionTemplate; 9935 } 9936 9937 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9938 CompleteMemberSpecialization(NewFD, Previous); 9939 } 9940 9941 for (const ParmVarDecl *Param : NewFD->parameters()) { 9942 QualType PT = Param->getType(); 9943 9944 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9945 // types. 9946 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9947 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9948 QualType ElemTy = PipeTy->getElementType(); 9949 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9950 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9951 D.setInvalidType(); 9952 } 9953 } 9954 } 9955 } 9956 9957 // Here we have an function template explicit specialization at class scope. 9958 // The actual specialization will be postponed to template instatiation 9959 // time via the ClassScopeFunctionSpecializationDecl node. 9960 if (isDependentClassScopeExplicitSpecialization) { 9961 ClassScopeFunctionSpecializationDecl *NewSpec = 9962 ClassScopeFunctionSpecializationDecl::Create( 9963 Context, CurContext, NewFD->getLocation(), 9964 cast<CXXMethodDecl>(NewFD), 9965 HasExplicitTemplateArgs, TemplateArgs); 9966 CurContext->addDecl(NewSpec); 9967 AddToScope = false; 9968 } 9969 9970 // Diagnose availability attributes. Availability cannot be used on functions 9971 // that are run during load/unload. 9972 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9973 if (NewFD->hasAttr<ConstructorAttr>()) { 9974 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9975 << 1; 9976 NewFD->dropAttr<AvailabilityAttr>(); 9977 } 9978 if (NewFD->hasAttr<DestructorAttr>()) { 9979 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9980 << 2; 9981 NewFD->dropAttr<AvailabilityAttr>(); 9982 } 9983 } 9984 9985 // Diagnose no_builtin attribute on function declaration that are not a 9986 // definition. 9987 // FIXME: We should really be doing this in 9988 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9989 // the FunctionDecl and at this point of the code 9990 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9991 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9992 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9993 switch (D.getFunctionDefinitionKind()) { 9994 case FunctionDefinitionKind::Defaulted: 9995 case FunctionDefinitionKind::Deleted: 9996 Diag(NBA->getLocation(), 9997 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9998 << NBA->getSpelling(); 9999 break; 10000 case FunctionDefinitionKind::Declaration: 10001 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 10002 << NBA->getSpelling(); 10003 break; 10004 case FunctionDefinitionKind::Definition: 10005 break; 10006 } 10007 10008 return NewFD; 10009 } 10010 10011 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 10012 /// when __declspec(code_seg) "is applied to a class, all member functions of 10013 /// the class and nested classes -- this includes compiler-generated special 10014 /// member functions -- are put in the specified segment." 10015 /// The actual behavior is a little more complicated. The Microsoft compiler 10016 /// won't check outer classes if there is an active value from #pragma code_seg. 10017 /// The CodeSeg is always applied from the direct parent but only from outer 10018 /// classes when the #pragma code_seg stack is empty. See: 10019 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 10020 /// available since MS has removed the page. 10021 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 10022 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 10023 if (!Method) 10024 return nullptr; 10025 const CXXRecordDecl *Parent = Method->getParent(); 10026 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10027 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10028 NewAttr->setImplicit(true); 10029 return NewAttr; 10030 } 10031 10032 // The Microsoft compiler won't check outer classes for the CodeSeg 10033 // when the #pragma code_seg stack is active. 10034 if (S.CodeSegStack.CurrentValue) 10035 return nullptr; 10036 10037 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 10038 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10039 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10040 NewAttr->setImplicit(true); 10041 return NewAttr; 10042 } 10043 } 10044 return nullptr; 10045 } 10046 10047 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 10048 /// containing class. Otherwise it will return implicit SectionAttr if the 10049 /// function is a definition and there is an active value on CodeSegStack 10050 /// (from the current #pragma code-seg value). 10051 /// 10052 /// \param FD Function being declared. 10053 /// \param IsDefinition Whether it is a definition or just a declarartion. 10054 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 10055 /// nullptr if no attribute should be added. 10056 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 10057 bool IsDefinition) { 10058 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 10059 return A; 10060 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 10061 CodeSegStack.CurrentValue) 10062 return SectionAttr::CreateImplicit( 10063 getASTContext(), CodeSegStack.CurrentValue->getString(), 10064 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 10065 SectionAttr::Declspec_allocate); 10066 return nullptr; 10067 } 10068 10069 /// Determines if we can perform a correct type check for \p D as a 10070 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 10071 /// best-effort check. 10072 /// 10073 /// \param NewD The new declaration. 10074 /// \param OldD The old declaration. 10075 /// \param NewT The portion of the type of the new declaration to check. 10076 /// \param OldT The portion of the type of the old declaration to check. 10077 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 10078 QualType NewT, QualType OldT) { 10079 if (!NewD->getLexicalDeclContext()->isDependentContext()) 10080 return true; 10081 10082 // For dependently-typed local extern declarations and friends, we can't 10083 // perform a correct type check in general until instantiation: 10084 // 10085 // int f(); 10086 // template<typename T> void g() { T f(); } 10087 // 10088 // (valid if g() is only instantiated with T = int). 10089 if (NewT->isDependentType() && 10090 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10091 return false; 10092 10093 // Similarly, if the previous declaration was a dependent local extern 10094 // declaration, we don't really know its type yet. 10095 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10096 return false; 10097 10098 return true; 10099 } 10100 10101 /// Checks if the new declaration declared in dependent context must be 10102 /// put in the same redeclaration chain as the specified declaration. 10103 /// 10104 /// \param D Declaration that is checked. 10105 /// \param PrevDecl Previous declaration found with proper lookup method for the 10106 /// same declaration name. 10107 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10108 /// belongs to. 10109 /// 10110 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10111 if (!D->getLexicalDeclContext()->isDependentContext()) 10112 return true; 10113 10114 // Don't chain dependent friend function definitions until instantiation, to 10115 // permit cases like 10116 // 10117 // void func(); 10118 // template<typename T> class C1 { friend void func() {} }; 10119 // template<typename T> class C2 { friend void func() {} }; 10120 // 10121 // ... which is valid if only one of C1 and C2 is ever instantiated. 10122 // 10123 // FIXME: This need only apply to function definitions. For now, we proxy 10124 // this by checking for a file-scope function. We do not want this to apply 10125 // to friend declarations nominating member functions, because that gets in 10126 // the way of access checks. 10127 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10128 return false; 10129 10130 auto *VD = dyn_cast<ValueDecl>(D); 10131 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10132 return !VD || !PrevVD || 10133 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10134 PrevVD->getType()); 10135 } 10136 10137 /// Check the target attribute of the function for MultiVersion 10138 /// validity. 10139 /// 10140 /// Returns true if there was an error, false otherwise. 10141 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10142 const auto *TA = FD->getAttr<TargetAttr>(); 10143 assert(TA && "MultiVersion Candidate requires a target attribute"); 10144 ParsedTargetAttr ParseInfo = TA->parse(); 10145 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10146 enum ErrType { Feature = 0, Architecture = 1 }; 10147 10148 if (!ParseInfo.Architecture.empty() && 10149 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10150 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10151 << Architecture << ParseInfo.Architecture; 10152 return true; 10153 } 10154 10155 for (const auto &Feat : ParseInfo.Features) { 10156 auto BareFeat = StringRef{Feat}.substr(1); 10157 if (Feat[0] == '-') { 10158 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10159 << Feature << ("no-" + BareFeat).str(); 10160 return true; 10161 } 10162 10163 if (!TargetInfo.validateCpuSupports(BareFeat) || 10164 !TargetInfo.isValidFeatureName(BareFeat)) { 10165 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10166 << Feature << BareFeat; 10167 return true; 10168 } 10169 } 10170 return false; 10171 } 10172 10173 // Provide a white-list of attributes that are allowed to be combined with 10174 // multiversion functions. 10175 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10176 MultiVersionKind MVType) { 10177 // Note: this list/diagnosis must match the list in 10178 // checkMultiversionAttributesAllSame. 10179 switch (Kind) { 10180 default: 10181 return false; 10182 case attr::Used: 10183 return MVType == MultiVersionKind::Target; 10184 case attr::NonNull: 10185 case attr::NoThrow: 10186 return true; 10187 } 10188 } 10189 10190 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10191 const FunctionDecl *FD, 10192 const FunctionDecl *CausedFD, 10193 MultiVersionKind MVType) { 10194 bool IsCPUSpecificCPUDispatchMVType = 10195 MVType == MultiVersionKind::CPUDispatch || 10196 MVType == MultiVersionKind::CPUSpecific; 10197 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType]( 10198 Sema &S, const Attr *A) { 10199 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10200 << IsCPUSpecificCPUDispatchMVType << A; 10201 if (CausedFD) 10202 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10203 return true; 10204 }; 10205 10206 for (const Attr *A : FD->attrs()) { 10207 switch (A->getKind()) { 10208 case attr::CPUDispatch: 10209 case attr::CPUSpecific: 10210 if (MVType != MultiVersionKind::CPUDispatch && 10211 MVType != MultiVersionKind::CPUSpecific) 10212 return Diagnose(S, A); 10213 break; 10214 case attr::Target: 10215 if (MVType != MultiVersionKind::Target) 10216 return Diagnose(S, A); 10217 break; 10218 default: 10219 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10220 return Diagnose(S, A); 10221 break; 10222 } 10223 } 10224 return false; 10225 } 10226 10227 bool Sema::areMultiversionVariantFunctionsCompatible( 10228 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10229 const PartialDiagnostic &NoProtoDiagID, 10230 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10231 const PartialDiagnosticAt &NoSupportDiagIDAt, 10232 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10233 bool ConstexprSupported, bool CLinkageMayDiffer) { 10234 enum DoesntSupport { 10235 FuncTemplates = 0, 10236 VirtFuncs = 1, 10237 DeducedReturn = 2, 10238 Constructors = 3, 10239 Destructors = 4, 10240 DeletedFuncs = 5, 10241 DefaultedFuncs = 6, 10242 ConstexprFuncs = 7, 10243 ConstevalFuncs = 8, 10244 }; 10245 enum Different { 10246 CallingConv = 0, 10247 ReturnType = 1, 10248 ConstexprSpec = 2, 10249 InlineSpec = 3, 10250 StorageClass = 4, 10251 Linkage = 5, 10252 }; 10253 10254 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10255 !OldFD->getType()->getAs<FunctionProtoType>()) { 10256 Diag(OldFD->getLocation(), NoProtoDiagID); 10257 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10258 return true; 10259 } 10260 10261 if (NoProtoDiagID.getDiagID() != 0 && 10262 !NewFD->getType()->getAs<FunctionProtoType>()) 10263 return Diag(NewFD->getLocation(), NoProtoDiagID); 10264 10265 if (!TemplatesSupported && 10266 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10267 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10268 << FuncTemplates; 10269 10270 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10271 if (NewCXXFD->isVirtual()) 10272 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10273 << VirtFuncs; 10274 10275 if (isa<CXXConstructorDecl>(NewCXXFD)) 10276 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10277 << Constructors; 10278 10279 if (isa<CXXDestructorDecl>(NewCXXFD)) 10280 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10281 << Destructors; 10282 } 10283 10284 if (NewFD->isDeleted()) 10285 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10286 << DeletedFuncs; 10287 10288 if (NewFD->isDefaulted()) 10289 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10290 << DefaultedFuncs; 10291 10292 if (!ConstexprSupported && NewFD->isConstexpr()) 10293 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10294 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10295 10296 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10297 const auto *NewType = cast<FunctionType>(NewQType); 10298 QualType NewReturnType = NewType->getReturnType(); 10299 10300 if (NewReturnType->isUndeducedType()) 10301 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10302 << DeducedReturn; 10303 10304 // Ensure the return type is identical. 10305 if (OldFD) { 10306 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10307 const auto *OldType = cast<FunctionType>(OldQType); 10308 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10309 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10310 10311 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10312 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10313 10314 QualType OldReturnType = OldType->getReturnType(); 10315 10316 if (OldReturnType != NewReturnType) 10317 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10318 10319 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10320 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10321 10322 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10323 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10324 10325 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10326 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10327 10328 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10329 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10330 10331 if (CheckEquivalentExceptionSpec( 10332 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10333 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10334 return true; 10335 } 10336 return false; 10337 } 10338 10339 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10340 const FunctionDecl *NewFD, 10341 bool CausesMV, 10342 MultiVersionKind MVType) { 10343 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10344 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10345 if (OldFD) 10346 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10347 return true; 10348 } 10349 10350 bool IsCPUSpecificCPUDispatchMVType = 10351 MVType == MultiVersionKind::CPUDispatch || 10352 MVType == MultiVersionKind::CPUSpecific; 10353 10354 if (CausesMV && OldFD && 10355 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType)) 10356 return true; 10357 10358 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType)) 10359 return true; 10360 10361 // Only allow transition to MultiVersion if it hasn't been used. 10362 if (OldFD && CausesMV && OldFD->isUsed(false)) 10363 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10364 10365 return S.areMultiversionVariantFunctionsCompatible( 10366 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10367 PartialDiagnosticAt(NewFD->getLocation(), 10368 S.PDiag(diag::note_multiversioning_caused_here)), 10369 PartialDiagnosticAt(NewFD->getLocation(), 10370 S.PDiag(diag::err_multiversion_doesnt_support) 10371 << IsCPUSpecificCPUDispatchMVType), 10372 PartialDiagnosticAt(NewFD->getLocation(), 10373 S.PDiag(diag::err_multiversion_diff)), 10374 /*TemplatesSupported=*/false, 10375 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10376 /*CLinkageMayDiffer=*/false); 10377 } 10378 10379 /// Check the validity of a multiversion function declaration that is the 10380 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10381 /// 10382 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10383 /// 10384 /// Returns true if there was an error, false otherwise. 10385 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10386 MultiVersionKind MVType, 10387 const TargetAttr *TA) { 10388 assert(MVType != MultiVersionKind::None && 10389 "Function lacks multiversion attribute"); 10390 10391 // Target only causes MV if it is default, otherwise this is a normal 10392 // function. 10393 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10394 return false; 10395 10396 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10397 FD->setInvalidDecl(); 10398 return true; 10399 } 10400 10401 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10402 FD->setInvalidDecl(); 10403 return true; 10404 } 10405 10406 FD->setIsMultiVersion(); 10407 return false; 10408 } 10409 10410 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10411 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10412 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10413 return true; 10414 } 10415 10416 return false; 10417 } 10418 10419 static bool CheckTargetCausesMultiVersioning( 10420 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10421 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10422 LookupResult &Previous) { 10423 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10424 ParsedTargetAttr NewParsed = NewTA->parse(); 10425 // Sort order doesn't matter, it just needs to be consistent. 10426 llvm::sort(NewParsed.Features); 10427 10428 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10429 // to change, this is a simple redeclaration. 10430 if (!NewTA->isDefaultVersion() && 10431 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10432 return false; 10433 10434 // Otherwise, this decl causes MultiVersioning. 10435 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10436 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10437 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10438 NewFD->setInvalidDecl(); 10439 return true; 10440 } 10441 10442 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10443 MultiVersionKind::Target)) { 10444 NewFD->setInvalidDecl(); 10445 return true; 10446 } 10447 10448 if (CheckMultiVersionValue(S, NewFD)) { 10449 NewFD->setInvalidDecl(); 10450 return true; 10451 } 10452 10453 // If this is 'default', permit the forward declaration. 10454 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10455 Redeclaration = true; 10456 OldDecl = OldFD; 10457 OldFD->setIsMultiVersion(); 10458 NewFD->setIsMultiVersion(); 10459 return false; 10460 } 10461 10462 if (CheckMultiVersionValue(S, OldFD)) { 10463 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10464 NewFD->setInvalidDecl(); 10465 return true; 10466 } 10467 10468 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10469 10470 if (OldParsed == NewParsed) { 10471 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10472 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10473 NewFD->setInvalidDecl(); 10474 return true; 10475 } 10476 10477 for (const auto *FD : OldFD->redecls()) { 10478 const auto *CurTA = FD->getAttr<TargetAttr>(); 10479 // We allow forward declarations before ANY multiversioning attributes, but 10480 // nothing after the fact. 10481 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10482 (!CurTA || CurTA->isInherited())) { 10483 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10484 << 0; 10485 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10486 NewFD->setInvalidDecl(); 10487 return true; 10488 } 10489 } 10490 10491 OldFD->setIsMultiVersion(); 10492 NewFD->setIsMultiVersion(); 10493 Redeclaration = false; 10494 MergeTypeWithPrevious = false; 10495 OldDecl = nullptr; 10496 Previous.clear(); 10497 return false; 10498 } 10499 10500 /// Check the validity of a new function declaration being added to an existing 10501 /// multiversioned declaration collection. 10502 static bool CheckMultiVersionAdditionalDecl( 10503 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10504 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10505 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10506 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10507 LookupResult &Previous) { 10508 10509 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10510 // Disallow mixing of multiversioning types. 10511 if ((OldMVType == MultiVersionKind::Target && 10512 NewMVType != MultiVersionKind::Target) || 10513 (NewMVType == MultiVersionKind::Target && 10514 OldMVType != MultiVersionKind::Target)) { 10515 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10516 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10517 NewFD->setInvalidDecl(); 10518 return true; 10519 } 10520 10521 ParsedTargetAttr NewParsed; 10522 if (NewTA) { 10523 NewParsed = NewTA->parse(); 10524 llvm::sort(NewParsed.Features); 10525 } 10526 10527 bool UseMemberUsingDeclRules = 10528 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10529 10530 // Next, check ALL non-overloads to see if this is a redeclaration of a 10531 // previous member of the MultiVersion set. 10532 for (NamedDecl *ND : Previous) { 10533 FunctionDecl *CurFD = ND->getAsFunction(); 10534 if (!CurFD) 10535 continue; 10536 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10537 continue; 10538 10539 if (NewMVType == MultiVersionKind::Target) { 10540 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10541 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10542 NewFD->setIsMultiVersion(); 10543 Redeclaration = true; 10544 OldDecl = ND; 10545 return false; 10546 } 10547 10548 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10549 if (CurParsed == NewParsed) { 10550 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10551 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10552 NewFD->setInvalidDecl(); 10553 return true; 10554 } 10555 } else { 10556 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10557 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10558 // Handle CPUDispatch/CPUSpecific versions. 10559 // Only 1 CPUDispatch function is allowed, this will make it go through 10560 // the redeclaration errors. 10561 if (NewMVType == MultiVersionKind::CPUDispatch && 10562 CurFD->hasAttr<CPUDispatchAttr>()) { 10563 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10564 std::equal( 10565 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10566 NewCPUDisp->cpus_begin(), 10567 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10568 return Cur->getName() == New->getName(); 10569 })) { 10570 NewFD->setIsMultiVersion(); 10571 Redeclaration = true; 10572 OldDecl = ND; 10573 return false; 10574 } 10575 10576 // If the declarations don't match, this is an error condition. 10577 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10578 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10579 NewFD->setInvalidDecl(); 10580 return true; 10581 } 10582 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10583 10584 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10585 std::equal( 10586 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10587 NewCPUSpec->cpus_begin(), 10588 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10589 return Cur->getName() == New->getName(); 10590 })) { 10591 NewFD->setIsMultiVersion(); 10592 Redeclaration = true; 10593 OldDecl = ND; 10594 return false; 10595 } 10596 10597 // Only 1 version of CPUSpecific is allowed for each CPU. 10598 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10599 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10600 if (CurII == NewII) { 10601 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10602 << NewII; 10603 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10604 NewFD->setInvalidDecl(); 10605 return true; 10606 } 10607 } 10608 } 10609 } 10610 // If the two decls aren't the same MVType, there is no possible error 10611 // condition. 10612 } 10613 } 10614 10615 // Else, this is simply a non-redecl case. Checking the 'value' is only 10616 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10617 // handled in the attribute adding step. 10618 if (NewMVType == MultiVersionKind::Target && 10619 CheckMultiVersionValue(S, NewFD)) { 10620 NewFD->setInvalidDecl(); 10621 return true; 10622 } 10623 10624 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10625 !OldFD->isMultiVersion(), NewMVType)) { 10626 NewFD->setInvalidDecl(); 10627 return true; 10628 } 10629 10630 // Permit forward declarations in the case where these two are compatible. 10631 if (!OldFD->isMultiVersion()) { 10632 OldFD->setIsMultiVersion(); 10633 NewFD->setIsMultiVersion(); 10634 Redeclaration = true; 10635 OldDecl = OldFD; 10636 return false; 10637 } 10638 10639 NewFD->setIsMultiVersion(); 10640 Redeclaration = false; 10641 MergeTypeWithPrevious = false; 10642 OldDecl = nullptr; 10643 Previous.clear(); 10644 return false; 10645 } 10646 10647 10648 /// Check the validity of a mulitversion function declaration. 10649 /// Also sets the multiversion'ness' of the function itself. 10650 /// 10651 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10652 /// 10653 /// Returns true if there was an error, false otherwise. 10654 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10655 bool &Redeclaration, NamedDecl *&OldDecl, 10656 bool &MergeTypeWithPrevious, 10657 LookupResult &Previous) { 10658 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10659 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10660 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10661 10662 // Mixing Multiversioning types is prohibited. 10663 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10664 (NewCPUDisp && NewCPUSpec)) { 10665 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10666 NewFD->setInvalidDecl(); 10667 return true; 10668 } 10669 10670 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10671 10672 // Main isn't allowed to become a multiversion function, however it IS 10673 // permitted to have 'main' be marked with the 'target' optimization hint. 10674 if (NewFD->isMain()) { 10675 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10676 MVType == MultiVersionKind::CPUDispatch || 10677 MVType == MultiVersionKind::CPUSpecific) { 10678 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10679 NewFD->setInvalidDecl(); 10680 return true; 10681 } 10682 return false; 10683 } 10684 10685 if (!OldDecl || !OldDecl->getAsFunction() || 10686 OldDecl->getDeclContext()->getRedeclContext() != 10687 NewFD->getDeclContext()->getRedeclContext()) { 10688 // If there's no previous declaration, AND this isn't attempting to cause 10689 // multiversioning, this isn't an error condition. 10690 if (MVType == MultiVersionKind::None) 10691 return false; 10692 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10693 } 10694 10695 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10696 10697 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10698 return false; 10699 10700 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10701 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10702 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10703 NewFD->setInvalidDecl(); 10704 return true; 10705 } 10706 10707 // Handle the target potentially causes multiversioning case. 10708 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10709 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10710 Redeclaration, OldDecl, 10711 MergeTypeWithPrevious, Previous); 10712 10713 // At this point, we have a multiversion function decl (in OldFD) AND an 10714 // appropriate attribute in the current function decl. Resolve that these are 10715 // still compatible with previous declarations. 10716 return CheckMultiVersionAdditionalDecl( 10717 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10718 OldDecl, MergeTypeWithPrevious, Previous); 10719 } 10720 10721 /// Perform semantic checking of a new function declaration. 10722 /// 10723 /// Performs semantic analysis of the new function declaration 10724 /// NewFD. This routine performs all semantic checking that does not 10725 /// require the actual declarator involved in the declaration, and is 10726 /// used both for the declaration of functions as they are parsed 10727 /// (called via ActOnDeclarator) and for the declaration of functions 10728 /// that have been instantiated via C++ template instantiation (called 10729 /// via InstantiateDecl). 10730 /// 10731 /// \param IsMemberSpecialization whether this new function declaration is 10732 /// a member specialization (that replaces any definition provided by the 10733 /// previous declaration). 10734 /// 10735 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10736 /// 10737 /// \returns true if the function declaration is a redeclaration. 10738 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10739 LookupResult &Previous, 10740 bool IsMemberSpecialization) { 10741 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10742 "Variably modified return types are not handled here"); 10743 10744 // Determine whether the type of this function should be merged with 10745 // a previous visible declaration. This never happens for functions in C++, 10746 // and always happens in C if the previous declaration was visible. 10747 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10748 !Previous.isShadowed(); 10749 10750 bool Redeclaration = false; 10751 NamedDecl *OldDecl = nullptr; 10752 bool MayNeedOverloadableChecks = false; 10753 10754 // Merge or overload the declaration with an existing declaration of 10755 // the same name, if appropriate. 10756 if (!Previous.empty()) { 10757 // Determine whether NewFD is an overload of PrevDecl or 10758 // a declaration that requires merging. If it's an overload, 10759 // there's no more work to do here; we'll just add the new 10760 // function to the scope. 10761 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10762 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10763 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10764 Redeclaration = true; 10765 OldDecl = Candidate; 10766 } 10767 } else { 10768 MayNeedOverloadableChecks = true; 10769 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10770 /*NewIsUsingDecl*/ false)) { 10771 case Ovl_Match: 10772 Redeclaration = true; 10773 break; 10774 10775 case Ovl_NonFunction: 10776 Redeclaration = true; 10777 break; 10778 10779 case Ovl_Overload: 10780 Redeclaration = false; 10781 break; 10782 } 10783 } 10784 } 10785 10786 // Check for a previous extern "C" declaration with this name. 10787 if (!Redeclaration && 10788 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10789 if (!Previous.empty()) { 10790 // This is an extern "C" declaration with the same name as a previous 10791 // declaration, and thus redeclares that entity... 10792 Redeclaration = true; 10793 OldDecl = Previous.getFoundDecl(); 10794 MergeTypeWithPrevious = false; 10795 10796 // ... except in the presence of __attribute__((overloadable)). 10797 if (OldDecl->hasAttr<OverloadableAttr>() || 10798 NewFD->hasAttr<OverloadableAttr>()) { 10799 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10800 MayNeedOverloadableChecks = true; 10801 Redeclaration = false; 10802 OldDecl = nullptr; 10803 } 10804 } 10805 } 10806 } 10807 10808 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10809 MergeTypeWithPrevious, Previous)) 10810 return Redeclaration; 10811 10812 // PPC MMA non-pointer types are not allowed as function return types. 10813 if (Context.getTargetInfo().getTriple().isPPC64() && 10814 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 10815 NewFD->setInvalidDecl(); 10816 } 10817 10818 // C++11 [dcl.constexpr]p8: 10819 // A constexpr specifier for a non-static member function that is not 10820 // a constructor declares that member function to be const. 10821 // 10822 // This needs to be delayed until we know whether this is an out-of-line 10823 // definition of a static member function. 10824 // 10825 // This rule is not present in C++1y, so we produce a backwards 10826 // compatibility warning whenever it happens in C++11. 10827 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10828 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10829 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10830 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10831 CXXMethodDecl *OldMD = nullptr; 10832 if (OldDecl) 10833 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10834 if (!OldMD || !OldMD->isStatic()) { 10835 const FunctionProtoType *FPT = 10836 MD->getType()->castAs<FunctionProtoType>(); 10837 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10838 EPI.TypeQuals.addConst(); 10839 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10840 FPT->getParamTypes(), EPI)); 10841 10842 // Warn that we did this, if we're not performing template instantiation. 10843 // In that case, we'll have warned already when the template was defined. 10844 if (!inTemplateInstantiation()) { 10845 SourceLocation AddConstLoc; 10846 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10847 .IgnoreParens().getAs<FunctionTypeLoc>()) 10848 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10849 10850 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10851 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10852 } 10853 } 10854 } 10855 10856 if (Redeclaration) { 10857 // NewFD and OldDecl represent declarations that need to be 10858 // merged. 10859 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10860 NewFD->setInvalidDecl(); 10861 return Redeclaration; 10862 } 10863 10864 Previous.clear(); 10865 Previous.addDecl(OldDecl); 10866 10867 if (FunctionTemplateDecl *OldTemplateDecl = 10868 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10869 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10870 FunctionTemplateDecl *NewTemplateDecl 10871 = NewFD->getDescribedFunctionTemplate(); 10872 assert(NewTemplateDecl && "Template/non-template mismatch"); 10873 10874 // The call to MergeFunctionDecl above may have created some state in 10875 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10876 // can add it as a redeclaration. 10877 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10878 10879 NewFD->setPreviousDeclaration(OldFD); 10880 if (NewFD->isCXXClassMember()) { 10881 NewFD->setAccess(OldTemplateDecl->getAccess()); 10882 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10883 } 10884 10885 // If this is an explicit specialization of a member that is a function 10886 // template, mark it as a member specialization. 10887 if (IsMemberSpecialization && 10888 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10889 NewTemplateDecl->setMemberSpecialization(); 10890 assert(OldTemplateDecl->isMemberSpecialization()); 10891 // Explicit specializations of a member template do not inherit deleted 10892 // status from the parent member template that they are specializing. 10893 if (OldFD->isDeleted()) { 10894 // FIXME: This assert will not hold in the presence of modules. 10895 assert(OldFD->getCanonicalDecl() == OldFD); 10896 // FIXME: We need an update record for this AST mutation. 10897 OldFD->setDeletedAsWritten(false); 10898 } 10899 } 10900 10901 } else { 10902 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10903 auto *OldFD = cast<FunctionDecl>(OldDecl); 10904 // This needs to happen first so that 'inline' propagates. 10905 NewFD->setPreviousDeclaration(OldFD); 10906 if (NewFD->isCXXClassMember()) 10907 NewFD->setAccess(OldFD->getAccess()); 10908 } 10909 } 10910 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10911 !NewFD->getAttr<OverloadableAttr>()) { 10912 assert((Previous.empty() || 10913 llvm::any_of(Previous, 10914 [](const NamedDecl *ND) { 10915 return ND->hasAttr<OverloadableAttr>(); 10916 })) && 10917 "Non-redecls shouldn't happen without overloadable present"); 10918 10919 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10920 const auto *FD = dyn_cast<FunctionDecl>(ND); 10921 return FD && !FD->hasAttr<OverloadableAttr>(); 10922 }); 10923 10924 if (OtherUnmarkedIter != Previous.end()) { 10925 Diag(NewFD->getLocation(), 10926 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10927 Diag((*OtherUnmarkedIter)->getLocation(), 10928 diag::note_attribute_overloadable_prev_overload) 10929 << false; 10930 10931 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10932 } 10933 } 10934 10935 if (LangOpts.OpenMP) 10936 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 10937 10938 // Semantic checking for this function declaration (in isolation). 10939 10940 if (getLangOpts().CPlusPlus) { 10941 // C++-specific checks. 10942 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10943 CheckConstructor(Constructor); 10944 } else if (CXXDestructorDecl *Destructor = 10945 dyn_cast<CXXDestructorDecl>(NewFD)) { 10946 CXXRecordDecl *Record = Destructor->getParent(); 10947 QualType ClassType = Context.getTypeDeclType(Record); 10948 10949 // FIXME: Shouldn't we be able to perform this check even when the class 10950 // type is dependent? Both gcc and edg can handle that. 10951 if (!ClassType->isDependentType()) { 10952 DeclarationName Name 10953 = Context.DeclarationNames.getCXXDestructorName( 10954 Context.getCanonicalType(ClassType)); 10955 if (NewFD->getDeclName() != Name) { 10956 Diag(NewFD->getLocation(), diag::err_destructor_name); 10957 NewFD->setInvalidDecl(); 10958 return Redeclaration; 10959 } 10960 } 10961 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10962 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10963 CheckDeductionGuideTemplate(TD); 10964 10965 // A deduction guide is not on the list of entities that can be 10966 // explicitly specialized. 10967 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10968 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10969 << /*explicit specialization*/ 1; 10970 } 10971 10972 // Find any virtual functions that this function overrides. 10973 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10974 if (!Method->isFunctionTemplateSpecialization() && 10975 !Method->getDescribedFunctionTemplate() && 10976 Method->isCanonicalDecl()) { 10977 AddOverriddenMethods(Method->getParent(), Method); 10978 } 10979 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10980 // C++2a [class.virtual]p6 10981 // A virtual method shall not have a requires-clause. 10982 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10983 diag::err_constrained_virtual_method); 10984 10985 if (Method->isStatic()) 10986 checkThisInStaticMemberFunctionType(Method); 10987 } 10988 10989 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 10990 ActOnConversionDeclarator(Conversion); 10991 10992 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10993 if (NewFD->isOverloadedOperator() && 10994 CheckOverloadedOperatorDeclaration(NewFD)) { 10995 NewFD->setInvalidDecl(); 10996 return Redeclaration; 10997 } 10998 10999 // Extra checking for C++0x literal operators (C++0x [over.literal]). 11000 if (NewFD->getLiteralIdentifier() && 11001 CheckLiteralOperatorDeclaration(NewFD)) { 11002 NewFD->setInvalidDecl(); 11003 return Redeclaration; 11004 } 11005 11006 // In C++, check default arguments now that we have merged decls. Unless 11007 // the lexical context is the class, because in this case this is done 11008 // during delayed parsing anyway. 11009 if (!CurContext->isRecord()) 11010 CheckCXXDefaultArguments(NewFD); 11011 11012 // If this function is declared as being extern "C", then check to see if 11013 // the function returns a UDT (class, struct, or union type) that is not C 11014 // compatible, and if it does, warn the user. 11015 // But, issue any diagnostic on the first declaration only. 11016 if (Previous.empty() && NewFD->isExternC()) { 11017 QualType R = NewFD->getReturnType(); 11018 if (R->isIncompleteType() && !R->isVoidType()) 11019 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 11020 << NewFD << R; 11021 else if (!R.isPODType(Context) && !R->isVoidType() && 11022 !R->isObjCObjectPointerType()) 11023 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 11024 } 11025 11026 // C++1z [dcl.fct]p6: 11027 // [...] whether the function has a non-throwing exception-specification 11028 // [is] part of the function type 11029 // 11030 // This results in an ABI break between C++14 and C++17 for functions whose 11031 // declared type includes an exception-specification in a parameter or 11032 // return type. (Exception specifications on the function itself are OK in 11033 // most cases, and exception specifications are not permitted in most other 11034 // contexts where they could make it into a mangling.) 11035 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 11036 auto HasNoexcept = [&](QualType T) -> bool { 11037 // Strip off declarator chunks that could be between us and a function 11038 // type. We don't need to look far, exception specifications are very 11039 // restricted prior to C++17. 11040 if (auto *RT = T->getAs<ReferenceType>()) 11041 T = RT->getPointeeType(); 11042 else if (T->isAnyPointerType()) 11043 T = T->getPointeeType(); 11044 else if (auto *MPT = T->getAs<MemberPointerType>()) 11045 T = MPT->getPointeeType(); 11046 if (auto *FPT = T->getAs<FunctionProtoType>()) 11047 if (FPT->isNothrow()) 11048 return true; 11049 return false; 11050 }; 11051 11052 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 11053 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 11054 for (QualType T : FPT->param_types()) 11055 AnyNoexcept |= HasNoexcept(T); 11056 if (AnyNoexcept) 11057 Diag(NewFD->getLocation(), 11058 diag::warn_cxx17_compat_exception_spec_in_signature) 11059 << NewFD; 11060 } 11061 11062 if (!Redeclaration && LangOpts.CUDA) 11063 checkCUDATargetOverload(NewFD, Previous); 11064 } 11065 return Redeclaration; 11066 } 11067 11068 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11069 // C++11 [basic.start.main]p3: 11070 // A program that [...] declares main to be inline, static or 11071 // constexpr is ill-formed. 11072 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11073 // appear in a declaration of main. 11074 // static main is not an error under C99, but we should warn about it. 11075 // We accept _Noreturn main as an extension. 11076 if (FD->getStorageClass() == SC_Static) 11077 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11078 ? diag::err_static_main : diag::warn_static_main) 11079 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11080 if (FD->isInlineSpecified()) 11081 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11082 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11083 if (DS.isNoreturnSpecified()) { 11084 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11085 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11086 Diag(NoreturnLoc, diag::ext_noreturn_main); 11087 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11088 << FixItHint::CreateRemoval(NoreturnRange); 11089 } 11090 if (FD->isConstexpr()) { 11091 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11092 << FD->isConsteval() 11093 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11094 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11095 } 11096 11097 if (getLangOpts().OpenCL) { 11098 Diag(FD->getLocation(), diag::err_opencl_no_main) 11099 << FD->hasAttr<OpenCLKernelAttr>(); 11100 FD->setInvalidDecl(); 11101 return; 11102 } 11103 11104 QualType T = FD->getType(); 11105 assert(T->isFunctionType() && "function decl is not of function type"); 11106 const FunctionType* FT = T->castAs<FunctionType>(); 11107 11108 // Set default calling convention for main() 11109 if (FT->getCallConv() != CC_C) { 11110 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11111 FD->setType(QualType(FT, 0)); 11112 T = Context.getCanonicalType(FD->getType()); 11113 } 11114 11115 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11116 // In C with GNU extensions we allow main() to have non-integer return 11117 // type, but we should warn about the extension, and we disable the 11118 // implicit-return-zero rule. 11119 11120 // GCC in C mode accepts qualified 'int'. 11121 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11122 FD->setHasImplicitReturnZero(true); 11123 else { 11124 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11125 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11126 if (RTRange.isValid()) 11127 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11128 << FixItHint::CreateReplacement(RTRange, "int"); 11129 } 11130 } else { 11131 // In C and C++, main magically returns 0 if you fall off the end; 11132 // set the flag which tells us that. 11133 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11134 11135 // All the standards say that main() should return 'int'. 11136 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11137 FD->setHasImplicitReturnZero(true); 11138 else { 11139 // Otherwise, this is just a flat-out error. 11140 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11141 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11142 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11143 : FixItHint()); 11144 FD->setInvalidDecl(true); 11145 } 11146 } 11147 11148 // Treat protoless main() as nullary. 11149 if (isa<FunctionNoProtoType>(FT)) return; 11150 11151 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11152 unsigned nparams = FTP->getNumParams(); 11153 assert(FD->getNumParams() == nparams); 11154 11155 bool HasExtraParameters = (nparams > 3); 11156 11157 if (FTP->isVariadic()) { 11158 Diag(FD->getLocation(), diag::ext_variadic_main); 11159 // FIXME: if we had information about the location of the ellipsis, we 11160 // could add a FixIt hint to remove it as a parameter. 11161 } 11162 11163 // Darwin passes an undocumented fourth argument of type char**. If 11164 // other platforms start sprouting these, the logic below will start 11165 // getting shifty. 11166 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11167 HasExtraParameters = false; 11168 11169 if (HasExtraParameters) { 11170 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11171 FD->setInvalidDecl(true); 11172 nparams = 3; 11173 } 11174 11175 // FIXME: a lot of the following diagnostics would be improved 11176 // if we had some location information about types. 11177 11178 QualType CharPP = 11179 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11180 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11181 11182 for (unsigned i = 0; i < nparams; ++i) { 11183 QualType AT = FTP->getParamType(i); 11184 11185 bool mismatch = true; 11186 11187 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11188 mismatch = false; 11189 else if (Expected[i] == CharPP) { 11190 // As an extension, the following forms are okay: 11191 // char const ** 11192 // char const * const * 11193 // char * const * 11194 11195 QualifierCollector qs; 11196 const PointerType* PT; 11197 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11198 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11199 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11200 Context.CharTy)) { 11201 qs.removeConst(); 11202 mismatch = !qs.empty(); 11203 } 11204 } 11205 11206 if (mismatch) { 11207 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11208 // TODO: suggest replacing given type with expected type 11209 FD->setInvalidDecl(true); 11210 } 11211 } 11212 11213 if (nparams == 1 && !FD->isInvalidDecl()) { 11214 Diag(FD->getLocation(), diag::warn_main_one_arg); 11215 } 11216 11217 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11218 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11219 FD->setInvalidDecl(); 11220 } 11221 } 11222 11223 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 11224 11225 // Default calling convention for main and wmain is __cdecl 11226 if (FD->getName() == "main" || FD->getName() == "wmain") 11227 return false; 11228 11229 // Default calling convention for MinGW is __cdecl 11230 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 11231 if (T.isWindowsGNUEnvironment()) 11232 return false; 11233 11234 // Default calling convention for WinMain, wWinMain and DllMain 11235 // is __stdcall on 32 bit Windows 11236 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 11237 return true; 11238 11239 return false; 11240 } 11241 11242 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11243 QualType T = FD->getType(); 11244 assert(T->isFunctionType() && "function decl is not of function type"); 11245 const FunctionType *FT = T->castAs<FunctionType>(); 11246 11247 // Set an implicit return of 'zero' if the function can return some integral, 11248 // enumeration, pointer or nullptr type. 11249 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11250 FT->getReturnType()->isAnyPointerType() || 11251 FT->getReturnType()->isNullPtrType()) 11252 // DllMain is exempt because a return value of zero means it failed. 11253 if (FD->getName() != "DllMain") 11254 FD->setHasImplicitReturnZero(true); 11255 11256 // Explicity specified calling conventions are applied to MSVC entry points 11257 if (!hasExplicitCallingConv(T)) { 11258 if (isDefaultStdCall(FD, *this)) { 11259 if (FT->getCallConv() != CC_X86StdCall) { 11260 FT = Context.adjustFunctionType( 11261 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 11262 FD->setType(QualType(FT, 0)); 11263 } 11264 } else if (FT->getCallConv() != CC_C) { 11265 FT = Context.adjustFunctionType(FT, 11266 FT->getExtInfo().withCallingConv(CC_C)); 11267 FD->setType(QualType(FT, 0)); 11268 } 11269 } 11270 11271 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11272 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11273 FD->setInvalidDecl(); 11274 } 11275 } 11276 11277 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11278 // FIXME: Need strict checking. In C89, we need to check for 11279 // any assignment, increment, decrement, function-calls, or 11280 // commas outside of a sizeof. In C99, it's the same list, 11281 // except that the aforementioned are allowed in unevaluated 11282 // expressions. Everything else falls under the 11283 // "may accept other forms of constant expressions" exception. 11284 // 11285 // Regular C++ code will not end up here (exceptions: language extensions, 11286 // OpenCL C++ etc), so the constant expression rules there don't matter. 11287 if (Init->isValueDependent()) { 11288 assert(Init->containsErrors() && 11289 "Dependent code should only occur in error-recovery path."); 11290 return true; 11291 } 11292 const Expr *Culprit; 11293 if (Init->isConstantInitializer(Context, false, &Culprit)) 11294 return false; 11295 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11296 << Culprit->getSourceRange(); 11297 return true; 11298 } 11299 11300 namespace { 11301 // Visits an initialization expression to see if OrigDecl is evaluated in 11302 // its own initialization and throws a warning if it does. 11303 class SelfReferenceChecker 11304 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11305 Sema &S; 11306 Decl *OrigDecl; 11307 bool isRecordType; 11308 bool isPODType; 11309 bool isReferenceType; 11310 11311 bool isInitList; 11312 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11313 11314 public: 11315 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11316 11317 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11318 S(S), OrigDecl(OrigDecl) { 11319 isPODType = false; 11320 isRecordType = false; 11321 isReferenceType = false; 11322 isInitList = false; 11323 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11324 isPODType = VD->getType().isPODType(S.Context); 11325 isRecordType = VD->getType()->isRecordType(); 11326 isReferenceType = VD->getType()->isReferenceType(); 11327 } 11328 } 11329 11330 // For most expressions, just call the visitor. For initializer lists, 11331 // track the index of the field being initialized since fields are 11332 // initialized in order allowing use of previously initialized fields. 11333 void CheckExpr(Expr *E) { 11334 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11335 if (!InitList) { 11336 Visit(E); 11337 return; 11338 } 11339 11340 // Track and increment the index here. 11341 isInitList = true; 11342 InitFieldIndex.push_back(0); 11343 for (auto Child : InitList->children()) { 11344 CheckExpr(cast<Expr>(Child)); 11345 ++InitFieldIndex.back(); 11346 } 11347 InitFieldIndex.pop_back(); 11348 } 11349 11350 // Returns true if MemberExpr is checked and no further checking is needed. 11351 // Returns false if additional checking is required. 11352 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11353 llvm::SmallVector<FieldDecl*, 4> Fields; 11354 Expr *Base = E; 11355 bool ReferenceField = false; 11356 11357 // Get the field members used. 11358 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11359 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11360 if (!FD) 11361 return false; 11362 Fields.push_back(FD); 11363 if (FD->getType()->isReferenceType()) 11364 ReferenceField = true; 11365 Base = ME->getBase()->IgnoreParenImpCasts(); 11366 } 11367 11368 // Keep checking only if the base Decl is the same. 11369 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11370 if (!DRE || DRE->getDecl() != OrigDecl) 11371 return false; 11372 11373 // A reference field can be bound to an unininitialized field. 11374 if (CheckReference && !ReferenceField) 11375 return true; 11376 11377 // Convert FieldDecls to their index number. 11378 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11379 for (const FieldDecl *I : llvm::reverse(Fields)) 11380 UsedFieldIndex.push_back(I->getFieldIndex()); 11381 11382 // See if a warning is needed by checking the first difference in index 11383 // numbers. If field being used has index less than the field being 11384 // initialized, then the use is safe. 11385 for (auto UsedIter = UsedFieldIndex.begin(), 11386 UsedEnd = UsedFieldIndex.end(), 11387 OrigIter = InitFieldIndex.begin(), 11388 OrigEnd = InitFieldIndex.end(); 11389 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11390 if (*UsedIter < *OrigIter) 11391 return true; 11392 if (*UsedIter > *OrigIter) 11393 break; 11394 } 11395 11396 // TODO: Add a different warning which will print the field names. 11397 HandleDeclRefExpr(DRE); 11398 return true; 11399 } 11400 11401 // For most expressions, the cast is directly above the DeclRefExpr. 11402 // For conditional operators, the cast can be outside the conditional 11403 // operator if both expressions are DeclRefExpr's. 11404 void HandleValue(Expr *E) { 11405 E = E->IgnoreParens(); 11406 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11407 HandleDeclRefExpr(DRE); 11408 return; 11409 } 11410 11411 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11412 Visit(CO->getCond()); 11413 HandleValue(CO->getTrueExpr()); 11414 HandleValue(CO->getFalseExpr()); 11415 return; 11416 } 11417 11418 if (BinaryConditionalOperator *BCO = 11419 dyn_cast<BinaryConditionalOperator>(E)) { 11420 Visit(BCO->getCond()); 11421 HandleValue(BCO->getFalseExpr()); 11422 return; 11423 } 11424 11425 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11426 HandleValue(OVE->getSourceExpr()); 11427 return; 11428 } 11429 11430 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11431 if (BO->getOpcode() == BO_Comma) { 11432 Visit(BO->getLHS()); 11433 HandleValue(BO->getRHS()); 11434 return; 11435 } 11436 } 11437 11438 if (isa<MemberExpr>(E)) { 11439 if (isInitList) { 11440 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11441 false /*CheckReference*/)) 11442 return; 11443 } 11444 11445 Expr *Base = E->IgnoreParenImpCasts(); 11446 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11447 // Check for static member variables and don't warn on them. 11448 if (!isa<FieldDecl>(ME->getMemberDecl())) 11449 return; 11450 Base = ME->getBase()->IgnoreParenImpCasts(); 11451 } 11452 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11453 HandleDeclRefExpr(DRE); 11454 return; 11455 } 11456 11457 Visit(E); 11458 } 11459 11460 // Reference types not handled in HandleValue are handled here since all 11461 // uses of references are bad, not just r-value uses. 11462 void VisitDeclRefExpr(DeclRefExpr *E) { 11463 if (isReferenceType) 11464 HandleDeclRefExpr(E); 11465 } 11466 11467 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11468 if (E->getCastKind() == CK_LValueToRValue) { 11469 HandleValue(E->getSubExpr()); 11470 return; 11471 } 11472 11473 Inherited::VisitImplicitCastExpr(E); 11474 } 11475 11476 void VisitMemberExpr(MemberExpr *E) { 11477 if (isInitList) { 11478 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11479 return; 11480 } 11481 11482 // Don't warn on arrays since they can be treated as pointers. 11483 if (E->getType()->canDecayToPointerType()) return; 11484 11485 // Warn when a non-static method call is followed by non-static member 11486 // field accesses, which is followed by a DeclRefExpr. 11487 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11488 bool Warn = (MD && !MD->isStatic()); 11489 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11490 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11491 if (!isa<FieldDecl>(ME->getMemberDecl())) 11492 Warn = false; 11493 Base = ME->getBase()->IgnoreParenImpCasts(); 11494 } 11495 11496 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11497 if (Warn) 11498 HandleDeclRefExpr(DRE); 11499 return; 11500 } 11501 11502 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11503 // Visit that expression. 11504 Visit(Base); 11505 } 11506 11507 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11508 Expr *Callee = E->getCallee(); 11509 11510 if (isa<UnresolvedLookupExpr>(Callee)) 11511 return Inherited::VisitCXXOperatorCallExpr(E); 11512 11513 Visit(Callee); 11514 for (auto Arg: E->arguments()) 11515 HandleValue(Arg->IgnoreParenImpCasts()); 11516 } 11517 11518 void VisitUnaryOperator(UnaryOperator *E) { 11519 // For POD record types, addresses of its own members are well-defined. 11520 if (E->getOpcode() == UO_AddrOf && isRecordType && 11521 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11522 if (!isPODType) 11523 HandleValue(E->getSubExpr()); 11524 return; 11525 } 11526 11527 if (E->isIncrementDecrementOp()) { 11528 HandleValue(E->getSubExpr()); 11529 return; 11530 } 11531 11532 Inherited::VisitUnaryOperator(E); 11533 } 11534 11535 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11536 11537 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11538 if (E->getConstructor()->isCopyConstructor()) { 11539 Expr *ArgExpr = E->getArg(0); 11540 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11541 if (ILE->getNumInits() == 1) 11542 ArgExpr = ILE->getInit(0); 11543 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11544 if (ICE->getCastKind() == CK_NoOp) 11545 ArgExpr = ICE->getSubExpr(); 11546 HandleValue(ArgExpr); 11547 return; 11548 } 11549 Inherited::VisitCXXConstructExpr(E); 11550 } 11551 11552 void VisitCallExpr(CallExpr *E) { 11553 // Treat std::move as a use. 11554 if (E->isCallToStdMove()) { 11555 HandleValue(E->getArg(0)); 11556 return; 11557 } 11558 11559 Inherited::VisitCallExpr(E); 11560 } 11561 11562 void VisitBinaryOperator(BinaryOperator *E) { 11563 if (E->isCompoundAssignmentOp()) { 11564 HandleValue(E->getLHS()); 11565 Visit(E->getRHS()); 11566 return; 11567 } 11568 11569 Inherited::VisitBinaryOperator(E); 11570 } 11571 11572 // A custom visitor for BinaryConditionalOperator is needed because the 11573 // regular visitor would check the condition and true expression separately 11574 // but both point to the same place giving duplicate diagnostics. 11575 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11576 Visit(E->getCond()); 11577 Visit(E->getFalseExpr()); 11578 } 11579 11580 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11581 Decl* ReferenceDecl = DRE->getDecl(); 11582 if (OrigDecl != ReferenceDecl) return; 11583 unsigned diag; 11584 if (isReferenceType) { 11585 diag = diag::warn_uninit_self_reference_in_reference_init; 11586 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11587 diag = diag::warn_static_self_reference_in_init; 11588 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11589 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11590 DRE->getDecl()->getType()->isRecordType()) { 11591 diag = diag::warn_uninit_self_reference_in_init; 11592 } else { 11593 // Local variables will be handled by the CFG analysis. 11594 return; 11595 } 11596 11597 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11598 S.PDiag(diag) 11599 << DRE->getDecl() << OrigDecl->getLocation() 11600 << DRE->getSourceRange()); 11601 } 11602 }; 11603 11604 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11605 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11606 bool DirectInit) { 11607 // Parameters arguments are occassionially constructed with itself, 11608 // for instance, in recursive functions. Skip them. 11609 if (isa<ParmVarDecl>(OrigDecl)) 11610 return; 11611 11612 E = E->IgnoreParens(); 11613 11614 // Skip checking T a = a where T is not a record or reference type. 11615 // Doing so is a way to silence uninitialized warnings. 11616 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11617 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11618 if (ICE->getCastKind() == CK_LValueToRValue) 11619 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11620 if (DRE->getDecl() == OrigDecl) 11621 return; 11622 11623 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11624 } 11625 } // end anonymous namespace 11626 11627 namespace { 11628 // Simple wrapper to add the name of a variable or (if no variable is 11629 // available) a DeclarationName into a diagnostic. 11630 struct VarDeclOrName { 11631 VarDecl *VDecl; 11632 DeclarationName Name; 11633 11634 friend const Sema::SemaDiagnosticBuilder & 11635 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11636 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11637 } 11638 }; 11639 } // end anonymous namespace 11640 11641 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11642 DeclarationName Name, QualType Type, 11643 TypeSourceInfo *TSI, 11644 SourceRange Range, bool DirectInit, 11645 Expr *Init) { 11646 bool IsInitCapture = !VDecl; 11647 assert((!VDecl || !VDecl->isInitCapture()) && 11648 "init captures are expected to be deduced prior to initialization"); 11649 11650 VarDeclOrName VN{VDecl, Name}; 11651 11652 DeducedType *Deduced = Type->getContainedDeducedType(); 11653 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11654 11655 // C++11 [dcl.spec.auto]p3 11656 if (!Init) { 11657 assert(VDecl && "no init for init capture deduction?"); 11658 11659 // Except for class argument deduction, and then for an initializing 11660 // declaration only, i.e. no static at class scope or extern. 11661 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11662 VDecl->hasExternalStorage() || 11663 VDecl->isStaticDataMember()) { 11664 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11665 << VDecl->getDeclName() << Type; 11666 return QualType(); 11667 } 11668 } 11669 11670 ArrayRef<Expr*> DeduceInits; 11671 if (Init) 11672 DeduceInits = Init; 11673 11674 if (DirectInit) { 11675 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11676 DeduceInits = PL->exprs(); 11677 } 11678 11679 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11680 assert(VDecl && "non-auto type for init capture deduction?"); 11681 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11682 InitializationKind Kind = InitializationKind::CreateForInit( 11683 VDecl->getLocation(), DirectInit, Init); 11684 // FIXME: Initialization should not be taking a mutable list of inits. 11685 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11686 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11687 InitsCopy); 11688 } 11689 11690 if (DirectInit) { 11691 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11692 DeduceInits = IL->inits(); 11693 } 11694 11695 // Deduction only works if we have exactly one source expression. 11696 if (DeduceInits.empty()) { 11697 // It isn't possible to write this directly, but it is possible to 11698 // end up in this situation with "auto x(some_pack...);" 11699 Diag(Init->getBeginLoc(), IsInitCapture 11700 ? diag::err_init_capture_no_expression 11701 : diag::err_auto_var_init_no_expression) 11702 << VN << Type << Range; 11703 return QualType(); 11704 } 11705 11706 if (DeduceInits.size() > 1) { 11707 Diag(DeduceInits[1]->getBeginLoc(), 11708 IsInitCapture ? diag::err_init_capture_multiple_expressions 11709 : diag::err_auto_var_init_multiple_expressions) 11710 << VN << Type << Range; 11711 return QualType(); 11712 } 11713 11714 Expr *DeduceInit = DeduceInits[0]; 11715 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11716 Diag(Init->getBeginLoc(), IsInitCapture 11717 ? diag::err_init_capture_paren_braces 11718 : diag::err_auto_var_init_paren_braces) 11719 << isa<InitListExpr>(Init) << VN << Type << Range; 11720 return QualType(); 11721 } 11722 11723 // Expressions default to 'id' when we're in a debugger. 11724 bool DefaultedAnyToId = false; 11725 if (getLangOpts().DebuggerCastResultToId && 11726 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11727 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11728 if (Result.isInvalid()) { 11729 return QualType(); 11730 } 11731 Init = Result.get(); 11732 DefaultedAnyToId = true; 11733 } 11734 11735 // C++ [dcl.decomp]p1: 11736 // If the assignment-expression [...] has array type A and no ref-qualifier 11737 // is present, e has type cv A 11738 if (VDecl && isa<DecompositionDecl>(VDecl) && 11739 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11740 DeduceInit->getType()->isConstantArrayType()) 11741 return Context.getQualifiedType(DeduceInit->getType(), 11742 Type.getQualifiers()); 11743 11744 QualType DeducedType; 11745 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11746 if (!IsInitCapture) 11747 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11748 else if (isa<InitListExpr>(Init)) 11749 Diag(Range.getBegin(), 11750 diag::err_init_capture_deduction_failure_from_init_list) 11751 << VN 11752 << (DeduceInit->getType().isNull() ? TSI->getType() 11753 : DeduceInit->getType()) 11754 << DeduceInit->getSourceRange(); 11755 else 11756 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11757 << VN << TSI->getType() 11758 << (DeduceInit->getType().isNull() ? TSI->getType() 11759 : DeduceInit->getType()) 11760 << DeduceInit->getSourceRange(); 11761 } 11762 11763 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11764 // 'id' instead of a specific object type prevents most of our usual 11765 // checks. 11766 // We only want to warn outside of template instantiations, though: 11767 // inside a template, the 'id' could have come from a parameter. 11768 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11769 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11770 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11771 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11772 } 11773 11774 return DeducedType; 11775 } 11776 11777 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11778 Expr *Init) { 11779 assert(!Init || !Init->containsErrors()); 11780 QualType DeducedType = deduceVarTypeFromInitializer( 11781 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11782 VDecl->getSourceRange(), DirectInit, Init); 11783 if (DeducedType.isNull()) { 11784 VDecl->setInvalidDecl(); 11785 return true; 11786 } 11787 11788 VDecl->setType(DeducedType); 11789 assert(VDecl->isLinkageValid()); 11790 11791 // In ARC, infer lifetime. 11792 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11793 VDecl->setInvalidDecl(); 11794 11795 if (getLangOpts().OpenCL) 11796 deduceOpenCLAddressSpace(VDecl); 11797 11798 // If this is a redeclaration, check that the type we just deduced matches 11799 // the previously declared type. 11800 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11801 // We never need to merge the type, because we cannot form an incomplete 11802 // array of auto, nor deduce such a type. 11803 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11804 } 11805 11806 // Check the deduced type is valid for a variable declaration. 11807 CheckVariableDeclarationType(VDecl); 11808 return VDecl->isInvalidDecl(); 11809 } 11810 11811 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11812 SourceLocation Loc) { 11813 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11814 Init = EWC->getSubExpr(); 11815 11816 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11817 Init = CE->getSubExpr(); 11818 11819 QualType InitType = Init->getType(); 11820 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11821 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11822 "shouldn't be called if type doesn't have a non-trivial C struct"); 11823 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11824 for (auto I : ILE->inits()) { 11825 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11826 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11827 continue; 11828 SourceLocation SL = I->getExprLoc(); 11829 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11830 } 11831 return; 11832 } 11833 11834 if (isa<ImplicitValueInitExpr>(Init)) { 11835 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11836 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11837 NTCUK_Init); 11838 } else { 11839 // Assume all other explicit initializers involving copying some existing 11840 // object. 11841 // TODO: ignore any explicit initializers where we can guarantee 11842 // copy-elision. 11843 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11844 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11845 } 11846 } 11847 11848 namespace { 11849 11850 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11851 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11852 // in the source code or implicitly by the compiler if it is in a union 11853 // defined in a system header and has non-trivial ObjC ownership 11854 // qualifications. We don't want those fields to participate in determining 11855 // whether the containing union is non-trivial. 11856 return FD->hasAttr<UnavailableAttr>(); 11857 } 11858 11859 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11860 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11861 void> { 11862 using Super = 11863 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11864 void>; 11865 11866 DiagNonTrivalCUnionDefaultInitializeVisitor( 11867 QualType OrigTy, SourceLocation OrigLoc, 11868 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11869 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11870 11871 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11872 const FieldDecl *FD, bool InNonTrivialUnion) { 11873 if (const auto *AT = S.Context.getAsArrayType(QT)) 11874 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11875 InNonTrivialUnion); 11876 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11877 } 11878 11879 void visitARCStrong(QualType QT, const FieldDecl *FD, 11880 bool InNonTrivialUnion) { 11881 if (InNonTrivialUnion) 11882 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11883 << 1 << 0 << QT << FD->getName(); 11884 } 11885 11886 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11887 if (InNonTrivialUnion) 11888 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11889 << 1 << 0 << QT << FD->getName(); 11890 } 11891 11892 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11893 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11894 if (RD->isUnion()) { 11895 if (OrigLoc.isValid()) { 11896 bool IsUnion = false; 11897 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11898 IsUnion = OrigRD->isUnion(); 11899 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11900 << 0 << OrigTy << IsUnion << UseContext; 11901 // Reset OrigLoc so that this diagnostic is emitted only once. 11902 OrigLoc = SourceLocation(); 11903 } 11904 InNonTrivialUnion = true; 11905 } 11906 11907 if (InNonTrivialUnion) 11908 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11909 << 0 << 0 << QT.getUnqualifiedType() << ""; 11910 11911 for (const FieldDecl *FD : RD->fields()) 11912 if (!shouldIgnoreForRecordTriviality(FD)) 11913 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11914 } 11915 11916 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11917 11918 // The non-trivial C union type or the struct/union type that contains a 11919 // non-trivial C union. 11920 QualType OrigTy; 11921 SourceLocation OrigLoc; 11922 Sema::NonTrivialCUnionContext UseContext; 11923 Sema &S; 11924 }; 11925 11926 struct DiagNonTrivalCUnionDestructedTypeVisitor 11927 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11928 using Super = 11929 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11930 11931 DiagNonTrivalCUnionDestructedTypeVisitor( 11932 QualType OrigTy, SourceLocation OrigLoc, 11933 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11934 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11935 11936 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11937 const FieldDecl *FD, bool InNonTrivialUnion) { 11938 if (const auto *AT = S.Context.getAsArrayType(QT)) 11939 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11940 InNonTrivialUnion); 11941 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11942 } 11943 11944 void visitARCStrong(QualType QT, const FieldDecl *FD, 11945 bool InNonTrivialUnion) { 11946 if (InNonTrivialUnion) 11947 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11948 << 1 << 1 << QT << FD->getName(); 11949 } 11950 11951 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11952 if (InNonTrivialUnion) 11953 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11954 << 1 << 1 << QT << FD->getName(); 11955 } 11956 11957 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11958 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11959 if (RD->isUnion()) { 11960 if (OrigLoc.isValid()) { 11961 bool IsUnion = false; 11962 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11963 IsUnion = OrigRD->isUnion(); 11964 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11965 << 1 << OrigTy << IsUnion << UseContext; 11966 // Reset OrigLoc so that this diagnostic is emitted only once. 11967 OrigLoc = SourceLocation(); 11968 } 11969 InNonTrivialUnion = true; 11970 } 11971 11972 if (InNonTrivialUnion) 11973 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11974 << 0 << 1 << QT.getUnqualifiedType() << ""; 11975 11976 for (const FieldDecl *FD : RD->fields()) 11977 if (!shouldIgnoreForRecordTriviality(FD)) 11978 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11979 } 11980 11981 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11982 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11983 bool InNonTrivialUnion) {} 11984 11985 // The non-trivial C union type or the struct/union type that contains a 11986 // non-trivial C union. 11987 QualType OrigTy; 11988 SourceLocation OrigLoc; 11989 Sema::NonTrivialCUnionContext UseContext; 11990 Sema &S; 11991 }; 11992 11993 struct DiagNonTrivalCUnionCopyVisitor 11994 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11995 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11996 11997 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11998 Sema::NonTrivialCUnionContext UseContext, 11999 Sema &S) 12000 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12001 12002 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 12003 const FieldDecl *FD, bool InNonTrivialUnion) { 12004 if (const auto *AT = S.Context.getAsArrayType(QT)) 12005 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12006 InNonTrivialUnion); 12007 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 12008 } 12009 12010 void visitARCStrong(QualType QT, const FieldDecl *FD, 12011 bool InNonTrivialUnion) { 12012 if (InNonTrivialUnion) 12013 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12014 << 1 << 2 << QT << FD->getName(); 12015 } 12016 12017 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12018 if (InNonTrivialUnion) 12019 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12020 << 1 << 2 << QT << FD->getName(); 12021 } 12022 12023 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12024 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12025 if (RD->isUnion()) { 12026 if (OrigLoc.isValid()) { 12027 bool IsUnion = false; 12028 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12029 IsUnion = OrigRD->isUnion(); 12030 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12031 << 2 << OrigTy << IsUnion << UseContext; 12032 // Reset OrigLoc so that this diagnostic is emitted only once. 12033 OrigLoc = SourceLocation(); 12034 } 12035 InNonTrivialUnion = true; 12036 } 12037 12038 if (InNonTrivialUnion) 12039 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12040 << 0 << 2 << QT.getUnqualifiedType() << ""; 12041 12042 for (const FieldDecl *FD : RD->fields()) 12043 if (!shouldIgnoreForRecordTriviality(FD)) 12044 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12045 } 12046 12047 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 12048 const FieldDecl *FD, bool InNonTrivialUnion) {} 12049 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12050 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 12051 bool InNonTrivialUnion) {} 12052 12053 // The non-trivial C union type or the struct/union type that contains a 12054 // non-trivial C union. 12055 QualType OrigTy; 12056 SourceLocation OrigLoc; 12057 Sema::NonTrivialCUnionContext UseContext; 12058 Sema &S; 12059 }; 12060 12061 } // namespace 12062 12063 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 12064 NonTrivialCUnionContext UseContext, 12065 unsigned NonTrivialKind) { 12066 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12067 QT.hasNonTrivialToPrimitiveDestructCUnion() || 12068 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 12069 "shouldn't be called if type doesn't have a non-trivial C union"); 12070 12071 if ((NonTrivialKind & NTCUK_Init) && 12072 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12073 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 12074 .visit(QT, nullptr, false); 12075 if ((NonTrivialKind & NTCUK_Destruct) && 12076 QT.hasNonTrivialToPrimitiveDestructCUnion()) 12077 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 12078 .visit(QT, nullptr, false); 12079 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 12080 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 12081 .visit(QT, nullptr, false); 12082 } 12083 12084 /// AddInitializerToDecl - Adds the initializer Init to the 12085 /// declaration dcl. If DirectInit is true, this is C++ direct 12086 /// initialization rather than copy initialization. 12087 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 12088 // If there is no declaration, there was an error parsing it. Just ignore 12089 // the initializer. 12090 if (!RealDecl || RealDecl->isInvalidDecl()) { 12091 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 12092 return; 12093 } 12094 12095 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 12096 // Pure-specifiers are handled in ActOnPureSpecifier. 12097 Diag(Method->getLocation(), diag::err_member_function_initialization) 12098 << Method->getDeclName() << Init->getSourceRange(); 12099 Method->setInvalidDecl(); 12100 return; 12101 } 12102 12103 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12104 if (!VDecl) { 12105 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 12106 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12107 RealDecl->setInvalidDecl(); 12108 return; 12109 } 12110 12111 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12112 if (VDecl->getType()->isUndeducedType()) { 12113 // Attempt typo correction early so that the type of the init expression can 12114 // be deduced based on the chosen correction if the original init contains a 12115 // TypoExpr. 12116 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12117 if (!Res.isUsable()) { 12118 // There are unresolved typos in Init, just drop them. 12119 // FIXME: improve the recovery strategy to preserve the Init. 12120 RealDecl->setInvalidDecl(); 12121 return; 12122 } 12123 if (Res.get()->containsErrors()) { 12124 // Invalidate the decl as we don't know the type for recovery-expr yet. 12125 RealDecl->setInvalidDecl(); 12126 VDecl->setInit(Res.get()); 12127 return; 12128 } 12129 Init = Res.get(); 12130 12131 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12132 return; 12133 } 12134 12135 // dllimport cannot be used on variable definitions. 12136 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12137 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12138 VDecl->setInvalidDecl(); 12139 return; 12140 } 12141 12142 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12143 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12144 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12145 VDecl->setInvalidDecl(); 12146 return; 12147 } 12148 12149 if (!VDecl->getType()->isDependentType()) { 12150 // A definition must end up with a complete type, which means it must be 12151 // complete with the restriction that an array type might be completed by 12152 // the initializer; note that later code assumes this restriction. 12153 QualType BaseDeclType = VDecl->getType(); 12154 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12155 BaseDeclType = Array->getElementType(); 12156 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12157 diag::err_typecheck_decl_incomplete_type)) { 12158 RealDecl->setInvalidDecl(); 12159 return; 12160 } 12161 12162 // The variable can not have an abstract class type. 12163 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12164 diag::err_abstract_type_in_decl, 12165 AbstractVariableType)) 12166 VDecl->setInvalidDecl(); 12167 } 12168 12169 // If adding the initializer will turn this declaration into a definition, 12170 // and we already have a definition for this variable, diagnose or otherwise 12171 // handle the situation. 12172 VarDecl *Def; 12173 if ((Def = VDecl->getDefinition()) && Def != VDecl && 12174 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12175 !VDecl->isThisDeclarationADemotedDefinition() && 12176 checkVarDeclRedefinition(Def, VDecl)) 12177 return; 12178 12179 if (getLangOpts().CPlusPlus) { 12180 // C++ [class.static.data]p4 12181 // If a static data member is of const integral or const 12182 // enumeration type, its declaration in the class definition can 12183 // specify a constant-initializer which shall be an integral 12184 // constant expression (5.19). In that case, the member can appear 12185 // in integral constant expressions. The member shall still be 12186 // defined in a namespace scope if it is used in the program and the 12187 // namespace scope definition shall not contain an initializer. 12188 // 12189 // We already performed a redefinition check above, but for static 12190 // data members we also need to check whether there was an in-class 12191 // declaration with an initializer. 12192 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12193 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12194 << VDecl->getDeclName(); 12195 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12196 diag::note_previous_initializer) 12197 << 0; 12198 return; 12199 } 12200 12201 if (VDecl->hasLocalStorage()) 12202 setFunctionHasBranchProtectedScope(); 12203 12204 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12205 VDecl->setInvalidDecl(); 12206 return; 12207 } 12208 } 12209 12210 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12211 // a kernel function cannot be initialized." 12212 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12213 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12214 VDecl->setInvalidDecl(); 12215 return; 12216 } 12217 12218 // The LoaderUninitialized attribute acts as a definition (of undef). 12219 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12220 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12221 VDecl->setInvalidDecl(); 12222 return; 12223 } 12224 12225 // Get the decls type and save a reference for later, since 12226 // CheckInitializerTypes may change it. 12227 QualType DclT = VDecl->getType(), SavT = DclT; 12228 12229 // Expressions default to 'id' when we're in a debugger 12230 // and we are assigning it to a variable of Objective-C pointer type. 12231 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12232 Init->getType() == Context.UnknownAnyTy) { 12233 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12234 if (Result.isInvalid()) { 12235 VDecl->setInvalidDecl(); 12236 return; 12237 } 12238 Init = Result.get(); 12239 } 12240 12241 // Perform the initialization. 12242 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12243 if (!VDecl->isInvalidDecl()) { 12244 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12245 InitializationKind Kind = InitializationKind::CreateForInit( 12246 VDecl->getLocation(), DirectInit, Init); 12247 12248 MultiExprArg Args = Init; 12249 if (CXXDirectInit) 12250 Args = MultiExprArg(CXXDirectInit->getExprs(), 12251 CXXDirectInit->getNumExprs()); 12252 12253 // Try to correct any TypoExprs in the initialization arguments. 12254 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12255 ExprResult Res = CorrectDelayedTyposInExpr( 12256 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12257 [this, Entity, Kind](Expr *E) { 12258 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12259 return Init.Failed() ? ExprError() : E; 12260 }); 12261 if (Res.isInvalid()) { 12262 VDecl->setInvalidDecl(); 12263 } else if (Res.get() != Args[Idx]) { 12264 Args[Idx] = Res.get(); 12265 } 12266 } 12267 if (VDecl->isInvalidDecl()) 12268 return; 12269 12270 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12271 /*TopLevelOfInitList=*/false, 12272 /*TreatUnavailableAsInvalid=*/false); 12273 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12274 if (Result.isInvalid()) { 12275 // If the provied initializer fails to initialize the var decl, 12276 // we attach a recovery expr for better recovery. 12277 auto RecoveryExpr = 12278 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12279 if (RecoveryExpr.get()) 12280 VDecl->setInit(RecoveryExpr.get()); 12281 return; 12282 } 12283 12284 Init = Result.getAs<Expr>(); 12285 } 12286 12287 // Check for self-references within variable initializers. 12288 // Variables declared within a function/method body (except for references) 12289 // are handled by a dataflow analysis. 12290 // This is undefined behavior in C++, but valid in C. 12291 if (getLangOpts().CPlusPlus) { 12292 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12293 VDecl->getType()->isReferenceType()) { 12294 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12295 } 12296 } 12297 12298 // If the type changed, it means we had an incomplete type that was 12299 // completed by the initializer. For example: 12300 // int ary[] = { 1, 3, 5 }; 12301 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12302 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12303 VDecl->setType(DclT); 12304 12305 if (!VDecl->isInvalidDecl()) { 12306 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12307 12308 if (VDecl->hasAttr<BlocksAttr>()) 12309 checkRetainCycles(VDecl, Init); 12310 12311 // It is safe to assign a weak reference into a strong variable. 12312 // Although this code can still have problems: 12313 // id x = self.weakProp; 12314 // id y = self.weakProp; 12315 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12316 // paths through the function. This should be revisited if 12317 // -Wrepeated-use-of-weak is made flow-sensitive. 12318 if (FunctionScopeInfo *FSI = getCurFunction()) 12319 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12320 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12321 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12322 Init->getBeginLoc())) 12323 FSI->markSafeWeakUse(Init); 12324 } 12325 12326 // The initialization is usually a full-expression. 12327 // 12328 // FIXME: If this is a braced initialization of an aggregate, it is not 12329 // an expression, and each individual field initializer is a separate 12330 // full-expression. For instance, in: 12331 // 12332 // struct Temp { ~Temp(); }; 12333 // struct S { S(Temp); }; 12334 // struct T { S a, b; } t = { Temp(), Temp() } 12335 // 12336 // we should destroy the first Temp before constructing the second. 12337 ExprResult Result = 12338 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12339 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12340 if (Result.isInvalid()) { 12341 VDecl->setInvalidDecl(); 12342 return; 12343 } 12344 Init = Result.get(); 12345 12346 // Attach the initializer to the decl. 12347 VDecl->setInit(Init); 12348 12349 if (VDecl->isLocalVarDecl()) { 12350 // Don't check the initializer if the declaration is malformed. 12351 if (VDecl->isInvalidDecl()) { 12352 // do nothing 12353 12354 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12355 // This is true even in C++ for OpenCL. 12356 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12357 CheckForConstantInitializer(Init, DclT); 12358 12359 // Otherwise, C++ does not restrict the initializer. 12360 } else if (getLangOpts().CPlusPlus) { 12361 // do nothing 12362 12363 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12364 // static storage duration shall be constant expressions or string literals. 12365 } else if (VDecl->getStorageClass() == SC_Static) { 12366 CheckForConstantInitializer(Init, DclT); 12367 12368 // C89 is stricter than C99 for aggregate initializers. 12369 // C89 6.5.7p3: All the expressions [...] in an initializer list 12370 // for an object that has aggregate or union type shall be 12371 // constant expressions. 12372 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12373 isa<InitListExpr>(Init)) { 12374 const Expr *Culprit; 12375 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12376 Diag(Culprit->getExprLoc(), 12377 diag::ext_aggregate_init_not_constant) 12378 << Culprit->getSourceRange(); 12379 } 12380 } 12381 12382 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12383 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12384 if (VDecl->hasLocalStorage()) 12385 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12386 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12387 VDecl->getLexicalDeclContext()->isRecord()) { 12388 // This is an in-class initialization for a static data member, e.g., 12389 // 12390 // struct S { 12391 // static const int value = 17; 12392 // }; 12393 12394 // C++ [class.mem]p4: 12395 // A member-declarator can contain a constant-initializer only 12396 // if it declares a static member (9.4) of const integral or 12397 // const enumeration type, see 9.4.2. 12398 // 12399 // C++11 [class.static.data]p3: 12400 // If a non-volatile non-inline const static data member is of integral 12401 // or enumeration type, its declaration in the class definition can 12402 // specify a brace-or-equal-initializer in which every initializer-clause 12403 // that is an assignment-expression is a constant expression. A static 12404 // data member of literal type can be declared in the class definition 12405 // with the constexpr specifier; if so, its declaration shall specify a 12406 // brace-or-equal-initializer in which every initializer-clause that is 12407 // an assignment-expression is a constant expression. 12408 12409 // Do nothing on dependent types. 12410 if (DclT->isDependentType()) { 12411 12412 // Allow any 'static constexpr' members, whether or not they are of literal 12413 // type. We separately check that every constexpr variable is of literal 12414 // type. 12415 } else if (VDecl->isConstexpr()) { 12416 12417 // Require constness. 12418 } else if (!DclT.isConstQualified()) { 12419 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12420 << Init->getSourceRange(); 12421 VDecl->setInvalidDecl(); 12422 12423 // We allow integer constant expressions in all cases. 12424 } else if (DclT->isIntegralOrEnumerationType()) { 12425 // Check whether the expression is a constant expression. 12426 SourceLocation Loc; 12427 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12428 // In C++11, a non-constexpr const static data member with an 12429 // in-class initializer cannot be volatile. 12430 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12431 else if (Init->isValueDependent()) 12432 ; // Nothing to check. 12433 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12434 ; // Ok, it's an ICE! 12435 else if (Init->getType()->isScopedEnumeralType() && 12436 Init->isCXX11ConstantExpr(Context)) 12437 ; // Ok, it is a scoped-enum constant expression. 12438 else if (Init->isEvaluatable(Context)) { 12439 // If we can constant fold the initializer through heroics, accept it, 12440 // but report this as a use of an extension for -pedantic. 12441 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12442 << Init->getSourceRange(); 12443 } else { 12444 // Otherwise, this is some crazy unknown case. Report the issue at the 12445 // location provided by the isIntegerConstantExpr failed check. 12446 Diag(Loc, diag::err_in_class_initializer_non_constant) 12447 << Init->getSourceRange(); 12448 VDecl->setInvalidDecl(); 12449 } 12450 12451 // We allow foldable floating-point constants as an extension. 12452 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12453 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12454 // it anyway and provide a fixit to add the 'constexpr'. 12455 if (getLangOpts().CPlusPlus11) { 12456 Diag(VDecl->getLocation(), 12457 diag::ext_in_class_initializer_float_type_cxx11) 12458 << DclT << Init->getSourceRange(); 12459 Diag(VDecl->getBeginLoc(), 12460 diag::note_in_class_initializer_float_type_cxx11) 12461 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12462 } else { 12463 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12464 << DclT << Init->getSourceRange(); 12465 12466 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12467 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12468 << Init->getSourceRange(); 12469 VDecl->setInvalidDecl(); 12470 } 12471 } 12472 12473 // Suggest adding 'constexpr' in C++11 for literal types. 12474 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12475 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12476 << DclT << Init->getSourceRange() 12477 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12478 VDecl->setConstexpr(true); 12479 12480 } else { 12481 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12482 << DclT << Init->getSourceRange(); 12483 VDecl->setInvalidDecl(); 12484 } 12485 } else if (VDecl->isFileVarDecl()) { 12486 // In C, extern is typically used to avoid tentative definitions when 12487 // declaring variables in headers, but adding an intializer makes it a 12488 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12489 // In C++, extern is often used to give implictly static const variables 12490 // external linkage, so don't warn in that case. If selectany is present, 12491 // this might be header code intended for C and C++ inclusion, so apply the 12492 // C++ rules. 12493 if (VDecl->getStorageClass() == SC_Extern && 12494 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12495 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12496 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12497 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12498 Diag(VDecl->getLocation(), diag::warn_extern_init); 12499 12500 // In Microsoft C++ mode, a const variable defined in namespace scope has 12501 // external linkage by default if the variable is declared with 12502 // __declspec(dllexport). 12503 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12504 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12505 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12506 VDecl->setStorageClass(SC_Extern); 12507 12508 // C99 6.7.8p4. All file scoped initializers need to be constant. 12509 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12510 CheckForConstantInitializer(Init, DclT); 12511 } 12512 12513 QualType InitType = Init->getType(); 12514 if (!InitType.isNull() && 12515 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12516 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12517 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12518 12519 // We will represent direct-initialization similarly to copy-initialization: 12520 // int x(1); -as-> int x = 1; 12521 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12522 // 12523 // Clients that want to distinguish between the two forms, can check for 12524 // direct initializer using VarDecl::getInitStyle(). 12525 // A major benefit is that clients that don't particularly care about which 12526 // exactly form was it (like the CodeGen) can handle both cases without 12527 // special case code. 12528 12529 // C++ 8.5p11: 12530 // The form of initialization (using parentheses or '=') is generally 12531 // insignificant, but does matter when the entity being initialized has a 12532 // class type. 12533 if (CXXDirectInit) { 12534 assert(DirectInit && "Call-style initializer must be direct init."); 12535 VDecl->setInitStyle(VarDecl::CallInit); 12536 } else if (DirectInit) { 12537 // This must be list-initialization. No other way is direct-initialization. 12538 VDecl->setInitStyle(VarDecl::ListInit); 12539 } 12540 12541 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12542 DeclsToCheckForDeferredDiags.insert(VDecl); 12543 CheckCompleteVariableDeclaration(VDecl); 12544 } 12545 12546 /// ActOnInitializerError - Given that there was an error parsing an 12547 /// initializer for the given declaration, try to return to some form 12548 /// of sanity. 12549 void Sema::ActOnInitializerError(Decl *D) { 12550 // Our main concern here is re-establishing invariants like "a 12551 // variable's type is either dependent or complete". 12552 if (!D || D->isInvalidDecl()) return; 12553 12554 VarDecl *VD = dyn_cast<VarDecl>(D); 12555 if (!VD) return; 12556 12557 // Bindings are not usable if we can't make sense of the initializer. 12558 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12559 for (auto *BD : DD->bindings()) 12560 BD->setInvalidDecl(); 12561 12562 // Auto types are meaningless if we can't make sense of the initializer. 12563 if (VD->getType()->isUndeducedType()) { 12564 D->setInvalidDecl(); 12565 return; 12566 } 12567 12568 QualType Ty = VD->getType(); 12569 if (Ty->isDependentType()) return; 12570 12571 // Require a complete type. 12572 if (RequireCompleteType(VD->getLocation(), 12573 Context.getBaseElementType(Ty), 12574 diag::err_typecheck_decl_incomplete_type)) { 12575 VD->setInvalidDecl(); 12576 return; 12577 } 12578 12579 // Require a non-abstract type. 12580 if (RequireNonAbstractType(VD->getLocation(), Ty, 12581 diag::err_abstract_type_in_decl, 12582 AbstractVariableType)) { 12583 VD->setInvalidDecl(); 12584 return; 12585 } 12586 12587 // Don't bother complaining about constructors or destructors, 12588 // though. 12589 } 12590 12591 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12592 // If there is no declaration, there was an error parsing it. Just ignore it. 12593 if (!RealDecl) 12594 return; 12595 12596 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12597 QualType Type = Var->getType(); 12598 12599 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12600 if (isa<DecompositionDecl>(RealDecl)) { 12601 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12602 Var->setInvalidDecl(); 12603 return; 12604 } 12605 12606 if (Type->isUndeducedType() && 12607 DeduceVariableDeclarationType(Var, false, nullptr)) 12608 return; 12609 12610 // C++11 [class.static.data]p3: A static data member can be declared with 12611 // the constexpr specifier; if so, its declaration shall specify 12612 // a brace-or-equal-initializer. 12613 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12614 // the definition of a variable [...] or the declaration of a static data 12615 // member. 12616 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12617 !Var->isThisDeclarationADemotedDefinition()) { 12618 if (Var->isStaticDataMember()) { 12619 // C++1z removes the relevant rule; the in-class declaration is always 12620 // a definition there. 12621 if (!getLangOpts().CPlusPlus17 && 12622 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12623 Diag(Var->getLocation(), 12624 diag::err_constexpr_static_mem_var_requires_init) 12625 << Var; 12626 Var->setInvalidDecl(); 12627 return; 12628 } 12629 } else { 12630 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12631 Var->setInvalidDecl(); 12632 return; 12633 } 12634 } 12635 12636 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12637 // be initialized. 12638 if (!Var->isInvalidDecl() && 12639 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12640 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12641 bool HasConstExprDefaultConstructor = false; 12642 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12643 for (auto *Ctor : RD->ctors()) { 12644 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && 12645 Ctor->getMethodQualifiers().getAddressSpace() == 12646 LangAS::opencl_constant) { 12647 HasConstExprDefaultConstructor = true; 12648 } 12649 } 12650 } 12651 if (!HasConstExprDefaultConstructor) { 12652 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12653 Var->setInvalidDecl(); 12654 return; 12655 } 12656 } 12657 12658 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12659 if (Var->getStorageClass() == SC_Extern) { 12660 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12661 << Var; 12662 Var->setInvalidDecl(); 12663 return; 12664 } 12665 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12666 diag::err_typecheck_decl_incomplete_type)) { 12667 Var->setInvalidDecl(); 12668 return; 12669 } 12670 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12671 if (!RD->hasTrivialDefaultConstructor()) { 12672 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12673 Var->setInvalidDecl(); 12674 return; 12675 } 12676 } 12677 // The declaration is unitialized, no need for further checks. 12678 return; 12679 } 12680 12681 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12682 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12683 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12684 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12685 NTCUC_DefaultInitializedObject, NTCUK_Init); 12686 12687 12688 switch (DefKind) { 12689 case VarDecl::Definition: 12690 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12691 break; 12692 12693 // We have an out-of-line definition of a static data member 12694 // that has an in-class initializer, so we type-check this like 12695 // a declaration. 12696 // 12697 LLVM_FALLTHROUGH; 12698 12699 case VarDecl::DeclarationOnly: 12700 // It's only a declaration. 12701 12702 // Block scope. C99 6.7p7: If an identifier for an object is 12703 // declared with no linkage (C99 6.2.2p6), the type for the 12704 // object shall be complete. 12705 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12706 !Var->hasLinkage() && !Var->isInvalidDecl() && 12707 RequireCompleteType(Var->getLocation(), Type, 12708 diag::err_typecheck_decl_incomplete_type)) 12709 Var->setInvalidDecl(); 12710 12711 // Make sure that the type is not abstract. 12712 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12713 RequireNonAbstractType(Var->getLocation(), Type, 12714 diag::err_abstract_type_in_decl, 12715 AbstractVariableType)) 12716 Var->setInvalidDecl(); 12717 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12718 Var->getStorageClass() == SC_PrivateExtern) { 12719 Diag(Var->getLocation(), diag::warn_private_extern); 12720 Diag(Var->getLocation(), diag::note_private_extern); 12721 } 12722 12723 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 12724 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12725 ExternalDeclarations.push_back(Var); 12726 12727 return; 12728 12729 case VarDecl::TentativeDefinition: 12730 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12731 // object that has file scope without an initializer, and without a 12732 // storage-class specifier or with the storage-class specifier "static", 12733 // constitutes a tentative definition. Note: A tentative definition with 12734 // external linkage is valid (C99 6.2.2p5). 12735 if (!Var->isInvalidDecl()) { 12736 if (const IncompleteArrayType *ArrayT 12737 = Context.getAsIncompleteArrayType(Type)) { 12738 if (RequireCompleteSizedType( 12739 Var->getLocation(), ArrayT->getElementType(), 12740 diag::err_array_incomplete_or_sizeless_type)) 12741 Var->setInvalidDecl(); 12742 } else if (Var->getStorageClass() == SC_Static) { 12743 // C99 6.9.2p3: If the declaration of an identifier for an object is 12744 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12745 // declared type shall not be an incomplete type. 12746 // NOTE: code such as the following 12747 // static struct s; 12748 // struct s { int a; }; 12749 // is accepted by gcc. Hence here we issue a warning instead of 12750 // an error and we do not invalidate the static declaration. 12751 // NOTE: to avoid multiple warnings, only check the first declaration. 12752 if (Var->isFirstDecl()) 12753 RequireCompleteType(Var->getLocation(), Type, 12754 diag::ext_typecheck_decl_incomplete_type); 12755 } 12756 } 12757 12758 // Record the tentative definition; we're done. 12759 if (!Var->isInvalidDecl()) 12760 TentativeDefinitions.push_back(Var); 12761 return; 12762 } 12763 12764 // Provide a specific diagnostic for uninitialized variable 12765 // definitions with incomplete array type. 12766 if (Type->isIncompleteArrayType()) { 12767 Diag(Var->getLocation(), 12768 diag::err_typecheck_incomplete_array_needs_initializer); 12769 Var->setInvalidDecl(); 12770 return; 12771 } 12772 12773 // Provide a specific diagnostic for uninitialized variable 12774 // definitions with reference type. 12775 if (Type->isReferenceType()) { 12776 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12777 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 12778 Var->setInvalidDecl(); 12779 return; 12780 } 12781 12782 // Do not attempt to type-check the default initializer for a 12783 // variable with dependent type. 12784 if (Type->isDependentType()) 12785 return; 12786 12787 if (Var->isInvalidDecl()) 12788 return; 12789 12790 if (!Var->hasAttr<AliasAttr>()) { 12791 if (RequireCompleteType(Var->getLocation(), 12792 Context.getBaseElementType(Type), 12793 diag::err_typecheck_decl_incomplete_type)) { 12794 Var->setInvalidDecl(); 12795 return; 12796 } 12797 } else { 12798 return; 12799 } 12800 12801 // The variable can not have an abstract class type. 12802 if (RequireNonAbstractType(Var->getLocation(), Type, 12803 diag::err_abstract_type_in_decl, 12804 AbstractVariableType)) { 12805 Var->setInvalidDecl(); 12806 return; 12807 } 12808 12809 // Check for jumps past the implicit initializer. C++0x 12810 // clarifies that this applies to a "variable with automatic 12811 // storage duration", not a "local variable". 12812 // C++11 [stmt.dcl]p3 12813 // A program that jumps from a point where a variable with automatic 12814 // storage duration is not in scope to a point where it is in scope is 12815 // ill-formed unless the variable has scalar type, class type with a 12816 // trivial default constructor and a trivial destructor, a cv-qualified 12817 // version of one of these types, or an array of one of the preceding 12818 // types and is declared without an initializer. 12819 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12820 if (const RecordType *Record 12821 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12822 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12823 // Mark the function (if we're in one) for further checking even if the 12824 // looser rules of C++11 do not require such checks, so that we can 12825 // diagnose incompatibilities with C++98. 12826 if (!CXXRecord->isPOD()) 12827 setFunctionHasBranchProtectedScope(); 12828 } 12829 } 12830 // In OpenCL, we can't initialize objects in the __local address space, 12831 // even implicitly, so don't synthesize an implicit initializer. 12832 if (getLangOpts().OpenCL && 12833 Var->getType().getAddressSpace() == LangAS::opencl_local) 12834 return; 12835 // C++03 [dcl.init]p9: 12836 // If no initializer is specified for an object, and the 12837 // object is of (possibly cv-qualified) non-POD class type (or 12838 // array thereof), the object shall be default-initialized; if 12839 // the object is of const-qualified type, the underlying class 12840 // type shall have a user-declared default 12841 // constructor. Otherwise, if no initializer is specified for 12842 // a non- static object, the object and its subobjects, if 12843 // any, have an indeterminate initial value); if the object 12844 // or any of its subobjects are of const-qualified type, the 12845 // program is ill-formed. 12846 // C++0x [dcl.init]p11: 12847 // If no initializer is specified for an object, the object is 12848 // default-initialized; [...]. 12849 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12850 InitializationKind Kind 12851 = InitializationKind::CreateDefault(Var->getLocation()); 12852 12853 InitializationSequence InitSeq(*this, Entity, Kind, None); 12854 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12855 12856 if (Init.get()) { 12857 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12858 // This is important for template substitution. 12859 Var->setInitStyle(VarDecl::CallInit); 12860 } else if (Init.isInvalid()) { 12861 // If default-init fails, attach a recovery-expr initializer to track 12862 // that initialization was attempted and failed. 12863 auto RecoveryExpr = 12864 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12865 if (RecoveryExpr.get()) 12866 Var->setInit(RecoveryExpr.get()); 12867 } 12868 12869 CheckCompleteVariableDeclaration(Var); 12870 } 12871 } 12872 12873 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12874 // If there is no declaration, there was an error parsing it. Ignore it. 12875 if (!D) 12876 return; 12877 12878 VarDecl *VD = dyn_cast<VarDecl>(D); 12879 if (!VD) { 12880 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12881 D->setInvalidDecl(); 12882 return; 12883 } 12884 12885 VD->setCXXForRangeDecl(true); 12886 12887 // for-range-declaration cannot be given a storage class specifier. 12888 int Error = -1; 12889 switch (VD->getStorageClass()) { 12890 case SC_None: 12891 break; 12892 case SC_Extern: 12893 Error = 0; 12894 break; 12895 case SC_Static: 12896 Error = 1; 12897 break; 12898 case SC_PrivateExtern: 12899 Error = 2; 12900 break; 12901 case SC_Auto: 12902 Error = 3; 12903 break; 12904 case SC_Register: 12905 Error = 4; 12906 break; 12907 } 12908 12909 // for-range-declaration cannot be given a storage class specifier con't. 12910 switch (VD->getTSCSpec()) { 12911 case TSCS_thread_local: 12912 Error = 6; 12913 break; 12914 case TSCS___thread: 12915 case TSCS__Thread_local: 12916 case TSCS_unspecified: 12917 break; 12918 } 12919 12920 if (Error != -1) { 12921 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12922 << VD << Error; 12923 D->setInvalidDecl(); 12924 } 12925 } 12926 12927 StmtResult 12928 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12929 IdentifierInfo *Ident, 12930 ParsedAttributes &Attrs, 12931 SourceLocation AttrEnd) { 12932 // C++1y [stmt.iter]p1: 12933 // A range-based for statement of the form 12934 // for ( for-range-identifier : for-range-initializer ) statement 12935 // is equivalent to 12936 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12937 DeclSpec DS(Attrs.getPool().getFactory()); 12938 12939 const char *PrevSpec; 12940 unsigned DiagID; 12941 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12942 getPrintingPolicy()); 12943 12944 Declarator D(DS, DeclaratorContext::ForInit); 12945 D.SetIdentifier(Ident, IdentLoc); 12946 D.takeAttributes(Attrs, AttrEnd); 12947 12948 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12949 IdentLoc); 12950 Decl *Var = ActOnDeclarator(S, D); 12951 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12952 FinalizeDeclaration(Var); 12953 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12954 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12955 } 12956 12957 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12958 if (var->isInvalidDecl()) return; 12959 12960 if (getLangOpts().OpenCL) { 12961 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12962 // initialiser 12963 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12964 !var->hasInit()) { 12965 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12966 << 1 /*Init*/; 12967 var->setInvalidDecl(); 12968 return; 12969 } 12970 } 12971 12972 // In Objective-C, don't allow jumps past the implicit initialization of a 12973 // local retaining variable. 12974 if (getLangOpts().ObjC && 12975 var->hasLocalStorage()) { 12976 switch (var->getType().getObjCLifetime()) { 12977 case Qualifiers::OCL_None: 12978 case Qualifiers::OCL_ExplicitNone: 12979 case Qualifiers::OCL_Autoreleasing: 12980 break; 12981 12982 case Qualifiers::OCL_Weak: 12983 case Qualifiers::OCL_Strong: 12984 setFunctionHasBranchProtectedScope(); 12985 break; 12986 } 12987 } 12988 12989 if (var->hasLocalStorage() && 12990 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12991 setFunctionHasBranchProtectedScope(); 12992 12993 // Warn about externally-visible variables being defined without a 12994 // prior declaration. We only want to do this for global 12995 // declarations, but we also specifically need to avoid doing it for 12996 // class members because the linkage of an anonymous class can 12997 // change if it's later given a typedef name. 12998 if (var->isThisDeclarationADefinition() && 12999 var->getDeclContext()->getRedeclContext()->isFileContext() && 13000 var->isExternallyVisible() && var->hasLinkage() && 13001 !var->isInline() && !var->getDescribedVarTemplate() && 13002 !isa<VarTemplatePartialSpecializationDecl>(var) && 13003 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 13004 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 13005 var->getLocation())) { 13006 // Find a previous declaration that's not a definition. 13007 VarDecl *prev = var->getPreviousDecl(); 13008 while (prev && prev->isThisDeclarationADefinition()) 13009 prev = prev->getPreviousDecl(); 13010 13011 if (!prev) { 13012 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 13013 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 13014 << /* variable */ 0; 13015 } 13016 } 13017 13018 // Cache the result of checking for constant initialization. 13019 Optional<bool> CacheHasConstInit; 13020 const Expr *CacheCulprit = nullptr; 13021 auto checkConstInit = [&]() mutable { 13022 if (!CacheHasConstInit) 13023 CacheHasConstInit = var->getInit()->isConstantInitializer( 13024 Context, var->getType()->isReferenceType(), &CacheCulprit); 13025 return *CacheHasConstInit; 13026 }; 13027 13028 if (var->getTLSKind() == VarDecl::TLS_Static) { 13029 if (var->getType().isDestructedType()) { 13030 // GNU C++98 edits for __thread, [basic.start.term]p3: 13031 // The type of an object with thread storage duration shall not 13032 // have a non-trivial destructor. 13033 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 13034 if (getLangOpts().CPlusPlus11) 13035 Diag(var->getLocation(), diag::note_use_thread_local); 13036 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 13037 if (!checkConstInit()) { 13038 // GNU C++98 edits for __thread, [basic.start.init]p4: 13039 // An object of thread storage duration shall not require dynamic 13040 // initialization. 13041 // FIXME: Need strict checking here. 13042 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 13043 << CacheCulprit->getSourceRange(); 13044 if (getLangOpts().CPlusPlus11) 13045 Diag(var->getLocation(), diag::note_use_thread_local); 13046 } 13047 } 13048 } 13049 13050 // Apply section attributes and pragmas to global variables. 13051 bool GlobalStorage = var->hasGlobalStorage(); 13052 if (GlobalStorage && var->isThisDeclarationADefinition() && 13053 !inTemplateInstantiation()) { 13054 PragmaStack<StringLiteral *> *Stack = nullptr; 13055 int SectionFlags = ASTContext::PSF_Read; 13056 if (var->getType().isConstQualified()) 13057 Stack = &ConstSegStack; 13058 else if (!var->getInit()) { 13059 Stack = &BSSSegStack; 13060 SectionFlags |= ASTContext::PSF_Write; 13061 } else { 13062 Stack = &DataSegStack; 13063 SectionFlags |= ASTContext::PSF_Write; 13064 } 13065 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 13066 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 13067 SectionFlags |= ASTContext::PSF_Implicit; 13068 UnifySection(SA->getName(), SectionFlags, var); 13069 } else if (Stack->CurrentValue) { 13070 SectionFlags |= ASTContext::PSF_Implicit; 13071 auto SectionName = Stack->CurrentValue->getString(); 13072 var->addAttr(SectionAttr::CreateImplicit( 13073 Context, SectionName, Stack->CurrentPragmaLocation, 13074 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 13075 if (UnifySection(SectionName, SectionFlags, var)) 13076 var->dropAttr<SectionAttr>(); 13077 } 13078 13079 // Apply the init_seg attribute if this has an initializer. If the 13080 // initializer turns out to not be dynamic, we'll end up ignoring this 13081 // attribute. 13082 if (CurInitSeg && var->getInit()) 13083 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 13084 CurInitSegLoc, 13085 AttributeCommonInfo::AS_Pragma)); 13086 } 13087 13088 if (!var->getType()->isStructureType() && var->hasInit() && 13089 isa<InitListExpr>(var->getInit())) { 13090 const auto *ILE = cast<InitListExpr>(var->getInit()); 13091 unsigned NumInits = ILE->getNumInits(); 13092 if (NumInits > 2) 13093 for (unsigned I = 0; I < NumInits; ++I) { 13094 const auto *Init = ILE->getInit(I); 13095 if (!Init) 13096 break; 13097 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13098 if (!SL) 13099 break; 13100 13101 unsigned NumConcat = SL->getNumConcatenated(); 13102 // Diagnose missing comma in string array initialization. 13103 // Do not warn when all the elements in the initializer are concatenated 13104 // together. Do not warn for macros too. 13105 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 13106 bool OnlyOneMissingComma = true; 13107 for (unsigned J = I + 1; J < NumInits; ++J) { 13108 const auto *Init = ILE->getInit(J); 13109 if (!Init) 13110 break; 13111 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13112 if (!SLJ || SLJ->getNumConcatenated() > 1) { 13113 OnlyOneMissingComma = false; 13114 break; 13115 } 13116 } 13117 13118 if (OnlyOneMissingComma) { 13119 SmallVector<FixItHint, 1> Hints; 13120 for (unsigned i = 0; i < NumConcat - 1; ++i) 13121 Hints.push_back(FixItHint::CreateInsertion( 13122 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13123 13124 Diag(SL->getStrTokenLoc(1), 13125 diag::warn_concatenated_literal_array_init) 13126 << Hints; 13127 Diag(SL->getBeginLoc(), 13128 diag::note_concatenated_string_literal_silence); 13129 } 13130 // In any case, stop now. 13131 break; 13132 } 13133 } 13134 } 13135 13136 // All the following checks are C++ only. 13137 if (!getLangOpts().CPlusPlus) { 13138 // If this variable must be emitted, add it as an initializer for the 13139 // current module. 13140 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13141 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13142 return; 13143 } 13144 13145 QualType type = var->getType(); 13146 13147 if (var->hasAttr<BlocksAttr>()) 13148 getCurFunction()->addByrefBlockVar(var); 13149 13150 Expr *Init = var->getInit(); 13151 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13152 QualType baseType = Context.getBaseElementType(type); 13153 13154 // Check whether the initializer is sufficiently constant. 13155 if (!type->isDependentType() && Init && !Init->isValueDependent() && 13156 (GlobalStorage || var->isConstexpr() || 13157 var->mightBeUsableInConstantExpressions(Context))) { 13158 // If this variable might have a constant initializer or might be usable in 13159 // constant expressions, check whether or not it actually is now. We can't 13160 // do this lazily, because the result might depend on things that change 13161 // later, such as which constexpr functions happen to be defined. 13162 SmallVector<PartialDiagnosticAt, 8> Notes; 13163 bool HasConstInit; 13164 if (!getLangOpts().CPlusPlus11) { 13165 // Prior to C++11, in contexts where a constant initializer is required, 13166 // the set of valid constant initializers is described by syntactic rules 13167 // in [expr.const]p2-6. 13168 // FIXME: Stricter checking for these rules would be useful for constinit / 13169 // -Wglobal-constructors. 13170 HasConstInit = checkConstInit(); 13171 13172 // Compute and cache the constant value, and remember that we have a 13173 // constant initializer. 13174 if (HasConstInit) { 13175 (void)var->checkForConstantInitialization(Notes); 13176 Notes.clear(); 13177 } else if (CacheCulprit) { 13178 Notes.emplace_back(CacheCulprit->getExprLoc(), 13179 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13180 Notes.back().second << CacheCulprit->getSourceRange(); 13181 } 13182 } else { 13183 // Evaluate the initializer to see if it's a constant initializer. 13184 HasConstInit = var->checkForConstantInitialization(Notes); 13185 } 13186 13187 if (HasConstInit) { 13188 // FIXME: Consider replacing the initializer with a ConstantExpr. 13189 } else if (var->isConstexpr()) { 13190 SourceLocation DiagLoc = var->getLocation(); 13191 // If the note doesn't add any useful information other than a source 13192 // location, fold it into the primary diagnostic. 13193 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13194 diag::note_invalid_subexpr_in_const_expr) { 13195 DiagLoc = Notes[0].first; 13196 Notes.clear(); 13197 } 13198 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13199 << var << Init->getSourceRange(); 13200 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13201 Diag(Notes[I].first, Notes[I].second); 13202 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13203 auto *Attr = var->getAttr<ConstInitAttr>(); 13204 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13205 << Init->getSourceRange(); 13206 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13207 << Attr->getRange() << Attr->isConstinit(); 13208 for (auto &it : Notes) 13209 Diag(it.first, it.second); 13210 } else if (IsGlobal && 13211 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13212 var->getLocation())) { 13213 // Warn about globals which don't have a constant initializer. Don't 13214 // warn about globals with a non-trivial destructor because we already 13215 // warned about them. 13216 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13217 if (!(RD && !RD->hasTrivialDestructor())) { 13218 // checkConstInit() here permits trivial default initialization even in 13219 // C++11 onwards, where such an initializer is not a constant initializer 13220 // but nonetheless doesn't require a global constructor. 13221 if (!checkConstInit()) 13222 Diag(var->getLocation(), diag::warn_global_constructor) 13223 << Init->getSourceRange(); 13224 } 13225 } 13226 } 13227 13228 // Require the destructor. 13229 if (!type->isDependentType()) 13230 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13231 FinalizeVarWithDestructor(var, recordType); 13232 13233 // If this variable must be emitted, add it as an initializer for the current 13234 // module. 13235 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13236 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13237 13238 // Build the bindings if this is a structured binding declaration. 13239 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13240 CheckCompleteDecompositionDeclaration(DD); 13241 } 13242 13243 /// Determines if a variable's alignment is dependent. 13244 static bool hasDependentAlignment(VarDecl *VD) { 13245 if (VD->getType()->isDependentType()) 13246 return true; 13247 for (auto *I : VD->specific_attrs<AlignedAttr>()) 13248 if (I->isAlignmentDependent()) 13249 return true; 13250 return false; 13251 } 13252 13253 /// Check if VD needs to be dllexport/dllimport due to being in a 13254 /// dllexport/import function. 13255 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13256 assert(VD->isStaticLocal()); 13257 13258 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13259 13260 // Find outermost function when VD is in lambda function. 13261 while (FD && !getDLLAttr(FD) && 13262 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13263 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13264 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13265 } 13266 13267 if (!FD) 13268 return; 13269 13270 // Static locals inherit dll attributes from their function. 13271 if (Attr *A = getDLLAttr(FD)) { 13272 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13273 NewAttr->setInherited(true); 13274 VD->addAttr(NewAttr); 13275 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13276 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13277 NewAttr->setInherited(true); 13278 VD->addAttr(NewAttr); 13279 13280 // Export this function to enforce exporting this static variable even 13281 // if it is not used in this compilation unit. 13282 if (!FD->hasAttr<DLLExportAttr>()) 13283 FD->addAttr(NewAttr); 13284 13285 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13286 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13287 NewAttr->setInherited(true); 13288 VD->addAttr(NewAttr); 13289 } 13290 } 13291 13292 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13293 /// any semantic actions necessary after any initializer has been attached. 13294 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13295 // Note that we are no longer parsing the initializer for this declaration. 13296 ParsingInitForAutoVars.erase(ThisDecl); 13297 13298 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13299 if (!VD) 13300 return; 13301 13302 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13303 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13304 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13305 if (PragmaClangBSSSection.Valid) 13306 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13307 Context, PragmaClangBSSSection.SectionName, 13308 PragmaClangBSSSection.PragmaLocation, 13309 AttributeCommonInfo::AS_Pragma)); 13310 if (PragmaClangDataSection.Valid) 13311 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13312 Context, PragmaClangDataSection.SectionName, 13313 PragmaClangDataSection.PragmaLocation, 13314 AttributeCommonInfo::AS_Pragma)); 13315 if (PragmaClangRodataSection.Valid) 13316 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13317 Context, PragmaClangRodataSection.SectionName, 13318 PragmaClangRodataSection.PragmaLocation, 13319 AttributeCommonInfo::AS_Pragma)); 13320 if (PragmaClangRelroSection.Valid) 13321 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13322 Context, PragmaClangRelroSection.SectionName, 13323 PragmaClangRelroSection.PragmaLocation, 13324 AttributeCommonInfo::AS_Pragma)); 13325 } 13326 13327 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13328 for (auto *BD : DD->bindings()) { 13329 FinalizeDeclaration(BD); 13330 } 13331 } 13332 13333 checkAttributesAfterMerging(*this, *VD); 13334 13335 // Perform TLS alignment check here after attributes attached to the variable 13336 // which may affect the alignment have been processed. Only perform the check 13337 // if the target has a maximum TLS alignment (zero means no constraints). 13338 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13339 // Protect the check so that it's not performed on dependent types and 13340 // dependent alignments (we can't determine the alignment in that case). 13341 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 13342 !VD->isInvalidDecl()) { 13343 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13344 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13345 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13346 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13347 << (unsigned)MaxAlignChars.getQuantity(); 13348 } 13349 } 13350 } 13351 13352 if (VD->isStaticLocal()) 13353 CheckStaticLocalForDllExport(VD); 13354 13355 // Perform check for initializers of device-side global variables. 13356 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13357 // 7.5). We must also apply the same checks to all __shared__ 13358 // variables whether they are local or not. CUDA also allows 13359 // constant initializers for __constant__ and __device__ variables. 13360 if (getLangOpts().CUDA) 13361 checkAllowedCUDAInitializer(VD); 13362 13363 // Grab the dllimport or dllexport attribute off of the VarDecl. 13364 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13365 13366 // Imported static data members cannot be defined out-of-line. 13367 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13368 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13369 VD->isThisDeclarationADefinition()) { 13370 // We allow definitions of dllimport class template static data members 13371 // with a warning. 13372 CXXRecordDecl *Context = 13373 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13374 bool IsClassTemplateMember = 13375 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13376 Context->getDescribedClassTemplate(); 13377 13378 Diag(VD->getLocation(), 13379 IsClassTemplateMember 13380 ? diag::warn_attribute_dllimport_static_field_definition 13381 : diag::err_attribute_dllimport_static_field_definition); 13382 Diag(IA->getLocation(), diag::note_attribute); 13383 if (!IsClassTemplateMember) 13384 VD->setInvalidDecl(); 13385 } 13386 } 13387 13388 // dllimport/dllexport variables cannot be thread local, their TLS index 13389 // isn't exported with the variable. 13390 if (DLLAttr && VD->getTLSKind()) { 13391 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13392 if (F && getDLLAttr(F)) { 13393 assert(VD->isStaticLocal()); 13394 // But if this is a static local in a dlimport/dllexport function, the 13395 // function will never be inlined, which means the var would never be 13396 // imported, so having it marked import/export is safe. 13397 } else { 13398 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13399 << DLLAttr; 13400 VD->setInvalidDecl(); 13401 } 13402 } 13403 13404 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13405 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13406 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13407 << Attr; 13408 VD->dropAttr<UsedAttr>(); 13409 } 13410 } 13411 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 13412 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13413 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13414 << Attr; 13415 VD->dropAttr<RetainAttr>(); 13416 } 13417 } 13418 13419 const DeclContext *DC = VD->getDeclContext(); 13420 // If there's a #pragma GCC visibility in scope, and this isn't a class 13421 // member, set the visibility of this variable. 13422 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13423 AddPushedVisibilityAttribute(VD); 13424 13425 // FIXME: Warn on unused var template partial specializations. 13426 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13427 MarkUnusedFileScopedDecl(VD); 13428 13429 // Now we have parsed the initializer and can update the table of magic 13430 // tag values. 13431 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13432 !VD->getType()->isIntegralOrEnumerationType()) 13433 return; 13434 13435 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13436 const Expr *MagicValueExpr = VD->getInit(); 13437 if (!MagicValueExpr) { 13438 continue; 13439 } 13440 Optional<llvm::APSInt> MagicValueInt; 13441 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13442 Diag(I->getRange().getBegin(), 13443 diag::err_type_tag_for_datatype_not_ice) 13444 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13445 continue; 13446 } 13447 if (MagicValueInt->getActiveBits() > 64) { 13448 Diag(I->getRange().getBegin(), 13449 diag::err_type_tag_for_datatype_too_large) 13450 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13451 continue; 13452 } 13453 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13454 RegisterTypeTagForDatatype(I->getArgumentKind(), 13455 MagicValue, 13456 I->getMatchingCType(), 13457 I->getLayoutCompatible(), 13458 I->getMustBeNull()); 13459 } 13460 } 13461 13462 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13463 auto *VD = dyn_cast<VarDecl>(DD); 13464 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13465 } 13466 13467 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13468 ArrayRef<Decl *> Group) { 13469 SmallVector<Decl*, 8> Decls; 13470 13471 if (DS.isTypeSpecOwned()) 13472 Decls.push_back(DS.getRepAsDecl()); 13473 13474 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13475 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13476 bool DiagnosedMultipleDecomps = false; 13477 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13478 bool DiagnosedNonDeducedAuto = false; 13479 13480 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13481 if (Decl *D = Group[i]) { 13482 // For declarators, there are some additional syntactic-ish checks we need 13483 // to perform. 13484 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13485 if (!FirstDeclaratorInGroup) 13486 FirstDeclaratorInGroup = DD; 13487 if (!FirstDecompDeclaratorInGroup) 13488 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13489 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13490 !hasDeducedAuto(DD)) 13491 FirstNonDeducedAutoInGroup = DD; 13492 13493 if (FirstDeclaratorInGroup != DD) { 13494 // A decomposition declaration cannot be combined with any other 13495 // declaration in the same group. 13496 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13497 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13498 diag::err_decomp_decl_not_alone) 13499 << FirstDeclaratorInGroup->getSourceRange() 13500 << DD->getSourceRange(); 13501 DiagnosedMultipleDecomps = true; 13502 } 13503 13504 // A declarator that uses 'auto' in any way other than to declare a 13505 // variable with a deduced type cannot be combined with any other 13506 // declarator in the same group. 13507 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13508 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13509 diag::err_auto_non_deduced_not_alone) 13510 << FirstNonDeducedAutoInGroup->getType() 13511 ->hasAutoForTrailingReturnType() 13512 << FirstDeclaratorInGroup->getSourceRange() 13513 << DD->getSourceRange(); 13514 DiagnosedNonDeducedAuto = true; 13515 } 13516 } 13517 } 13518 13519 Decls.push_back(D); 13520 } 13521 } 13522 13523 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13524 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13525 handleTagNumbering(Tag, S); 13526 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13527 getLangOpts().CPlusPlus) 13528 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13529 } 13530 } 13531 13532 return BuildDeclaratorGroup(Decls); 13533 } 13534 13535 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13536 /// group, performing any necessary semantic checking. 13537 Sema::DeclGroupPtrTy 13538 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13539 // C++14 [dcl.spec.auto]p7: (DR1347) 13540 // If the type that replaces the placeholder type is not the same in each 13541 // deduction, the program is ill-formed. 13542 if (Group.size() > 1) { 13543 QualType Deduced; 13544 VarDecl *DeducedDecl = nullptr; 13545 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13546 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13547 if (!D || D->isInvalidDecl()) 13548 break; 13549 DeducedType *DT = D->getType()->getContainedDeducedType(); 13550 if (!DT || DT->getDeducedType().isNull()) 13551 continue; 13552 if (Deduced.isNull()) { 13553 Deduced = DT->getDeducedType(); 13554 DeducedDecl = D; 13555 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13556 auto *AT = dyn_cast<AutoType>(DT); 13557 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13558 diag::err_auto_different_deductions) 13559 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13560 << DeducedDecl->getDeclName() << DT->getDeducedType() 13561 << D->getDeclName(); 13562 if (DeducedDecl->hasInit()) 13563 Dia << DeducedDecl->getInit()->getSourceRange(); 13564 if (D->getInit()) 13565 Dia << D->getInit()->getSourceRange(); 13566 D->setInvalidDecl(); 13567 break; 13568 } 13569 } 13570 } 13571 13572 ActOnDocumentableDecls(Group); 13573 13574 return DeclGroupPtrTy::make( 13575 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13576 } 13577 13578 void Sema::ActOnDocumentableDecl(Decl *D) { 13579 ActOnDocumentableDecls(D); 13580 } 13581 13582 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13583 // Don't parse the comment if Doxygen diagnostics are ignored. 13584 if (Group.empty() || !Group[0]) 13585 return; 13586 13587 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13588 Group[0]->getLocation()) && 13589 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13590 Group[0]->getLocation())) 13591 return; 13592 13593 if (Group.size() >= 2) { 13594 // This is a decl group. Normally it will contain only declarations 13595 // produced from declarator list. But in case we have any definitions or 13596 // additional declaration references: 13597 // 'typedef struct S {} S;' 13598 // 'typedef struct S *S;' 13599 // 'struct S *pS;' 13600 // FinalizeDeclaratorGroup adds these as separate declarations. 13601 Decl *MaybeTagDecl = Group[0]; 13602 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13603 Group = Group.slice(1); 13604 } 13605 } 13606 13607 // FIMXE: We assume every Decl in the group is in the same file. 13608 // This is false when preprocessor constructs the group from decls in 13609 // different files (e. g. macros or #include). 13610 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13611 } 13612 13613 /// Common checks for a parameter-declaration that should apply to both function 13614 /// parameters and non-type template parameters. 13615 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13616 // Check that there are no default arguments inside the type of this 13617 // parameter. 13618 if (getLangOpts().CPlusPlus) 13619 CheckExtraCXXDefaultArguments(D); 13620 13621 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13622 if (D.getCXXScopeSpec().isSet()) { 13623 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13624 << D.getCXXScopeSpec().getRange(); 13625 } 13626 13627 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13628 // simple identifier except [...irrelevant cases...]. 13629 switch (D.getName().getKind()) { 13630 case UnqualifiedIdKind::IK_Identifier: 13631 break; 13632 13633 case UnqualifiedIdKind::IK_OperatorFunctionId: 13634 case UnqualifiedIdKind::IK_ConversionFunctionId: 13635 case UnqualifiedIdKind::IK_LiteralOperatorId: 13636 case UnqualifiedIdKind::IK_ConstructorName: 13637 case UnqualifiedIdKind::IK_DestructorName: 13638 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13639 case UnqualifiedIdKind::IK_DeductionGuideName: 13640 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13641 << GetNameForDeclarator(D).getName(); 13642 break; 13643 13644 case UnqualifiedIdKind::IK_TemplateId: 13645 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13646 // GetNameForDeclarator would not produce a useful name in this case. 13647 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13648 break; 13649 } 13650 } 13651 13652 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13653 /// to introduce parameters into function prototype scope. 13654 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13655 const DeclSpec &DS = D.getDeclSpec(); 13656 13657 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13658 13659 // C++03 [dcl.stc]p2 also permits 'auto'. 13660 StorageClass SC = SC_None; 13661 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13662 SC = SC_Register; 13663 // In C++11, the 'register' storage class specifier is deprecated. 13664 // In C++17, it is not allowed, but we tolerate it as an extension. 13665 if (getLangOpts().CPlusPlus11) { 13666 Diag(DS.getStorageClassSpecLoc(), 13667 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13668 : diag::warn_deprecated_register) 13669 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13670 } 13671 } else if (getLangOpts().CPlusPlus && 13672 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13673 SC = SC_Auto; 13674 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13675 Diag(DS.getStorageClassSpecLoc(), 13676 diag::err_invalid_storage_class_in_func_decl); 13677 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13678 } 13679 13680 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13681 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13682 << DeclSpec::getSpecifierName(TSCS); 13683 if (DS.isInlineSpecified()) 13684 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13685 << getLangOpts().CPlusPlus17; 13686 if (DS.hasConstexprSpecifier()) 13687 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13688 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 13689 13690 DiagnoseFunctionSpecifiers(DS); 13691 13692 CheckFunctionOrTemplateParamDeclarator(S, D); 13693 13694 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13695 QualType parmDeclType = TInfo->getType(); 13696 13697 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13698 IdentifierInfo *II = D.getIdentifier(); 13699 if (II) { 13700 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13701 ForVisibleRedeclaration); 13702 LookupName(R, S); 13703 if (R.isSingleResult()) { 13704 NamedDecl *PrevDecl = R.getFoundDecl(); 13705 if (PrevDecl->isTemplateParameter()) { 13706 // Maybe we will complain about the shadowed template parameter. 13707 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13708 // Just pretend that we didn't see the previous declaration. 13709 PrevDecl = nullptr; 13710 } else if (S->isDeclScope(PrevDecl)) { 13711 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13712 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13713 13714 // Recover by removing the name 13715 II = nullptr; 13716 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13717 D.setInvalidType(true); 13718 } 13719 } 13720 } 13721 13722 // Temporarily put parameter variables in the translation unit, not 13723 // the enclosing context. This prevents them from accidentally 13724 // looking like class members in C++. 13725 ParmVarDecl *New = 13726 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13727 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13728 13729 if (D.isInvalidType()) 13730 New->setInvalidDecl(); 13731 13732 assert(S->isFunctionPrototypeScope()); 13733 assert(S->getFunctionPrototypeDepth() >= 1); 13734 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13735 S->getNextFunctionPrototypeIndex()); 13736 13737 // Add the parameter declaration into this scope. 13738 S->AddDecl(New); 13739 if (II) 13740 IdResolver.AddDecl(New); 13741 13742 ProcessDeclAttributes(S, New, D); 13743 13744 if (D.getDeclSpec().isModulePrivateSpecified()) 13745 Diag(New->getLocation(), diag::err_module_private_local) 13746 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13747 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13748 13749 if (New->hasAttr<BlocksAttr>()) { 13750 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13751 } 13752 13753 if (getLangOpts().OpenCL) 13754 deduceOpenCLAddressSpace(New); 13755 13756 return New; 13757 } 13758 13759 /// Synthesizes a variable for a parameter arising from a 13760 /// typedef. 13761 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13762 SourceLocation Loc, 13763 QualType T) { 13764 /* FIXME: setting StartLoc == Loc. 13765 Would it be worth to modify callers so as to provide proper source 13766 location for the unnamed parameters, embedding the parameter's type? */ 13767 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13768 T, Context.getTrivialTypeSourceInfo(T, Loc), 13769 SC_None, nullptr); 13770 Param->setImplicit(); 13771 return Param; 13772 } 13773 13774 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13775 // Don't diagnose unused-parameter errors in template instantiations; we 13776 // will already have done so in the template itself. 13777 if (inTemplateInstantiation()) 13778 return; 13779 13780 for (const ParmVarDecl *Parameter : Parameters) { 13781 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13782 !Parameter->hasAttr<UnusedAttr>()) { 13783 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13784 << Parameter->getDeclName(); 13785 } 13786 } 13787 } 13788 13789 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13790 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13791 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13792 return; 13793 13794 // Warn if the return value is pass-by-value and larger than the specified 13795 // threshold. 13796 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13797 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13798 if (Size > LangOpts.NumLargeByValueCopy) 13799 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 13800 } 13801 13802 // Warn if any parameter is pass-by-value and larger than the specified 13803 // threshold. 13804 for (const ParmVarDecl *Parameter : Parameters) { 13805 QualType T = Parameter->getType(); 13806 if (T->isDependentType() || !T.isPODType(Context)) 13807 continue; 13808 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13809 if (Size > LangOpts.NumLargeByValueCopy) 13810 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13811 << Parameter << Size; 13812 } 13813 } 13814 13815 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13816 SourceLocation NameLoc, IdentifierInfo *Name, 13817 QualType T, TypeSourceInfo *TSInfo, 13818 StorageClass SC) { 13819 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13820 if (getLangOpts().ObjCAutoRefCount && 13821 T.getObjCLifetime() == Qualifiers::OCL_None && 13822 T->isObjCLifetimeType()) { 13823 13824 Qualifiers::ObjCLifetime lifetime; 13825 13826 // Special cases for arrays: 13827 // - if it's const, use __unsafe_unretained 13828 // - otherwise, it's an error 13829 if (T->isArrayType()) { 13830 if (!T.isConstQualified()) { 13831 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13832 DelayedDiagnostics.add( 13833 sema::DelayedDiagnostic::makeForbiddenType( 13834 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13835 else 13836 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13837 << TSInfo->getTypeLoc().getSourceRange(); 13838 } 13839 lifetime = Qualifiers::OCL_ExplicitNone; 13840 } else { 13841 lifetime = T->getObjCARCImplicitLifetime(); 13842 } 13843 T = Context.getLifetimeQualifiedType(T, lifetime); 13844 } 13845 13846 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13847 Context.getAdjustedParameterType(T), 13848 TSInfo, SC, nullptr); 13849 13850 // Make a note if we created a new pack in the scope of a lambda, so that 13851 // we know that references to that pack must also be expanded within the 13852 // lambda scope. 13853 if (New->isParameterPack()) 13854 if (auto *LSI = getEnclosingLambda()) 13855 LSI->LocalPacks.push_back(New); 13856 13857 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13858 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13859 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13860 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13861 13862 // Parameters can not be abstract class types. 13863 // For record types, this is done by the AbstractClassUsageDiagnoser once 13864 // the class has been completely parsed. 13865 if (!CurContext->isRecord() && 13866 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13867 AbstractParamType)) 13868 New->setInvalidDecl(); 13869 13870 // Parameter declarators cannot be interface types. All ObjC objects are 13871 // passed by reference. 13872 if (T->isObjCObjectType()) { 13873 SourceLocation TypeEndLoc = 13874 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13875 Diag(NameLoc, 13876 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13877 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13878 T = Context.getObjCObjectPointerType(T); 13879 New->setType(T); 13880 } 13881 13882 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13883 // duration shall not be qualified by an address-space qualifier." 13884 // Since all parameters have automatic store duration, they can not have 13885 // an address space. 13886 if (T.getAddressSpace() != LangAS::Default && 13887 // OpenCL allows function arguments declared to be an array of a type 13888 // to be qualified with an address space. 13889 !(getLangOpts().OpenCL && 13890 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13891 Diag(NameLoc, diag::err_arg_with_address_space); 13892 New->setInvalidDecl(); 13893 } 13894 13895 // PPC MMA non-pointer types are not allowed as function argument types. 13896 if (Context.getTargetInfo().getTriple().isPPC64() && 13897 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 13898 New->setInvalidDecl(); 13899 } 13900 13901 return New; 13902 } 13903 13904 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13905 SourceLocation LocAfterDecls) { 13906 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13907 13908 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13909 // for a K&R function. 13910 if (!FTI.hasPrototype) { 13911 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13912 --i; 13913 if (FTI.Params[i].Param == nullptr) { 13914 SmallString<256> Code; 13915 llvm::raw_svector_ostream(Code) 13916 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13917 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13918 << FTI.Params[i].Ident 13919 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13920 13921 // Implicitly declare the argument as type 'int' for lack of a better 13922 // type. 13923 AttributeFactory attrs; 13924 DeclSpec DS(attrs); 13925 const char* PrevSpec; // unused 13926 unsigned DiagID; // unused 13927 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13928 DiagID, Context.getPrintingPolicy()); 13929 // Use the identifier location for the type source range. 13930 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13931 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13932 Declarator ParamD(DS, DeclaratorContext::KNRTypeList); 13933 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13934 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13935 } 13936 } 13937 } 13938 } 13939 13940 Decl * 13941 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13942 MultiTemplateParamsArg TemplateParameterLists, 13943 SkipBodyInfo *SkipBody) { 13944 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13945 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13946 Scope *ParentScope = FnBodyScope->getParent(); 13947 13948 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 13949 // we define a non-templated function definition, we will create a declaration 13950 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 13951 // The base function declaration will have the equivalent of an `omp declare 13952 // variant` annotation which specifies the mangled definition as a 13953 // specialization function under the OpenMP context defined as part of the 13954 // `omp begin declare variant`. 13955 SmallVector<FunctionDecl *, 4> Bases; 13956 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 13957 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 13958 ParentScope, D, TemplateParameterLists, Bases); 13959 13960 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 13961 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13962 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13963 13964 if (!Bases.empty()) 13965 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 13966 13967 return Dcl; 13968 } 13969 13970 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13971 Consumer.HandleInlineFunctionDefinition(D); 13972 } 13973 13974 static bool 13975 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13976 const FunctionDecl *&PossiblePrototype) { 13977 // Don't warn about invalid declarations. 13978 if (FD->isInvalidDecl()) 13979 return false; 13980 13981 // Or declarations that aren't global. 13982 if (!FD->isGlobal()) 13983 return false; 13984 13985 // Don't warn about C++ member functions. 13986 if (isa<CXXMethodDecl>(FD)) 13987 return false; 13988 13989 // Don't warn about 'main'. 13990 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13991 if (IdentifierInfo *II = FD->getIdentifier()) 13992 if (II->isStr("main") || II->isStr("efi_main")) 13993 return false; 13994 13995 // Don't warn about inline functions. 13996 if (FD->isInlined()) 13997 return false; 13998 13999 // Don't warn about function templates. 14000 if (FD->getDescribedFunctionTemplate()) 14001 return false; 14002 14003 // Don't warn about function template specializations. 14004 if (FD->isFunctionTemplateSpecialization()) 14005 return false; 14006 14007 // Don't warn for OpenCL kernels. 14008 if (FD->hasAttr<OpenCLKernelAttr>()) 14009 return false; 14010 14011 // Don't warn on explicitly deleted functions. 14012 if (FD->isDeleted()) 14013 return false; 14014 14015 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 14016 Prev; Prev = Prev->getPreviousDecl()) { 14017 // Ignore any declarations that occur in function or method 14018 // scope, because they aren't visible from the header. 14019 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 14020 continue; 14021 14022 PossiblePrototype = Prev; 14023 return Prev->getType()->isFunctionNoProtoType(); 14024 } 14025 14026 return true; 14027 } 14028 14029 void 14030 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 14031 const FunctionDecl *EffectiveDefinition, 14032 SkipBodyInfo *SkipBody) { 14033 const FunctionDecl *Definition = EffectiveDefinition; 14034 if (!Definition && 14035 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 14036 return; 14037 14038 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 14039 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 14040 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 14041 // A merged copy of the same function, instantiated as a member of 14042 // the same class, is OK. 14043 if (declaresSameEntity(OrigFD, OrigDef) && 14044 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 14045 cast<Decl>(FD->getLexicalDeclContext()))) 14046 return; 14047 } 14048 } 14049 } 14050 14051 if (canRedefineFunction(Definition, getLangOpts())) 14052 return; 14053 14054 // Don't emit an error when this is redefinition of a typo-corrected 14055 // definition. 14056 if (TypoCorrectedFunctionDefinitions.count(Definition)) 14057 return; 14058 14059 // If we don't have a visible definition of the function, and it's inline or 14060 // a template, skip the new definition. 14061 if (SkipBody && !hasVisibleDefinition(Definition) && 14062 (Definition->getFormalLinkage() == InternalLinkage || 14063 Definition->isInlined() || 14064 Definition->getDescribedFunctionTemplate() || 14065 Definition->getNumTemplateParameterLists())) { 14066 SkipBody->ShouldSkip = true; 14067 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 14068 if (auto *TD = Definition->getDescribedFunctionTemplate()) 14069 makeMergedDefinitionVisible(TD); 14070 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 14071 return; 14072 } 14073 14074 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 14075 Definition->getStorageClass() == SC_Extern) 14076 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 14077 << FD << getLangOpts().CPlusPlus; 14078 else 14079 Diag(FD->getLocation(), diag::err_redefinition) << FD; 14080 14081 Diag(Definition->getLocation(), diag::note_previous_definition); 14082 FD->setInvalidDecl(); 14083 } 14084 14085 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 14086 Sema &S) { 14087 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 14088 14089 LambdaScopeInfo *LSI = S.PushLambdaScope(); 14090 LSI->CallOperator = CallOperator; 14091 LSI->Lambda = LambdaClass; 14092 LSI->ReturnType = CallOperator->getReturnType(); 14093 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 14094 14095 if (LCD == LCD_None) 14096 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 14097 else if (LCD == LCD_ByCopy) 14098 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 14099 else if (LCD == LCD_ByRef) 14100 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 14101 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 14102 14103 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 14104 LSI->Mutable = !CallOperator->isConst(); 14105 14106 // Add the captures to the LSI so they can be noted as already 14107 // captured within tryCaptureVar. 14108 auto I = LambdaClass->field_begin(); 14109 for (const auto &C : LambdaClass->captures()) { 14110 if (C.capturesVariable()) { 14111 VarDecl *VD = C.getCapturedVar(); 14112 if (VD->isInitCapture()) 14113 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 14114 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 14115 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 14116 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 14117 /*EllipsisLoc*/C.isPackExpansion() 14118 ? C.getEllipsisLoc() : SourceLocation(), 14119 I->getType(), /*Invalid*/false); 14120 14121 } else if (C.capturesThis()) { 14122 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 14123 C.getCaptureKind() == LCK_StarThis); 14124 } else { 14125 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14126 I->getType()); 14127 } 14128 ++I; 14129 } 14130 } 14131 14132 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14133 SkipBodyInfo *SkipBody) { 14134 if (!D) { 14135 // Parsing the function declaration failed in some way. Push on a fake scope 14136 // anyway so we can try to parse the function body. 14137 PushFunctionScope(); 14138 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14139 return D; 14140 } 14141 14142 FunctionDecl *FD = nullptr; 14143 14144 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14145 FD = FunTmpl->getTemplatedDecl(); 14146 else 14147 FD = cast<FunctionDecl>(D); 14148 14149 // Do not push if it is a lambda because one is already pushed when building 14150 // the lambda in ActOnStartOfLambdaDefinition(). 14151 if (!isLambdaCallOperator(FD)) 14152 PushExpressionEvaluationContext( 14153 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14154 : ExprEvalContexts.back().Context); 14155 14156 // Check for defining attributes before the check for redefinition. 14157 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14158 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14159 FD->dropAttr<AliasAttr>(); 14160 FD->setInvalidDecl(); 14161 } 14162 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14163 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14164 FD->dropAttr<IFuncAttr>(); 14165 FD->setInvalidDecl(); 14166 } 14167 14168 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14169 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14170 Ctor->isDefaultConstructor() && 14171 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14172 // If this is an MS ABI dllexport default constructor, instantiate any 14173 // default arguments. 14174 InstantiateDefaultCtorDefaultArgs(Ctor); 14175 } 14176 } 14177 14178 // See if this is a redefinition. If 'will have body' (or similar) is already 14179 // set, then these checks were already performed when it was set. 14180 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14181 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14182 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14183 14184 // If we're skipping the body, we're done. Don't enter the scope. 14185 if (SkipBody && SkipBody->ShouldSkip) 14186 return D; 14187 } 14188 14189 // Mark this function as "will have a body eventually". This lets users to 14190 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14191 // this function. 14192 FD->setWillHaveBody(); 14193 14194 // If we are instantiating a generic lambda call operator, push 14195 // a LambdaScopeInfo onto the function stack. But use the information 14196 // that's already been calculated (ActOnLambdaExpr) to prime the current 14197 // LambdaScopeInfo. 14198 // When the template operator is being specialized, the LambdaScopeInfo, 14199 // has to be properly restored so that tryCaptureVariable doesn't try 14200 // and capture any new variables. In addition when calculating potential 14201 // captures during transformation of nested lambdas, it is necessary to 14202 // have the LSI properly restored. 14203 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14204 assert(inTemplateInstantiation() && 14205 "There should be an active template instantiation on the stack " 14206 "when instantiating a generic lambda!"); 14207 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14208 } else { 14209 // Enter a new function scope 14210 PushFunctionScope(); 14211 } 14212 14213 // Builtin functions cannot be defined. 14214 if (unsigned BuiltinID = FD->getBuiltinID()) { 14215 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14216 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14217 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14218 FD->setInvalidDecl(); 14219 } 14220 } 14221 14222 // The return type of a function definition must be complete 14223 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14224 QualType ResultType = FD->getReturnType(); 14225 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14226 !FD->isInvalidDecl() && 14227 RequireCompleteType(FD->getLocation(), ResultType, 14228 diag::err_func_def_incomplete_result)) 14229 FD->setInvalidDecl(); 14230 14231 if (FnBodyScope) 14232 PushDeclContext(FnBodyScope, FD); 14233 14234 // Check the validity of our function parameters 14235 CheckParmsForFunctionDef(FD->parameters(), 14236 /*CheckParameterNames=*/true); 14237 14238 // Add non-parameter declarations already in the function to the current 14239 // scope. 14240 if (FnBodyScope) { 14241 for (Decl *NPD : FD->decls()) { 14242 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14243 if (!NonParmDecl) 14244 continue; 14245 assert(!isa<ParmVarDecl>(NonParmDecl) && 14246 "parameters should not be in newly created FD yet"); 14247 14248 // If the decl has a name, make it accessible in the current scope. 14249 if (NonParmDecl->getDeclName()) 14250 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14251 14252 // Similarly, dive into enums and fish their constants out, making them 14253 // accessible in this scope. 14254 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14255 for (auto *EI : ED->enumerators()) 14256 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14257 } 14258 } 14259 } 14260 14261 // Introduce our parameters into the function scope 14262 for (auto Param : FD->parameters()) { 14263 Param->setOwningFunction(FD); 14264 14265 // If this has an identifier, add it to the scope stack. 14266 if (Param->getIdentifier() && FnBodyScope) { 14267 CheckShadow(FnBodyScope, Param); 14268 14269 PushOnScopeChains(Param, FnBodyScope); 14270 } 14271 } 14272 14273 // Ensure that the function's exception specification is instantiated. 14274 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14275 ResolveExceptionSpec(D->getLocation(), FPT); 14276 14277 // dllimport cannot be applied to non-inline function definitions. 14278 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14279 !FD->isTemplateInstantiation()) { 14280 assert(!FD->hasAttr<DLLExportAttr>()); 14281 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14282 FD->setInvalidDecl(); 14283 return D; 14284 } 14285 // We want to attach documentation to original Decl (which might be 14286 // a function template). 14287 ActOnDocumentableDecl(D); 14288 if (getCurLexicalContext()->isObjCContainer() && 14289 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14290 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14291 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14292 14293 return D; 14294 } 14295 14296 /// Given the set of return statements within a function body, 14297 /// compute the variables that are subject to the named return value 14298 /// optimization. 14299 /// 14300 /// Each of the variables that is subject to the named return value 14301 /// optimization will be marked as NRVO variables in the AST, and any 14302 /// return statement that has a marked NRVO variable as its NRVO candidate can 14303 /// use the named return value optimization. 14304 /// 14305 /// This function applies a very simplistic algorithm for NRVO: if every return 14306 /// statement in the scope of a variable has the same NRVO candidate, that 14307 /// candidate is an NRVO variable. 14308 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14309 ReturnStmt **Returns = Scope->Returns.data(); 14310 14311 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14312 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14313 if (!NRVOCandidate->isNRVOVariable()) 14314 Returns[I]->setNRVOCandidate(nullptr); 14315 } 14316 } 14317 } 14318 14319 bool Sema::canDelayFunctionBody(const Declarator &D) { 14320 // We can't delay parsing the body of a constexpr function template (yet). 14321 if (D.getDeclSpec().hasConstexprSpecifier()) 14322 return false; 14323 14324 // We can't delay parsing the body of a function template with a deduced 14325 // return type (yet). 14326 if (D.getDeclSpec().hasAutoTypeSpec()) { 14327 // If the placeholder introduces a non-deduced trailing return type, 14328 // we can still delay parsing it. 14329 if (D.getNumTypeObjects()) { 14330 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14331 if (Outer.Kind == DeclaratorChunk::Function && 14332 Outer.Fun.hasTrailingReturnType()) { 14333 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14334 return Ty.isNull() || !Ty->isUndeducedType(); 14335 } 14336 } 14337 return false; 14338 } 14339 14340 return true; 14341 } 14342 14343 bool Sema::canSkipFunctionBody(Decl *D) { 14344 // We cannot skip the body of a function (or function template) which is 14345 // constexpr, since we may need to evaluate its body in order to parse the 14346 // rest of the file. 14347 // We cannot skip the body of a function with an undeduced return type, 14348 // because any callers of that function need to know the type. 14349 if (const FunctionDecl *FD = D->getAsFunction()) { 14350 if (FD->isConstexpr()) 14351 return false; 14352 // We can't simply call Type::isUndeducedType here, because inside template 14353 // auto can be deduced to a dependent type, which is not considered 14354 // "undeduced". 14355 if (FD->getReturnType()->getContainedDeducedType()) 14356 return false; 14357 } 14358 return Consumer.shouldSkipFunctionBody(D); 14359 } 14360 14361 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14362 if (!Decl) 14363 return nullptr; 14364 if (FunctionDecl *FD = Decl->getAsFunction()) 14365 FD->setHasSkippedBody(); 14366 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14367 MD->setHasSkippedBody(); 14368 return Decl; 14369 } 14370 14371 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14372 return ActOnFinishFunctionBody(D, BodyArg, false); 14373 } 14374 14375 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14376 /// body. 14377 class ExitFunctionBodyRAII { 14378 public: 14379 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14380 ~ExitFunctionBodyRAII() { 14381 if (!IsLambda) 14382 S.PopExpressionEvaluationContext(); 14383 } 14384 14385 private: 14386 Sema &S; 14387 bool IsLambda = false; 14388 }; 14389 14390 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14391 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14392 14393 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14394 if (EscapeInfo.count(BD)) 14395 return EscapeInfo[BD]; 14396 14397 bool R = false; 14398 const BlockDecl *CurBD = BD; 14399 14400 do { 14401 R = !CurBD->doesNotEscape(); 14402 if (R) 14403 break; 14404 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14405 } while (CurBD); 14406 14407 return EscapeInfo[BD] = R; 14408 }; 14409 14410 // If the location where 'self' is implicitly retained is inside a escaping 14411 // block, emit a diagnostic. 14412 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14413 S.ImplicitlyRetainedSelfLocs) 14414 if (IsOrNestedInEscapingBlock(P.second)) 14415 S.Diag(P.first, diag::warn_implicitly_retains_self) 14416 << FixItHint::CreateInsertion(P.first, "self->"); 14417 } 14418 14419 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14420 bool IsInstantiation) { 14421 FunctionScopeInfo *FSI = getCurFunction(); 14422 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14423 14424 if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>()) 14425 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14426 14427 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14428 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14429 14430 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14431 CheckCompletedCoroutineBody(FD, Body); 14432 14433 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14434 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14435 // meant to pop the context added in ActOnStartOfFunctionDef(). 14436 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14437 14438 if (FD) { 14439 FD->setBody(Body); 14440 FD->setWillHaveBody(false); 14441 14442 if (getLangOpts().CPlusPlus14) { 14443 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14444 FD->getReturnType()->isUndeducedType()) { 14445 // If the function has a deduced result type but contains no 'return' 14446 // statements, the result type as written must be exactly 'auto', and 14447 // the deduced result type is 'void'. 14448 if (!FD->getReturnType()->getAs<AutoType>()) { 14449 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14450 << FD->getReturnType(); 14451 FD->setInvalidDecl(); 14452 } else { 14453 // Substitute 'void' for the 'auto' in the type. 14454 TypeLoc ResultType = getReturnTypeLoc(FD); 14455 Context.adjustDeducedFunctionResultType( 14456 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14457 } 14458 } 14459 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14460 // In C++11, we don't use 'auto' deduction rules for lambda call 14461 // operators because we don't support return type deduction. 14462 auto *LSI = getCurLambda(); 14463 if (LSI->HasImplicitReturnType) { 14464 deduceClosureReturnType(*LSI); 14465 14466 // C++11 [expr.prim.lambda]p4: 14467 // [...] if there are no return statements in the compound-statement 14468 // [the deduced type is] the type void 14469 QualType RetType = 14470 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14471 14472 // Update the return type to the deduced type. 14473 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14474 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14475 Proto->getExtProtoInfo())); 14476 } 14477 } 14478 14479 // If the function implicitly returns zero (like 'main') or is naked, 14480 // don't complain about missing return statements. 14481 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14482 WP.disableCheckFallThrough(); 14483 14484 // MSVC permits the use of pure specifier (=0) on function definition, 14485 // defined at class scope, warn about this non-standard construct. 14486 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14487 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14488 14489 if (!FD->isInvalidDecl()) { 14490 // Don't diagnose unused parameters of defaulted or deleted functions. 14491 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14492 DiagnoseUnusedParameters(FD->parameters()); 14493 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14494 FD->getReturnType(), FD); 14495 14496 // If this is a structor, we need a vtable. 14497 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14498 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14499 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14500 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14501 14502 // Try to apply the named return value optimization. We have to check 14503 // if we can do this here because lambdas keep return statements around 14504 // to deduce an implicit return type. 14505 if (FD->getReturnType()->isRecordType() && 14506 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14507 computeNRVO(Body, FSI); 14508 } 14509 14510 // GNU warning -Wmissing-prototypes: 14511 // Warn if a global function is defined without a previous 14512 // prototype declaration. This warning is issued even if the 14513 // definition itself provides a prototype. The aim is to detect 14514 // global functions that fail to be declared in header files. 14515 const FunctionDecl *PossiblePrototype = nullptr; 14516 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14517 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14518 14519 if (PossiblePrototype) { 14520 // We found a declaration that is not a prototype, 14521 // but that could be a zero-parameter prototype 14522 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14523 TypeLoc TL = TI->getTypeLoc(); 14524 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14525 Diag(PossiblePrototype->getLocation(), 14526 diag::note_declaration_not_a_prototype) 14527 << (FD->getNumParams() != 0) 14528 << (FD->getNumParams() == 0 14529 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14530 : FixItHint{}); 14531 } 14532 } else { 14533 // Returns true if the token beginning at this Loc is `const`. 14534 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14535 const LangOptions &LangOpts) { 14536 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14537 if (LocInfo.first.isInvalid()) 14538 return false; 14539 14540 bool Invalid = false; 14541 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14542 if (Invalid) 14543 return false; 14544 14545 if (LocInfo.second > Buffer.size()) 14546 return false; 14547 14548 const char *LexStart = Buffer.data() + LocInfo.second; 14549 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14550 14551 return StartTok.consume_front("const") && 14552 (StartTok.empty() || isWhitespace(StartTok[0]) || 14553 StartTok.startswith("/*") || StartTok.startswith("//")); 14554 }; 14555 14556 auto findBeginLoc = [&]() { 14557 // If the return type has `const` qualifier, we want to insert 14558 // `static` before `const` (and not before the typename). 14559 if ((FD->getReturnType()->isAnyPointerType() && 14560 FD->getReturnType()->getPointeeType().isConstQualified()) || 14561 FD->getReturnType().isConstQualified()) { 14562 // But only do this if we can determine where the `const` is. 14563 14564 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14565 getLangOpts())) 14566 14567 return FD->getBeginLoc(); 14568 } 14569 return FD->getTypeSpecStartLoc(); 14570 }; 14571 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14572 << /* function */ 1 14573 << (FD->getStorageClass() == SC_None 14574 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14575 : FixItHint{}); 14576 } 14577 14578 // GNU warning -Wstrict-prototypes 14579 // Warn if K&R function is defined without a previous declaration. 14580 // This warning is issued only if the definition itself does not provide 14581 // a prototype. Only K&R definitions do not provide a prototype. 14582 if (!FD->hasWrittenPrototype()) { 14583 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14584 TypeLoc TL = TI->getTypeLoc(); 14585 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14586 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14587 } 14588 } 14589 14590 // Warn on CPUDispatch with an actual body. 14591 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14592 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14593 if (!CmpndBody->body_empty()) 14594 Diag(CmpndBody->body_front()->getBeginLoc(), 14595 diag::warn_dispatch_body_ignored); 14596 14597 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14598 const CXXMethodDecl *KeyFunction; 14599 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14600 MD->isVirtual() && 14601 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14602 MD == KeyFunction->getCanonicalDecl()) { 14603 // Update the key-function state if necessary for this ABI. 14604 if (FD->isInlined() && 14605 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14606 Context.setNonKeyFunction(MD); 14607 14608 // If the newly-chosen key function is already defined, then we 14609 // need to mark the vtable as used retroactively. 14610 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14611 const FunctionDecl *Definition; 14612 if (KeyFunction && KeyFunction->isDefined(Definition)) 14613 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14614 } else { 14615 // We just defined they key function; mark the vtable as used. 14616 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14617 } 14618 } 14619 } 14620 14621 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14622 "Function parsing confused"); 14623 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14624 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14625 MD->setBody(Body); 14626 if (!MD->isInvalidDecl()) { 14627 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14628 MD->getReturnType(), MD); 14629 14630 if (Body) 14631 computeNRVO(Body, FSI); 14632 } 14633 if (FSI->ObjCShouldCallSuper) { 14634 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14635 << MD->getSelector().getAsString(); 14636 FSI->ObjCShouldCallSuper = false; 14637 } 14638 if (FSI->ObjCWarnForNoDesignatedInitChain) { 14639 const ObjCMethodDecl *InitMethod = nullptr; 14640 bool isDesignated = 14641 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14642 assert(isDesignated && InitMethod); 14643 (void)isDesignated; 14644 14645 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14646 auto IFace = MD->getClassInterface(); 14647 if (!IFace) 14648 return false; 14649 auto SuperD = IFace->getSuperClass(); 14650 if (!SuperD) 14651 return false; 14652 return SuperD->getIdentifier() == 14653 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14654 }; 14655 // Don't issue this warning for unavailable inits or direct subclasses 14656 // of NSObject. 14657 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14658 Diag(MD->getLocation(), 14659 diag::warn_objc_designated_init_missing_super_call); 14660 Diag(InitMethod->getLocation(), 14661 diag::note_objc_designated_init_marked_here); 14662 } 14663 FSI->ObjCWarnForNoDesignatedInitChain = false; 14664 } 14665 if (FSI->ObjCWarnForNoInitDelegation) { 14666 // Don't issue this warning for unavaialable inits. 14667 if (!MD->isUnavailable()) 14668 Diag(MD->getLocation(), 14669 diag::warn_objc_secondary_init_missing_init_call); 14670 FSI->ObjCWarnForNoInitDelegation = false; 14671 } 14672 14673 diagnoseImplicitlyRetainedSelf(*this); 14674 } else { 14675 // Parsing the function declaration failed in some way. Pop the fake scope 14676 // we pushed on. 14677 PopFunctionScopeInfo(ActivePolicy, dcl); 14678 return nullptr; 14679 } 14680 14681 if (Body && FSI->HasPotentialAvailabilityViolations) 14682 DiagnoseUnguardedAvailabilityViolations(dcl); 14683 14684 assert(!FSI->ObjCShouldCallSuper && 14685 "This should only be set for ObjC methods, which should have been " 14686 "handled in the block above."); 14687 14688 // Verify and clean out per-function state. 14689 if (Body && (!FD || !FD->isDefaulted())) { 14690 // C++ constructors that have function-try-blocks can't have return 14691 // statements in the handlers of that block. (C++ [except.handle]p14) 14692 // Verify this. 14693 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14694 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14695 14696 // Verify that gotos and switch cases don't jump into scopes illegally. 14697 if (FSI->NeedsScopeChecking() && 14698 !PP.isCodeCompletionEnabled()) 14699 DiagnoseInvalidJumps(Body); 14700 14701 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14702 if (!Destructor->getParent()->isDependentType()) 14703 CheckDestructor(Destructor); 14704 14705 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14706 Destructor->getParent()); 14707 } 14708 14709 // If any errors have occurred, clear out any temporaries that may have 14710 // been leftover. This ensures that these temporaries won't be picked up for 14711 // deletion in some later function. 14712 if (hasUncompilableErrorOccurred() || 14713 getDiagnostics().getSuppressAllDiagnostics()) { 14714 DiscardCleanupsInEvaluationContext(); 14715 } 14716 if (!hasUncompilableErrorOccurred() && 14717 !isa<FunctionTemplateDecl>(dcl)) { 14718 // Since the body is valid, issue any analysis-based warnings that are 14719 // enabled. 14720 ActivePolicy = &WP; 14721 } 14722 14723 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14724 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14725 FD->setInvalidDecl(); 14726 14727 if (FD && FD->hasAttr<NakedAttr>()) { 14728 for (const Stmt *S : Body->children()) { 14729 // Allow local register variables without initializer as they don't 14730 // require prologue. 14731 bool RegisterVariables = false; 14732 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14733 for (const auto *Decl : DS->decls()) { 14734 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14735 RegisterVariables = 14736 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14737 if (!RegisterVariables) 14738 break; 14739 } 14740 } 14741 } 14742 if (RegisterVariables) 14743 continue; 14744 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14745 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14746 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14747 FD->setInvalidDecl(); 14748 break; 14749 } 14750 } 14751 } 14752 14753 assert(ExprCleanupObjects.size() == 14754 ExprEvalContexts.back().NumCleanupObjects && 14755 "Leftover temporaries in function"); 14756 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14757 assert(MaybeODRUseExprs.empty() && 14758 "Leftover expressions for odr-use checking"); 14759 } 14760 14761 if (!IsInstantiation) 14762 PopDeclContext(); 14763 14764 PopFunctionScopeInfo(ActivePolicy, dcl); 14765 // If any errors have occurred, clear out any temporaries that may have 14766 // been leftover. This ensures that these temporaries won't be picked up for 14767 // deletion in some later function. 14768 if (hasUncompilableErrorOccurred()) { 14769 DiscardCleanupsInEvaluationContext(); 14770 } 14771 14772 if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 14773 auto ES = getEmissionStatus(FD); 14774 if (ES == Sema::FunctionEmissionStatus::Emitted || 14775 ES == Sema::FunctionEmissionStatus::Unknown) 14776 DeclsToCheckForDeferredDiags.insert(FD); 14777 } 14778 14779 return dcl; 14780 } 14781 14782 /// When we finish delayed parsing of an attribute, we must attach it to the 14783 /// relevant Decl. 14784 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14785 ParsedAttributes &Attrs) { 14786 // Always attach attributes to the underlying decl. 14787 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14788 D = TD->getTemplatedDecl(); 14789 ProcessDeclAttributeList(S, D, Attrs); 14790 14791 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14792 if (Method->isStatic()) 14793 checkThisInStaticMemberFunctionAttributes(Method); 14794 } 14795 14796 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14797 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14798 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14799 IdentifierInfo &II, Scope *S) { 14800 // Find the scope in which the identifier is injected and the corresponding 14801 // DeclContext. 14802 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14803 // In that case, we inject the declaration into the translation unit scope 14804 // instead. 14805 Scope *BlockScope = S; 14806 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14807 BlockScope = BlockScope->getParent(); 14808 14809 Scope *ContextScope = BlockScope; 14810 while (!ContextScope->getEntity()) 14811 ContextScope = ContextScope->getParent(); 14812 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14813 14814 // Before we produce a declaration for an implicitly defined 14815 // function, see whether there was a locally-scoped declaration of 14816 // this name as a function or variable. If so, use that 14817 // (non-visible) declaration, and complain about it. 14818 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14819 if (ExternCPrev) { 14820 // We still need to inject the function into the enclosing block scope so 14821 // that later (non-call) uses can see it. 14822 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14823 14824 // C89 footnote 38: 14825 // If in fact it is not defined as having type "function returning int", 14826 // the behavior is undefined. 14827 if (!isa<FunctionDecl>(ExternCPrev) || 14828 !Context.typesAreCompatible( 14829 cast<FunctionDecl>(ExternCPrev)->getType(), 14830 Context.getFunctionNoProtoType(Context.IntTy))) { 14831 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14832 << ExternCPrev << !getLangOpts().C99; 14833 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14834 return ExternCPrev; 14835 } 14836 } 14837 14838 // Extension in C99. Legal in C90, but warn about it. 14839 unsigned diag_id; 14840 if (II.getName().startswith("__builtin_")) 14841 diag_id = diag::warn_builtin_unknown; 14842 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14843 else if (getLangOpts().OpenCL) 14844 diag_id = diag::err_opencl_implicit_function_decl; 14845 else if (getLangOpts().C99) 14846 diag_id = diag::ext_implicit_function_decl; 14847 else 14848 diag_id = diag::warn_implicit_function_decl; 14849 Diag(Loc, diag_id) << &II; 14850 14851 // If we found a prior declaration of this function, don't bother building 14852 // another one. We've already pushed that one into scope, so there's nothing 14853 // more to do. 14854 if (ExternCPrev) 14855 return ExternCPrev; 14856 14857 // Because typo correction is expensive, only do it if the implicit 14858 // function declaration is going to be treated as an error. 14859 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14860 TypoCorrection Corrected; 14861 DeclFilterCCC<FunctionDecl> CCC{}; 14862 if (S && (Corrected = 14863 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14864 S, nullptr, CCC, CTK_NonError))) 14865 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14866 /*ErrorRecovery*/false); 14867 } 14868 14869 // Set a Declarator for the implicit definition: int foo(); 14870 const char *Dummy; 14871 AttributeFactory attrFactory; 14872 DeclSpec DS(attrFactory); 14873 unsigned DiagID; 14874 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14875 Context.getPrintingPolicy()); 14876 (void)Error; // Silence warning. 14877 assert(!Error && "Error setting up implicit decl!"); 14878 SourceLocation NoLoc; 14879 Declarator D(DS, DeclaratorContext::Block); 14880 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14881 /*IsAmbiguous=*/false, 14882 /*LParenLoc=*/NoLoc, 14883 /*Params=*/nullptr, 14884 /*NumParams=*/0, 14885 /*EllipsisLoc=*/NoLoc, 14886 /*RParenLoc=*/NoLoc, 14887 /*RefQualifierIsLvalueRef=*/true, 14888 /*RefQualifierLoc=*/NoLoc, 14889 /*MutableLoc=*/NoLoc, EST_None, 14890 /*ESpecRange=*/SourceRange(), 14891 /*Exceptions=*/nullptr, 14892 /*ExceptionRanges=*/nullptr, 14893 /*NumExceptions=*/0, 14894 /*NoexceptExpr=*/nullptr, 14895 /*ExceptionSpecTokens=*/nullptr, 14896 /*DeclsInPrototype=*/None, Loc, 14897 Loc, D), 14898 std::move(DS.getAttributes()), SourceLocation()); 14899 D.SetIdentifier(&II, Loc); 14900 14901 // Insert this function into the enclosing block scope. 14902 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14903 FD->setImplicit(); 14904 14905 AddKnownFunctionAttributes(FD); 14906 14907 return FD; 14908 } 14909 14910 /// If this function is a C++ replaceable global allocation function 14911 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14912 /// adds any function attributes that we know a priori based on the standard. 14913 /// 14914 /// We need to check for duplicate attributes both here and where user-written 14915 /// attributes are applied to declarations. 14916 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14917 FunctionDecl *FD) { 14918 if (FD->isInvalidDecl()) 14919 return; 14920 14921 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14922 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14923 return; 14924 14925 Optional<unsigned> AlignmentParam; 14926 bool IsNothrow = false; 14927 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14928 return; 14929 14930 // C++2a [basic.stc.dynamic.allocation]p4: 14931 // An allocation function that has a non-throwing exception specification 14932 // indicates failure by returning a null pointer value. Any other allocation 14933 // function never returns a null pointer value and indicates failure only by 14934 // throwing an exception [...] 14935 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14936 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14937 14938 // C++2a [basic.stc.dynamic.allocation]p2: 14939 // An allocation function attempts to allocate the requested amount of 14940 // storage. [...] If the request succeeds, the value returned by a 14941 // replaceable allocation function is a [...] pointer value p0 different 14942 // from any previously returned value p1 [...] 14943 // 14944 // However, this particular information is being added in codegen, 14945 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14946 14947 // C++2a [basic.stc.dynamic.allocation]p2: 14948 // An allocation function attempts to allocate the requested amount of 14949 // storage. If it is successful, it returns the address of the start of a 14950 // block of storage whose length in bytes is at least as large as the 14951 // requested size. 14952 if (!FD->hasAttr<AllocSizeAttr>()) { 14953 FD->addAttr(AllocSizeAttr::CreateImplicit( 14954 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14955 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14956 } 14957 14958 // C++2a [basic.stc.dynamic.allocation]p3: 14959 // For an allocation function [...], the pointer returned on a successful 14960 // call shall represent the address of storage that is aligned as follows: 14961 // (3.1) If the allocation function takes an argument of type 14962 // std::align_val_t, the storage will have the alignment 14963 // specified by the value of this argument. 14964 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14965 FD->addAttr(AllocAlignAttr::CreateImplicit( 14966 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14967 } 14968 14969 // FIXME: 14970 // C++2a [basic.stc.dynamic.allocation]p3: 14971 // For an allocation function [...], the pointer returned on a successful 14972 // call shall represent the address of storage that is aligned as follows: 14973 // (3.2) Otherwise, if the allocation function is named operator new[], 14974 // the storage is aligned for any object that does not have 14975 // new-extended alignment ([basic.align]) and is no larger than the 14976 // requested size. 14977 // (3.3) Otherwise, the storage is aligned for any object that does not 14978 // have new-extended alignment and is of the requested size. 14979 } 14980 14981 /// Adds any function attributes that we know a priori based on 14982 /// the declaration of this function. 14983 /// 14984 /// These attributes can apply both to implicitly-declared builtins 14985 /// (like __builtin___printf_chk) or to library-declared functions 14986 /// like NSLog or printf. 14987 /// 14988 /// We need to check for duplicate attributes both here and where user-written 14989 /// attributes are applied to declarations. 14990 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14991 if (FD->isInvalidDecl()) 14992 return; 14993 14994 // If this is a built-in function, map its builtin attributes to 14995 // actual attributes. 14996 if (unsigned BuiltinID = FD->getBuiltinID()) { 14997 // Handle printf-formatting attributes. 14998 unsigned FormatIdx; 14999 bool HasVAListArg; 15000 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 15001 if (!FD->hasAttr<FormatAttr>()) { 15002 const char *fmt = "printf"; 15003 unsigned int NumParams = FD->getNumParams(); 15004 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 15005 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 15006 fmt = "NSString"; 15007 FD->addAttr(FormatAttr::CreateImplicit(Context, 15008 &Context.Idents.get(fmt), 15009 FormatIdx+1, 15010 HasVAListArg ? 0 : FormatIdx+2, 15011 FD->getLocation())); 15012 } 15013 } 15014 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 15015 HasVAListArg)) { 15016 if (!FD->hasAttr<FormatAttr>()) 15017 FD->addAttr(FormatAttr::CreateImplicit(Context, 15018 &Context.Idents.get("scanf"), 15019 FormatIdx+1, 15020 HasVAListArg ? 0 : FormatIdx+2, 15021 FD->getLocation())); 15022 } 15023 15024 // Handle automatically recognized callbacks. 15025 SmallVector<int, 4> Encoding; 15026 if (!FD->hasAttr<CallbackAttr>() && 15027 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 15028 FD->addAttr(CallbackAttr::CreateImplicit( 15029 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 15030 15031 // Mark const if we don't care about errno and that is the only thing 15032 // preventing the function from being const. This allows IRgen to use LLVM 15033 // intrinsics for such functions. 15034 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 15035 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 15036 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15037 15038 // We make "fma" on some platforms const because we know it does not set 15039 // errno in those environments even though it could set errno based on the 15040 // C standard. 15041 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 15042 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 15043 !FD->hasAttr<ConstAttr>()) { 15044 switch (BuiltinID) { 15045 case Builtin::BI__builtin_fma: 15046 case Builtin::BI__builtin_fmaf: 15047 case Builtin::BI__builtin_fmal: 15048 case Builtin::BIfma: 15049 case Builtin::BIfmaf: 15050 case Builtin::BIfmal: 15051 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15052 break; 15053 default: 15054 break; 15055 } 15056 } 15057 15058 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 15059 !FD->hasAttr<ReturnsTwiceAttr>()) 15060 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 15061 FD->getLocation())); 15062 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 15063 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15064 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 15065 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 15066 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 15067 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15068 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 15069 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 15070 // Add the appropriate attribute, depending on the CUDA compilation mode 15071 // and which target the builtin belongs to. For example, during host 15072 // compilation, aux builtins are __device__, while the rest are __host__. 15073 if (getLangOpts().CUDAIsDevice != 15074 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 15075 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 15076 else 15077 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 15078 } 15079 } 15080 15081 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 15082 15083 // If C++ exceptions are enabled but we are told extern "C" functions cannot 15084 // throw, add an implicit nothrow attribute to any extern "C" function we come 15085 // across. 15086 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 15087 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 15088 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 15089 if (!FPT || FPT->getExceptionSpecType() == EST_None) 15090 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15091 } 15092 15093 IdentifierInfo *Name = FD->getIdentifier(); 15094 if (!Name) 15095 return; 15096 if ((!getLangOpts().CPlusPlus && 15097 FD->getDeclContext()->isTranslationUnit()) || 15098 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 15099 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 15100 LinkageSpecDecl::lang_c)) { 15101 // Okay: this could be a libc/libm/Objective-C function we know 15102 // about. 15103 } else 15104 return; 15105 15106 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 15107 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 15108 // target-specific builtins, perhaps? 15109 if (!FD->hasAttr<FormatAttr>()) 15110 FD->addAttr(FormatAttr::CreateImplicit(Context, 15111 &Context.Idents.get("printf"), 2, 15112 Name->isStr("vasprintf") ? 0 : 3, 15113 FD->getLocation())); 15114 } 15115 15116 if (Name->isStr("__CFStringMakeConstantString")) { 15117 // We already have a __builtin___CFStringMakeConstantString, 15118 // but builds that use -fno-constant-cfstrings don't go through that. 15119 if (!FD->hasAttr<FormatArgAttr>()) 15120 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 15121 FD->getLocation())); 15122 } 15123 } 15124 15125 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15126 TypeSourceInfo *TInfo) { 15127 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 15128 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15129 15130 if (!TInfo) { 15131 assert(D.isInvalidType() && "no declarator info for valid type"); 15132 TInfo = Context.getTrivialTypeSourceInfo(T); 15133 } 15134 15135 // Scope manipulation handled by caller. 15136 TypedefDecl *NewTD = 15137 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15138 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15139 15140 // Bail out immediately if we have an invalid declaration. 15141 if (D.isInvalidType()) { 15142 NewTD->setInvalidDecl(); 15143 return NewTD; 15144 } 15145 15146 if (D.getDeclSpec().isModulePrivateSpecified()) { 15147 if (CurContext->isFunctionOrMethod()) 15148 Diag(NewTD->getLocation(), diag::err_module_private_local) 15149 << 2 << NewTD 15150 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15151 << FixItHint::CreateRemoval( 15152 D.getDeclSpec().getModulePrivateSpecLoc()); 15153 else 15154 NewTD->setModulePrivate(); 15155 } 15156 15157 // C++ [dcl.typedef]p8: 15158 // If the typedef declaration defines an unnamed class (or 15159 // enum), the first typedef-name declared by the declaration 15160 // to be that class type (or enum type) is used to denote the 15161 // class type (or enum type) for linkage purposes only. 15162 // We need to check whether the type was declared in the declaration. 15163 switch (D.getDeclSpec().getTypeSpecType()) { 15164 case TST_enum: 15165 case TST_struct: 15166 case TST_interface: 15167 case TST_union: 15168 case TST_class: { 15169 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15170 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15171 break; 15172 } 15173 15174 default: 15175 break; 15176 } 15177 15178 return NewTD; 15179 } 15180 15181 /// Check that this is a valid underlying type for an enum declaration. 15182 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15183 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15184 QualType T = TI->getType(); 15185 15186 if (T->isDependentType()) 15187 return false; 15188 15189 // This doesn't use 'isIntegralType' despite the error message mentioning 15190 // integral type because isIntegralType would also allow enum types in C. 15191 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15192 if (BT->isInteger()) 15193 return false; 15194 15195 if (T->isExtIntType()) 15196 return false; 15197 15198 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15199 } 15200 15201 /// Check whether this is a valid redeclaration of a previous enumeration. 15202 /// \return true if the redeclaration was invalid. 15203 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15204 QualType EnumUnderlyingTy, bool IsFixed, 15205 const EnumDecl *Prev) { 15206 if (IsScoped != Prev->isScoped()) { 15207 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15208 << Prev->isScoped(); 15209 Diag(Prev->getLocation(), diag::note_previous_declaration); 15210 return true; 15211 } 15212 15213 if (IsFixed && Prev->isFixed()) { 15214 if (!EnumUnderlyingTy->isDependentType() && 15215 !Prev->getIntegerType()->isDependentType() && 15216 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15217 Prev->getIntegerType())) { 15218 // TODO: Highlight the underlying type of the redeclaration. 15219 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15220 << EnumUnderlyingTy << Prev->getIntegerType(); 15221 Diag(Prev->getLocation(), diag::note_previous_declaration) 15222 << Prev->getIntegerTypeRange(); 15223 return true; 15224 } 15225 } else if (IsFixed != Prev->isFixed()) { 15226 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15227 << Prev->isFixed(); 15228 Diag(Prev->getLocation(), diag::note_previous_declaration); 15229 return true; 15230 } 15231 15232 return false; 15233 } 15234 15235 /// Get diagnostic %select index for tag kind for 15236 /// redeclaration diagnostic message. 15237 /// WARNING: Indexes apply to particular diagnostics only! 15238 /// 15239 /// \returns diagnostic %select index. 15240 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15241 switch (Tag) { 15242 case TTK_Struct: return 0; 15243 case TTK_Interface: return 1; 15244 case TTK_Class: return 2; 15245 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15246 } 15247 } 15248 15249 /// Determine if tag kind is a class-key compatible with 15250 /// class for redeclaration (class, struct, or __interface). 15251 /// 15252 /// \returns true iff the tag kind is compatible. 15253 static bool isClassCompatTagKind(TagTypeKind Tag) 15254 { 15255 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15256 } 15257 15258 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15259 TagTypeKind TTK) { 15260 if (isa<TypedefDecl>(PrevDecl)) 15261 return NTK_Typedef; 15262 else if (isa<TypeAliasDecl>(PrevDecl)) 15263 return NTK_TypeAlias; 15264 else if (isa<ClassTemplateDecl>(PrevDecl)) 15265 return NTK_Template; 15266 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15267 return NTK_TypeAliasTemplate; 15268 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15269 return NTK_TemplateTemplateArgument; 15270 switch (TTK) { 15271 case TTK_Struct: 15272 case TTK_Interface: 15273 case TTK_Class: 15274 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15275 case TTK_Union: 15276 return NTK_NonUnion; 15277 case TTK_Enum: 15278 return NTK_NonEnum; 15279 } 15280 llvm_unreachable("invalid TTK"); 15281 } 15282 15283 /// Determine whether a tag with a given kind is acceptable 15284 /// as a redeclaration of the given tag declaration. 15285 /// 15286 /// \returns true if the new tag kind is acceptable, false otherwise. 15287 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15288 TagTypeKind NewTag, bool isDefinition, 15289 SourceLocation NewTagLoc, 15290 const IdentifierInfo *Name) { 15291 // C++ [dcl.type.elab]p3: 15292 // The class-key or enum keyword present in the 15293 // elaborated-type-specifier shall agree in kind with the 15294 // declaration to which the name in the elaborated-type-specifier 15295 // refers. This rule also applies to the form of 15296 // elaborated-type-specifier that declares a class-name or 15297 // friend class since it can be construed as referring to the 15298 // definition of the class. Thus, in any 15299 // elaborated-type-specifier, the enum keyword shall be used to 15300 // refer to an enumeration (7.2), the union class-key shall be 15301 // used to refer to a union (clause 9), and either the class or 15302 // struct class-key shall be used to refer to a class (clause 9) 15303 // declared using the class or struct class-key. 15304 TagTypeKind OldTag = Previous->getTagKind(); 15305 if (OldTag != NewTag && 15306 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15307 return false; 15308 15309 // Tags are compatible, but we might still want to warn on mismatched tags. 15310 // Non-class tags can't be mismatched at this point. 15311 if (!isClassCompatTagKind(NewTag)) 15312 return true; 15313 15314 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15315 // by our warning analysis. We don't want to warn about mismatches with (eg) 15316 // declarations in system headers that are designed to be specialized, but if 15317 // a user asks us to warn, we should warn if their code contains mismatched 15318 // declarations. 15319 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15320 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15321 Loc); 15322 }; 15323 if (IsIgnoredLoc(NewTagLoc)) 15324 return true; 15325 15326 auto IsIgnored = [&](const TagDecl *Tag) { 15327 return IsIgnoredLoc(Tag->getLocation()); 15328 }; 15329 while (IsIgnored(Previous)) { 15330 Previous = Previous->getPreviousDecl(); 15331 if (!Previous) 15332 return true; 15333 OldTag = Previous->getTagKind(); 15334 } 15335 15336 bool isTemplate = false; 15337 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15338 isTemplate = Record->getDescribedClassTemplate(); 15339 15340 if (inTemplateInstantiation()) { 15341 if (OldTag != NewTag) { 15342 // In a template instantiation, do not offer fix-its for tag mismatches 15343 // since they usually mess up the template instead of fixing the problem. 15344 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15345 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15346 << getRedeclDiagFromTagKind(OldTag); 15347 // FIXME: Note previous location? 15348 } 15349 return true; 15350 } 15351 15352 if (isDefinition) { 15353 // On definitions, check all previous tags and issue a fix-it for each 15354 // one that doesn't match the current tag. 15355 if (Previous->getDefinition()) { 15356 // Don't suggest fix-its for redefinitions. 15357 return true; 15358 } 15359 15360 bool previousMismatch = false; 15361 for (const TagDecl *I : Previous->redecls()) { 15362 if (I->getTagKind() != NewTag) { 15363 // Ignore previous declarations for which the warning was disabled. 15364 if (IsIgnored(I)) 15365 continue; 15366 15367 if (!previousMismatch) { 15368 previousMismatch = true; 15369 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15370 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15371 << getRedeclDiagFromTagKind(I->getTagKind()); 15372 } 15373 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15374 << getRedeclDiagFromTagKind(NewTag) 15375 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15376 TypeWithKeyword::getTagTypeKindName(NewTag)); 15377 } 15378 } 15379 return true; 15380 } 15381 15382 // Identify the prevailing tag kind: this is the kind of the definition (if 15383 // there is a non-ignored definition), or otherwise the kind of the prior 15384 // (non-ignored) declaration. 15385 const TagDecl *PrevDef = Previous->getDefinition(); 15386 if (PrevDef && IsIgnored(PrevDef)) 15387 PrevDef = nullptr; 15388 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15389 if (Redecl->getTagKind() != NewTag) { 15390 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15391 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15392 << getRedeclDiagFromTagKind(OldTag); 15393 Diag(Redecl->getLocation(), diag::note_previous_use); 15394 15395 // If there is a previous definition, suggest a fix-it. 15396 if (PrevDef) { 15397 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15398 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15399 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15400 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15401 } 15402 } 15403 15404 return true; 15405 } 15406 15407 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15408 /// from an outer enclosing namespace or file scope inside a friend declaration. 15409 /// This should provide the commented out code in the following snippet: 15410 /// namespace N { 15411 /// struct X; 15412 /// namespace M { 15413 /// struct Y { friend struct /*N::*/ X; }; 15414 /// } 15415 /// } 15416 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15417 SourceLocation NameLoc) { 15418 // While the decl is in a namespace, do repeated lookup of that name and see 15419 // if we get the same namespace back. If we do not, continue until 15420 // translation unit scope, at which point we have a fully qualified NNS. 15421 SmallVector<IdentifierInfo *, 4> Namespaces; 15422 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15423 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15424 // This tag should be declared in a namespace, which can only be enclosed by 15425 // other namespaces. Bail if there's an anonymous namespace in the chain. 15426 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15427 if (!Namespace || Namespace->isAnonymousNamespace()) 15428 return FixItHint(); 15429 IdentifierInfo *II = Namespace->getIdentifier(); 15430 Namespaces.push_back(II); 15431 NamedDecl *Lookup = SemaRef.LookupSingleName( 15432 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15433 if (Lookup == Namespace) 15434 break; 15435 } 15436 15437 // Once we have all the namespaces, reverse them to go outermost first, and 15438 // build an NNS. 15439 SmallString<64> Insertion; 15440 llvm::raw_svector_ostream OS(Insertion); 15441 if (DC->isTranslationUnit()) 15442 OS << "::"; 15443 std::reverse(Namespaces.begin(), Namespaces.end()); 15444 for (auto *II : Namespaces) 15445 OS << II->getName() << "::"; 15446 return FixItHint::CreateInsertion(NameLoc, Insertion); 15447 } 15448 15449 /// Determine whether a tag originally declared in context \p OldDC can 15450 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15451 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15452 /// using-declaration). 15453 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15454 DeclContext *NewDC) { 15455 OldDC = OldDC->getRedeclContext(); 15456 NewDC = NewDC->getRedeclContext(); 15457 15458 if (OldDC->Equals(NewDC)) 15459 return true; 15460 15461 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15462 // encloses the other). 15463 if (S.getLangOpts().MSVCCompat && 15464 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15465 return true; 15466 15467 return false; 15468 } 15469 15470 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15471 /// former case, Name will be non-null. In the later case, Name will be null. 15472 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15473 /// reference/declaration/definition of a tag. 15474 /// 15475 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15476 /// trailing-type-specifier) other than one in an alias-declaration. 15477 /// 15478 /// \param SkipBody If non-null, will be set to indicate if the caller should 15479 /// skip the definition of this tag and treat it as if it were a declaration. 15480 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15481 SourceLocation KWLoc, CXXScopeSpec &SS, 15482 IdentifierInfo *Name, SourceLocation NameLoc, 15483 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15484 SourceLocation ModulePrivateLoc, 15485 MultiTemplateParamsArg TemplateParameterLists, 15486 bool &OwnedDecl, bool &IsDependent, 15487 SourceLocation ScopedEnumKWLoc, 15488 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15489 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15490 SkipBodyInfo *SkipBody) { 15491 // If this is not a definition, it must have a name. 15492 IdentifierInfo *OrigName = Name; 15493 assert((Name != nullptr || TUK == TUK_Definition) && 15494 "Nameless record must be a definition!"); 15495 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15496 15497 OwnedDecl = false; 15498 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15499 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15500 15501 // FIXME: Check member specializations more carefully. 15502 bool isMemberSpecialization = false; 15503 bool Invalid = false; 15504 15505 // We only need to do this matching if we have template parameters 15506 // or a scope specifier, which also conveniently avoids this work 15507 // for non-C++ cases. 15508 if (TemplateParameterLists.size() > 0 || 15509 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15510 if (TemplateParameterList *TemplateParams = 15511 MatchTemplateParametersToScopeSpecifier( 15512 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15513 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15514 if (Kind == TTK_Enum) { 15515 Diag(KWLoc, diag::err_enum_template); 15516 return nullptr; 15517 } 15518 15519 if (TemplateParams->size() > 0) { 15520 // This is a declaration or definition of a class template (which may 15521 // be a member of another template). 15522 15523 if (Invalid) 15524 return nullptr; 15525 15526 OwnedDecl = false; 15527 DeclResult Result = CheckClassTemplate( 15528 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15529 AS, ModulePrivateLoc, 15530 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15531 TemplateParameterLists.data(), SkipBody); 15532 return Result.get(); 15533 } else { 15534 // The "template<>" header is extraneous. 15535 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15536 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15537 isMemberSpecialization = true; 15538 } 15539 } 15540 15541 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15542 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15543 return nullptr; 15544 } 15545 15546 // Figure out the underlying type if this a enum declaration. We need to do 15547 // this early, because it's needed to detect if this is an incompatible 15548 // redeclaration. 15549 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15550 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15551 15552 if (Kind == TTK_Enum) { 15553 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15554 // No underlying type explicitly specified, or we failed to parse the 15555 // type, default to int. 15556 EnumUnderlying = Context.IntTy.getTypePtr(); 15557 } else if (UnderlyingType.get()) { 15558 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15559 // integral type; any cv-qualification is ignored. 15560 TypeSourceInfo *TI = nullptr; 15561 GetTypeFromParser(UnderlyingType.get(), &TI); 15562 EnumUnderlying = TI; 15563 15564 if (CheckEnumUnderlyingType(TI)) 15565 // Recover by falling back to int. 15566 EnumUnderlying = Context.IntTy.getTypePtr(); 15567 15568 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15569 UPPC_FixedUnderlyingType)) 15570 EnumUnderlying = Context.IntTy.getTypePtr(); 15571 15572 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15573 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15574 // of 'int'. However, if this is an unfixed forward declaration, don't set 15575 // the underlying type unless the user enables -fms-compatibility. This 15576 // makes unfixed forward declared enums incomplete and is more conforming. 15577 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15578 EnumUnderlying = Context.IntTy.getTypePtr(); 15579 } 15580 } 15581 15582 DeclContext *SearchDC = CurContext; 15583 DeclContext *DC = CurContext; 15584 bool isStdBadAlloc = false; 15585 bool isStdAlignValT = false; 15586 15587 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15588 if (TUK == TUK_Friend || TUK == TUK_Reference) 15589 Redecl = NotForRedeclaration; 15590 15591 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15592 /// implemented asks for structural equivalence checking, the returned decl 15593 /// here is passed back to the parser, allowing the tag body to be parsed. 15594 auto createTagFromNewDecl = [&]() -> TagDecl * { 15595 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15596 // If there is an identifier, use the location of the identifier as the 15597 // location of the decl, otherwise use the location of the struct/union 15598 // keyword. 15599 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15600 TagDecl *New = nullptr; 15601 15602 if (Kind == TTK_Enum) { 15603 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15604 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15605 // If this is an undefined enum, bail. 15606 if (TUK != TUK_Definition && !Invalid) 15607 return nullptr; 15608 if (EnumUnderlying) { 15609 EnumDecl *ED = cast<EnumDecl>(New); 15610 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15611 ED->setIntegerTypeSourceInfo(TI); 15612 else 15613 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15614 ED->setPromotionType(ED->getIntegerType()); 15615 } 15616 } else { // struct/union 15617 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15618 nullptr); 15619 } 15620 15621 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15622 // Add alignment attributes if necessary; these attributes are checked 15623 // when the ASTContext lays out the structure. 15624 // 15625 // It is important for implementing the correct semantics that this 15626 // happen here (in ActOnTag). The #pragma pack stack is 15627 // maintained as a result of parser callbacks which can occur at 15628 // many points during the parsing of a struct declaration (because 15629 // the #pragma tokens are effectively skipped over during the 15630 // parsing of the struct). 15631 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15632 AddAlignmentAttributesForRecord(RD); 15633 AddMsStructLayoutForRecord(RD); 15634 } 15635 } 15636 New->setLexicalDeclContext(CurContext); 15637 return New; 15638 }; 15639 15640 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15641 if (Name && SS.isNotEmpty()) { 15642 // We have a nested-name tag ('struct foo::bar'). 15643 15644 // Check for invalid 'foo::'. 15645 if (SS.isInvalid()) { 15646 Name = nullptr; 15647 goto CreateNewDecl; 15648 } 15649 15650 // If this is a friend or a reference to a class in a dependent 15651 // context, don't try to make a decl for it. 15652 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15653 DC = computeDeclContext(SS, false); 15654 if (!DC) { 15655 IsDependent = true; 15656 return nullptr; 15657 } 15658 } else { 15659 DC = computeDeclContext(SS, true); 15660 if (!DC) { 15661 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15662 << SS.getRange(); 15663 return nullptr; 15664 } 15665 } 15666 15667 if (RequireCompleteDeclContext(SS, DC)) 15668 return nullptr; 15669 15670 SearchDC = DC; 15671 // Look-up name inside 'foo::'. 15672 LookupQualifiedName(Previous, DC); 15673 15674 if (Previous.isAmbiguous()) 15675 return nullptr; 15676 15677 if (Previous.empty()) { 15678 // Name lookup did not find anything. However, if the 15679 // nested-name-specifier refers to the current instantiation, 15680 // and that current instantiation has any dependent base 15681 // classes, we might find something at instantiation time: treat 15682 // this as a dependent elaborated-type-specifier. 15683 // But this only makes any sense for reference-like lookups. 15684 if (Previous.wasNotFoundInCurrentInstantiation() && 15685 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15686 IsDependent = true; 15687 return nullptr; 15688 } 15689 15690 // A tag 'foo::bar' must already exist. 15691 Diag(NameLoc, diag::err_not_tag_in_scope) 15692 << Kind << Name << DC << SS.getRange(); 15693 Name = nullptr; 15694 Invalid = true; 15695 goto CreateNewDecl; 15696 } 15697 } else if (Name) { 15698 // C++14 [class.mem]p14: 15699 // If T is the name of a class, then each of the following shall have a 15700 // name different from T: 15701 // -- every member of class T that is itself a type 15702 if (TUK != TUK_Reference && TUK != TUK_Friend && 15703 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15704 return nullptr; 15705 15706 // If this is a named struct, check to see if there was a previous forward 15707 // declaration or definition. 15708 // FIXME: We're looking into outer scopes here, even when we 15709 // shouldn't be. Doing so can result in ambiguities that we 15710 // shouldn't be diagnosing. 15711 LookupName(Previous, S); 15712 15713 // When declaring or defining a tag, ignore ambiguities introduced 15714 // by types using'ed into this scope. 15715 if (Previous.isAmbiguous() && 15716 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15717 LookupResult::Filter F = Previous.makeFilter(); 15718 while (F.hasNext()) { 15719 NamedDecl *ND = F.next(); 15720 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15721 SearchDC->getRedeclContext())) 15722 F.erase(); 15723 } 15724 F.done(); 15725 } 15726 15727 // C++11 [namespace.memdef]p3: 15728 // If the name in a friend declaration is neither qualified nor 15729 // a template-id and the declaration is a function or an 15730 // elaborated-type-specifier, the lookup to determine whether 15731 // the entity has been previously declared shall not consider 15732 // any scopes outside the innermost enclosing namespace. 15733 // 15734 // MSVC doesn't implement the above rule for types, so a friend tag 15735 // declaration may be a redeclaration of a type declared in an enclosing 15736 // scope. They do implement this rule for friend functions. 15737 // 15738 // Does it matter that this should be by scope instead of by 15739 // semantic context? 15740 if (!Previous.empty() && TUK == TUK_Friend) { 15741 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15742 LookupResult::Filter F = Previous.makeFilter(); 15743 bool FriendSawTagOutsideEnclosingNamespace = false; 15744 while (F.hasNext()) { 15745 NamedDecl *ND = F.next(); 15746 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15747 if (DC->isFileContext() && 15748 !EnclosingNS->Encloses(ND->getDeclContext())) { 15749 if (getLangOpts().MSVCCompat) 15750 FriendSawTagOutsideEnclosingNamespace = true; 15751 else 15752 F.erase(); 15753 } 15754 } 15755 F.done(); 15756 15757 // Diagnose this MSVC extension in the easy case where lookup would have 15758 // unambiguously found something outside the enclosing namespace. 15759 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15760 NamedDecl *ND = Previous.getFoundDecl(); 15761 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15762 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15763 } 15764 } 15765 15766 // Note: there used to be some attempt at recovery here. 15767 if (Previous.isAmbiguous()) 15768 return nullptr; 15769 15770 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15771 // FIXME: This makes sure that we ignore the contexts associated 15772 // with C structs, unions, and enums when looking for a matching 15773 // tag declaration or definition. See the similar lookup tweak 15774 // in Sema::LookupName; is there a better way to deal with this? 15775 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15776 SearchDC = SearchDC->getParent(); 15777 } 15778 } 15779 15780 if (Previous.isSingleResult() && 15781 Previous.getFoundDecl()->isTemplateParameter()) { 15782 // Maybe we will complain about the shadowed template parameter. 15783 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15784 // Just pretend that we didn't see the previous declaration. 15785 Previous.clear(); 15786 } 15787 15788 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15789 DC->Equals(getStdNamespace())) { 15790 if (Name->isStr("bad_alloc")) { 15791 // This is a declaration of or a reference to "std::bad_alloc". 15792 isStdBadAlloc = true; 15793 15794 // If std::bad_alloc has been implicitly declared (but made invisible to 15795 // name lookup), fill in this implicit declaration as the previous 15796 // declaration, so that the declarations get chained appropriately. 15797 if (Previous.empty() && StdBadAlloc) 15798 Previous.addDecl(getStdBadAlloc()); 15799 } else if (Name->isStr("align_val_t")) { 15800 isStdAlignValT = true; 15801 if (Previous.empty() && StdAlignValT) 15802 Previous.addDecl(getStdAlignValT()); 15803 } 15804 } 15805 15806 // If we didn't find a previous declaration, and this is a reference 15807 // (or friend reference), move to the correct scope. In C++, we 15808 // also need to do a redeclaration lookup there, just in case 15809 // there's a shadow friend decl. 15810 if (Name && Previous.empty() && 15811 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15812 if (Invalid) goto CreateNewDecl; 15813 assert(SS.isEmpty()); 15814 15815 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15816 // C++ [basic.scope.pdecl]p5: 15817 // -- for an elaborated-type-specifier of the form 15818 // 15819 // class-key identifier 15820 // 15821 // if the elaborated-type-specifier is used in the 15822 // decl-specifier-seq or parameter-declaration-clause of a 15823 // function defined in namespace scope, the identifier is 15824 // declared as a class-name in the namespace that contains 15825 // the declaration; otherwise, except as a friend 15826 // declaration, the identifier is declared in the smallest 15827 // non-class, non-function-prototype scope that contains the 15828 // declaration. 15829 // 15830 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15831 // C structs and unions. 15832 // 15833 // It is an error in C++ to declare (rather than define) an enum 15834 // type, including via an elaborated type specifier. We'll 15835 // diagnose that later; for now, declare the enum in the same 15836 // scope as we would have picked for any other tag type. 15837 // 15838 // GNU C also supports this behavior as part of its incomplete 15839 // enum types extension, while GNU C++ does not. 15840 // 15841 // Find the context where we'll be declaring the tag. 15842 // FIXME: We would like to maintain the current DeclContext as the 15843 // lexical context, 15844 SearchDC = getTagInjectionContext(SearchDC); 15845 15846 // Find the scope where we'll be declaring the tag. 15847 S = getTagInjectionScope(S, getLangOpts()); 15848 } else { 15849 assert(TUK == TUK_Friend); 15850 // C++ [namespace.memdef]p3: 15851 // If a friend declaration in a non-local class first declares a 15852 // class or function, the friend class or function is a member of 15853 // the innermost enclosing namespace. 15854 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15855 } 15856 15857 // In C++, we need to do a redeclaration lookup to properly 15858 // diagnose some problems. 15859 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15860 // hidden declaration so that we don't get ambiguity errors when using a 15861 // type declared by an elaborated-type-specifier. In C that is not correct 15862 // and we should instead merge compatible types found by lookup. 15863 if (getLangOpts().CPlusPlus) { 15864 // FIXME: This can perform qualified lookups into function contexts, 15865 // which are meaningless. 15866 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15867 LookupQualifiedName(Previous, SearchDC); 15868 } else { 15869 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15870 LookupName(Previous, S); 15871 } 15872 } 15873 15874 // If we have a known previous declaration to use, then use it. 15875 if (Previous.empty() && SkipBody && SkipBody->Previous) 15876 Previous.addDecl(SkipBody->Previous); 15877 15878 if (!Previous.empty()) { 15879 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15880 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15881 15882 // It's okay to have a tag decl in the same scope as a typedef 15883 // which hides a tag decl in the same scope. Finding this 15884 // insanity with a redeclaration lookup can only actually happen 15885 // in C++. 15886 // 15887 // This is also okay for elaborated-type-specifiers, which is 15888 // technically forbidden by the current standard but which is 15889 // okay according to the likely resolution of an open issue; 15890 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15891 if (getLangOpts().CPlusPlus) { 15892 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15893 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15894 TagDecl *Tag = TT->getDecl(); 15895 if (Tag->getDeclName() == Name && 15896 Tag->getDeclContext()->getRedeclContext() 15897 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15898 PrevDecl = Tag; 15899 Previous.clear(); 15900 Previous.addDecl(Tag); 15901 Previous.resolveKind(); 15902 } 15903 } 15904 } 15905 } 15906 15907 // If this is a redeclaration of a using shadow declaration, it must 15908 // declare a tag in the same context. In MSVC mode, we allow a 15909 // redefinition if either context is within the other. 15910 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15911 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15912 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15913 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15914 !(OldTag && isAcceptableTagRedeclContext( 15915 *this, OldTag->getDeclContext(), SearchDC))) { 15916 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15917 Diag(Shadow->getTargetDecl()->getLocation(), 15918 diag::note_using_decl_target); 15919 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15920 << 0; 15921 // Recover by ignoring the old declaration. 15922 Previous.clear(); 15923 goto CreateNewDecl; 15924 } 15925 } 15926 15927 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15928 // If this is a use of a previous tag, or if the tag is already declared 15929 // in the same scope (so that the definition/declaration completes or 15930 // rementions the tag), reuse the decl. 15931 if (TUK == TUK_Reference || TUK == TUK_Friend || 15932 isDeclInScope(DirectPrevDecl, SearchDC, S, 15933 SS.isNotEmpty() || isMemberSpecialization)) { 15934 // Make sure that this wasn't declared as an enum and now used as a 15935 // struct or something similar. 15936 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15937 TUK == TUK_Definition, KWLoc, 15938 Name)) { 15939 bool SafeToContinue 15940 = (PrevTagDecl->getTagKind() != TTK_Enum && 15941 Kind != TTK_Enum); 15942 if (SafeToContinue) 15943 Diag(KWLoc, diag::err_use_with_wrong_tag) 15944 << Name 15945 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15946 PrevTagDecl->getKindName()); 15947 else 15948 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15949 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15950 15951 if (SafeToContinue) 15952 Kind = PrevTagDecl->getTagKind(); 15953 else { 15954 // Recover by making this an anonymous redefinition. 15955 Name = nullptr; 15956 Previous.clear(); 15957 Invalid = true; 15958 } 15959 } 15960 15961 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15962 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15963 if (TUK == TUK_Reference || TUK == TUK_Friend) 15964 return PrevTagDecl; 15965 15966 QualType EnumUnderlyingTy; 15967 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15968 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15969 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15970 EnumUnderlyingTy = QualType(T, 0); 15971 15972 // All conflicts with previous declarations are recovered by 15973 // returning the previous declaration, unless this is a definition, 15974 // in which case we want the caller to bail out. 15975 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15976 ScopedEnum, EnumUnderlyingTy, 15977 IsFixed, PrevEnum)) 15978 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15979 } 15980 15981 // C++11 [class.mem]p1: 15982 // A member shall not be declared twice in the member-specification, 15983 // except that a nested class or member class template can be declared 15984 // and then later defined. 15985 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15986 S->isDeclScope(PrevDecl)) { 15987 Diag(NameLoc, diag::ext_member_redeclared); 15988 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15989 } 15990 15991 if (!Invalid) { 15992 // If this is a use, just return the declaration we found, unless 15993 // we have attributes. 15994 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15995 if (!Attrs.empty()) { 15996 // FIXME: Diagnose these attributes. For now, we create a new 15997 // declaration to hold them. 15998 } else if (TUK == TUK_Reference && 15999 (PrevTagDecl->getFriendObjectKind() == 16000 Decl::FOK_Undeclared || 16001 PrevDecl->getOwningModule() != getCurrentModule()) && 16002 SS.isEmpty()) { 16003 // This declaration is a reference to an existing entity, but 16004 // has different visibility from that entity: it either makes 16005 // a friend visible or it makes a type visible in a new module. 16006 // In either case, create a new declaration. We only do this if 16007 // the declaration would have meant the same thing if no prior 16008 // declaration were found, that is, if it was found in the same 16009 // scope where we would have injected a declaration. 16010 if (!getTagInjectionContext(CurContext)->getRedeclContext() 16011 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 16012 return PrevTagDecl; 16013 // This is in the injected scope, create a new declaration in 16014 // that scope. 16015 S = getTagInjectionScope(S, getLangOpts()); 16016 } else { 16017 return PrevTagDecl; 16018 } 16019 } 16020 16021 // Diagnose attempts to redefine a tag. 16022 if (TUK == TUK_Definition) { 16023 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 16024 // If we're defining a specialization and the previous definition 16025 // is from an implicit instantiation, don't emit an error 16026 // here; we'll catch this in the general case below. 16027 bool IsExplicitSpecializationAfterInstantiation = false; 16028 if (isMemberSpecialization) { 16029 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 16030 IsExplicitSpecializationAfterInstantiation = 16031 RD->getTemplateSpecializationKind() != 16032 TSK_ExplicitSpecialization; 16033 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 16034 IsExplicitSpecializationAfterInstantiation = 16035 ED->getTemplateSpecializationKind() != 16036 TSK_ExplicitSpecialization; 16037 } 16038 16039 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 16040 // not keep more that one definition around (merge them). However, 16041 // ensure the decl passes the structural compatibility check in 16042 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 16043 NamedDecl *Hidden = nullptr; 16044 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 16045 // There is a definition of this tag, but it is not visible. We 16046 // explicitly make use of C++'s one definition rule here, and 16047 // assume that this definition is identical to the hidden one 16048 // we already have. Make the existing definition visible and 16049 // use it in place of this one. 16050 if (!getLangOpts().CPlusPlus) { 16051 // Postpone making the old definition visible until after we 16052 // complete parsing the new one and do the structural 16053 // comparison. 16054 SkipBody->CheckSameAsPrevious = true; 16055 SkipBody->New = createTagFromNewDecl(); 16056 SkipBody->Previous = Def; 16057 return Def; 16058 } else { 16059 SkipBody->ShouldSkip = true; 16060 SkipBody->Previous = Def; 16061 makeMergedDefinitionVisible(Hidden); 16062 // Carry on and handle it like a normal definition. We'll 16063 // skip starting the definitiion later. 16064 } 16065 } else if (!IsExplicitSpecializationAfterInstantiation) { 16066 // A redeclaration in function prototype scope in C isn't 16067 // visible elsewhere, so merely issue a warning. 16068 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 16069 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 16070 else 16071 Diag(NameLoc, diag::err_redefinition) << Name; 16072 notePreviousDefinition(Def, 16073 NameLoc.isValid() ? NameLoc : KWLoc); 16074 // If this is a redefinition, recover by making this 16075 // struct be anonymous, which will make any later 16076 // references get the previous definition. 16077 Name = nullptr; 16078 Previous.clear(); 16079 Invalid = true; 16080 } 16081 } else { 16082 // If the type is currently being defined, complain 16083 // about a nested redefinition. 16084 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 16085 if (TD->isBeingDefined()) { 16086 Diag(NameLoc, diag::err_nested_redefinition) << Name; 16087 Diag(PrevTagDecl->getLocation(), 16088 diag::note_previous_definition); 16089 Name = nullptr; 16090 Previous.clear(); 16091 Invalid = true; 16092 } 16093 } 16094 16095 // Okay, this is definition of a previously declared or referenced 16096 // tag. We're going to create a new Decl for it. 16097 } 16098 16099 // Okay, we're going to make a redeclaration. If this is some kind 16100 // of reference, make sure we build the redeclaration in the same DC 16101 // as the original, and ignore the current access specifier. 16102 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16103 SearchDC = PrevTagDecl->getDeclContext(); 16104 AS = AS_none; 16105 } 16106 } 16107 // If we get here we have (another) forward declaration or we 16108 // have a definition. Just create a new decl. 16109 16110 } else { 16111 // If we get here, this is a definition of a new tag type in a nested 16112 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 16113 // new decl/type. We set PrevDecl to NULL so that the entities 16114 // have distinct types. 16115 Previous.clear(); 16116 } 16117 // If we get here, we're going to create a new Decl. If PrevDecl 16118 // is non-NULL, it's a definition of the tag declared by 16119 // PrevDecl. If it's NULL, we have a new definition. 16120 16121 // Otherwise, PrevDecl is not a tag, but was found with tag 16122 // lookup. This is only actually possible in C++, where a few 16123 // things like templates still live in the tag namespace. 16124 } else { 16125 // Use a better diagnostic if an elaborated-type-specifier 16126 // found the wrong kind of type on the first 16127 // (non-redeclaration) lookup. 16128 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16129 !Previous.isForRedeclaration()) { 16130 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16131 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16132 << Kind; 16133 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16134 Invalid = true; 16135 16136 // Otherwise, only diagnose if the declaration is in scope. 16137 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16138 SS.isNotEmpty() || isMemberSpecialization)) { 16139 // do nothing 16140 16141 // Diagnose implicit declarations introduced by elaborated types. 16142 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16143 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16144 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16145 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16146 Invalid = true; 16147 16148 // Otherwise it's a declaration. Call out a particularly common 16149 // case here. 16150 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16151 unsigned Kind = 0; 16152 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16153 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16154 << Name << Kind << TND->getUnderlyingType(); 16155 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16156 Invalid = true; 16157 16158 // Otherwise, diagnose. 16159 } else { 16160 // The tag name clashes with something else in the target scope, 16161 // issue an error and recover by making this tag be anonymous. 16162 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16163 notePreviousDefinition(PrevDecl, NameLoc); 16164 Name = nullptr; 16165 Invalid = true; 16166 } 16167 16168 // The existing declaration isn't relevant to us; we're in a 16169 // new scope, so clear out the previous declaration. 16170 Previous.clear(); 16171 } 16172 } 16173 16174 CreateNewDecl: 16175 16176 TagDecl *PrevDecl = nullptr; 16177 if (Previous.isSingleResult()) 16178 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16179 16180 // If there is an identifier, use the location of the identifier as the 16181 // location of the decl, otherwise use the location of the struct/union 16182 // keyword. 16183 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16184 16185 // Otherwise, create a new declaration. If there is a previous 16186 // declaration of the same entity, the two will be linked via 16187 // PrevDecl. 16188 TagDecl *New; 16189 16190 if (Kind == TTK_Enum) { 16191 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16192 // enum X { A, B, C } D; D should chain to X. 16193 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16194 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16195 ScopedEnumUsesClassTag, IsFixed); 16196 16197 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16198 StdAlignValT = cast<EnumDecl>(New); 16199 16200 // If this is an undefined enum, warn. 16201 if (TUK != TUK_Definition && !Invalid) { 16202 TagDecl *Def; 16203 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16204 // C++0x: 7.2p2: opaque-enum-declaration. 16205 // Conflicts are diagnosed above. Do nothing. 16206 } 16207 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16208 Diag(Loc, diag::ext_forward_ref_enum_def) 16209 << New; 16210 Diag(Def->getLocation(), diag::note_previous_definition); 16211 } else { 16212 unsigned DiagID = diag::ext_forward_ref_enum; 16213 if (getLangOpts().MSVCCompat) 16214 DiagID = diag::ext_ms_forward_ref_enum; 16215 else if (getLangOpts().CPlusPlus) 16216 DiagID = diag::err_forward_ref_enum; 16217 Diag(Loc, DiagID); 16218 } 16219 } 16220 16221 if (EnumUnderlying) { 16222 EnumDecl *ED = cast<EnumDecl>(New); 16223 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16224 ED->setIntegerTypeSourceInfo(TI); 16225 else 16226 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16227 ED->setPromotionType(ED->getIntegerType()); 16228 assert(ED->isComplete() && "enum with type should be complete"); 16229 } 16230 } else { 16231 // struct/union/class 16232 16233 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16234 // struct X { int A; } D; D should chain to X. 16235 if (getLangOpts().CPlusPlus) { 16236 // FIXME: Look for a way to use RecordDecl for simple structs. 16237 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16238 cast_or_null<CXXRecordDecl>(PrevDecl)); 16239 16240 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16241 StdBadAlloc = cast<CXXRecordDecl>(New); 16242 } else 16243 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16244 cast_or_null<RecordDecl>(PrevDecl)); 16245 } 16246 16247 // C++11 [dcl.type]p3: 16248 // A type-specifier-seq shall not define a class or enumeration [...]. 16249 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16250 TUK == TUK_Definition) { 16251 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16252 << Context.getTagDeclType(New); 16253 Invalid = true; 16254 } 16255 16256 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16257 DC->getDeclKind() == Decl::Enum) { 16258 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16259 << Context.getTagDeclType(New); 16260 Invalid = true; 16261 } 16262 16263 // Maybe add qualifier info. 16264 if (SS.isNotEmpty()) { 16265 if (SS.isSet()) { 16266 // If this is either a declaration or a definition, check the 16267 // nested-name-specifier against the current context. 16268 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16269 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16270 isMemberSpecialization)) 16271 Invalid = true; 16272 16273 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16274 if (TemplateParameterLists.size() > 0) { 16275 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16276 } 16277 } 16278 else 16279 Invalid = true; 16280 } 16281 16282 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16283 // Add alignment attributes if necessary; these attributes are checked when 16284 // the ASTContext lays out the structure. 16285 // 16286 // It is important for implementing the correct semantics that this 16287 // happen here (in ActOnTag). The #pragma pack stack is 16288 // maintained as a result of parser callbacks which can occur at 16289 // many points during the parsing of a struct declaration (because 16290 // the #pragma tokens are effectively skipped over during the 16291 // parsing of the struct). 16292 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16293 AddAlignmentAttributesForRecord(RD); 16294 AddMsStructLayoutForRecord(RD); 16295 } 16296 } 16297 16298 if (ModulePrivateLoc.isValid()) { 16299 if (isMemberSpecialization) 16300 Diag(New->getLocation(), diag::err_module_private_specialization) 16301 << 2 16302 << FixItHint::CreateRemoval(ModulePrivateLoc); 16303 // __module_private__ does not apply to local classes. However, we only 16304 // diagnose this as an error when the declaration specifiers are 16305 // freestanding. Here, we just ignore the __module_private__. 16306 else if (!SearchDC->isFunctionOrMethod()) 16307 New->setModulePrivate(); 16308 } 16309 16310 // If this is a specialization of a member class (of a class template), 16311 // check the specialization. 16312 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16313 Invalid = true; 16314 16315 // If we're declaring or defining a tag in function prototype scope in C, 16316 // note that this type can only be used within the function and add it to 16317 // the list of decls to inject into the function definition scope. 16318 if ((Name || Kind == TTK_Enum) && 16319 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16320 if (getLangOpts().CPlusPlus) { 16321 // C++ [dcl.fct]p6: 16322 // Types shall not be defined in return or parameter types. 16323 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16324 Diag(Loc, diag::err_type_defined_in_param_type) 16325 << Name; 16326 Invalid = true; 16327 } 16328 } else if (!PrevDecl) { 16329 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16330 } 16331 } 16332 16333 if (Invalid) 16334 New->setInvalidDecl(); 16335 16336 // Set the lexical context. If the tag has a C++ scope specifier, the 16337 // lexical context will be different from the semantic context. 16338 New->setLexicalDeclContext(CurContext); 16339 16340 // Mark this as a friend decl if applicable. 16341 // In Microsoft mode, a friend declaration also acts as a forward 16342 // declaration so we always pass true to setObjectOfFriendDecl to make 16343 // the tag name visible. 16344 if (TUK == TUK_Friend) 16345 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16346 16347 // Set the access specifier. 16348 if (!Invalid && SearchDC->isRecord()) 16349 SetMemberAccessSpecifier(New, PrevDecl, AS); 16350 16351 if (PrevDecl) 16352 CheckRedeclarationModuleOwnership(New, PrevDecl); 16353 16354 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16355 New->startDefinition(); 16356 16357 ProcessDeclAttributeList(S, New, Attrs); 16358 AddPragmaAttributes(S, New); 16359 16360 // If this has an identifier, add it to the scope stack. 16361 if (TUK == TUK_Friend) { 16362 // We might be replacing an existing declaration in the lookup tables; 16363 // if so, borrow its access specifier. 16364 if (PrevDecl) 16365 New->setAccess(PrevDecl->getAccess()); 16366 16367 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16368 DC->makeDeclVisibleInContext(New); 16369 if (Name) // can be null along some error paths 16370 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16371 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16372 } else if (Name) { 16373 S = getNonFieldDeclScope(S); 16374 PushOnScopeChains(New, S, true); 16375 } else { 16376 CurContext->addDecl(New); 16377 } 16378 16379 // If this is the C FILE type, notify the AST context. 16380 if (IdentifierInfo *II = New->getIdentifier()) 16381 if (!New->isInvalidDecl() && 16382 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16383 II->isStr("FILE")) 16384 Context.setFILEDecl(New); 16385 16386 if (PrevDecl) 16387 mergeDeclAttributes(New, PrevDecl); 16388 16389 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16390 inferGslOwnerPointerAttribute(CXXRD); 16391 16392 // If there's a #pragma GCC visibility in scope, set the visibility of this 16393 // record. 16394 AddPushedVisibilityAttribute(New); 16395 16396 if (isMemberSpecialization && !New->isInvalidDecl()) 16397 CompleteMemberSpecialization(New, Previous); 16398 16399 OwnedDecl = true; 16400 // In C++, don't return an invalid declaration. We can't recover well from 16401 // the cases where we make the type anonymous. 16402 if (Invalid && getLangOpts().CPlusPlus) { 16403 if (New->isBeingDefined()) 16404 if (auto RD = dyn_cast<RecordDecl>(New)) 16405 RD->completeDefinition(); 16406 return nullptr; 16407 } else if (SkipBody && SkipBody->ShouldSkip) { 16408 return SkipBody->Previous; 16409 } else { 16410 return New; 16411 } 16412 } 16413 16414 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16415 AdjustDeclIfTemplate(TagD); 16416 TagDecl *Tag = cast<TagDecl>(TagD); 16417 16418 // Enter the tag context. 16419 PushDeclContext(S, Tag); 16420 16421 ActOnDocumentableDecl(TagD); 16422 16423 // If there's a #pragma GCC visibility in scope, set the visibility of this 16424 // record. 16425 AddPushedVisibilityAttribute(Tag); 16426 } 16427 16428 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16429 SkipBodyInfo &SkipBody) { 16430 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16431 return false; 16432 16433 // Make the previous decl visible. 16434 makeMergedDefinitionVisible(SkipBody.Previous); 16435 return true; 16436 } 16437 16438 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16439 assert(isa<ObjCContainerDecl>(IDecl) && 16440 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16441 DeclContext *OCD = cast<DeclContext>(IDecl); 16442 assert(OCD->getLexicalParent() == CurContext && 16443 "The next DeclContext should be lexically contained in the current one."); 16444 CurContext = OCD; 16445 return IDecl; 16446 } 16447 16448 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16449 SourceLocation FinalLoc, 16450 bool IsFinalSpelledSealed, 16451 SourceLocation LBraceLoc) { 16452 AdjustDeclIfTemplate(TagD); 16453 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16454 16455 FieldCollector->StartClass(); 16456 16457 if (!Record->getIdentifier()) 16458 return; 16459 16460 if (FinalLoc.isValid()) 16461 Record->addAttr(FinalAttr::Create( 16462 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16463 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16464 16465 // C++ [class]p2: 16466 // [...] The class-name is also inserted into the scope of the 16467 // class itself; this is known as the injected-class-name. For 16468 // purposes of access checking, the injected-class-name is treated 16469 // as if it were a public member name. 16470 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16471 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16472 Record->getLocation(), Record->getIdentifier(), 16473 /*PrevDecl=*/nullptr, 16474 /*DelayTypeCreation=*/true); 16475 Context.getTypeDeclType(InjectedClassName, Record); 16476 InjectedClassName->setImplicit(); 16477 InjectedClassName->setAccess(AS_public); 16478 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16479 InjectedClassName->setDescribedClassTemplate(Template); 16480 PushOnScopeChains(InjectedClassName, S); 16481 assert(InjectedClassName->isInjectedClassName() && 16482 "Broken injected-class-name"); 16483 } 16484 16485 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16486 SourceRange BraceRange) { 16487 AdjustDeclIfTemplate(TagD); 16488 TagDecl *Tag = cast<TagDecl>(TagD); 16489 Tag->setBraceRange(BraceRange); 16490 16491 // Make sure we "complete" the definition even it is invalid. 16492 if (Tag->isBeingDefined()) { 16493 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16494 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16495 RD->completeDefinition(); 16496 } 16497 16498 if (isa<CXXRecordDecl>(Tag)) { 16499 FieldCollector->FinishClass(); 16500 } 16501 16502 // Exit this scope of this tag's definition. 16503 PopDeclContext(); 16504 16505 if (getCurLexicalContext()->isObjCContainer() && 16506 Tag->getDeclContext()->isFileContext()) 16507 Tag->setTopLevelDeclInObjCContainer(); 16508 16509 // Notify the consumer that we've defined a tag. 16510 if (!Tag->isInvalidDecl()) 16511 Consumer.HandleTagDeclDefinition(Tag); 16512 } 16513 16514 void Sema::ActOnObjCContainerFinishDefinition() { 16515 // Exit this scope of this interface definition. 16516 PopDeclContext(); 16517 } 16518 16519 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16520 assert(DC == CurContext && "Mismatch of container contexts"); 16521 OriginalLexicalContext = DC; 16522 ActOnObjCContainerFinishDefinition(); 16523 } 16524 16525 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16526 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16527 OriginalLexicalContext = nullptr; 16528 } 16529 16530 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16531 AdjustDeclIfTemplate(TagD); 16532 TagDecl *Tag = cast<TagDecl>(TagD); 16533 Tag->setInvalidDecl(); 16534 16535 // Make sure we "complete" the definition even it is invalid. 16536 if (Tag->isBeingDefined()) { 16537 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16538 RD->completeDefinition(); 16539 } 16540 16541 // We're undoing ActOnTagStartDefinition here, not 16542 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16543 // the FieldCollector. 16544 16545 PopDeclContext(); 16546 } 16547 16548 // Note that FieldName may be null for anonymous bitfields. 16549 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16550 IdentifierInfo *FieldName, 16551 QualType FieldTy, bool IsMsStruct, 16552 Expr *BitWidth, bool *ZeroWidth) { 16553 assert(BitWidth); 16554 if (BitWidth->containsErrors()) 16555 return ExprError(); 16556 16557 // Default to true; that shouldn't confuse checks for emptiness 16558 if (ZeroWidth) 16559 *ZeroWidth = true; 16560 16561 // C99 6.7.2.1p4 - verify the field type. 16562 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16563 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16564 // Handle incomplete and sizeless types with a specific error. 16565 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16566 diag::err_field_incomplete_or_sizeless)) 16567 return ExprError(); 16568 if (FieldName) 16569 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16570 << FieldName << FieldTy << BitWidth->getSourceRange(); 16571 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16572 << FieldTy << BitWidth->getSourceRange(); 16573 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16574 UPPC_BitFieldWidth)) 16575 return ExprError(); 16576 16577 // If the bit-width is type- or value-dependent, don't try to check 16578 // it now. 16579 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16580 return BitWidth; 16581 16582 llvm::APSInt Value; 16583 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 16584 if (ICE.isInvalid()) 16585 return ICE; 16586 BitWidth = ICE.get(); 16587 16588 if (Value != 0 && ZeroWidth) 16589 *ZeroWidth = false; 16590 16591 // Zero-width bitfield is ok for anonymous field. 16592 if (Value == 0 && FieldName) 16593 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16594 16595 if (Value.isSigned() && Value.isNegative()) { 16596 if (FieldName) 16597 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16598 << FieldName << Value.toString(10); 16599 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16600 << Value.toString(10); 16601 } 16602 16603 // The size of the bit-field must not exceed our maximum permitted object 16604 // size. 16605 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 16606 return Diag(FieldLoc, diag::err_bitfield_too_wide) 16607 << !FieldName << FieldName << Value.toString(10); 16608 } 16609 16610 if (!FieldTy->isDependentType()) { 16611 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16612 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16613 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16614 16615 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16616 // ABI. 16617 bool CStdConstraintViolation = 16618 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16619 bool MSBitfieldViolation = 16620 Value.ugt(TypeStorageSize) && 16621 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16622 if (CStdConstraintViolation || MSBitfieldViolation) { 16623 unsigned DiagWidth = 16624 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16625 if (FieldName) 16626 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16627 << FieldName << Value.toString(10) 16628 << !CStdConstraintViolation << DiagWidth; 16629 16630 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16631 << Value.toString(10) << !CStdConstraintViolation 16632 << DiagWidth; 16633 } 16634 16635 // Warn on types where the user might conceivably expect to get all 16636 // specified bits as value bits: that's all integral types other than 16637 // 'bool'. 16638 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 16639 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16640 << FieldName << Value.toString(10) 16641 << (unsigned)TypeWidth; 16642 } 16643 } 16644 16645 return BitWidth; 16646 } 16647 16648 /// ActOnField - Each field of a C struct/union is passed into this in order 16649 /// to create a FieldDecl object for it. 16650 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16651 Declarator &D, Expr *BitfieldWidth) { 16652 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16653 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16654 /*InitStyle=*/ICIS_NoInit, AS_public); 16655 return Res; 16656 } 16657 16658 /// HandleField - Analyze a field of a C struct or a C++ data member. 16659 /// 16660 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16661 SourceLocation DeclStart, 16662 Declarator &D, Expr *BitWidth, 16663 InClassInitStyle InitStyle, 16664 AccessSpecifier AS) { 16665 if (D.isDecompositionDeclarator()) { 16666 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16667 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16668 << Decomp.getSourceRange(); 16669 return nullptr; 16670 } 16671 16672 IdentifierInfo *II = D.getIdentifier(); 16673 SourceLocation Loc = DeclStart; 16674 if (II) Loc = D.getIdentifierLoc(); 16675 16676 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16677 QualType T = TInfo->getType(); 16678 if (getLangOpts().CPlusPlus) { 16679 CheckExtraCXXDefaultArguments(D); 16680 16681 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16682 UPPC_DataMemberType)) { 16683 D.setInvalidType(); 16684 T = Context.IntTy; 16685 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16686 } 16687 } 16688 16689 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16690 16691 if (D.getDeclSpec().isInlineSpecified()) 16692 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16693 << getLangOpts().CPlusPlus17; 16694 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16695 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16696 diag::err_invalid_thread) 16697 << DeclSpec::getSpecifierName(TSCS); 16698 16699 // Check to see if this name was declared as a member previously 16700 NamedDecl *PrevDecl = nullptr; 16701 LookupResult Previous(*this, II, Loc, LookupMemberName, 16702 ForVisibleRedeclaration); 16703 LookupName(Previous, S); 16704 switch (Previous.getResultKind()) { 16705 case LookupResult::Found: 16706 case LookupResult::FoundUnresolvedValue: 16707 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16708 break; 16709 16710 case LookupResult::FoundOverloaded: 16711 PrevDecl = Previous.getRepresentativeDecl(); 16712 break; 16713 16714 case LookupResult::NotFound: 16715 case LookupResult::NotFoundInCurrentInstantiation: 16716 case LookupResult::Ambiguous: 16717 break; 16718 } 16719 Previous.suppressDiagnostics(); 16720 16721 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16722 // Maybe we will complain about the shadowed template parameter. 16723 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16724 // Just pretend that we didn't see the previous declaration. 16725 PrevDecl = nullptr; 16726 } 16727 16728 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16729 PrevDecl = nullptr; 16730 16731 bool Mutable 16732 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16733 SourceLocation TSSL = D.getBeginLoc(); 16734 FieldDecl *NewFD 16735 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16736 TSSL, AS, PrevDecl, &D); 16737 16738 if (NewFD->isInvalidDecl()) 16739 Record->setInvalidDecl(); 16740 16741 if (D.getDeclSpec().isModulePrivateSpecified()) 16742 NewFD->setModulePrivate(); 16743 16744 if (NewFD->isInvalidDecl() && PrevDecl) { 16745 // Don't introduce NewFD into scope; there's already something 16746 // with the same name in the same scope. 16747 } else if (II) { 16748 PushOnScopeChains(NewFD, S); 16749 } else 16750 Record->addDecl(NewFD); 16751 16752 return NewFD; 16753 } 16754 16755 /// Build a new FieldDecl and check its well-formedness. 16756 /// 16757 /// This routine builds a new FieldDecl given the fields name, type, 16758 /// record, etc. \p PrevDecl should refer to any previous declaration 16759 /// with the same name and in the same scope as the field to be 16760 /// created. 16761 /// 16762 /// \returns a new FieldDecl. 16763 /// 16764 /// \todo The Declarator argument is a hack. It will be removed once 16765 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16766 TypeSourceInfo *TInfo, 16767 RecordDecl *Record, SourceLocation Loc, 16768 bool Mutable, Expr *BitWidth, 16769 InClassInitStyle InitStyle, 16770 SourceLocation TSSL, 16771 AccessSpecifier AS, NamedDecl *PrevDecl, 16772 Declarator *D) { 16773 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16774 bool InvalidDecl = false; 16775 if (D) InvalidDecl = D->isInvalidType(); 16776 16777 // If we receive a broken type, recover by assuming 'int' and 16778 // marking this declaration as invalid. 16779 if (T.isNull() || T->containsErrors()) { 16780 InvalidDecl = true; 16781 T = Context.IntTy; 16782 } 16783 16784 QualType EltTy = Context.getBaseElementType(T); 16785 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16786 if (RequireCompleteSizedType(Loc, EltTy, 16787 diag::err_field_incomplete_or_sizeless)) { 16788 // Fields of incomplete type force their record to be invalid. 16789 Record->setInvalidDecl(); 16790 InvalidDecl = true; 16791 } else { 16792 NamedDecl *Def; 16793 EltTy->isIncompleteType(&Def); 16794 if (Def && Def->isInvalidDecl()) { 16795 Record->setInvalidDecl(); 16796 InvalidDecl = true; 16797 } 16798 } 16799 } 16800 16801 // TR 18037 does not allow fields to be declared with address space 16802 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16803 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16804 Diag(Loc, diag::err_field_with_address_space); 16805 Record->setInvalidDecl(); 16806 InvalidDecl = true; 16807 } 16808 16809 if (LangOpts.OpenCL) { 16810 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16811 // used as structure or union field: image, sampler, event or block types. 16812 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16813 T->isBlockPointerType()) { 16814 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16815 Record->setInvalidDecl(); 16816 InvalidDecl = true; 16817 } 16818 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16819 if (BitWidth) { 16820 Diag(Loc, diag::err_opencl_bitfields); 16821 InvalidDecl = true; 16822 } 16823 } 16824 16825 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16826 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16827 T.hasQualifiers()) { 16828 InvalidDecl = true; 16829 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16830 } 16831 16832 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16833 // than a variably modified type. 16834 if (!InvalidDecl && T->isVariablyModifiedType()) { 16835 if (!tryToFixVariablyModifiedVarType( 16836 TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 16837 InvalidDecl = true; 16838 } 16839 16840 // Fields can not have abstract class types 16841 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16842 diag::err_abstract_type_in_decl, 16843 AbstractFieldType)) 16844 InvalidDecl = true; 16845 16846 bool ZeroWidth = false; 16847 if (InvalidDecl) 16848 BitWidth = nullptr; 16849 // If this is declared as a bit-field, check the bit-field. 16850 if (BitWidth) { 16851 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16852 &ZeroWidth).get(); 16853 if (!BitWidth) { 16854 InvalidDecl = true; 16855 BitWidth = nullptr; 16856 ZeroWidth = false; 16857 } 16858 } 16859 16860 // Check that 'mutable' is consistent with the type of the declaration. 16861 if (!InvalidDecl && Mutable) { 16862 unsigned DiagID = 0; 16863 if (T->isReferenceType()) 16864 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16865 : diag::err_mutable_reference; 16866 else if (T.isConstQualified()) 16867 DiagID = diag::err_mutable_const; 16868 16869 if (DiagID) { 16870 SourceLocation ErrLoc = Loc; 16871 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16872 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16873 Diag(ErrLoc, DiagID); 16874 if (DiagID != diag::ext_mutable_reference) { 16875 Mutable = false; 16876 InvalidDecl = true; 16877 } 16878 } 16879 } 16880 16881 // C++11 [class.union]p8 (DR1460): 16882 // At most one variant member of a union may have a 16883 // brace-or-equal-initializer. 16884 if (InitStyle != ICIS_NoInit) 16885 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16886 16887 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16888 BitWidth, Mutable, InitStyle); 16889 if (InvalidDecl) 16890 NewFD->setInvalidDecl(); 16891 16892 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16893 Diag(Loc, diag::err_duplicate_member) << II; 16894 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16895 NewFD->setInvalidDecl(); 16896 } 16897 16898 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16899 if (Record->isUnion()) { 16900 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16901 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16902 if (RDecl->getDefinition()) { 16903 // C++ [class.union]p1: An object of a class with a non-trivial 16904 // constructor, a non-trivial copy constructor, a non-trivial 16905 // destructor, or a non-trivial copy assignment operator 16906 // cannot be a member of a union, nor can an array of such 16907 // objects. 16908 if (CheckNontrivialField(NewFD)) 16909 NewFD->setInvalidDecl(); 16910 } 16911 } 16912 16913 // C++ [class.union]p1: If a union contains a member of reference type, 16914 // the program is ill-formed, except when compiling with MSVC extensions 16915 // enabled. 16916 if (EltTy->isReferenceType()) { 16917 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16918 diag::ext_union_member_of_reference_type : 16919 diag::err_union_member_of_reference_type) 16920 << NewFD->getDeclName() << EltTy; 16921 if (!getLangOpts().MicrosoftExt) 16922 NewFD->setInvalidDecl(); 16923 } 16924 } 16925 } 16926 16927 // FIXME: We need to pass in the attributes given an AST 16928 // representation, not a parser representation. 16929 if (D) { 16930 // FIXME: The current scope is almost... but not entirely... correct here. 16931 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16932 16933 if (NewFD->hasAttrs()) 16934 CheckAlignasUnderalignment(NewFD); 16935 } 16936 16937 // In auto-retain/release, infer strong retension for fields of 16938 // retainable type. 16939 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16940 NewFD->setInvalidDecl(); 16941 16942 if (T.isObjCGCWeak()) 16943 Diag(Loc, diag::warn_attribute_weak_on_field); 16944 16945 // PPC MMA non-pointer types are not allowed as field types. 16946 if (Context.getTargetInfo().getTriple().isPPC64() && 16947 CheckPPCMMAType(T, NewFD->getLocation())) 16948 NewFD->setInvalidDecl(); 16949 16950 NewFD->setAccess(AS); 16951 return NewFD; 16952 } 16953 16954 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16955 assert(FD); 16956 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16957 16958 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16959 return false; 16960 16961 QualType EltTy = Context.getBaseElementType(FD->getType()); 16962 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16963 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16964 if (RDecl->getDefinition()) { 16965 // We check for copy constructors before constructors 16966 // because otherwise we'll never get complaints about 16967 // copy constructors. 16968 16969 CXXSpecialMember member = CXXInvalid; 16970 // We're required to check for any non-trivial constructors. Since the 16971 // implicit default constructor is suppressed if there are any 16972 // user-declared constructors, we just need to check that there is a 16973 // trivial default constructor and a trivial copy constructor. (We don't 16974 // worry about move constructors here, since this is a C++98 check.) 16975 if (RDecl->hasNonTrivialCopyConstructor()) 16976 member = CXXCopyConstructor; 16977 else if (!RDecl->hasTrivialDefaultConstructor()) 16978 member = CXXDefaultConstructor; 16979 else if (RDecl->hasNonTrivialCopyAssignment()) 16980 member = CXXCopyAssignment; 16981 else if (RDecl->hasNonTrivialDestructor()) 16982 member = CXXDestructor; 16983 16984 if (member != CXXInvalid) { 16985 if (!getLangOpts().CPlusPlus11 && 16986 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16987 // Objective-C++ ARC: it is an error to have a non-trivial field of 16988 // a union. However, system headers in Objective-C programs 16989 // occasionally have Objective-C lifetime objects within unions, 16990 // and rather than cause the program to fail, we make those 16991 // members unavailable. 16992 SourceLocation Loc = FD->getLocation(); 16993 if (getSourceManager().isInSystemHeader(Loc)) { 16994 if (!FD->hasAttr<UnavailableAttr>()) 16995 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16996 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16997 return false; 16998 } 16999 } 17000 17001 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 17002 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 17003 diag::err_illegal_union_or_anon_struct_member) 17004 << FD->getParent()->isUnion() << FD->getDeclName() << member; 17005 DiagnoseNontrivial(RDecl, member); 17006 return !getLangOpts().CPlusPlus11; 17007 } 17008 } 17009 } 17010 17011 return false; 17012 } 17013 17014 /// TranslateIvarVisibility - Translate visibility from a token ID to an 17015 /// AST enum value. 17016 static ObjCIvarDecl::AccessControl 17017 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 17018 switch (ivarVisibility) { 17019 default: llvm_unreachable("Unknown visitibility kind"); 17020 case tok::objc_private: return ObjCIvarDecl::Private; 17021 case tok::objc_public: return ObjCIvarDecl::Public; 17022 case tok::objc_protected: return ObjCIvarDecl::Protected; 17023 case tok::objc_package: return ObjCIvarDecl::Package; 17024 } 17025 } 17026 17027 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 17028 /// in order to create an IvarDecl object for it. 17029 Decl *Sema::ActOnIvar(Scope *S, 17030 SourceLocation DeclStart, 17031 Declarator &D, Expr *BitfieldWidth, 17032 tok::ObjCKeywordKind Visibility) { 17033 17034 IdentifierInfo *II = D.getIdentifier(); 17035 Expr *BitWidth = (Expr*)BitfieldWidth; 17036 SourceLocation Loc = DeclStart; 17037 if (II) Loc = D.getIdentifierLoc(); 17038 17039 // FIXME: Unnamed fields can be handled in various different ways, for 17040 // example, unnamed unions inject all members into the struct namespace! 17041 17042 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17043 QualType T = TInfo->getType(); 17044 17045 if (BitWidth) { 17046 // 6.7.2.1p3, 6.7.2.1p4 17047 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 17048 if (!BitWidth) 17049 D.setInvalidType(); 17050 } else { 17051 // Not a bitfield. 17052 17053 // validate II. 17054 17055 } 17056 if (T->isReferenceType()) { 17057 Diag(Loc, diag::err_ivar_reference_type); 17058 D.setInvalidType(); 17059 } 17060 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17061 // than a variably modified type. 17062 else if (T->isVariablyModifiedType()) { 17063 if (!tryToFixVariablyModifiedVarType( 17064 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 17065 D.setInvalidType(); 17066 } 17067 17068 // Get the visibility (access control) for this ivar. 17069 ObjCIvarDecl::AccessControl ac = 17070 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 17071 : ObjCIvarDecl::None; 17072 // Must set ivar's DeclContext to its enclosing interface. 17073 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 17074 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 17075 return nullptr; 17076 ObjCContainerDecl *EnclosingContext; 17077 if (ObjCImplementationDecl *IMPDecl = 17078 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17079 if (LangOpts.ObjCRuntime.isFragile()) { 17080 // Case of ivar declared in an implementation. Context is that of its class. 17081 EnclosingContext = IMPDecl->getClassInterface(); 17082 assert(EnclosingContext && "Implementation has no class interface!"); 17083 } 17084 else 17085 EnclosingContext = EnclosingDecl; 17086 } else { 17087 if (ObjCCategoryDecl *CDecl = 17088 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17089 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 17090 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 17091 return nullptr; 17092 } 17093 } 17094 EnclosingContext = EnclosingDecl; 17095 } 17096 17097 // Construct the decl. 17098 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 17099 DeclStart, Loc, II, T, 17100 TInfo, ac, (Expr *)BitfieldWidth); 17101 17102 if (II) { 17103 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 17104 ForVisibleRedeclaration); 17105 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 17106 && !isa<TagDecl>(PrevDecl)) { 17107 Diag(Loc, diag::err_duplicate_member) << II; 17108 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17109 NewID->setInvalidDecl(); 17110 } 17111 } 17112 17113 // Process attributes attached to the ivar. 17114 ProcessDeclAttributes(S, NewID, D); 17115 17116 if (D.isInvalidType()) 17117 NewID->setInvalidDecl(); 17118 17119 // In ARC, infer 'retaining' for ivars of retainable type. 17120 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 17121 NewID->setInvalidDecl(); 17122 17123 if (D.getDeclSpec().isModulePrivateSpecified()) 17124 NewID->setModulePrivate(); 17125 17126 if (II) { 17127 // FIXME: When interfaces are DeclContexts, we'll need to add 17128 // these to the interface. 17129 S->AddDecl(NewID); 17130 IdResolver.AddDecl(NewID); 17131 } 17132 17133 if (LangOpts.ObjCRuntime.isNonFragile() && 17134 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17135 Diag(Loc, diag::warn_ivars_in_interface); 17136 17137 return NewID; 17138 } 17139 17140 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17141 /// class and class extensions. For every class \@interface and class 17142 /// extension \@interface, if the last ivar is a bitfield of any type, 17143 /// then add an implicit `char :0` ivar to the end of that interface. 17144 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17145 SmallVectorImpl<Decl *> &AllIvarDecls) { 17146 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17147 return; 17148 17149 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17150 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17151 17152 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17153 return; 17154 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17155 if (!ID) { 17156 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17157 if (!CD->IsClassExtension()) 17158 return; 17159 } 17160 // No need to add this to end of @implementation. 17161 else 17162 return; 17163 } 17164 // All conditions are met. Add a new bitfield to the tail end of ivars. 17165 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17166 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17167 17168 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17169 DeclLoc, DeclLoc, nullptr, 17170 Context.CharTy, 17171 Context.getTrivialTypeSourceInfo(Context.CharTy, 17172 DeclLoc), 17173 ObjCIvarDecl::Private, BW, 17174 true); 17175 AllIvarDecls.push_back(Ivar); 17176 } 17177 17178 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17179 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17180 SourceLocation RBrac, 17181 const ParsedAttributesView &Attrs) { 17182 assert(EnclosingDecl && "missing record or interface decl"); 17183 17184 // If this is an Objective-C @implementation or category and we have 17185 // new fields here we should reset the layout of the interface since 17186 // it will now change. 17187 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17188 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17189 switch (DC->getKind()) { 17190 default: break; 17191 case Decl::ObjCCategory: 17192 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17193 break; 17194 case Decl::ObjCImplementation: 17195 Context. 17196 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17197 break; 17198 } 17199 } 17200 17201 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17202 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17203 17204 // Start counting up the number of named members; make sure to include 17205 // members of anonymous structs and unions in the total. 17206 unsigned NumNamedMembers = 0; 17207 if (Record) { 17208 for (const auto *I : Record->decls()) { 17209 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17210 if (IFD->getDeclName()) 17211 ++NumNamedMembers; 17212 } 17213 } 17214 17215 // Verify that all the fields are okay. 17216 SmallVector<FieldDecl*, 32> RecFields; 17217 17218 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17219 i != end; ++i) { 17220 FieldDecl *FD = cast<FieldDecl>(*i); 17221 17222 // Get the type for the field. 17223 const Type *FDTy = FD->getType().getTypePtr(); 17224 17225 if (!FD->isAnonymousStructOrUnion()) { 17226 // Remember all fields written by the user. 17227 RecFields.push_back(FD); 17228 } 17229 17230 // If the field is already invalid for some reason, don't emit more 17231 // diagnostics about it. 17232 if (FD->isInvalidDecl()) { 17233 EnclosingDecl->setInvalidDecl(); 17234 continue; 17235 } 17236 17237 // C99 6.7.2.1p2: 17238 // A structure or union shall not contain a member with 17239 // incomplete or function type (hence, a structure shall not 17240 // contain an instance of itself, but may contain a pointer to 17241 // an instance of itself), except that the last member of a 17242 // structure with more than one named member may have incomplete 17243 // array type; such a structure (and any union containing, 17244 // possibly recursively, a member that is such a structure) 17245 // shall not be a member of a structure or an element of an 17246 // array. 17247 bool IsLastField = (i + 1 == Fields.end()); 17248 if (FDTy->isFunctionType()) { 17249 // Field declared as a function. 17250 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17251 << FD->getDeclName(); 17252 FD->setInvalidDecl(); 17253 EnclosingDecl->setInvalidDecl(); 17254 continue; 17255 } else if (FDTy->isIncompleteArrayType() && 17256 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17257 if (Record) { 17258 // Flexible array member. 17259 // Microsoft and g++ is more permissive regarding flexible array. 17260 // It will accept flexible array in union and also 17261 // as the sole element of a struct/class. 17262 unsigned DiagID = 0; 17263 if (!Record->isUnion() && !IsLastField) { 17264 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17265 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17266 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17267 FD->setInvalidDecl(); 17268 EnclosingDecl->setInvalidDecl(); 17269 continue; 17270 } else if (Record->isUnion()) 17271 DiagID = getLangOpts().MicrosoftExt 17272 ? diag::ext_flexible_array_union_ms 17273 : getLangOpts().CPlusPlus 17274 ? diag::ext_flexible_array_union_gnu 17275 : diag::err_flexible_array_union; 17276 else if (NumNamedMembers < 1) 17277 DiagID = getLangOpts().MicrosoftExt 17278 ? diag::ext_flexible_array_empty_aggregate_ms 17279 : getLangOpts().CPlusPlus 17280 ? diag::ext_flexible_array_empty_aggregate_gnu 17281 : diag::err_flexible_array_empty_aggregate; 17282 17283 if (DiagID) 17284 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17285 << Record->getTagKind(); 17286 // While the layout of types that contain virtual bases is not specified 17287 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17288 // virtual bases after the derived members. This would make a flexible 17289 // array member declared at the end of an object not adjacent to the end 17290 // of the type. 17291 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17292 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17293 << FD->getDeclName() << Record->getTagKind(); 17294 if (!getLangOpts().C99) 17295 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17296 << FD->getDeclName() << Record->getTagKind(); 17297 17298 // If the element type has a non-trivial destructor, we would not 17299 // implicitly destroy the elements, so disallow it for now. 17300 // 17301 // FIXME: GCC allows this. We should probably either implicitly delete 17302 // the destructor of the containing class, or just allow this. 17303 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17304 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17305 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17306 << FD->getDeclName() << FD->getType(); 17307 FD->setInvalidDecl(); 17308 EnclosingDecl->setInvalidDecl(); 17309 continue; 17310 } 17311 // Okay, we have a legal flexible array member at the end of the struct. 17312 Record->setHasFlexibleArrayMember(true); 17313 } else { 17314 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17315 // unless they are followed by another ivar. That check is done 17316 // elsewhere, after synthesized ivars are known. 17317 } 17318 } else if (!FDTy->isDependentType() && 17319 RequireCompleteSizedType( 17320 FD->getLocation(), FD->getType(), 17321 diag::err_field_incomplete_or_sizeless)) { 17322 // Incomplete type 17323 FD->setInvalidDecl(); 17324 EnclosingDecl->setInvalidDecl(); 17325 continue; 17326 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17327 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17328 // A type which contains a flexible array member is considered to be a 17329 // flexible array member. 17330 Record->setHasFlexibleArrayMember(true); 17331 if (!Record->isUnion()) { 17332 // If this is a struct/class and this is not the last element, reject 17333 // it. Note that GCC supports variable sized arrays in the middle of 17334 // structures. 17335 if (!IsLastField) 17336 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17337 << FD->getDeclName() << FD->getType(); 17338 else { 17339 // We support flexible arrays at the end of structs in 17340 // other structs as an extension. 17341 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17342 << FD->getDeclName(); 17343 } 17344 } 17345 } 17346 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17347 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17348 diag::err_abstract_type_in_decl, 17349 AbstractIvarType)) { 17350 // Ivars can not have abstract class types 17351 FD->setInvalidDecl(); 17352 } 17353 if (Record && FDTTy->getDecl()->hasObjectMember()) 17354 Record->setHasObjectMember(true); 17355 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17356 Record->setHasVolatileMember(true); 17357 } else if (FDTy->isObjCObjectType()) { 17358 /// A field cannot be an Objective-c object 17359 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17360 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17361 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17362 FD->setType(T); 17363 } else if (Record && Record->isUnion() && 17364 FD->getType().hasNonTrivialObjCLifetime() && 17365 getSourceManager().isInSystemHeader(FD->getLocation()) && 17366 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17367 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17368 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17369 // For backward compatibility, fields of C unions declared in system 17370 // headers that have non-trivial ObjC ownership qualifications are marked 17371 // as unavailable unless the qualifier is explicit and __strong. This can 17372 // break ABI compatibility between programs compiled with ARC and MRR, but 17373 // is a better option than rejecting programs using those unions under 17374 // ARC. 17375 FD->addAttr(UnavailableAttr::CreateImplicit( 17376 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17377 FD->getLocation())); 17378 } else if (getLangOpts().ObjC && 17379 getLangOpts().getGC() != LangOptions::NonGC && Record && 17380 !Record->hasObjectMember()) { 17381 if (FD->getType()->isObjCObjectPointerType() || 17382 FD->getType().isObjCGCStrong()) 17383 Record->setHasObjectMember(true); 17384 else if (Context.getAsArrayType(FD->getType())) { 17385 QualType BaseType = Context.getBaseElementType(FD->getType()); 17386 if (BaseType->isRecordType() && 17387 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17388 Record->setHasObjectMember(true); 17389 else if (BaseType->isObjCObjectPointerType() || 17390 BaseType.isObjCGCStrong()) 17391 Record->setHasObjectMember(true); 17392 } 17393 } 17394 17395 if (Record && !getLangOpts().CPlusPlus && 17396 !shouldIgnoreForRecordTriviality(FD)) { 17397 QualType FT = FD->getType(); 17398 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17399 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17400 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17401 Record->isUnion()) 17402 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17403 } 17404 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17405 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17406 Record->setNonTrivialToPrimitiveCopy(true); 17407 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17408 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17409 } 17410 if (FT.isDestructedType()) { 17411 Record->setNonTrivialToPrimitiveDestroy(true); 17412 Record->setParamDestroyedInCallee(true); 17413 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17414 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17415 } 17416 17417 if (const auto *RT = FT->getAs<RecordType>()) { 17418 if (RT->getDecl()->getArgPassingRestrictions() == 17419 RecordDecl::APK_CanNeverPassInRegs) 17420 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17421 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17422 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17423 } 17424 17425 if (Record && FD->getType().isVolatileQualified()) 17426 Record->setHasVolatileMember(true); 17427 // Keep track of the number of named members. 17428 if (FD->getIdentifier()) 17429 ++NumNamedMembers; 17430 } 17431 17432 // Okay, we successfully defined 'Record'. 17433 if (Record) { 17434 bool Completed = false; 17435 if (CXXRecord) { 17436 if (!CXXRecord->isInvalidDecl()) { 17437 // Set access bits correctly on the directly-declared conversions. 17438 for (CXXRecordDecl::conversion_iterator 17439 I = CXXRecord->conversion_begin(), 17440 E = CXXRecord->conversion_end(); I != E; ++I) 17441 I.setAccess((*I)->getAccess()); 17442 } 17443 17444 // Add any implicitly-declared members to this class. 17445 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17446 17447 if (!CXXRecord->isDependentType()) { 17448 if (!CXXRecord->isInvalidDecl()) { 17449 // If we have virtual base classes, we may end up finding multiple 17450 // final overriders for a given virtual function. Check for this 17451 // problem now. 17452 if (CXXRecord->getNumVBases()) { 17453 CXXFinalOverriderMap FinalOverriders; 17454 CXXRecord->getFinalOverriders(FinalOverriders); 17455 17456 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17457 MEnd = FinalOverriders.end(); 17458 M != MEnd; ++M) { 17459 for (OverridingMethods::iterator SO = M->second.begin(), 17460 SOEnd = M->second.end(); 17461 SO != SOEnd; ++SO) { 17462 assert(SO->second.size() > 0 && 17463 "Virtual function without overriding functions?"); 17464 if (SO->second.size() == 1) 17465 continue; 17466 17467 // C++ [class.virtual]p2: 17468 // In a derived class, if a virtual member function of a base 17469 // class subobject has more than one final overrider the 17470 // program is ill-formed. 17471 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17472 << (const NamedDecl *)M->first << Record; 17473 Diag(M->first->getLocation(), 17474 diag::note_overridden_virtual_function); 17475 for (OverridingMethods::overriding_iterator 17476 OM = SO->second.begin(), 17477 OMEnd = SO->second.end(); 17478 OM != OMEnd; ++OM) 17479 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17480 << (const NamedDecl *)M->first << OM->Method->getParent(); 17481 17482 Record->setInvalidDecl(); 17483 } 17484 } 17485 CXXRecord->completeDefinition(&FinalOverriders); 17486 Completed = true; 17487 } 17488 } 17489 } 17490 } 17491 17492 if (!Completed) 17493 Record->completeDefinition(); 17494 17495 // Handle attributes before checking the layout. 17496 ProcessDeclAttributeList(S, Record, Attrs); 17497 17498 // We may have deferred checking for a deleted destructor. Check now. 17499 if (CXXRecord) { 17500 auto *Dtor = CXXRecord->getDestructor(); 17501 if (Dtor && Dtor->isImplicit() && 17502 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17503 CXXRecord->setImplicitDestructorIsDeleted(); 17504 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17505 } 17506 } 17507 17508 if (Record->hasAttrs()) { 17509 CheckAlignasUnderalignment(Record); 17510 17511 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17512 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17513 IA->getRange(), IA->getBestCase(), 17514 IA->getInheritanceModel()); 17515 } 17516 17517 // Check if the structure/union declaration is a type that can have zero 17518 // size in C. For C this is a language extension, for C++ it may cause 17519 // compatibility problems. 17520 bool CheckForZeroSize; 17521 if (!getLangOpts().CPlusPlus) { 17522 CheckForZeroSize = true; 17523 } else { 17524 // For C++ filter out types that cannot be referenced in C code. 17525 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17526 CheckForZeroSize = 17527 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17528 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 17529 CXXRecord->isCLike(); 17530 } 17531 if (CheckForZeroSize) { 17532 bool ZeroSize = true; 17533 bool IsEmpty = true; 17534 unsigned NonBitFields = 0; 17535 for (RecordDecl::field_iterator I = Record->field_begin(), 17536 E = Record->field_end(); 17537 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17538 IsEmpty = false; 17539 if (I->isUnnamedBitfield()) { 17540 if (!I->isZeroLengthBitField(Context)) 17541 ZeroSize = false; 17542 } else { 17543 ++NonBitFields; 17544 QualType FieldType = I->getType(); 17545 if (FieldType->isIncompleteType() || 17546 !Context.getTypeSizeInChars(FieldType).isZero()) 17547 ZeroSize = false; 17548 } 17549 } 17550 17551 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17552 // allowed in C++, but warn if its declaration is inside 17553 // extern "C" block. 17554 if (ZeroSize) { 17555 Diag(RecLoc, getLangOpts().CPlusPlus ? 17556 diag::warn_zero_size_struct_union_in_extern_c : 17557 diag::warn_zero_size_struct_union_compat) 17558 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17559 } 17560 17561 // Structs without named members are extension in C (C99 6.7.2.1p7), 17562 // but are accepted by GCC. 17563 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17564 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17565 diag::ext_no_named_members_in_struct_union) 17566 << Record->isUnion(); 17567 } 17568 } 17569 } else { 17570 ObjCIvarDecl **ClsFields = 17571 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17572 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17573 ID->setEndOfDefinitionLoc(RBrac); 17574 // Add ivar's to class's DeclContext. 17575 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17576 ClsFields[i]->setLexicalDeclContext(ID); 17577 ID->addDecl(ClsFields[i]); 17578 } 17579 // Must enforce the rule that ivars in the base classes may not be 17580 // duplicates. 17581 if (ID->getSuperClass()) 17582 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17583 } else if (ObjCImplementationDecl *IMPDecl = 17584 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17585 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17586 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17587 // Ivar declared in @implementation never belongs to the implementation. 17588 // Only it is in implementation's lexical context. 17589 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17590 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17591 IMPDecl->setIvarLBraceLoc(LBrac); 17592 IMPDecl->setIvarRBraceLoc(RBrac); 17593 } else if (ObjCCategoryDecl *CDecl = 17594 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17595 // case of ivars in class extension; all other cases have been 17596 // reported as errors elsewhere. 17597 // FIXME. Class extension does not have a LocEnd field. 17598 // CDecl->setLocEnd(RBrac); 17599 // Add ivar's to class extension's DeclContext. 17600 // Diagnose redeclaration of private ivars. 17601 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17602 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17603 if (IDecl) { 17604 if (const ObjCIvarDecl *ClsIvar = 17605 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17606 Diag(ClsFields[i]->getLocation(), 17607 diag::err_duplicate_ivar_declaration); 17608 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17609 continue; 17610 } 17611 for (const auto *Ext : IDecl->known_extensions()) { 17612 if (const ObjCIvarDecl *ClsExtIvar 17613 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17614 Diag(ClsFields[i]->getLocation(), 17615 diag::err_duplicate_ivar_declaration); 17616 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17617 continue; 17618 } 17619 } 17620 } 17621 ClsFields[i]->setLexicalDeclContext(CDecl); 17622 CDecl->addDecl(ClsFields[i]); 17623 } 17624 CDecl->setIvarLBraceLoc(LBrac); 17625 CDecl->setIvarRBraceLoc(RBrac); 17626 } 17627 } 17628 } 17629 17630 /// Determine whether the given integral value is representable within 17631 /// the given type T. 17632 static bool isRepresentableIntegerValue(ASTContext &Context, 17633 llvm::APSInt &Value, 17634 QualType T) { 17635 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17636 "Integral type required!"); 17637 unsigned BitWidth = Context.getIntWidth(T); 17638 17639 if (Value.isUnsigned() || Value.isNonNegative()) { 17640 if (T->isSignedIntegerOrEnumerationType()) 17641 --BitWidth; 17642 return Value.getActiveBits() <= BitWidth; 17643 } 17644 return Value.getMinSignedBits() <= BitWidth; 17645 } 17646 17647 // Given an integral type, return the next larger integral type 17648 // (or a NULL type of no such type exists). 17649 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17650 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17651 // enum checking below. 17652 assert((T->isIntegralType(Context) || 17653 T->isEnumeralType()) && "Integral type required!"); 17654 const unsigned NumTypes = 4; 17655 QualType SignedIntegralTypes[NumTypes] = { 17656 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17657 }; 17658 QualType UnsignedIntegralTypes[NumTypes] = { 17659 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17660 Context.UnsignedLongLongTy 17661 }; 17662 17663 unsigned BitWidth = Context.getTypeSize(T); 17664 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17665 : UnsignedIntegralTypes; 17666 for (unsigned I = 0; I != NumTypes; ++I) 17667 if (Context.getTypeSize(Types[I]) > BitWidth) 17668 return Types[I]; 17669 17670 return QualType(); 17671 } 17672 17673 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17674 EnumConstantDecl *LastEnumConst, 17675 SourceLocation IdLoc, 17676 IdentifierInfo *Id, 17677 Expr *Val) { 17678 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17679 llvm::APSInt EnumVal(IntWidth); 17680 QualType EltTy; 17681 17682 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17683 Val = nullptr; 17684 17685 if (Val) 17686 Val = DefaultLvalueConversion(Val).get(); 17687 17688 if (Val) { 17689 if (Enum->isDependentType() || Val->isTypeDependent()) 17690 EltTy = Context.DependentTy; 17691 else { 17692 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 17693 // underlying type, but do allow it in all other contexts. 17694 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17695 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17696 // constant-expression in the enumerator-definition shall be a converted 17697 // constant expression of the underlying type. 17698 EltTy = Enum->getIntegerType(); 17699 ExprResult Converted = 17700 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17701 CCEK_Enumerator); 17702 if (Converted.isInvalid()) 17703 Val = nullptr; 17704 else 17705 Val = Converted.get(); 17706 } else if (!Val->isValueDependent() && 17707 !(Val = 17708 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 17709 .get())) { 17710 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17711 } else { 17712 if (Enum->isComplete()) { 17713 EltTy = Enum->getIntegerType(); 17714 17715 // In Obj-C and Microsoft mode, require the enumeration value to be 17716 // representable in the underlying type of the enumeration. In C++11, 17717 // we perform a non-narrowing conversion as part of converted constant 17718 // expression checking. 17719 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17720 if (Context.getTargetInfo() 17721 .getTriple() 17722 .isWindowsMSVCEnvironment()) { 17723 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17724 } else { 17725 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17726 } 17727 } 17728 17729 // Cast to the underlying type. 17730 Val = ImpCastExprToType(Val, EltTy, 17731 EltTy->isBooleanType() ? CK_IntegralToBoolean 17732 : CK_IntegralCast) 17733 .get(); 17734 } else if (getLangOpts().CPlusPlus) { 17735 // C++11 [dcl.enum]p5: 17736 // If the underlying type is not fixed, the type of each enumerator 17737 // is the type of its initializing value: 17738 // - If an initializer is specified for an enumerator, the 17739 // initializing value has the same type as the expression. 17740 EltTy = Val->getType(); 17741 } else { 17742 // C99 6.7.2.2p2: 17743 // The expression that defines the value of an enumeration constant 17744 // shall be an integer constant expression that has a value 17745 // representable as an int. 17746 17747 // Complain if the value is not representable in an int. 17748 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17749 Diag(IdLoc, diag::ext_enum_value_not_int) 17750 << EnumVal.toString(10) << Val->getSourceRange() 17751 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17752 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17753 // Force the type of the expression to 'int'. 17754 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17755 } 17756 EltTy = Val->getType(); 17757 } 17758 } 17759 } 17760 } 17761 17762 if (!Val) { 17763 if (Enum->isDependentType()) 17764 EltTy = Context.DependentTy; 17765 else if (!LastEnumConst) { 17766 // C++0x [dcl.enum]p5: 17767 // If the underlying type is not fixed, the type of each enumerator 17768 // is the type of its initializing value: 17769 // - If no initializer is specified for the first enumerator, the 17770 // initializing value has an unspecified integral type. 17771 // 17772 // GCC uses 'int' for its unspecified integral type, as does 17773 // C99 6.7.2.2p3. 17774 if (Enum->isFixed()) { 17775 EltTy = Enum->getIntegerType(); 17776 } 17777 else { 17778 EltTy = Context.IntTy; 17779 } 17780 } else { 17781 // Assign the last value + 1. 17782 EnumVal = LastEnumConst->getInitVal(); 17783 ++EnumVal; 17784 EltTy = LastEnumConst->getType(); 17785 17786 // Check for overflow on increment. 17787 if (EnumVal < LastEnumConst->getInitVal()) { 17788 // C++0x [dcl.enum]p5: 17789 // If the underlying type is not fixed, the type of each enumerator 17790 // is the type of its initializing value: 17791 // 17792 // - Otherwise the type of the initializing value is the same as 17793 // the type of the initializing value of the preceding enumerator 17794 // unless the incremented value is not representable in that type, 17795 // in which case the type is an unspecified integral type 17796 // sufficient to contain the incremented value. If no such type 17797 // exists, the program is ill-formed. 17798 QualType T = getNextLargerIntegralType(Context, EltTy); 17799 if (T.isNull() || Enum->isFixed()) { 17800 // There is no integral type larger enough to represent this 17801 // value. Complain, then allow the value to wrap around. 17802 EnumVal = LastEnumConst->getInitVal(); 17803 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17804 ++EnumVal; 17805 if (Enum->isFixed()) 17806 // When the underlying type is fixed, this is ill-formed. 17807 Diag(IdLoc, diag::err_enumerator_wrapped) 17808 << EnumVal.toString(10) 17809 << EltTy; 17810 else 17811 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17812 << EnumVal.toString(10); 17813 } else { 17814 EltTy = T; 17815 } 17816 17817 // Retrieve the last enumerator's value, extent that type to the 17818 // type that is supposed to be large enough to represent the incremented 17819 // value, then increment. 17820 EnumVal = LastEnumConst->getInitVal(); 17821 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17822 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17823 ++EnumVal; 17824 17825 // If we're not in C++, diagnose the overflow of enumerator values, 17826 // which in C99 means that the enumerator value is not representable in 17827 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17828 // permits enumerator values that are representable in some larger 17829 // integral type. 17830 if (!getLangOpts().CPlusPlus && !T.isNull()) 17831 Diag(IdLoc, diag::warn_enum_value_overflow); 17832 } else if (!getLangOpts().CPlusPlus && 17833 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17834 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17835 Diag(IdLoc, diag::ext_enum_value_not_int) 17836 << EnumVal.toString(10) << 1; 17837 } 17838 } 17839 } 17840 17841 if (!EltTy->isDependentType()) { 17842 // Make the enumerator value match the signedness and size of the 17843 // enumerator's type. 17844 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17845 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17846 } 17847 17848 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17849 Val, EnumVal); 17850 } 17851 17852 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17853 SourceLocation IILoc) { 17854 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17855 !getLangOpts().CPlusPlus) 17856 return SkipBodyInfo(); 17857 17858 // We have an anonymous enum definition. Look up the first enumerator to 17859 // determine if we should merge the definition with an existing one and 17860 // skip the body. 17861 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17862 forRedeclarationInCurContext()); 17863 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17864 if (!PrevECD) 17865 return SkipBodyInfo(); 17866 17867 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17868 NamedDecl *Hidden; 17869 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17870 SkipBodyInfo Skip; 17871 Skip.Previous = Hidden; 17872 return Skip; 17873 } 17874 17875 return SkipBodyInfo(); 17876 } 17877 17878 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17879 SourceLocation IdLoc, IdentifierInfo *Id, 17880 const ParsedAttributesView &Attrs, 17881 SourceLocation EqualLoc, Expr *Val) { 17882 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17883 EnumConstantDecl *LastEnumConst = 17884 cast_or_null<EnumConstantDecl>(lastEnumConst); 17885 17886 // The scope passed in may not be a decl scope. Zip up the scope tree until 17887 // we find one that is. 17888 S = getNonFieldDeclScope(S); 17889 17890 // Verify that there isn't already something declared with this name in this 17891 // scope. 17892 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17893 LookupName(R, S); 17894 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17895 17896 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17897 // Maybe we will complain about the shadowed template parameter. 17898 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17899 // Just pretend that we didn't see the previous declaration. 17900 PrevDecl = nullptr; 17901 } 17902 17903 // C++ [class.mem]p15: 17904 // If T is the name of a class, then each of the following shall have a name 17905 // different from T: 17906 // - every enumerator of every member of class T that is an unscoped 17907 // enumerated type 17908 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17909 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17910 DeclarationNameInfo(Id, IdLoc)); 17911 17912 EnumConstantDecl *New = 17913 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17914 if (!New) 17915 return nullptr; 17916 17917 if (PrevDecl) { 17918 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17919 // Check for other kinds of shadowing not already handled. 17920 CheckShadow(New, PrevDecl, R); 17921 } 17922 17923 // When in C++, we may get a TagDecl with the same name; in this case the 17924 // enum constant will 'hide' the tag. 17925 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17926 "Received TagDecl when not in C++!"); 17927 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17928 if (isa<EnumConstantDecl>(PrevDecl)) 17929 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17930 else 17931 Diag(IdLoc, diag::err_redefinition) << Id; 17932 notePreviousDefinition(PrevDecl, IdLoc); 17933 return nullptr; 17934 } 17935 } 17936 17937 // Process attributes. 17938 ProcessDeclAttributeList(S, New, Attrs); 17939 AddPragmaAttributes(S, New); 17940 17941 // Register this decl in the current scope stack. 17942 New->setAccess(TheEnumDecl->getAccess()); 17943 PushOnScopeChains(New, S); 17944 17945 ActOnDocumentableDecl(New); 17946 17947 return New; 17948 } 17949 17950 // Returns true when the enum initial expression does not trigger the 17951 // duplicate enum warning. A few common cases are exempted as follows: 17952 // Element2 = Element1 17953 // Element2 = Element1 + 1 17954 // Element2 = Element1 - 1 17955 // Where Element2 and Element1 are from the same enum. 17956 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17957 Expr *InitExpr = ECD->getInitExpr(); 17958 if (!InitExpr) 17959 return true; 17960 InitExpr = InitExpr->IgnoreImpCasts(); 17961 17962 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17963 if (!BO->isAdditiveOp()) 17964 return true; 17965 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17966 if (!IL) 17967 return true; 17968 if (IL->getValue() != 1) 17969 return true; 17970 17971 InitExpr = BO->getLHS(); 17972 } 17973 17974 // This checks if the elements are from the same enum. 17975 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17976 if (!DRE) 17977 return true; 17978 17979 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17980 if (!EnumConstant) 17981 return true; 17982 17983 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17984 Enum) 17985 return true; 17986 17987 return false; 17988 } 17989 17990 // Emits a warning when an element is implicitly set a value that 17991 // a previous element has already been set to. 17992 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17993 EnumDecl *Enum, QualType EnumType) { 17994 // Avoid anonymous enums 17995 if (!Enum->getIdentifier()) 17996 return; 17997 17998 // Only check for small enums. 17999 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 18000 return; 18001 18002 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 18003 return; 18004 18005 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 18006 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 18007 18008 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 18009 18010 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 18011 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 18012 18013 // Use int64_t as a key to avoid needing special handling for map keys. 18014 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 18015 llvm::APSInt Val = D->getInitVal(); 18016 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 18017 }; 18018 18019 DuplicatesVector DupVector; 18020 ValueToVectorMap EnumMap; 18021 18022 // Populate the EnumMap with all values represented by enum constants without 18023 // an initializer. 18024 for (auto *Element : Elements) { 18025 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 18026 18027 // Null EnumConstantDecl means a previous diagnostic has been emitted for 18028 // this constant. Skip this enum since it may be ill-formed. 18029 if (!ECD) { 18030 return; 18031 } 18032 18033 // Constants with initalizers are handled in the next loop. 18034 if (ECD->getInitExpr()) 18035 continue; 18036 18037 // Duplicate values are handled in the next loop. 18038 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 18039 } 18040 18041 if (EnumMap.size() == 0) 18042 return; 18043 18044 // Create vectors for any values that has duplicates. 18045 for (auto *Element : Elements) { 18046 // The last loop returned if any constant was null. 18047 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 18048 if (!ValidDuplicateEnum(ECD, Enum)) 18049 continue; 18050 18051 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 18052 if (Iter == EnumMap.end()) 18053 continue; 18054 18055 DeclOrVector& Entry = Iter->second; 18056 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 18057 // Ensure constants are different. 18058 if (D == ECD) 18059 continue; 18060 18061 // Create new vector and push values onto it. 18062 auto Vec = std::make_unique<ECDVector>(); 18063 Vec->push_back(D); 18064 Vec->push_back(ECD); 18065 18066 // Update entry to point to the duplicates vector. 18067 Entry = Vec.get(); 18068 18069 // Store the vector somewhere we can consult later for quick emission of 18070 // diagnostics. 18071 DupVector.emplace_back(std::move(Vec)); 18072 continue; 18073 } 18074 18075 ECDVector *Vec = Entry.get<ECDVector*>(); 18076 // Make sure constants are not added more than once. 18077 if (*Vec->begin() == ECD) 18078 continue; 18079 18080 Vec->push_back(ECD); 18081 } 18082 18083 // Emit diagnostics. 18084 for (const auto &Vec : DupVector) { 18085 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 18086 18087 // Emit warning for one enum constant. 18088 auto *FirstECD = Vec->front(); 18089 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 18090 << FirstECD << FirstECD->getInitVal().toString(10) 18091 << FirstECD->getSourceRange(); 18092 18093 // Emit one note for each of the remaining enum constants with 18094 // the same value. 18095 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 18096 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 18097 << ECD << ECD->getInitVal().toString(10) 18098 << ECD->getSourceRange(); 18099 } 18100 } 18101 18102 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 18103 bool AllowMask) const { 18104 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 18105 assert(ED->isCompleteDefinition() && "expected enum definition"); 18106 18107 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 18108 llvm::APInt &FlagBits = R.first->second; 18109 18110 if (R.second) { 18111 for (auto *E : ED->enumerators()) { 18112 const auto &EVal = E->getInitVal(); 18113 // Only single-bit enumerators introduce new flag values. 18114 if (EVal.isPowerOf2()) 18115 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 18116 } 18117 } 18118 18119 // A value is in a flag enum if either its bits are a subset of the enum's 18120 // flag bits (the first condition) or we are allowing masks and the same is 18121 // true of its complement (the second condition). When masks are allowed, we 18122 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 18123 // 18124 // While it's true that any value could be used as a mask, the assumption is 18125 // that a mask will have all of the insignificant bits set. Anything else is 18126 // likely a logic error. 18127 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18128 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18129 } 18130 18131 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18132 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18133 const ParsedAttributesView &Attrs) { 18134 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18135 QualType EnumType = Context.getTypeDeclType(Enum); 18136 18137 ProcessDeclAttributeList(S, Enum, Attrs); 18138 18139 if (Enum->isDependentType()) { 18140 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18141 EnumConstantDecl *ECD = 18142 cast_or_null<EnumConstantDecl>(Elements[i]); 18143 if (!ECD) continue; 18144 18145 ECD->setType(EnumType); 18146 } 18147 18148 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18149 return; 18150 } 18151 18152 // TODO: If the result value doesn't fit in an int, it must be a long or long 18153 // long value. ISO C does not support this, but GCC does as an extension, 18154 // emit a warning. 18155 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18156 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18157 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18158 18159 // Verify that all the values are okay, compute the size of the values, and 18160 // reverse the list. 18161 unsigned NumNegativeBits = 0; 18162 unsigned NumPositiveBits = 0; 18163 18164 // Keep track of whether all elements have type int. 18165 bool AllElementsInt = true; 18166 18167 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18168 EnumConstantDecl *ECD = 18169 cast_or_null<EnumConstantDecl>(Elements[i]); 18170 if (!ECD) continue; // Already issued a diagnostic. 18171 18172 const llvm::APSInt &InitVal = ECD->getInitVal(); 18173 18174 // Keep track of the size of positive and negative values. 18175 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18176 NumPositiveBits = std::max(NumPositiveBits, 18177 (unsigned)InitVal.getActiveBits()); 18178 else 18179 NumNegativeBits = std::max(NumNegativeBits, 18180 (unsigned)InitVal.getMinSignedBits()); 18181 18182 // Keep track of whether every enum element has type int (very common). 18183 if (AllElementsInt) 18184 AllElementsInt = ECD->getType() == Context.IntTy; 18185 } 18186 18187 // Figure out the type that should be used for this enum. 18188 QualType BestType; 18189 unsigned BestWidth; 18190 18191 // C++0x N3000 [conv.prom]p3: 18192 // An rvalue of an unscoped enumeration type whose underlying 18193 // type is not fixed can be converted to an rvalue of the first 18194 // of the following types that can represent all the values of 18195 // the enumeration: int, unsigned int, long int, unsigned long 18196 // int, long long int, or unsigned long long int. 18197 // C99 6.4.4.3p2: 18198 // An identifier declared as an enumeration constant has type int. 18199 // The C99 rule is modified by a gcc extension 18200 QualType BestPromotionType; 18201 18202 bool Packed = Enum->hasAttr<PackedAttr>(); 18203 // -fshort-enums is the equivalent to specifying the packed attribute on all 18204 // enum definitions. 18205 if (LangOpts.ShortEnums) 18206 Packed = true; 18207 18208 // If the enum already has a type because it is fixed or dictated by the 18209 // target, promote that type instead of analyzing the enumerators. 18210 if (Enum->isComplete()) { 18211 BestType = Enum->getIntegerType(); 18212 if (BestType->isPromotableIntegerType()) 18213 BestPromotionType = Context.getPromotedIntegerType(BestType); 18214 else 18215 BestPromotionType = BestType; 18216 18217 BestWidth = Context.getIntWidth(BestType); 18218 } 18219 else if (NumNegativeBits) { 18220 // If there is a negative value, figure out the smallest integer type (of 18221 // int/long/longlong) that fits. 18222 // If it's packed, check also if it fits a char or a short. 18223 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18224 BestType = Context.SignedCharTy; 18225 BestWidth = CharWidth; 18226 } else if (Packed && NumNegativeBits <= ShortWidth && 18227 NumPositiveBits < ShortWidth) { 18228 BestType = Context.ShortTy; 18229 BestWidth = ShortWidth; 18230 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18231 BestType = Context.IntTy; 18232 BestWidth = IntWidth; 18233 } else { 18234 BestWidth = Context.getTargetInfo().getLongWidth(); 18235 18236 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18237 BestType = Context.LongTy; 18238 } else { 18239 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18240 18241 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18242 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18243 BestType = Context.LongLongTy; 18244 } 18245 } 18246 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18247 } else { 18248 // If there is no negative value, figure out the smallest type that fits 18249 // all of the enumerator values. 18250 // If it's packed, check also if it fits a char or a short. 18251 if (Packed && NumPositiveBits <= CharWidth) { 18252 BestType = Context.UnsignedCharTy; 18253 BestPromotionType = Context.IntTy; 18254 BestWidth = CharWidth; 18255 } else if (Packed && NumPositiveBits <= ShortWidth) { 18256 BestType = Context.UnsignedShortTy; 18257 BestPromotionType = Context.IntTy; 18258 BestWidth = ShortWidth; 18259 } else if (NumPositiveBits <= IntWidth) { 18260 BestType = Context.UnsignedIntTy; 18261 BestWidth = IntWidth; 18262 BestPromotionType 18263 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18264 ? Context.UnsignedIntTy : Context.IntTy; 18265 } else if (NumPositiveBits <= 18266 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18267 BestType = Context.UnsignedLongTy; 18268 BestPromotionType 18269 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18270 ? Context.UnsignedLongTy : Context.LongTy; 18271 } else { 18272 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18273 assert(NumPositiveBits <= BestWidth && 18274 "How could an initializer get larger than ULL?"); 18275 BestType = Context.UnsignedLongLongTy; 18276 BestPromotionType 18277 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18278 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18279 } 18280 } 18281 18282 // Loop over all of the enumerator constants, changing their types to match 18283 // the type of the enum if needed. 18284 for (auto *D : Elements) { 18285 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18286 if (!ECD) continue; // Already issued a diagnostic. 18287 18288 // Standard C says the enumerators have int type, but we allow, as an 18289 // extension, the enumerators to be larger than int size. If each 18290 // enumerator value fits in an int, type it as an int, otherwise type it the 18291 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18292 // that X has type 'int', not 'unsigned'. 18293 18294 // Determine whether the value fits into an int. 18295 llvm::APSInt InitVal = ECD->getInitVal(); 18296 18297 // If it fits into an integer type, force it. Otherwise force it to match 18298 // the enum decl type. 18299 QualType NewTy; 18300 unsigned NewWidth; 18301 bool NewSign; 18302 if (!getLangOpts().CPlusPlus && 18303 !Enum->isFixed() && 18304 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18305 NewTy = Context.IntTy; 18306 NewWidth = IntWidth; 18307 NewSign = true; 18308 } else if (ECD->getType() == BestType) { 18309 // Already the right type! 18310 if (getLangOpts().CPlusPlus) 18311 // C++ [dcl.enum]p4: Following the closing brace of an 18312 // enum-specifier, each enumerator has the type of its 18313 // enumeration. 18314 ECD->setType(EnumType); 18315 continue; 18316 } else { 18317 NewTy = BestType; 18318 NewWidth = BestWidth; 18319 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18320 } 18321 18322 // Adjust the APSInt value. 18323 InitVal = InitVal.extOrTrunc(NewWidth); 18324 InitVal.setIsSigned(NewSign); 18325 ECD->setInitVal(InitVal); 18326 18327 // Adjust the Expr initializer and type. 18328 if (ECD->getInitExpr() && 18329 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18330 ECD->setInitExpr(ImplicitCastExpr::Create( 18331 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18332 /*base paths*/ nullptr, VK_RValue, FPOptionsOverride())); 18333 if (getLangOpts().CPlusPlus) 18334 // C++ [dcl.enum]p4: Following the closing brace of an 18335 // enum-specifier, each enumerator has the type of its 18336 // enumeration. 18337 ECD->setType(EnumType); 18338 else 18339 ECD->setType(NewTy); 18340 } 18341 18342 Enum->completeDefinition(BestType, BestPromotionType, 18343 NumPositiveBits, NumNegativeBits); 18344 18345 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18346 18347 if (Enum->isClosedFlag()) { 18348 for (Decl *D : Elements) { 18349 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18350 if (!ECD) continue; // Already issued a diagnostic. 18351 18352 llvm::APSInt InitVal = ECD->getInitVal(); 18353 if (InitVal != 0 && !InitVal.isPowerOf2() && 18354 !IsValueInFlagEnum(Enum, InitVal, true)) 18355 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18356 << ECD << Enum; 18357 } 18358 } 18359 18360 // Now that the enum type is defined, ensure it's not been underaligned. 18361 if (Enum->hasAttrs()) 18362 CheckAlignasUnderalignment(Enum); 18363 } 18364 18365 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18366 SourceLocation StartLoc, 18367 SourceLocation EndLoc) { 18368 StringLiteral *AsmString = cast<StringLiteral>(expr); 18369 18370 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18371 AsmString, StartLoc, 18372 EndLoc); 18373 CurContext->addDecl(New); 18374 return New; 18375 } 18376 18377 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18378 IdentifierInfo* AliasName, 18379 SourceLocation PragmaLoc, 18380 SourceLocation NameLoc, 18381 SourceLocation AliasNameLoc) { 18382 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18383 LookupOrdinaryName); 18384 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18385 AttributeCommonInfo::AS_Pragma); 18386 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18387 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18388 18389 // If a declaration that: 18390 // 1) declares a function or a variable 18391 // 2) has external linkage 18392 // already exists, add a label attribute to it. 18393 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18394 if (isDeclExternC(PrevDecl)) 18395 PrevDecl->addAttr(Attr); 18396 else 18397 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18398 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18399 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18400 } else 18401 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18402 } 18403 18404 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18405 SourceLocation PragmaLoc, 18406 SourceLocation NameLoc) { 18407 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18408 18409 if (PrevDecl) { 18410 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18411 } else { 18412 (void)WeakUndeclaredIdentifiers.insert( 18413 std::pair<IdentifierInfo*,WeakInfo> 18414 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18415 } 18416 } 18417 18418 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18419 IdentifierInfo* AliasName, 18420 SourceLocation PragmaLoc, 18421 SourceLocation NameLoc, 18422 SourceLocation AliasNameLoc) { 18423 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18424 LookupOrdinaryName); 18425 WeakInfo W = WeakInfo(Name, NameLoc); 18426 18427 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18428 if (!PrevDecl->hasAttr<AliasAttr>()) 18429 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18430 DeclApplyPragmaWeak(TUScope, ND, W); 18431 } else { 18432 (void)WeakUndeclaredIdentifiers.insert( 18433 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18434 } 18435 } 18436 18437 Decl *Sema::getObjCDeclContext() const { 18438 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18439 } 18440 18441 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18442 bool Final) { 18443 assert(FD && "Expected non-null FunctionDecl"); 18444 18445 // SYCL functions can be template, so we check if they have appropriate 18446 // attribute prior to checking if it is a template. 18447 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18448 return FunctionEmissionStatus::Emitted; 18449 18450 // Templates are emitted when they're instantiated. 18451 if (FD->isDependentContext()) 18452 return FunctionEmissionStatus::TemplateDiscarded; 18453 18454 // Check whether this function is an externally visible definition. 18455 auto IsEmittedForExternalSymbol = [this, FD]() { 18456 // We have to check the GVA linkage of the function's *definition* -- if we 18457 // only have a declaration, we don't know whether or not the function will 18458 // be emitted, because (say) the definition could include "inline". 18459 FunctionDecl *Def = FD->getDefinition(); 18460 18461 return Def && !isDiscardableGVALinkage( 18462 getASTContext().GetGVALinkageForFunction(Def)); 18463 }; 18464 18465 if (LangOpts.OpenMPIsDevice) { 18466 // In OpenMP device mode we will not emit host only functions, or functions 18467 // we don't need due to their linkage. 18468 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18469 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18470 // DevTy may be changed later by 18471 // #pragma omp declare target to(*) device_type(*). 18472 // Therefore DevTy having no value does not imply host. The emission status 18473 // will be checked again at the end of compilation unit with Final = true. 18474 if (DevTy.hasValue()) 18475 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18476 return FunctionEmissionStatus::OMPDiscarded; 18477 // If we have an explicit value for the device type, or we are in a target 18478 // declare context, we need to emit all extern and used symbols. 18479 if (isInOpenMPDeclareTargetContext() || DevTy.hasValue()) 18480 if (IsEmittedForExternalSymbol()) 18481 return FunctionEmissionStatus::Emitted; 18482 // Device mode only emits what it must, if it wasn't tagged yet and needed, 18483 // we'll omit it. 18484 if (Final) 18485 return FunctionEmissionStatus::OMPDiscarded; 18486 } else if (LangOpts.OpenMP > 45) { 18487 // In OpenMP host compilation prior to 5.0 everything was an emitted host 18488 // function. In 5.0, no_host was introduced which might cause a function to 18489 // be ommitted. 18490 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18491 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18492 if (DevTy.hasValue()) 18493 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 18494 return FunctionEmissionStatus::OMPDiscarded; 18495 } 18496 18497 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 18498 return FunctionEmissionStatus::Emitted; 18499 18500 if (LangOpts.CUDA) { 18501 // When compiling for device, host functions are never emitted. Similarly, 18502 // when compiling for host, device and global functions are never emitted. 18503 // (Technically, we do emit a host-side stub for global functions, but this 18504 // doesn't count for our purposes here.) 18505 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18506 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18507 return FunctionEmissionStatus::CUDADiscarded; 18508 if (!LangOpts.CUDAIsDevice && 18509 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18510 return FunctionEmissionStatus::CUDADiscarded; 18511 18512 if (IsEmittedForExternalSymbol()) 18513 return FunctionEmissionStatus::Emitted; 18514 } 18515 18516 // Otherwise, the function is known-emitted if it's in our set of 18517 // known-emitted functions. 18518 return FunctionEmissionStatus::Unknown; 18519 } 18520 18521 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18522 // Host-side references to a __global__ function refer to the stub, so the 18523 // function itself is never emitted and therefore should not be marked. 18524 // If we have host fn calls kernel fn calls host+device, the HD function 18525 // does not get instantiated on the host. We model this by omitting at the 18526 // call to the kernel from the callgraph. This ensures that, when compiling 18527 // for host, only HD functions actually called from the host get marked as 18528 // known-emitted. 18529 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18530 IdentifyCUDATarget(Callee) == CFT_Global; 18531 } 18532