1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TypeLocBuilder.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/CommentDiagnostic.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/NonTrivialTypeVisitor.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 36 #include "clang/Sema/CXXFieldCollector.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaInternal.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/ADT/SmallString.h" 47 #include "llvm/ADT/Triple.h" 48 #include <algorithm> 49 #include <cstring> 50 #include <functional> 51 #include <unordered_map> 52 53 using namespace clang; 54 using namespace sema; 55 56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 57 if (OwnedType) { 58 Decl *Group[2] = { OwnedType, Ptr }; 59 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 60 } 61 62 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 63 } 64 65 namespace { 66 67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 68 public: 69 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 70 bool AllowTemplates = false, 71 bool AllowNonTemplates = true) 72 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 73 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 74 WantExpressionKeywords = false; 75 WantCXXNamedCasts = false; 76 WantRemainingKeywords = false; 77 } 78 79 bool ValidateCandidate(const TypoCorrection &candidate) override { 80 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 81 if (!AllowInvalidDecl && ND->isInvalidDecl()) 82 return false; 83 84 if (getAsTypeTemplateDecl(ND)) 85 return AllowTemplates; 86 87 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 88 if (!IsType) 89 return false; 90 91 if (AllowNonTemplates) 92 return true; 93 94 // An injected-class-name of a class template (specialization) is valid 95 // as a template or as a non-template. 96 if (AllowTemplates) { 97 auto *RD = dyn_cast<CXXRecordDecl>(ND); 98 if (!RD || !RD->isInjectedClassName()) 99 return false; 100 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 101 return RD->getDescribedClassTemplate() || 102 isa<ClassTemplateSpecializationDecl>(RD); 103 } 104 105 return false; 106 } 107 108 return !WantClassName && candidate.isKeyword(); 109 } 110 111 std::unique_ptr<CorrectionCandidateCallback> clone() override { 112 return std::make_unique<TypeNameValidatorCCC>(*this); 113 } 114 115 private: 116 bool AllowInvalidDecl; 117 bool WantClassName; 118 bool AllowTemplates; 119 bool AllowNonTemplates; 120 }; 121 122 } // end anonymous namespace 123 124 /// Determine whether the token kind starts a simple-type-specifier. 125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 126 switch (Kind) { 127 // FIXME: Take into account the current language when deciding whether a 128 // token kind is a valid type specifier 129 case tok::kw_short: 130 case tok::kw_long: 131 case tok::kw___int64: 132 case tok::kw___int128: 133 case tok::kw_signed: 134 case tok::kw_unsigned: 135 case tok::kw_void: 136 case tok::kw_char: 137 case tok::kw_int: 138 case tok::kw_half: 139 case tok::kw_float: 140 case tok::kw_double: 141 case tok::kw___bf16: 142 case tok::kw__Float16: 143 case tok::kw___float128: 144 case tok::kw_wchar_t: 145 case tok::kw_bool: 146 case tok::kw___underlying_type: 147 case tok::kw___auto_type: 148 return true; 149 150 case tok::annot_typename: 151 case tok::kw_char16_t: 152 case tok::kw_char32_t: 153 case tok::kw_typeof: 154 case tok::annot_decltype: 155 case tok::kw_decltype: 156 return getLangOpts().CPlusPlus; 157 158 case tok::kw_char8_t: 159 return getLangOpts().Char8; 160 161 default: 162 break; 163 } 164 165 return false; 166 } 167 168 namespace { 169 enum class UnqualifiedTypeNameLookupResult { 170 NotFound, 171 FoundNonType, 172 FoundType 173 }; 174 } // end anonymous namespace 175 176 /// Tries to perform unqualified lookup of the type decls in bases for 177 /// dependent class. 178 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 179 /// type decl, \a FoundType if only type decls are found. 180 static UnqualifiedTypeNameLookupResult 181 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 182 SourceLocation NameLoc, 183 const CXXRecordDecl *RD) { 184 if (!RD->hasDefinition()) 185 return UnqualifiedTypeNameLookupResult::NotFound; 186 // Look for type decls in base classes. 187 UnqualifiedTypeNameLookupResult FoundTypeDecl = 188 UnqualifiedTypeNameLookupResult::NotFound; 189 for (const auto &Base : RD->bases()) { 190 const CXXRecordDecl *BaseRD = nullptr; 191 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 192 BaseRD = BaseTT->getAsCXXRecordDecl(); 193 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 194 // Look for type decls in dependent base classes that have known primary 195 // templates. 196 if (!TST || !TST->isDependentType()) 197 continue; 198 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 199 if (!TD) 200 continue; 201 if (auto *BasePrimaryTemplate = 202 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 204 BaseRD = BasePrimaryTemplate; 205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 206 if (const ClassTemplatePartialSpecializationDecl *PS = 207 CTD->findPartialSpecialization(Base.getType())) 208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 209 BaseRD = PS; 210 } 211 } 212 } 213 if (BaseRD) { 214 for (NamedDecl *ND : BaseRD->lookup(&II)) { 215 if (!isa<TypeDecl>(ND)) 216 return UnqualifiedTypeNameLookupResult::FoundNonType; 217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 218 } 219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 221 case UnqualifiedTypeNameLookupResult::FoundNonType: 222 return UnqualifiedTypeNameLookupResult::FoundNonType; 223 case UnqualifiedTypeNameLookupResult::FoundType: 224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 225 break; 226 case UnqualifiedTypeNameLookupResult::NotFound: 227 break; 228 } 229 } 230 } 231 } 232 233 return FoundTypeDecl; 234 } 235 236 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 237 const IdentifierInfo &II, 238 SourceLocation NameLoc) { 239 // Lookup in the parent class template context, if any. 240 const CXXRecordDecl *RD = nullptr; 241 UnqualifiedTypeNameLookupResult FoundTypeDecl = 242 UnqualifiedTypeNameLookupResult::NotFound; 243 for (DeclContext *DC = S.CurContext; 244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 245 DC = DC->getParent()) { 246 // Look for type decls in dependent base classes that have known primary 247 // templates. 248 RD = dyn_cast<CXXRecordDecl>(DC); 249 if (RD && RD->getDescribedClassTemplate()) 250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 251 } 252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 253 return nullptr; 254 255 // We found some types in dependent base classes. Recover as if the user 256 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 257 // lookup during template instantiation. 258 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II; 259 260 ASTContext &Context = S.Context; 261 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 262 cast<Type>(Context.getRecordType(RD))); 263 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 264 265 CXXScopeSpec SS; 266 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 267 268 TypeLocBuilder Builder; 269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 270 DepTL.setNameLoc(NameLoc); 271 DepTL.setElaboratedKeywordLoc(SourceLocation()); 272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 273 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 274 } 275 276 /// If the identifier refers to a type name within this scope, 277 /// return the declaration of that type. 278 /// 279 /// This routine performs ordinary name lookup of the identifier II 280 /// within the given scope, with optional C++ scope specifier SS, to 281 /// determine whether the name refers to a type. If so, returns an 282 /// opaque pointer (actually a QualType) corresponding to that 283 /// type. Otherwise, returns NULL. 284 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 285 Scope *S, CXXScopeSpec *SS, 286 bool isClassName, bool HasTrailingDot, 287 ParsedType ObjectTypePtr, 288 bool IsCtorOrDtorName, 289 bool WantNontrivialTypeSourceInfo, 290 bool IsClassTemplateDeductionContext, 291 IdentifierInfo **CorrectedII) { 292 // FIXME: Consider allowing this outside C++1z mode as an extension. 293 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 294 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 295 !isClassName && !HasTrailingDot; 296 297 // Determine where we will perform name lookup. 298 DeclContext *LookupCtx = nullptr; 299 if (ObjectTypePtr) { 300 QualType ObjectType = ObjectTypePtr.get(); 301 if (ObjectType->isRecordType()) 302 LookupCtx = computeDeclContext(ObjectType); 303 } else if (SS && SS->isNotEmpty()) { 304 LookupCtx = computeDeclContext(*SS, false); 305 306 if (!LookupCtx) { 307 if (isDependentScopeSpecifier(*SS)) { 308 // C++ [temp.res]p3: 309 // A qualified-id that refers to a type and in which the 310 // nested-name-specifier depends on a template-parameter (14.6.2) 311 // shall be prefixed by the keyword typename to indicate that the 312 // qualified-id denotes a type, forming an 313 // elaborated-type-specifier (7.1.5.3). 314 // 315 // We therefore do not perform any name lookup if the result would 316 // refer to a member of an unknown specialization. 317 if (!isClassName && !IsCtorOrDtorName) 318 return nullptr; 319 320 // We know from the grammar that this name refers to a type, 321 // so build a dependent node to describe the type. 322 if (WantNontrivialTypeSourceInfo) 323 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 324 325 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 326 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 327 II, NameLoc); 328 return ParsedType::make(T); 329 } 330 331 return nullptr; 332 } 333 334 if (!LookupCtx->isDependentContext() && 335 RequireCompleteDeclContext(*SS, LookupCtx)) 336 return nullptr; 337 } 338 339 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 340 // lookup for class-names. 341 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 342 LookupOrdinaryName; 343 LookupResult Result(*this, &II, NameLoc, Kind); 344 if (LookupCtx) { 345 // Perform "qualified" name lookup into the declaration context we 346 // computed, which is either the type of the base of a member access 347 // expression or the declaration context associated with a prior 348 // nested-name-specifier. 349 LookupQualifiedName(Result, LookupCtx); 350 351 if (ObjectTypePtr && Result.empty()) { 352 // C++ [basic.lookup.classref]p3: 353 // If the unqualified-id is ~type-name, the type-name is looked up 354 // in the context of the entire postfix-expression. If the type T of 355 // the object expression is of a class type C, the type-name is also 356 // looked up in the scope of class C. At least one of the lookups shall 357 // find a name that refers to (possibly cv-qualified) T. 358 LookupName(Result, S); 359 } 360 } else { 361 // Perform unqualified name lookup. 362 LookupName(Result, S); 363 364 // For unqualified lookup in a class template in MSVC mode, look into 365 // dependent base classes where the primary class template is known. 366 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 367 if (ParsedType TypeInBase = 368 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 369 return TypeInBase; 370 } 371 } 372 373 NamedDecl *IIDecl = nullptr; 374 switch (Result.getResultKind()) { 375 case LookupResult::NotFound: 376 case LookupResult::NotFoundInCurrentInstantiation: 377 if (CorrectedII) { 378 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 379 AllowDeducedTemplate); 380 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 381 S, SS, CCC, CTK_ErrorRecovery); 382 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 383 TemplateTy Template; 384 bool MemberOfUnknownSpecialization; 385 UnqualifiedId TemplateName; 386 TemplateName.setIdentifier(NewII, NameLoc); 387 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 388 CXXScopeSpec NewSS, *NewSSPtr = SS; 389 if (SS && NNS) { 390 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 391 NewSSPtr = &NewSS; 392 } 393 if (Correction && (NNS || NewII != &II) && 394 // Ignore a correction to a template type as the to-be-corrected 395 // identifier is not a template (typo correction for template names 396 // is handled elsewhere). 397 !(getLangOpts().CPlusPlus && NewSSPtr && 398 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 399 Template, MemberOfUnknownSpecialization))) { 400 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 401 isClassName, HasTrailingDot, ObjectTypePtr, 402 IsCtorOrDtorName, 403 WantNontrivialTypeSourceInfo, 404 IsClassTemplateDeductionContext); 405 if (Ty) { 406 diagnoseTypo(Correction, 407 PDiag(diag::err_unknown_type_or_class_name_suggest) 408 << Result.getLookupName() << isClassName); 409 if (SS && NNS) 410 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 411 *CorrectedII = NewII; 412 return Ty; 413 } 414 } 415 } 416 // If typo correction failed or was not performed, fall through 417 LLVM_FALLTHROUGH; 418 case LookupResult::FoundOverloaded: 419 case LookupResult::FoundUnresolvedValue: 420 Result.suppressDiagnostics(); 421 return nullptr; 422 423 case LookupResult::Ambiguous: 424 // Recover from type-hiding ambiguities by hiding the type. We'll 425 // do the lookup again when looking for an object, and we can 426 // diagnose the error then. If we don't do this, then the error 427 // about hiding the type will be immediately followed by an error 428 // that only makes sense if the identifier was treated like a type. 429 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 430 Result.suppressDiagnostics(); 431 return nullptr; 432 } 433 434 // Look to see if we have a type anywhere in the list of results. 435 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 436 Res != ResEnd; ++Res) { 437 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 438 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 439 if (!IIDecl || (*Res)->getLocation() < IIDecl->getLocation()) 440 IIDecl = *Res; 441 } 442 } 443 444 if (!IIDecl) { 445 // None of the entities we found is a type, so there is no way 446 // to even assume that the result is a type. In this case, don't 447 // complain about the ambiguity. The parser will either try to 448 // perform this lookup again (e.g., as an object name), which 449 // will produce the ambiguity, or will complain that it expected 450 // a type name. 451 Result.suppressDiagnostics(); 452 return nullptr; 453 } 454 455 // We found a type within the ambiguous lookup; diagnose the 456 // ambiguity and then return that type. This might be the right 457 // answer, or it might not be, but it suppresses any attempt to 458 // perform the name lookup again. 459 break; 460 461 case LookupResult::Found: 462 IIDecl = Result.getFoundDecl(); 463 break; 464 } 465 466 assert(IIDecl && "Didn't find decl"); 467 468 QualType T; 469 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 470 // C++ [class.qual]p2: A lookup that would find the injected-class-name 471 // instead names the constructors of the class, except when naming a class. 472 // This is ill-formed when we're not actually forming a ctor or dtor name. 473 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 474 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 475 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 476 FoundRD->isInjectedClassName() && 477 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 478 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 479 << &II << /*Type*/1; 480 481 DiagnoseUseOfDecl(IIDecl, NameLoc); 482 483 T = Context.getTypeDeclType(TD); 484 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 485 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 486 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 487 if (!HasTrailingDot) 488 T = Context.getObjCInterfaceType(IDecl); 489 } else if (AllowDeducedTemplate) { 490 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 491 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 492 QualType(), false); 493 } 494 495 if (T.isNull()) { 496 // If it's not plausibly a type, suppress diagnostics. 497 Result.suppressDiagnostics(); 498 return nullptr; 499 } 500 501 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 502 // constructor or destructor name (in such a case, the scope specifier 503 // will be attached to the enclosing Expr or Decl node). 504 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 505 !isa<ObjCInterfaceDecl>(IIDecl)) { 506 if (WantNontrivialTypeSourceInfo) { 507 // Construct a type with type-source information. 508 TypeLocBuilder Builder; 509 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 510 511 T = getElaboratedType(ETK_None, *SS, T); 512 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 513 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 514 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 515 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 516 } else { 517 T = getElaboratedType(ETK_None, *SS, T); 518 } 519 } 520 521 return ParsedType::make(T); 522 } 523 524 // Builds a fake NNS for the given decl context. 525 static NestedNameSpecifier * 526 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 527 for (;; DC = DC->getLookupParent()) { 528 DC = DC->getPrimaryContext(); 529 auto *ND = dyn_cast<NamespaceDecl>(DC); 530 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 531 return NestedNameSpecifier::Create(Context, nullptr, ND); 532 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 533 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 534 RD->getTypeForDecl()); 535 else if (isa<TranslationUnitDecl>(DC)) 536 return NestedNameSpecifier::GlobalSpecifier(Context); 537 } 538 llvm_unreachable("something isn't in TU scope?"); 539 } 540 541 /// Find the parent class with dependent bases of the innermost enclosing method 542 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 543 /// up allowing unqualified dependent type names at class-level, which MSVC 544 /// correctly rejects. 545 static const CXXRecordDecl * 546 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 547 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 548 DC = DC->getPrimaryContext(); 549 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 550 if (MD->getParent()->hasAnyDependentBases()) 551 return MD->getParent(); 552 } 553 return nullptr; 554 } 555 556 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 557 SourceLocation NameLoc, 558 bool IsTemplateTypeArg) { 559 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 560 561 NestedNameSpecifier *NNS = nullptr; 562 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 563 // If we weren't able to parse a default template argument, delay lookup 564 // until instantiation time by making a non-dependent DependentTypeName. We 565 // pretend we saw a NestedNameSpecifier referring to the current scope, and 566 // lookup is retried. 567 // FIXME: This hurts our diagnostic quality, since we get errors like "no 568 // type named 'Foo' in 'current_namespace'" when the user didn't write any 569 // name specifiers. 570 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 571 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 572 } else if (const CXXRecordDecl *RD = 573 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 574 // Build a DependentNameType that will perform lookup into RD at 575 // instantiation time. 576 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 577 RD->getTypeForDecl()); 578 579 // Diagnose that this identifier was undeclared, and retry the lookup during 580 // template instantiation. 581 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 582 << RD; 583 } else { 584 // This is not a situation that we should recover from. 585 return ParsedType(); 586 } 587 588 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 589 590 // Build type location information. We synthesized the qualifier, so we have 591 // to build a fake NestedNameSpecifierLoc. 592 NestedNameSpecifierLocBuilder NNSLocBuilder; 593 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 594 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 595 596 TypeLocBuilder Builder; 597 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 598 DepTL.setNameLoc(NameLoc); 599 DepTL.setElaboratedKeywordLoc(SourceLocation()); 600 DepTL.setQualifierLoc(QualifierLoc); 601 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 602 } 603 604 /// isTagName() - This method is called *for error recovery purposes only* 605 /// to determine if the specified name is a valid tag name ("struct foo"). If 606 /// so, this returns the TST for the tag corresponding to it (TST_enum, 607 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 608 /// cases in C where the user forgot to specify the tag. 609 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 610 // Do a tag name lookup in this scope. 611 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 612 LookupName(R, S, false); 613 R.suppressDiagnostics(); 614 if (R.getResultKind() == LookupResult::Found) 615 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 616 switch (TD->getTagKind()) { 617 case TTK_Struct: return DeclSpec::TST_struct; 618 case TTK_Interface: return DeclSpec::TST_interface; 619 case TTK_Union: return DeclSpec::TST_union; 620 case TTK_Class: return DeclSpec::TST_class; 621 case TTK_Enum: return DeclSpec::TST_enum; 622 } 623 } 624 625 return DeclSpec::TST_unspecified; 626 } 627 628 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 629 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 630 /// then downgrade the missing typename error to a warning. 631 /// This is needed for MSVC compatibility; Example: 632 /// @code 633 /// template<class T> class A { 634 /// public: 635 /// typedef int TYPE; 636 /// }; 637 /// template<class T> class B : public A<T> { 638 /// public: 639 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 640 /// }; 641 /// @endcode 642 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 643 if (CurContext->isRecord()) { 644 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 645 return true; 646 647 const Type *Ty = SS->getScopeRep()->getAsType(); 648 649 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 650 for (const auto &Base : RD->bases()) 651 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 652 return true; 653 return S->isFunctionPrototypeScope(); 654 } 655 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 656 } 657 658 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 659 SourceLocation IILoc, 660 Scope *S, 661 CXXScopeSpec *SS, 662 ParsedType &SuggestedType, 663 bool IsTemplateName) { 664 // Don't report typename errors for editor placeholders. 665 if (II->isEditorPlaceholder()) 666 return; 667 // We don't have anything to suggest (yet). 668 SuggestedType = nullptr; 669 670 // There may have been a typo in the name of the type. Look up typo 671 // results, in case we have something that we can suggest. 672 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 673 /*AllowTemplates=*/IsTemplateName, 674 /*AllowNonTemplates=*/!IsTemplateName); 675 if (TypoCorrection Corrected = 676 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 677 CCC, CTK_ErrorRecovery)) { 678 // FIXME: Support error recovery for the template-name case. 679 bool CanRecover = !IsTemplateName; 680 if (Corrected.isKeyword()) { 681 // We corrected to a keyword. 682 diagnoseTypo(Corrected, 683 PDiag(IsTemplateName ? diag::err_no_template_suggest 684 : diag::err_unknown_typename_suggest) 685 << II); 686 II = Corrected.getCorrectionAsIdentifierInfo(); 687 } else { 688 // We found a similarly-named type or interface; suggest that. 689 if (!SS || !SS->isSet()) { 690 diagnoseTypo(Corrected, 691 PDiag(IsTemplateName ? diag::err_no_template_suggest 692 : diag::err_unknown_typename_suggest) 693 << II, CanRecover); 694 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 695 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 696 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 697 II->getName().equals(CorrectedStr); 698 diagnoseTypo(Corrected, 699 PDiag(IsTemplateName 700 ? diag::err_no_member_template_suggest 701 : diag::err_unknown_nested_typename_suggest) 702 << II << DC << DroppedSpecifier << SS->getRange(), 703 CanRecover); 704 } else { 705 llvm_unreachable("could not have corrected a typo here"); 706 } 707 708 if (!CanRecover) 709 return; 710 711 CXXScopeSpec tmpSS; 712 if (Corrected.getCorrectionSpecifier()) 713 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 714 SourceRange(IILoc)); 715 // FIXME: Support class template argument deduction here. 716 SuggestedType = 717 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 718 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 719 /*IsCtorOrDtorName=*/false, 720 /*WantNontrivialTypeSourceInfo=*/true); 721 } 722 return; 723 } 724 725 if (getLangOpts().CPlusPlus && !IsTemplateName) { 726 // See if II is a class template that the user forgot to pass arguments to. 727 UnqualifiedId Name; 728 Name.setIdentifier(II, IILoc); 729 CXXScopeSpec EmptySS; 730 TemplateTy TemplateResult; 731 bool MemberOfUnknownSpecialization; 732 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 733 Name, nullptr, true, TemplateResult, 734 MemberOfUnknownSpecialization) == TNK_Type_template) { 735 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 736 return; 737 } 738 } 739 740 // FIXME: Should we move the logic that tries to recover from a missing tag 741 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 742 743 if (!SS || (!SS->isSet() && !SS->isInvalid())) 744 Diag(IILoc, IsTemplateName ? diag::err_no_template 745 : diag::err_unknown_typename) 746 << II; 747 else if (DeclContext *DC = computeDeclContext(*SS, false)) 748 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 749 : diag::err_typename_nested_not_found) 750 << II << DC << SS->getRange(); 751 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { 752 SuggestedType = 753 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); 754 } else if (isDependentScopeSpecifier(*SS)) { 755 unsigned DiagID = diag::err_typename_missing; 756 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 757 DiagID = diag::ext_typename_missing; 758 759 Diag(SS->getRange().getBegin(), DiagID) 760 << SS->getScopeRep() << II->getName() 761 << SourceRange(SS->getRange().getBegin(), IILoc) 762 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 763 SuggestedType = ActOnTypenameType(S, SourceLocation(), 764 *SS, *II, IILoc).get(); 765 } else { 766 assert(SS && SS->isInvalid() && 767 "Invalid scope specifier has already been diagnosed"); 768 } 769 } 770 771 /// Determine whether the given result set contains either a type name 772 /// or 773 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 774 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 775 NextToken.is(tok::less); 776 777 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 778 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 779 return true; 780 781 if (CheckTemplate && isa<TemplateDecl>(*I)) 782 return true; 783 } 784 785 return false; 786 } 787 788 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 789 Scope *S, CXXScopeSpec &SS, 790 IdentifierInfo *&Name, 791 SourceLocation NameLoc) { 792 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 793 SemaRef.LookupParsedName(R, S, &SS); 794 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 795 StringRef FixItTagName; 796 switch (Tag->getTagKind()) { 797 case TTK_Class: 798 FixItTagName = "class "; 799 break; 800 801 case TTK_Enum: 802 FixItTagName = "enum "; 803 break; 804 805 case TTK_Struct: 806 FixItTagName = "struct "; 807 break; 808 809 case TTK_Interface: 810 FixItTagName = "__interface "; 811 break; 812 813 case TTK_Union: 814 FixItTagName = "union "; 815 break; 816 } 817 818 StringRef TagName = FixItTagName.drop_back(); 819 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 820 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 821 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 822 823 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 824 I != IEnd; ++I) 825 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 826 << Name << TagName; 827 828 // Replace lookup results with just the tag decl. 829 Result.clear(Sema::LookupTagName); 830 SemaRef.LookupParsedName(Result, S, &SS); 831 return true; 832 } 833 834 return false; 835 } 836 837 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 838 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 839 QualType T, SourceLocation NameLoc) { 840 ASTContext &Context = S.Context; 841 842 TypeLocBuilder Builder; 843 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 844 845 T = S.getElaboratedType(ETK_None, SS, T); 846 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 847 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 848 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 849 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 850 } 851 852 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 853 IdentifierInfo *&Name, 854 SourceLocation NameLoc, 855 const Token &NextToken, 856 CorrectionCandidateCallback *CCC) { 857 DeclarationNameInfo NameInfo(Name, NameLoc); 858 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 859 860 assert(NextToken.isNot(tok::coloncolon) && 861 "parse nested name specifiers before calling ClassifyName"); 862 if (getLangOpts().CPlusPlus && SS.isSet() && 863 isCurrentClassName(*Name, S, &SS)) { 864 // Per [class.qual]p2, this names the constructors of SS, not the 865 // injected-class-name. We don't have a classification for that. 866 // There's not much point caching this result, since the parser 867 // will reject it later. 868 return NameClassification::Unknown(); 869 } 870 871 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 872 LookupParsedName(Result, S, &SS, !CurMethod); 873 874 if (SS.isInvalid()) 875 return NameClassification::Error(); 876 877 // For unqualified lookup in a class template in MSVC mode, look into 878 // dependent base classes where the primary class template is known. 879 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 880 if (ParsedType TypeInBase = 881 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 882 return TypeInBase; 883 } 884 885 // Perform lookup for Objective-C instance variables (including automatically 886 // synthesized instance variables), if we're in an Objective-C method. 887 // FIXME: This lookup really, really needs to be folded in to the normal 888 // unqualified lookup mechanism. 889 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 890 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 891 if (Ivar.isInvalid()) 892 return NameClassification::Error(); 893 if (Ivar.isUsable()) 894 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 895 896 // We defer builtin creation until after ivar lookup inside ObjC methods. 897 if (Result.empty()) 898 LookupBuiltin(Result); 899 } 900 901 bool SecondTry = false; 902 bool IsFilteredTemplateName = false; 903 904 Corrected: 905 switch (Result.getResultKind()) { 906 case LookupResult::NotFound: 907 // If an unqualified-id is followed by a '(', then we have a function 908 // call. 909 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 910 // In C++, this is an ADL-only call. 911 // FIXME: Reference? 912 if (getLangOpts().CPlusPlus) 913 return NameClassification::UndeclaredNonType(); 914 915 // C90 6.3.2.2: 916 // If the expression that precedes the parenthesized argument list in a 917 // function call consists solely of an identifier, and if no 918 // declaration is visible for this identifier, the identifier is 919 // implicitly declared exactly as if, in the innermost block containing 920 // the function call, the declaration 921 // 922 // extern int identifier (); 923 // 924 // appeared. 925 // 926 // We also allow this in C99 as an extension. 927 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 928 return NameClassification::NonType(D); 929 } 930 931 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 932 // In C++20 onwards, this could be an ADL-only call to a function 933 // template, and we're required to assume that this is a template name. 934 // 935 // FIXME: Find a way to still do typo correction in this case. 936 TemplateName Template = 937 Context.getAssumedTemplateName(NameInfo.getName()); 938 return NameClassification::UndeclaredTemplate(Template); 939 } 940 941 // In C, we first see whether there is a tag type by the same name, in 942 // which case it's likely that the user just forgot to write "enum", 943 // "struct", or "union". 944 if (!getLangOpts().CPlusPlus && !SecondTry && 945 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 946 break; 947 } 948 949 // Perform typo correction to determine if there is another name that is 950 // close to this name. 951 if (!SecondTry && CCC) { 952 SecondTry = true; 953 if (TypoCorrection Corrected = 954 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 955 &SS, *CCC, CTK_ErrorRecovery)) { 956 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 957 unsigned QualifiedDiag = diag::err_no_member_suggest; 958 959 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 960 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 961 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 962 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 963 UnqualifiedDiag = diag::err_no_template_suggest; 964 QualifiedDiag = diag::err_no_member_template_suggest; 965 } else if (UnderlyingFirstDecl && 966 (isa<TypeDecl>(UnderlyingFirstDecl) || 967 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 968 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 969 UnqualifiedDiag = diag::err_unknown_typename_suggest; 970 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 971 } 972 973 if (SS.isEmpty()) { 974 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 975 } else {// FIXME: is this even reachable? Test it. 976 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 977 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 978 Name->getName().equals(CorrectedStr); 979 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 980 << Name << computeDeclContext(SS, false) 981 << DroppedSpecifier << SS.getRange()); 982 } 983 984 // Update the name, so that the caller has the new name. 985 Name = Corrected.getCorrectionAsIdentifierInfo(); 986 987 // Typo correction corrected to a keyword. 988 if (Corrected.isKeyword()) 989 return Name; 990 991 // Also update the LookupResult... 992 // FIXME: This should probably go away at some point 993 Result.clear(); 994 Result.setLookupName(Corrected.getCorrection()); 995 if (FirstDecl) 996 Result.addDecl(FirstDecl); 997 998 // If we found an Objective-C instance variable, let 999 // LookupInObjCMethod build the appropriate expression to 1000 // reference the ivar. 1001 // FIXME: This is a gross hack. 1002 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1003 DeclResult R = 1004 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1005 if (R.isInvalid()) 1006 return NameClassification::Error(); 1007 if (R.isUsable()) 1008 return NameClassification::NonType(Ivar); 1009 } 1010 1011 goto Corrected; 1012 } 1013 } 1014 1015 // We failed to correct; just fall through and let the parser deal with it. 1016 Result.suppressDiagnostics(); 1017 return NameClassification::Unknown(); 1018 1019 case LookupResult::NotFoundInCurrentInstantiation: { 1020 // We performed name lookup into the current instantiation, and there were 1021 // dependent bases, so we treat this result the same way as any other 1022 // dependent nested-name-specifier. 1023 1024 // C++ [temp.res]p2: 1025 // A name used in a template declaration or definition and that is 1026 // dependent on a template-parameter is assumed not to name a type 1027 // unless the applicable name lookup finds a type name or the name is 1028 // qualified by the keyword typename. 1029 // 1030 // FIXME: If the next token is '<', we might want to ask the parser to 1031 // perform some heroics to see if we actually have a 1032 // template-argument-list, which would indicate a missing 'template' 1033 // keyword here. 1034 return NameClassification::DependentNonType(); 1035 } 1036 1037 case LookupResult::Found: 1038 case LookupResult::FoundOverloaded: 1039 case LookupResult::FoundUnresolvedValue: 1040 break; 1041 1042 case LookupResult::Ambiguous: 1043 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1044 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1045 /*AllowDependent=*/false)) { 1046 // C++ [temp.local]p3: 1047 // A lookup that finds an injected-class-name (10.2) can result in an 1048 // ambiguity in certain cases (for example, if it is found in more than 1049 // one base class). If all of the injected-class-names that are found 1050 // refer to specializations of the same class template, and if the name 1051 // is followed by a template-argument-list, the reference refers to the 1052 // class template itself and not a specialization thereof, and is not 1053 // ambiguous. 1054 // 1055 // This filtering can make an ambiguous result into an unambiguous one, 1056 // so try again after filtering out template names. 1057 FilterAcceptableTemplateNames(Result); 1058 if (!Result.isAmbiguous()) { 1059 IsFilteredTemplateName = true; 1060 break; 1061 } 1062 } 1063 1064 // Diagnose the ambiguity and return an error. 1065 return NameClassification::Error(); 1066 } 1067 1068 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1069 (IsFilteredTemplateName || 1070 hasAnyAcceptableTemplateNames( 1071 Result, /*AllowFunctionTemplates=*/true, 1072 /*AllowDependent=*/false, 1073 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1074 getLangOpts().CPlusPlus20))) { 1075 // C++ [temp.names]p3: 1076 // After name lookup (3.4) finds that a name is a template-name or that 1077 // an operator-function-id or a literal- operator-id refers to a set of 1078 // overloaded functions any member of which is a function template if 1079 // this is followed by a <, the < is always taken as the delimiter of a 1080 // template-argument-list and never as the less-than operator. 1081 // C++2a [temp.names]p2: 1082 // A name is also considered to refer to a template if it is an 1083 // unqualified-id followed by a < and name lookup finds either one 1084 // or more functions or finds nothing. 1085 if (!IsFilteredTemplateName) 1086 FilterAcceptableTemplateNames(Result); 1087 1088 bool IsFunctionTemplate; 1089 bool IsVarTemplate; 1090 TemplateName Template; 1091 if (Result.end() - Result.begin() > 1) { 1092 IsFunctionTemplate = true; 1093 Template = Context.getOverloadedTemplateName(Result.begin(), 1094 Result.end()); 1095 } else if (!Result.empty()) { 1096 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1097 *Result.begin(), /*AllowFunctionTemplates=*/true, 1098 /*AllowDependent=*/false)); 1099 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1100 IsVarTemplate = isa<VarTemplateDecl>(TD); 1101 1102 if (SS.isNotEmpty()) 1103 Template = 1104 Context.getQualifiedTemplateName(SS.getScopeRep(), 1105 /*TemplateKeyword=*/false, TD); 1106 else 1107 Template = TemplateName(TD); 1108 } else { 1109 // All results were non-template functions. This is a function template 1110 // name. 1111 IsFunctionTemplate = true; 1112 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1113 } 1114 1115 if (IsFunctionTemplate) { 1116 // Function templates always go through overload resolution, at which 1117 // point we'll perform the various checks (e.g., accessibility) we need 1118 // to based on which function we selected. 1119 Result.suppressDiagnostics(); 1120 1121 return NameClassification::FunctionTemplate(Template); 1122 } 1123 1124 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1125 : NameClassification::TypeTemplate(Template); 1126 } 1127 1128 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1129 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1130 DiagnoseUseOfDecl(Type, NameLoc); 1131 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1132 QualType T = Context.getTypeDeclType(Type); 1133 if (SS.isNotEmpty()) 1134 return buildNestedType(*this, SS, T, NameLoc); 1135 return ParsedType::make(T); 1136 } 1137 1138 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1139 if (!Class) { 1140 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1141 if (ObjCCompatibleAliasDecl *Alias = 1142 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1143 Class = Alias->getClassInterface(); 1144 } 1145 1146 if (Class) { 1147 DiagnoseUseOfDecl(Class, NameLoc); 1148 1149 if (NextToken.is(tok::period)) { 1150 // Interface. <something> is parsed as a property reference expression. 1151 // Just return "unknown" as a fall-through for now. 1152 Result.suppressDiagnostics(); 1153 return NameClassification::Unknown(); 1154 } 1155 1156 QualType T = Context.getObjCInterfaceType(Class); 1157 return ParsedType::make(T); 1158 } 1159 1160 if (isa<ConceptDecl>(FirstDecl)) 1161 return NameClassification::Concept( 1162 TemplateName(cast<TemplateDecl>(FirstDecl))); 1163 1164 // We can have a type template here if we're classifying a template argument. 1165 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1166 !isa<VarTemplateDecl>(FirstDecl)) 1167 return NameClassification::TypeTemplate( 1168 TemplateName(cast<TemplateDecl>(FirstDecl))); 1169 1170 // Check for a tag type hidden by a non-type decl in a few cases where it 1171 // seems likely a type is wanted instead of the non-type that was found. 1172 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1173 if ((NextToken.is(tok::identifier) || 1174 (NextIsOp && 1175 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1176 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1177 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1178 DiagnoseUseOfDecl(Type, NameLoc); 1179 QualType T = Context.getTypeDeclType(Type); 1180 if (SS.isNotEmpty()) 1181 return buildNestedType(*this, SS, T, NameLoc); 1182 return ParsedType::make(T); 1183 } 1184 1185 // If we already know which single declaration is referenced, just annotate 1186 // that declaration directly. Defer resolving even non-overloaded class 1187 // member accesses, as we need to defer certain access checks until we know 1188 // the context. 1189 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1190 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember()) 1191 return NameClassification::NonType(Result.getRepresentativeDecl()); 1192 1193 // Otherwise, this is an overload set that we will need to resolve later. 1194 Result.suppressDiagnostics(); 1195 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( 1196 Context, Result.getNamingClass(), SS.getWithLocInContext(Context), 1197 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), 1198 Result.begin(), Result.end())); 1199 } 1200 1201 ExprResult 1202 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1203 SourceLocation NameLoc) { 1204 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1205 CXXScopeSpec SS; 1206 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1207 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1208 } 1209 1210 ExprResult 1211 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1212 IdentifierInfo *Name, 1213 SourceLocation NameLoc, 1214 bool IsAddressOfOperand) { 1215 DeclarationNameInfo NameInfo(Name, NameLoc); 1216 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1217 NameInfo, IsAddressOfOperand, 1218 /*TemplateArgs=*/nullptr); 1219 } 1220 1221 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1222 NamedDecl *Found, 1223 SourceLocation NameLoc, 1224 const Token &NextToken) { 1225 if (getCurMethodDecl() && SS.isEmpty()) 1226 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1227 return BuildIvarRefExpr(S, NameLoc, Ivar); 1228 1229 // Reconstruct the lookup result. 1230 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1231 Result.addDecl(Found); 1232 Result.resolveKind(); 1233 1234 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1235 return BuildDeclarationNameExpr(SS, Result, ADL); 1236 } 1237 1238 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { 1239 // For an implicit class member access, transform the result into a member 1240 // access expression if necessary. 1241 auto *ULE = cast<UnresolvedLookupExpr>(E); 1242 if ((*ULE->decls_begin())->isCXXClassMember()) { 1243 CXXScopeSpec SS; 1244 SS.Adopt(ULE->getQualifierLoc()); 1245 1246 // Reconstruct the lookup result. 1247 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), 1248 LookupOrdinaryName); 1249 Result.setNamingClass(ULE->getNamingClass()); 1250 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) 1251 Result.addDecl(*I, I.getAccess()); 1252 Result.resolveKind(); 1253 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1254 nullptr, S); 1255 } 1256 1257 // Otherwise, this is already in the form we needed, and no further checks 1258 // are necessary. 1259 return ULE; 1260 } 1261 1262 Sema::TemplateNameKindForDiagnostics 1263 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1264 auto *TD = Name.getAsTemplateDecl(); 1265 if (!TD) 1266 return TemplateNameKindForDiagnostics::DependentTemplate; 1267 if (isa<ClassTemplateDecl>(TD)) 1268 return TemplateNameKindForDiagnostics::ClassTemplate; 1269 if (isa<FunctionTemplateDecl>(TD)) 1270 return TemplateNameKindForDiagnostics::FunctionTemplate; 1271 if (isa<VarTemplateDecl>(TD)) 1272 return TemplateNameKindForDiagnostics::VarTemplate; 1273 if (isa<TypeAliasTemplateDecl>(TD)) 1274 return TemplateNameKindForDiagnostics::AliasTemplate; 1275 if (isa<TemplateTemplateParmDecl>(TD)) 1276 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1277 if (isa<ConceptDecl>(TD)) 1278 return TemplateNameKindForDiagnostics::Concept; 1279 return TemplateNameKindForDiagnostics::DependentTemplate; 1280 } 1281 1282 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1283 assert(DC->getLexicalParent() == CurContext && 1284 "The next DeclContext should be lexically contained in the current one."); 1285 CurContext = DC; 1286 S->setEntity(DC); 1287 } 1288 1289 void Sema::PopDeclContext() { 1290 assert(CurContext && "DeclContext imbalance!"); 1291 1292 CurContext = CurContext->getLexicalParent(); 1293 assert(CurContext && "Popped translation unit!"); 1294 } 1295 1296 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1297 Decl *D) { 1298 // Unlike PushDeclContext, the context to which we return is not necessarily 1299 // the containing DC of TD, because the new context will be some pre-existing 1300 // TagDecl definition instead of a fresh one. 1301 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1302 CurContext = cast<TagDecl>(D)->getDefinition(); 1303 assert(CurContext && "skipping definition of undefined tag"); 1304 // Start lookups from the parent of the current context; we don't want to look 1305 // into the pre-existing complete definition. 1306 S->setEntity(CurContext->getLookupParent()); 1307 return Result; 1308 } 1309 1310 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1311 CurContext = static_cast<decltype(CurContext)>(Context); 1312 } 1313 1314 /// EnterDeclaratorContext - Used when we must lookup names in the context 1315 /// of a declarator's nested name specifier. 1316 /// 1317 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1318 // C++0x [basic.lookup.unqual]p13: 1319 // A name used in the definition of a static data member of class 1320 // X (after the qualified-id of the static member) is looked up as 1321 // if the name was used in a member function of X. 1322 // C++0x [basic.lookup.unqual]p14: 1323 // If a variable member of a namespace is defined outside of the 1324 // scope of its namespace then any name used in the definition of 1325 // the variable member (after the declarator-id) is looked up as 1326 // if the definition of the variable member occurred in its 1327 // namespace. 1328 // Both of these imply that we should push a scope whose context 1329 // is the semantic context of the declaration. We can't use 1330 // PushDeclContext here because that context is not necessarily 1331 // lexically contained in the current context. Fortunately, 1332 // the containing scope should have the appropriate information. 1333 1334 assert(!S->getEntity() && "scope already has entity"); 1335 1336 #ifndef NDEBUG 1337 Scope *Ancestor = S->getParent(); 1338 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1339 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1340 #endif 1341 1342 CurContext = DC; 1343 S->setEntity(DC); 1344 1345 if (S->getParent()->isTemplateParamScope()) { 1346 // Also set the corresponding entities for all immediately-enclosing 1347 // template parameter scopes. 1348 EnterTemplatedContext(S->getParent(), DC); 1349 } 1350 } 1351 1352 void Sema::ExitDeclaratorContext(Scope *S) { 1353 assert(S->getEntity() == CurContext && "Context imbalance!"); 1354 1355 // Switch back to the lexical context. The safety of this is 1356 // enforced by an assert in EnterDeclaratorContext. 1357 Scope *Ancestor = S->getParent(); 1358 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1359 CurContext = Ancestor->getEntity(); 1360 1361 // We don't need to do anything with the scope, which is going to 1362 // disappear. 1363 } 1364 1365 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1366 assert(S->isTemplateParamScope() && 1367 "expected to be initializing a template parameter scope"); 1368 1369 // C++20 [temp.local]p7: 1370 // In the definition of a member of a class template that appears outside 1371 // of the class template definition, the name of a member of the class 1372 // template hides the name of a template-parameter of any enclosing class 1373 // templates (but not a template-parameter of the member if the member is a 1374 // class or function template). 1375 // C++20 [temp.local]p9: 1376 // In the definition of a class template or in the definition of a member 1377 // of such a template that appears outside of the template definition, for 1378 // each non-dependent base class (13.8.2.1), if the name of the base class 1379 // or the name of a member of the base class is the same as the name of a 1380 // template-parameter, the base class name or member name hides the 1381 // template-parameter name (6.4.10). 1382 // 1383 // This means that a template parameter scope should be searched immediately 1384 // after searching the DeclContext for which it is a template parameter 1385 // scope. For example, for 1386 // template<typename T> template<typename U> template<typename V> 1387 // void N::A<T>::B<U>::f(...) 1388 // we search V then B<U> (and base classes) then U then A<T> (and base 1389 // classes) then T then N then ::. 1390 unsigned ScopeDepth = getTemplateDepth(S); 1391 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1392 DeclContext *SearchDCAfterScope = DC; 1393 for (; DC; DC = DC->getLookupParent()) { 1394 if (const TemplateParameterList *TPL = 1395 cast<Decl>(DC)->getDescribedTemplateParams()) { 1396 unsigned DCDepth = TPL->getDepth() + 1; 1397 if (DCDepth > ScopeDepth) 1398 continue; 1399 if (ScopeDepth == DCDepth) 1400 SearchDCAfterScope = DC = DC->getLookupParent(); 1401 break; 1402 } 1403 } 1404 S->setLookupEntity(SearchDCAfterScope); 1405 } 1406 } 1407 1408 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1409 // We assume that the caller has already called 1410 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1411 FunctionDecl *FD = D->getAsFunction(); 1412 if (!FD) 1413 return; 1414 1415 // Same implementation as PushDeclContext, but enters the context 1416 // from the lexical parent, rather than the top-level class. 1417 assert(CurContext == FD->getLexicalParent() && 1418 "The next DeclContext should be lexically contained in the current one."); 1419 CurContext = FD; 1420 S->setEntity(CurContext); 1421 1422 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1423 ParmVarDecl *Param = FD->getParamDecl(P); 1424 // If the parameter has an identifier, then add it to the scope 1425 if (Param->getIdentifier()) { 1426 S->AddDecl(Param); 1427 IdResolver.AddDecl(Param); 1428 } 1429 } 1430 } 1431 1432 void Sema::ActOnExitFunctionContext() { 1433 // Same implementation as PopDeclContext, but returns to the lexical parent, 1434 // rather than the top-level class. 1435 assert(CurContext && "DeclContext imbalance!"); 1436 CurContext = CurContext->getLexicalParent(); 1437 assert(CurContext && "Popped translation unit!"); 1438 } 1439 1440 /// Determine whether we allow overloading of the function 1441 /// PrevDecl with another declaration. 1442 /// 1443 /// This routine determines whether overloading is possible, not 1444 /// whether some new function is actually an overload. It will return 1445 /// true in C++ (where we can always provide overloads) or, as an 1446 /// extension, in C when the previous function is already an 1447 /// overloaded function declaration or has the "overloadable" 1448 /// attribute. 1449 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1450 ASTContext &Context, 1451 const FunctionDecl *New) { 1452 if (Context.getLangOpts().CPlusPlus) 1453 return true; 1454 1455 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1456 return true; 1457 1458 return Previous.getResultKind() == LookupResult::Found && 1459 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1460 New->hasAttr<OverloadableAttr>()); 1461 } 1462 1463 /// Add this decl to the scope shadowed decl chains. 1464 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1465 // Move up the scope chain until we find the nearest enclosing 1466 // non-transparent context. The declaration will be introduced into this 1467 // scope. 1468 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1469 S = S->getParent(); 1470 1471 // Add scoped declarations into their context, so that they can be 1472 // found later. Declarations without a context won't be inserted 1473 // into any context. 1474 if (AddToContext) 1475 CurContext->addDecl(D); 1476 1477 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1478 // are function-local declarations. 1479 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) 1480 return; 1481 1482 // Template instantiations should also not be pushed into scope. 1483 if (isa<FunctionDecl>(D) && 1484 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1485 return; 1486 1487 // If this replaces anything in the current scope, 1488 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1489 IEnd = IdResolver.end(); 1490 for (; I != IEnd; ++I) { 1491 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1492 S->RemoveDecl(*I); 1493 IdResolver.RemoveDecl(*I); 1494 1495 // Should only need to replace one decl. 1496 break; 1497 } 1498 } 1499 1500 S->AddDecl(D); 1501 1502 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1503 // Implicitly-generated labels may end up getting generated in an order that 1504 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1505 // the label at the appropriate place in the identifier chain. 1506 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1507 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1508 if (IDC == CurContext) { 1509 if (!S->isDeclScope(*I)) 1510 continue; 1511 } else if (IDC->Encloses(CurContext)) 1512 break; 1513 } 1514 1515 IdResolver.InsertDeclAfter(I, D); 1516 } else { 1517 IdResolver.AddDecl(D); 1518 } 1519 } 1520 1521 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1522 bool AllowInlineNamespace) { 1523 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1524 } 1525 1526 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1527 DeclContext *TargetDC = DC->getPrimaryContext(); 1528 do { 1529 if (DeclContext *ScopeDC = S->getEntity()) 1530 if (ScopeDC->getPrimaryContext() == TargetDC) 1531 return S; 1532 } while ((S = S->getParent())); 1533 1534 return nullptr; 1535 } 1536 1537 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1538 DeclContext*, 1539 ASTContext&); 1540 1541 /// Filters out lookup results that don't fall within the given scope 1542 /// as determined by isDeclInScope. 1543 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1544 bool ConsiderLinkage, 1545 bool AllowInlineNamespace) { 1546 LookupResult::Filter F = R.makeFilter(); 1547 while (F.hasNext()) { 1548 NamedDecl *D = F.next(); 1549 1550 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1551 continue; 1552 1553 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1554 continue; 1555 1556 F.erase(); 1557 } 1558 1559 F.done(); 1560 } 1561 1562 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1563 /// have compatible owning modules. 1564 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1565 // FIXME: The Modules TS is not clear about how friend declarations are 1566 // to be treated. It's not meaningful to have different owning modules for 1567 // linkage in redeclarations of the same entity, so for now allow the 1568 // redeclaration and change the owning modules to match. 1569 if (New->getFriendObjectKind() && 1570 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1571 New->setLocalOwningModule(Old->getOwningModule()); 1572 makeMergedDefinitionVisible(New); 1573 return false; 1574 } 1575 1576 Module *NewM = New->getOwningModule(); 1577 Module *OldM = Old->getOwningModule(); 1578 1579 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1580 NewM = NewM->Parent; 1581 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1582 OldM = OldM->Parent; 1583 1584 if (NewM == OldM) 1585 return false; 1586 1587 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1588 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1589 if (NewIsModuleInterface || OldIsModuleInterface) { 1590 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1591 // if a declaration of D [...] appears in the purview of a module, all 1592 // other such declarations shall appear in the purview of the same module 1593 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1594 << New 1595 << NewIsModuleInterface 1596 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1597 << OldIsModuleInterface 1598 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1599 Diag(Old->getLocation(), diag::note_previous_declaration); 1600 New->setInvalidDecl(); 1601 return true; 1602 } 1603 1604 return false; 1605 } 1606 1607 static bool isUsingDecl(NamedDecl *D) { 1608 return isa<UsingShadowDecl>(D) || 1609 isa<UnresolvedUsingTypenameDecl>(D) || 1610 isa<UnresolvedUsingValueDecl>(D); 1611 } 1612 1613 /// Removes using shadow declarations from the lookup results. 1614 static void RemoveUsingDecls(LookupResult &R) { 1615 LookupResult::Filter F = R.makeFilter(); 1616 while (F.hasNext()) 1617 if (isUsingDecl(F.next())) 1618 F.erase(); 1619 1620 F.done(); 1621 } 1622 1623 /// Check for this common pattern: 1624 /// @code 1625 /// class S { 1626 /// S(const S&); // DO NOT IMPLEMENT 1627 /// void operator=(const S&); // DO NOT IMPLEMENT 1628 /// }; 1629 /// @endcode 1630 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1631 // FIXME: Should check for private access too but access is set after we get 1632 // the decl here. 1633 if (D->doesThisDeclarationHaveABody()) 1634 return false; 1635 1636 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1637 return CD->isCopyConstructor(); 1638 return D->isCopyAssignmentOperator(); 1639 } 1640 1641 // We need this to handle 1642 // 1643 // typedef struct { 1644 // void *foo() { return 0; } 1645 // } A; 1646 // 1647 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1648 // for example. If 'A', foo will have external linkage. If we have '*A', 1649 // foo will have no linkage. Since we can't know until we get to the end 1650 // of the typedef, this function finds out if D might have non-external linkage. 1651 // Callers should verify at the end of the TU if it D has external linkage or 1652 // not. 1653 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1654 const DeclContext *DC = D->getDeclContext(); 1655 while (!DC->isTranslationUnit()) { 1656 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1657 if (!RD->hasNameForLinkage()) 1658 return true; 1659 } 1660 DC = DC->getParent(); 1661 } 1662 1663 return !D->isExternallyVisible(); 1664 } 1665 1666 // FIXME: This needs to be refactored; some other isInMainFile users want 1667 // these semantics. 1668 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1669 if (S.TUKind != TU_Complete) 1670 return false; 1671 return S.SourceMgr.isInMainFile(Loc); 1672 } 1673 1674 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1675 assert(D); 1676 1677 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1678 return false; 1679 1680 // Ignore all entities declared within templates, and out-of-line definitions 1681 // of members of class templates. 1682 if (D->getDeclContext()->isDependentContext() || 1683 D->getLexicalDeclContext()->isDependentContext()) 1684 return false; 1685 1686 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1687 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1688 return false; 1689 // A non-out-of-line declaration of a member specialization was implicitly 1690 // instantiated; it's the out-of-line declaration that we're interested in. 1691 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1692 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1693 return false; 1694 1695 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1696 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1697 return false; 1698 } else { 1699 // 'static inline' functions are defined in headers; don't warn. 1700 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1701 return false; 1702 } 1703 1704 if (FD->doesThisDeclarationHaveABody() && 1705 Context.DeclMustBeEmitted(FD)) 1706 return false; 1707 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1708 // Constants and utility variables are defined in headers with internal 1709 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1710 // like "inline".) 1711 if (!isMainFileLoc(*this, VD->getLocation())) 1712 return false; 1713 1714 if (Context.DeclMustBeEmitted(VD)) 1715 return false; 1716 1717 if (VD->isStaticDataMember() && 1718 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1719 return false; 1720 if (VD->isStaticDataMember() && 1721 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1722 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1723 return false; 1724 1725 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1726 return false; 1727 } else { 1728 return false; 1729 } 1730 1731 // Only warn for unused decls internal to the translation unit. 1732 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1733 // for inline functions defined in the main source file, for instance. 1734 return mightHaveNonExternalLinkage(D); 1735 } 1736 1737 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1738 if (!D) 1739 return; 1740 1741 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1742 const FunctionDecl *First = FD->getFirstDecl(); 1743 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1744 return; // First should already be in the vector. 1745 } 1746 1747 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1748 const VarDecl *First = VD->getFirstDecl(); 1749 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1750 return; // First should already be in the vector. 1751 } 1752 1753 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1754 UnusedFileScopedDecls.push_back(D); 1755 } 1756 1757 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1758 if (D->isInvalidDecl()) 1759 return false; 1760 1761 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1762 // For a decomposition declaration, warn if none of the bindings are 1763 // referenced, instead of if the variable itself is referenced (which 1764 // it is, by the bindings' expressions). 1765 for (auto *BD : DD->bindings()) 1766 if (BD->isReferenced()) 1767 return false; 1768 } else if (!D->getDeclName()) { 1769 return false; 1770 } else if (D->isReferenced() || D->isUsed()) { 1771 return false; 1772 } 1773 1774 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) 1775 return false; 1776 1777 if (isa<LabelDecl>(D)) 1778 return true; 1779 1780 // Except for labels, we only care about unused decls that are local to 1781 // functions. 1782 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1783 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1784 // For dependent types, the diagnostic is deferred. 1785 WithinFunction = 1786 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1787 if (!WithinFunction) 1788 return false; 1789 1790 if (isa<TypedefNameDecl>(D)) 1791 return true; 1792 1793 // White-list anything that isn't a local variable. 1794 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1795 return false; 1796 1797 // Types of valid local variables should be complete, so this should succeed. 1798 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1799 1800 // White-list anything with an __attribute__((unused)) type. 1801 const auto *Ty = VD->getType().getTypePtr(); 1802 1803 // Only look at the outermost level of typedef. 1804 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1805 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1806 return false; 1807 } 1808 1809 // If we failed to complete the type for some reason, or if the type is 1810 // dependent, don't diagnose the variable. 1811 if (Ty->isIncompleteType() || Ty->isDependentType()) 1812 return false; 1813 1814 // Look at the element type to ensure that the warning behaviour is 1815 // consistent for both scalars and arrays. 1816 Ty = Ty->getBaseElementTypeUnsafe(); 1817 1818 if (const TagType *TT = Ty->getAs<TagType>()) { 1819 const TagDecl *Tag = TT->getDecl(); 1820 if (Tag->hasAttr<UnusedAttr>()) 1821 return false; 1822 1823 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1824 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1825 return false; 1826 1827 if (const Expr *Init = VD->getInit()) { 1828 if (const ExprWithCleanups *Cleanups = 1829 dyn_cast<ExprWithCleanups>(Init)) 1830 Init = Cleanups->getSubExpr(); 1831 const CXXConstructExpr *Construct = 1832 dyn_cast<CXXConstructExpr>(Init); 1833 if (Construct && !Construct->isElidable()) { 1834 CXXConstructorDecl *CD = Construct->getConstructor(); 1835 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1836 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1837 return false; 1838 } 1839 1840 // Suppress the warning if we don't know how this is constructed, and 1841 // it could possibly be non-trivial constructor. 1842 if (Init->isTypeDependent()) 1843 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1844 if (!Ctor->isTrivial()) 1845 return false; 1846 } 1847 } 1848 } 1849 1850 // TODO: __attribute__((unused)) templates? 1851 } 1852 1853 return true; 1854 } 1855 1856 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1857 FixItHint &Hint) { 1858 if (isa<LabelDecl>(D)) { 1859 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1860 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1861 true); 1862 if (AfterColon.isInvalid()) 1863 return; 1864 Hint = FixItHint::CreateRemoval( 1865 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1866 } 1867 } 1868 1869 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1870 if (D->getTypeForDecl()->isDependentType()) 1871 return; 1872 1873 for (auto *TmpD : D->decls()) { 1874 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1875 DiagnoseUnusedDecl(T); 1876 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1877 DiagnoseUnusedNestedTypedefs(R); 1878 } 1879 } 1880 1881 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1882 /// unless they are marked attr(unused). 1883 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1884 if (!ShouldDiagnoseUnusedDecl(D)) 1885 return; 1886 1887 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1888 // typedefs can be referenced later on, so the diagnostics are emitted 1889 // at end-of-translation-unit. 1890 UnusedLocalTypedefNameCandidates.insert(TD); 1891 return; 1892 } 1893 1894 FixItHint Hint; 1895 GenerateFixForUnusedDecl(D, Context, Hint); 1896 1897 unsigned DiagID; 1898 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1899 DiagID = diag::warn_unused_exception_param; 1900 else if (isa<LabelDecl>(D)) 1901 DiagID = diag::warn_unused_label; 1902 else 1903 DiagID = diag::warn_unused_variable; 1904 1905 Diag(D->getLocation(), DiagID) << D << Hint; 1906 } 1907 1908 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1909 // Verify that we have no forward references left. If so, there was a goto 1910 // or address of a label taken, but no definition of it. Label fwd 1911 // definitions are indicated with a null substmt which is also not a resolved 1912 // MS inline assembly label name. 1913 bool Diagnose = false; 1914 if (L->isMSAsmLabel()) 1915 Diagnose = !L->isResolvedMSAsmLabel(); 1916 else 1917 Diagnose = L->getStmt() == nullptr; 1918 if (Diagnose) 1919 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; 1920 } 1921 1922 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1923 S->mergeNRVOIntoParent(); 1924 1925 if (S->decl_empty()) return; 1926 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1927 "Scope shouldn't contain decls!"); 1928 1929 for (auto *TmpD : S->decls()) { 1930 assert(TmpD && "This decl didn't get pushed??"); 1931 1932 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1933 NamedDecl *D = cast<NamedDecl>(TmpD); 1934 1935 // Diagnose unused variables in this scope. 1936 if (!S->hasUnrecoverableErrorOccurred()) { 1937 DiagnoseUnusedDecl(D); 1938 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1939 DiagnoseUnusedNestedTypedefs(RD); 1940 } 1941 1942 if (!D->getDeclName()) continue; 1943 1944 // If this was a forward reference to a label, verify it was defined. 1945 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1946 CheckPoppedLabel(LD, *this); 1947 1948 // Remove this name from our lexical scope, and warn on it if we haven't 1949 // already. 1950 IdResolver.RemoveDecl(D); 1951 auto ShadowI = ShadowingDecls.find(D); 1952 if (ShadowI != ShadowingDecls.end()) { 1953 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1954 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1955 << D << FD << FD->getParent(); 1956 Diag(FD->getLocation(), diag::note_previous_declaration); 1957 } 1958 ShadowingDecls.erase(ShadowI); 1959 } 1960 } 1961 } 1962 1963 /// Look for an Objective-C class in the translation unit. 1964 /// 1965 /// \param Id The name of the Objective-C class we're looking for. If 1966 /// typo-correction fixes this name, the Id will be updated 1967 /// to the fixed name. 1968 /// 1969 /// \param IdLoc The location of the name in the translation unit. 1970 /// 1971 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1972 /// if there is no class with the given name. 1973 /// 1974 /// \returns The declaration of the named Objective-C class, or NULL if the 1975 /// class could not be found. 1976 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1977 SourceLocation IdLoc, 1978 bool DoTypoCorrection) { 1979 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1980 // creation from this context. 1981 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1982 1983 if (!IDecl && DoTypoCorrection) { 1984 // Perform typo correction at the given location, but only if we 1985 // find an Objective-C class name. 1986 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1987 if (TypoCorrection C = 1988 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1989 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1990 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1991 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1992 Id = IDecl->getIdentifier(); 1993 } 1994 } 1995 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1996 // This routine must always return a class definition, if any. 1997 if (Def && Def->getDefinition()) 1998 Def = Def->getDefinition(); 1999 return Def; 2000 } 2001 2002 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2003 /// from S, where a non-field would be declared. This routine copes 2004 /// with the difference between C and C++ scoping rules in structs and 2005 /// unions. For example, the following code is well-formed in C but 2006 /// ill-formed in C++: 2007 /// @code 2008 /// struct S6 { 2009 /// enum { BAR } e; 2010 /// }; 2011 /// 2012 /// void test_S6() { 2013 /// struct S6 a; 2014 /// a.e = BAR; 2015 /// } 2016 /// @endcode 2017 /// For the declaration of BAR, this routine will return a different 2018 /// scope. The scope S will be the scope of the unnamed enumeration 2019 /// within S6. In C++, this routine will return the scope associated 2020 /// with S6, because the enumeration's scope is a transparent 2021 /// context but structures can contain non-field names. In C, this 2022 /// routine will return the translation unit scope, since the 2023 /// enumeration's scope is a transparent context and structures cannot 2024 /// contain non-field names. 2025 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2026 while (((S->getFlags() & Scope::DeclScope) == 0) || 2027 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2028 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2029 S = S->getParent(); 2030 return S; 2031 } 2032 2033 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2034 ASTContext::GetBuiltinTypeError Error) { 2035 switch (Error) { 2036 case ASTContext::GE_None: 2037 return ""; 2038 case ASTContext::GE_Missing_type: 2039 return BuiltinInfo.getHeaderName(ID); 2040 case ASTContext::GE_Missing_stdio: 2041 return "stdio.h"; 2042 case ASTContext::GE_Missing_setjmp: 2043 return "setjmp.h"; 2044 case ASTContext::GE_Missing_ucontext: 2045 return "ucontext.h"; 2046 } 2047 llvm_unreachable("unhandled error kind"); 2048 } 2049 2050 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2051 unsigned ID, SourceLocation Loc) { 2052 DeclContext *Parent = Context.getTranslationUnitDecl(); 2053 2054 if (getLangOpts().CPlusPlus) { 2055 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2056 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); 2057 CLinkageDecl->setImplicit(); 2058 Parent->addDecl(CLinkageDecl); 2059 Parent = CLinkageDecl; 2060 } 2061 2062 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2063 /*TInfo=*/nullptr, SC_Extern, false, 2064 Type->isFunctionProtoType()); 2065 New->setImplicit(); 2066 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2067 2068 // Create Decl objects for each parameter, adding them to the 2069 // FunctionDecl. 2070 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2071 SmallVector<ParmVarDecl *, 16> Params; 2072 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2073 ParmVarDecl *parm = ParmVarDecl::Create( 2074 Context, New, SourceLocation(), SourceLocation(), nullptr, 2075 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2076 parm->setScopeInfo(0, i); 2077 Params.push_back(parm); 2078 } 2079 New->setParams(Params); 2080 } 2081 2082 AddKnownFunctionAttributes(New); 2083 return New; 2084 } 2085 2086 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2087 /// file scope. lazily create a decl for it. ForRedeclaration is true 2088 /// if we're creating this built-in in anticipation of redeclaring the 2089 /// built-in. 2090 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2091 Scope *S, bool ForRedeclaration, 2092 SourceLocation Loc) { 2093 LookupNecessaryTypesForBuiltin(S, ID); 2094 2095 ASTContext::GetBuiltinTypeError Error; 2096 QualType R = Context.GetBuiltinType(ID, Error); 2097 if (Error) { 2098 if (!ForRedeclaration) 2099 return nullptr; 2100 2101 // If we have a builtin without an associated type we should not emit a 2102 // warning when we were not able to find a type for it. 2103 if (Error == ASTContext::GE_Missing_type || 2104 Context.BuiltinInfo.allowTypeMismatch(ID)) 2105 return nullptr; 2106 2107 // If we could not find a type for setjmp it is because the jmp_buf type was 2108 // not defined prior to the setjmp declaration. 2109 if (Error == ASTContext::GE_Missing_setjmp) { 2110 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2111 << Context.BuiltinInfo.getName(ID); 2112 return nullptr; 2113 } 2114 2115 // Generally, we emit a warning that the declaration requires the 2116 // appropriate header. 2117 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2118 << getHeaderName(Context.BuiltinInfo, ID, Error) 2119 << Context.BuiltinInfo.getName(ID); 2120 return nullptr; 2121 } 2122 2123 if (!ForRedeclaration && 2124 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2125 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2126 Diag(Loc, diag::ext_implicit_lib_function_decl) 2127 << Context.BuiltinInfo.getName(ID) << R; 2128 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2129 Diag(Loc, diag::note_include_header_or_declare) 2130 << Header << Context.BuiltinInfo.getName(ID); 2131 } 2132 2133 if (R.isNull()) 2134 return nullptr; 2135 2136 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2137 RegisterLocallyScopedExternCDecl(New, S); 2138 2139 // TUScope is the translation-unit scope to insert this function into. 2140 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2141 // relate Scopes to DeclContexts, and probably eliminate CurContext 2142 // entirely, but we're not there yet. 2143 DeclContext *SavedContext = CurContext; 2144 CurContext = New->getDeclContext(); 2145 PushOnScopeChains(New, TUScope); 2146 CurContext = SavedContext; 2147 return New; 2148 } 2149 2150 /// Typedef declarations don't have linkage, but they still denote the same 2151 /// entity if their types are the same. 2152 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2153 /// isSameEntity. 2154 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2155 TypedefNameDecl *Decl, 2156 LookupResult &Previous) { 2157 // This is only interesting when modules are enabled. 2158 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2159 return; 2160 2161 // Empty sets are uninteresting. 2162 if (Previous.empty()) 2163 return; 2164 2165 LookupResult::Filter Filter = Previous.makeFilter(); 2166 while (Filter.hasNext()) { 2167 NamedDecl *Old = Filter.next(); 2168 2169 // Non-hidden declarations are never ignored. 2170 if (S.isVisible(Old)) 2171 continue; 2172 2173 // Declarations of the same entity are not ignored, even if they have 2174 // different linkages. 2175 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2176 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2177 Decl->getUnderlyingType())) 2178 continue; 2179 2180 // If both declarations give a tag declaration a typedef name for linkage 2181 // purposes, then they declare the same entity. 2182 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2183 Decl->getAnonDeclWithTypedefName()) 2184 continue; 2185 } 2186 2187 Filter.erase(); 2188 } 2189 2190 Filter.done(); 2191 } 2192 2193 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2194 QualType OldType; 2195 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2196 OldType = OldTypedef->getUnderlyingType(); 2197 else 2198 OldType = Context.getTypeDeclType(Old); 2199 QualType NewType = New->getUnderlyingType(); 2200 2201 if (NewType->isVariablyModifiedType()) { 2202 // Must not redefine a typedef with a variably-modified type. 2203 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2204 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2205 << Kind << NewType; 2206 if (Old->getLocation().isValid()) 2207 notePreviousDefinition(Old, New->getLocation()); 2208 New->setInvalidDecl(); 2209 return true; 2210 } 2211 2212 if (OldType != NewType && 2213 !OldType->isDependentType() && 2214 !NewType->isDependentType() && 2215 !Context.hasSameType(OldType, NewType)) { 2216 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2217 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2218 << Kind << NewType << OldType; 2219 if (Old->getLocation().isValid()) 2220 notePreviousDefinition(Old, New->getLocation()); 2221 New->setInvalidDecl(); 2222 return true; 2223 } 2224 return false; 2225 } 2226 2227 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2228 /// same name and scope as a previous declaration 'Old'. Figure out 2229 /// how to resolve this situation, merging decls or emitting 2230 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2231 /// 2232 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2233 LookupResult &OldDecls) { 2234 // If the new decl is known invalid already, don't bother doing any 2235 // merging checks. 2236 if (New->isInvalidDecl()) return; 2237 2238 // Allow multiple definitions for ObjC built-in typedefs. 2239 // FIXME: Verify the underlying types are equivalent! 2240 if (getLangOpts().ObjC) { 2241 const IdentifierInfo *TypeID = New->getIdentifier(); 2242 switch (TypeID->getLength()) { 2243 default: break; 2244 case 2: 2245 { 2246 if (!TypeID->isStr("id")) 2247 break; 2248 QualType T = New->getUnderlyingType(); 2249 if (!T->isPointerType()) 2250 break; 2251 if (!T->isVoidPointerType()) { 2252 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2253 if (!PT->isStructureType()) 2254 break; 2255 } 2256 Context.setObjCIdRedefinitionType(T); 2257 // Install the built-in type for 'id', ignoring the current definition. 2258 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2259 return; 2260 } 2261 case 5: 2262 if (!TypeID->isStr("Class")) 2263 break; 2264 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2265 // Install the built-in type for 'Class', ignoring the current definition. 2266 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2267 return; 2268 case 3: 2269 if (!TypeID->isStr("SEL")) 2270 break; 2271 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2272 // Install the built-in type for 'SEL', ignoring the current definition. 2273 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2274 return; 2275 } 2276 // Fall through - the typedef name was not a builtin type. 2277 } 2278 2279 // Verify the old decl was also a type. 2280 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2281 if (!Old) { 2282 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2283 << New->getDeclName(); 2284 2285 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2286 if (OldD->getLocation().isValid()) 2287 notePreviousDefinition(OldD, New->getLocation()); 2288 2289 return New->setInvalidDecl(); 2290 } 2291 2292 // If the old declaration is invalid, just give up here. 2293 if (Old->isInvalidDecl()) 2294 return New->setInvalidDecl(); 2295 2296 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2297 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2298 auto *NewTag = New->getAnonDeclWithTypedefName(); 2299 NamedDecl *Hidden = nullptr; 2300 if (OldTag && NewTag && 2301 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2302 !hasVisibleDefinition(OldTag, &Hidden)) { 2303 // There is a definition of this tag, but it is not visible. Use it 2304 // instead of our tag. 2305 New->setTypeForDecl(OldTD->getTypeForDecl()); 2306 if (OldTD->isModed()) 2307 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2308 OldTD->getUnderlyingType()); 2309 else 2310 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2311 2312 // Make the old tag definition visible. 2313 makeMergedDefinitionVisible(Hidden); 2314 2315 // If this was an unscoped enumeration, yank all of its enumerators 2316 // out of the scope. 2317 if (isa<EnumDecl>(NewTag)) { 2318 Scope *EnumScope = getNonFieldDeclScope(S); 2319 for (auto *D : NewTag->decls()) { 2320 auto *ED = cast<EnumConstantDecl>(D); 2321 assert(EnumScope->isDeclScope(ED)); 2322 EnumScope->RemoveDecl(ED); 2323 IdResolver.RemoveDecl(ED); 2324 ED->getLexicalDeclContext()->removeDecl(ED); 2325 } 2326 } 2327 } 2328 } 2329 2330 // If the typedef types are not identical, reject them in all languages and 2331 // with any extensions enabled. 2332 if (isIncompatibleTypedef(Old, New)) 2333 return; 2334 2335 // The types match. Link up the redeclaration chain and merge attributes if 2336 // the old declaration was a typedef. 2337 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2338 New->setPreviousDecl(Typedef); 2339 mergeDeclAttributes(New, Old); 2340 } 2341 2342 if (getLangOpts().MicrosoftExt) 2343 return; 2344 2345 if (getLangOpts().CPlusPlus) { 2346 // C++ [dcl.typedef]p2: 2347 // In a given non-class scope, a typedef specifier can be used to 2348 // redefine the name of any type declared in that scope to refer 2349 // to the type to which it already refers. 2350 if (!isa<CXXRecordDecl>(CurContext)) 2351 return; 2352 2353 // C++0x [dcl.typedef]p4: 2354 // In a given class scope, a typedef specifier can be used to redefine 2355 // any class-name declared in that scope that is not also a typedef-name 2356 // to refer to the type to which it already refers. 2357 // 2358 // This wording came in via DR424, which was a correction to the 2359 // wording in DR56, which accidentally banned code like: 2360 // 2361 // struct S { 2362 // typedef struct A { } A; 2363 // }; 2364 // 2365 // in the C++03 standard. We implement the C++0x semantics, which 2366 // allow the above but disallow 2367 // 2368 // struct S { 2369 // typedef int I; 2370 // typedef int I; 2371 // }; 2372 // 2373 // since that was the intent of DR56. 2374 if (!isa<TypedefNameDecl>(Old)) 2375 return; 2376 2377 Diag(New->getLocation(), diag::err_redefinition) 2378 << New->getDeclName(); 2379 notePreviousDefinition(Old, New->getLocation()); 2380 return New->setInvalidDecl(); 2381 } 2382 2383 // Modules always permit redefinition of typedefs, as does C11. 2384 if (getLangOpts().Modules || getLangOpts().C11) 2385 return; 2386 2387 // If we have a redefinition of a typedef in C, emit a warning. This warning 2388 // is normally mapped to an error, but can be controlled with 2389 // -Wtypedef-redefinition. If either the original or the redefinition is 2390 // in a system header, don't emit this for compatibility with GCC. 2391 if (getDiagnostics().getSuppressSystemWarnings() && 2392 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2393 (Old->isImplicit() || 2394 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2395 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2396 return; 2397 2398 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2399 << New->getDeclName(); 2400 notePreviousDefinition(Old, New->getLocation()); 2401 } 2402 2403 /// DeclhasAttr - returns true if decl Declaration already has the target 2404 /// attribute. 2405 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2406 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2407 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2408 for (const auto *i : D->attrs()) 2409 if (i->getKind() == A->getKind()) { 2410 if (Ann) { 2411 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2412 return true; 2413 continue; 2414 } 2415 // FIXME: Don't hardcode this check 2416 if (OA && isa<OwnershipAttr>(i)) 2417 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2418 return true; 2419 } 2420 2421 return false; 2422 } 2423 2424 static bool isAttributeTargetADefinition(Decl *D) { 2425 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2426 return VD->isThisDeclarationADefinition(); 2427 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2428 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2429 return true; 2430 } 2431 2432 /// Merge alignment attributes from \p Old to \p New, taking into account the 2433 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2434 /// 2435 /// \return \c true if any attributes were added to \p New. 2436 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2437 // Look for alignas attributes on Old, and pick out whichever attribute 2438 // specifies the strictest alignment requirement. 2439 AlignedAttr *OldAlignasAttr = nullptr; 2440 AlignedAttr *OldStrictestAlignAttr = nullptr; 2441 unsigned OldAlign = 0; 2442 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2443 // FIXME: We have no way of representing inherited dependent alignments 2444 // in a case like: 2445 // template<int A, int B> struct alignas(A) X; 2446 // template<int A, int B> struct alignas(B) X {}; 2447 // For now, we just ignore any alignas attributes which are not on the 2448 // definition in such a case. 2449 if (I->isAlignmentDependent()) 2450 return false; 2451 2452 if (I->isAlignas()) 2453 OldAlignasAttr = I; 2454 2455 unsigned Align = I->getAlignment(S.Context); 2456 if (Align > OldAlign) { 2457 OldAlign = Align; 2458 OldStrictestAlignAttr = I; 2459 } 2460 } 2461 2462 // Look for alignas attributes on New. 2463 AlignedAttr *NewAlignasAttr = nullptr; 2464 unsigned NewAlign = 0; 2465 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2466 if (I->isAlignmentDependent()) 2467 return false; 2468 2469 if (I->isAlignas()) 2470 NewAlignasAttr = I; 2471 2472 unsigned Align = I->getAlignment(S.Context); 2473 if (Align > NewAlign) 2474 NewAlign = Align; 2475 } 2476 2477 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2478 // Both declarations have 'alignas' attributes. We require them to match. 2479 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2480 // fall short. (If two declarations both have alignas, they must both match 2481 // every definition, and so must match each other if there is a definition.) 2482 2483 // If either declaration only contains 'alignas(0)' specifiers, then it 2484 // specifies the natural alignment for the type. 2485 if (OldAlign == 0 || NewAlign == 0) { 2486 QualType Ty; 2487 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2488 Ty = VD->getType(); 2489 else 2490 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2491 2492 if (OldAlign == 0) 2493 OldAlign = S.Context.getTypeAlign(Ty); 2494 if (NewAlign == 0) 2495 NewAlign = S.Context.getTypeAlign(Ty); 2496 } 2497 2498 if (OldAlign != NewAlign) { 2499 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2500 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2501 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2502 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2503 } 2504 } 2505 2506 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2507 // C++11 [dcl.align]p6: 2508 // if any declaration of an entity has an alignment-specifier, 2509 // every defining declaration of that entity shall specify an 2510 // equivalent alignment. 2511 // C11 6.7.5/7: 2512 // If the definition of an object does not have an alignment 2513 // specifier, any other declaration of that object shall also 2514 // have no alignment specifier. 2515 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2516 << OldAlignasAttr; 2517 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2518 << OldAlignasAttr; 2519 } 2520 2521 bool AnyAdded = false; 2522 2523 // Ensure we have an attribute representing the strictest alignment. 2524 if (OldAlign > NewAlign) { 2525 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2526 Clone->setInherited(true); 2527 New->addAttr(Clone); 2528 AnyAdded = true; 2529 } 2530 2531 // Ensure we have an alignas attribute if the old declaration had one. 2532 if (OldAlignasAttr && !NewAlignasAttr && 2533 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2534 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2535 Clone->setInherited(true); 2536 New->addAttr(Clone); 2537 AnyAdded = true; 2538 } 2539 2540 return AnyAdded; 2541 } 2542 2543 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2544 const InheritableAttr *Attr, 2545 Sema::AvailabilityMergeKind AMK) { 2546 // This function copies an attribute Attr from a previous declaration to the 2547 // new declaration D if the new declaration doesn't itself have that attribute 2548 // yet or if that attribute allows duplicates. 2549 // If you're adding a new attribute that requires logic different from 2550 // "use explicit attribute on decl if present, else use attribute from 2551 // previous decl", for example if the attribute needs to be consistent 2552 // between redeclarations, you need to call a custom merge function here. 2553 InheritableAttr *NewAttr = nullptr; 2554 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2555 NewAttr = S.mergeAvailabilityAttr( 2556 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2557 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2558 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2559 AA->getPriority()); 2560 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2561 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2562 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2563 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2564 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2565 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2566 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2567 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2568 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2569 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2570 FA->getFirstArg()); 2571 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2572 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2573 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2574 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2575 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2576 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2577 IA->getInheritanceModel()); 2578 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2579 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2580 &S.Context.Idents.get(AA->getSpelling())); 2581 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2582 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2583 isa<CUDAGlobalAttr>(Attr))) { 2584 // CUDA target attributes are part of function signature for 2585 // overloading purposes and must not be merged. 2586 return false; 2587 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2588 NewAttr = S.mergeMinSizeAttr(D, *MA); 2589 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2590 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2591 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2592 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2593 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2594 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2595 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2596 NewAttr = S.mergeCommonAttr(D, *CommonA); 2597 else if (isa<AlignedAttr>(Attr)) 2598 // AlignedAttrs are handled separately, because we need to handle all 2599 // such attributes on a declaration at the same time. 2600 NewAttr = nullptr; 2601 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2602 (AMK == Sema::AMK_Override || 2603 AMK == Sema::AMK_ProtocolImplementation)) 2604 NewAttr = nullptr; 2605 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2606 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2607 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2608 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2609 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2610 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2611 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2612 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2613 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2614 NewAttr = S.mergeImportNameAttr(D, *INA); 2615 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 2616 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 2617 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 2618 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 2619 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2620 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2621 2622 if (NewAttr) { 2623 NewAttr->setInherited(true); 2624 D->addAttr(NewAttr); 2625 if (isa<MSInheritanceAttr>(NewAttr)) 2626 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2627 return true; 2628 } 2629 2630 return false; 2631 } 2632 2633 static const NamedDecl *getDefinition(const Decl *D) { 2634 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2635 return TD->getDefinition(); 2636 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2637 const VarDecl *Def = VD->getDefinition(); 2638 if (Def) 2639 return Def; 2640 return VD->getActingDefinition(); 2641 } 2642 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2643 const FunctionDecl *Def = nullptr; 2644 if (FD->isDefined(Def, true)) 2645 return Def; 2646 } 2647 return nullptr; 2648 } 2649 2650 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2651 for (const auto *Attribute : D->attrs()) 2652 if (Attribute->getKind() == Kind) 2653 return true; 2654 return false; 2655 } 2656 2657 /// checkNewAttributesAfterDef - If we already have a definition, check that 2658 /// there are no new attributes in this declaration. 2659 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2660 if (!New->hasAttrs()) 2661 return; 2662 2663 const NamedDecl *Def = getDefinition(Old); 2664 if (!Def || Def == New) 2665 return; 2666 2667 AttrVec &NewAttributes = New->getAttrs(); 2668 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2669 const Attr *NewAttribute = NewAttributes[I]; 2670 2671 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2672 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2673 Sema::SkipBodyInfo SkipBody; 2674 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2675 2676 // If we're skipping this definition, drop the "alias" attribute. 2677 if (SkipBody.ShouldSkip) { 2678 NewAttributes.erase(NewAttributes.begin() + I); 2679 --E; 2680 continue; 2681 } 2682 } else { 2683 VarDecl *VD = cast<VarDecl>(New); 2684 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2685 VarDecl::TentativeDefinition 2686 ? diag::err_alias_after_tentative 2687 : diag::err_redefinition; 2688 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2689 if (Diag == diag::err_redefinition) 2690 S.notePreviousDefinition(Def, VD->getLocation()); 2691 else 2692 S.Diag(Def->getLocation(), diag::note_previous_definition); 2693 VD->setInvalidDecl(); 2694 } 2695 ++I; 2696 continue; 2697 } 2698 2699 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2700 // Tentative definitions are only interesting for the alias check above. 2701 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2702 ++I; 2703 continue; 2704 } 2705 } 2706 2707 if (hasAttribute(Def, NewAttribute->getKind())) { 2708 ++I; 2709 continue; // regular attr merging will take care of validating this. 2710 } 2711 2712 if (isa<C11NoReturnAttr>(NewAttribute)) { 2713 // C's _Noreturn is allowed to be added to a function after it is defined. 2714 ++I; 2715 continue; 2716 } else if (isa<UuidAttr>(NewAttribute)) { 2717 // msvc will allow a subsequent definition to add an uuid to a class 2718 ++I; 2719 continue; 2720 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2721 if (AA->isAlignas()) { 2722 // C++11 [dcl.align]p6: 2723 // if any declaration of an entity has an alignment-specifier, 2724 // every defining declaration of that entity shall specify an 2725 // equivalent alignment. 2726 // C11 6.7.5/7: 2727 // If the definition of an object does not have an alignment 2728 // specifier, any other declaration of that object shall also 2729 // have no alignment specifier. 2730 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2731 << AA; 2732 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2733 << AA; 2734 NewAttributes.erase(NewAttributes.begin() + I); 2735 --E; 2736 continue; 2737 } 2738 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2739 // If there is a C definition followed by a redeclaration with this 2740 // attribute then there are two different definitions. In C++, prefer the 2741 // standard diagnostics. 2742 if (!S.getLangOpts().CPlusPlus) { 2743 S.Diag(NewAttribute->getLocation(), 2744 diag::err_loader_uninitialized_redeclaration); 2745 S.Diag(Def->getLocation(), diag::note_previous_definition); 2746 NewAttributes.erase(NewAttributes.begin() + I); 2747 --E; 2748 continue; 2749 } 2750 } else if (isa<SelectAnyAttr>(NewAttribute) && 2751 cast<VarDecl>(New)->isInline() && 2752 !cast<VarDecl>(New)->isInlineSpecified()) { 2753 // Don't warn about applying selectany to implicitly inline variables. 2754 // Older compilers and language modes would require the use of selectany 2755 // to make such variables inline, and it would have no effect if we 2756 // honored it. 2757 ++I; 2758 continue; 2759 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2760 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2761 // declarations after defintions. 2762 ++I; 2763 continue; 2764 } 2765 2766 S.Diag(NewAttribute->getLocation(), 2767 diag::warn_attribute_precede_definition); 2768 S.Diag(Def->getLocation(), diag::note_previous_definition); 2769 NewAttributes.erase(NewAttributes.begin() + I); 2770 --E; 2771 } 2772 } 2773 2774 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2775 const ConstInitAttr *CIAttr, 2776 bool AttrBeforeInit) { 2777 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2778 2779 // Figure out a good way to write this specifier on the old declaration. 2780 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2781 // enough of the attribute list spelling information to extract that without 2782 // heroics. 2783 std::string SuitableSpelling; 2784 if (S.getLangOpts().CPlusPlus20) 2785 SuitableSpelling = std::string( 2786 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2787 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2788 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2789 InsertLoc, {tok::l_square, tok::l_square, 2790 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2791 S.PP.getIdentifierInfo("require_constant_initialization"), 2792 tok::r_square, tok::r_square})); 2793 if (SuitableSpelling.empty()) 2794 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2795 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2796 S.PP.getIdentifierInfo("require_constant_initialization"), 2797 tok::r_paren, tok::r_paren})); 2798 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2799 SuitableSpelling = "constinit"; 2800 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2801 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2802 if (SuitableSpelling.empty()) 2803 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2804 SuitableSpelling += " "; 2805 2806 if (AttrBeforeInit) { 2807 // extern constinit int a; 2808 // int a = 0; // error (missing 'constinit'), accepted as extension 2809 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2810 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2811 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2812 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2813 } else { 2814 // int a = 0; 2815 // constinit extern int a; // error (missing 'constinit') 2816 S.Diag(CIAttr->getLocation(), 2817 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2818 : diag::warn_require_const_init_added_too_late) 2819 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2820 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2821 << CIAttr->isConstinit() 2822 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2823 } 2824 } 2825 2826 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2827 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2828 AvailabilityMergeKind AMK) { 2829 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2830 UsedAttr *NewAttr = OldAttr->clone(Context); 2831 NewAttr->setInherited(true); 2832 New->addAttr(NewAttr); 2833 } 2834 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { 2835 RetainAttr *NewAttr = OldAttr->clone(Context); 2836 NewAttr->setInherited(true); 2837 New->addAttr(NewAttr); 2838 } 2839 2840 if (!Old->hasAttrs() && !New->hasAttrs()) 2841 return; 2842 2843 // [dcl.constinit]p1: 2844 // If the [constinit] specifier is applied to any declaration of a 2845 // variable, it shall be applied to the initializing declaration. 2846 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2847 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2848 if (bool(OldConstInit) != bool(NewConstInit)) { 2849 const auto *OldVD = cast<VarDecl>(Old); 2850 auto *NewVD = cast<VarDecl>(New); 2851 2852 // Find the initializing declaration. Note that we might not have linked 2853 // the new declaration into the redeclaration chain yet. 2854 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2855 if (!InitDecl && 2856 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2857 InitDecl = NewVD; 2858 2859 if (InitDecl == NewVD) { 2860 // This is the initializing declaration. If it would inherit 'constinit', 2861 // that's ill-formed. (Note that we do not apply this to the attribute 2862 // form). 2863 if (OldConstInit && OldConstInit->isConstinit()) 2864 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2865 /*AttrBeforeInit=*/true); 2866 } else if (NewConstInit) { 2867 // This is the first time we've been told that this declaration should 2868 // have a constant initializer. If we already saw the initializing 2869 // declaration, this is too late. 2870 if (InitDecl && InitDecl != NewVD) { 2871 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2872 /*AttrBeforeInit=*/false); 2873 NewVD->dropAttr<ConstInitAttr>(); 2874 } 2875 } 2876 } 2877 2878 // Attributes declared post-definition are currently ignored. 2879 checkNewAttributesAfterDef(*this, New, Old); 2880 2881 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2882 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2883 if (!OldA->isEquivalent(NewA)) { 2884 // This redeclaration changes __asm__ label. 2885 Diag(New->getLocation(), diag::err_different_asm_label); 2886 Diag(OldA->getLocation(), diag::note_previous_declaration); 2887 } 2888 } else if (Old->isUsed()) { 2889 // This redeclaration adds an __asm__ label to a declaration that has 2890 // already been ODR-used. 2891 Diag(New->getLocation(), diag::err_late_asm_label_name) 2892 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2893 } 2894 } 2895 2896 // Re-declaration cannot add abi_tag's. 2897 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2898 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2899 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2900 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2901 NewTag) == OldAbiTagAttr->tags_end()) { 2902 Diag(NewAbiTagAttr->getLocation(), 2903 diag::err_new_abi_tag_on_redeclaration) 2904 << NewTag; 2905 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2906 } 2907 } 2908 } else { 2909 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2910 Diag(Old->getLocation(), diag::note_previous_declaration); 2911 } 2912 } 2913 2914 // This redeclaration adds a section attribute. 2915 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2916 if (auto *VD = dyn_cast<VarDecl>(New)) { 2917 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2918 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2919 Diag(Old->getLocation(), diag::note_previous_declaration); 2920 } 2921 } 2922 } 2923 2924 // Redeclaration adds code-seg attribute. 2925 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2926 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2927 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2928 Diag(New->getLocation(), diag::warn_mismatched_section) 2929 << 0 /*codeseg*/; 2930 Diag(Old->getLocation(), diag::note_previous_declaration); 2931 } 2932 2933 if (!Old->hasAttrs()) 2934 return; 2935 2936 bool foundAny = New->hasAttrs(); 2937 2938 // Ensure that any moving of objects within the allocated map is done before 2939 // we process them. 2940 if (!foundAny) New->setAttrs(AttrVec()); 2941 2942 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2943 // Ignore deprecated/unavailable/availability attributes if requested. 2944 AvailabilityMergeKind LocalAMK = AMK_None; 2945 if (isa<DeprecatedAttr>(I) || 2946 isa<UnavailableAttr>(I) || 2947 isa<AvailabilityAttr>(I)) { 2948 switch (AMK) { 2949 case AMK_None: 2950 continue; 2951 2952 case AMK_Redeclaration: 2953 case AMK_Override: 2954 case AMK_ProtocolImplementation: 2955 LocalAMK = AMK; 2956 break; 2957 } 2958 } 2959 2960 // Already handled. 2961 if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) 2962 continue; 2963 2964 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2965 foundAny = true; 2966 } 2967 2968 if (mergeAlignedAttrs(*this, New, Old)) 2969 foundAny = true; 2970 2971 if (!foundAny) New->dropAttrs(); 2972 } 2973 2974 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2975 /// to the new one. 2976 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2977 const ParmVarDecl *oldDecl, 2978 Sema &S) { 2979 // C++11 [dcl.attr.depend]p2: 2980 // The first declaration of a function shall specify the 2981 // carries_dependency attribute for its declarator-id if any declaration 2982 // of the function specifies the carries_dependency attribute. 2983 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2984 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2985 S.Diag(CDA->getLocation(), 2986 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2987 // Find the first declaration of the parameter. 2988 // FIXME: Should we build redeclaration chains for function parameters? 2989 const FunctionDecl *FirstFD = 2990 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2991 const ParmVarDecl *FirstVD = 2992 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2993 S.Diag(FirstVD->getLocation(), 2994 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2995 } 2996 2997 if (!oldDecl->hasAttrs()) 2998 return; 2999 3000 bool foundAny = newDecl->hasAttrs(); 3001 3002 // Ensure that any moving of objects within the allocated map is 3003 // done before we process them. 3004 if (!foundAny) newDecl->setAttrs(AttrVec()); 3005 3006 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3007 if (!DeclHasAttr(newDecl, I)) { 3008 InheritableAttr *newAttr = 3009 cast<InheritableParamAttr>(I->clone(S.Context)); 3010 newAttr->setInherited(true); 3011 newDecl->addAttr(newAttr); 3012 foundAny = true; 3013 } 3014 } 3015 3016 if (!foundAny) newDecl->dropAttrs(); 3017 } 3018 3019 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3020 const ParmVarDecl *OldParam, 3021 Sema &S) { 3022 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3023 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3024 if (*Oldnullability != *Newnullability) { 3025 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3026 << DiagNullabilityKind( 3027 *Newnullability, 3028 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3029 != 0)) 3030 << DiagNullabilityKind( 3031 *Oldnullability, 3032 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3033 != 0)); 3034 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3035 } 3036 } else { 3037 QualType NewT = NewParam->getType(); 3038 NewT = S.Context.getAttributedType( 3039 AttributedType::getNullabilityAttrKind(*Oldnullability), 3040 NewT, NewT); 3041 NewParam->setType(NewT); 3042 } 3043 } 3044 } 3045 3046 namespace { 3047 3048 /// Used in MergeFunctionDecl to keep track of function parameters in 3049 /// C. 3050 struct GNUCompatibleParamWarning { 3051 ParmVarDecl *OldParm; 3052 ParmVarDecl *NewParm; 3053 QualType PromotedType; 3054 }; 3055 3056 } // end anonymous namespace 3057 3058 // Determine whether the previous declaration was a definition, implicit 3059 // declaration, or a declaration. 3060 template <typename T> 3061 static std::pair<diag::kind, SourceLocation> 3062 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3063 diag::kind PrevDiag; 3064 SourceLocation OldLocation = Old->getLocation(); 3065 if (Old->isThisDeclarationADefinition()) 3066 PrevDiag = diag::note_previous_definition; 3067 else if (Old->isImplicit()) { 3068 PrevDiag = diag::note_previous_implicit_declaration; 3069 if (OldLocation.isInvalid()) 3070 OldLocation = New->getLocation(); 3071 } else 3072 PrevDiag = diag::note_previous_declaration; 3073 return std::make_pair(PrevDiag, OldLocation); 3074 } 3075 3076 /// canRedefineFunction - checks if a function can be redefined. Currently, 3077 /// only extern inline functions can be redefined, and even then only in 3078 /// GNU89 mode. 3079 static bool canRedefineFunction(const FunctionDecl *FD, 3080 const LangOptions& LangOpts) { 3081 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3082 !LangOpts.CPlusPlus && 3083 FD->isInlineSpecified() && 3084 FD->getStorageClass() == SC_Extern); 3085 } 3086 3087 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3088 const AttributedType *AT = T->getAs<AttributedType>(); 3089 while (AT && !AT->isCallingConv()) 3090 AT = AT->getModifiedType()->getAs<AttributedType>(); 3091 return AT; 3092 } 3093 3094 template <typename T> 3095 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3096 const DeclContext *DC = Old->getDeclContext(); 3097 if (DC->isRecord()) 3098 return false; 3099 3100 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3101 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3102 return true; 3103 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3104 return true; 3105 return false; 3106 } 3107 3108 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3109 static bool isExternC(VarTemplateDecl *) { return false; } 3110 3111 /// Check whether a redeclaration of an entity introduced by a 3112 /// using-declaration is valid, given that we know it's not an overload 3113 /// (nor a hidden tag declaration). 3114 template<typename ExpectedDecl> 3115 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3116 ExpectedDecl *New) { 3117 // C++11 [basic.scope.declarative]p4: 3118 // Given a set of declarations in a single declarative region, each of 3119 // which specifies the same unqualified name, 3120 // -- they shall all refer to the same entity, or all refer to functions 3121 // and function templates; or 3122 // -- exactly one declaration shall declare a class name or enumeration 3123 // name that is not a typedef name and the other declarations shall all 3124 // refer to the same variable or enumerator, or all refer to functions 3125 // and function templates; in this case the class name or enumeration 3126 // name is hidden (3.3.10). 3127 3128 // C++11 [namespace.udecl]p14: 3129 // If a function declaration in namespace scope or block scope has the 3130 // same name and the same parameter-type-list as a function introduced 3131 // by a using-declaration, and the declarations do not declare the same 3132 // function, the program is ill-formed. 3133 3134 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3135 if (Old && 3136 !Old->getDeclContext()->getRedeclContext()->Equals( 3137 New->getDeclContext()->getRedeclContext()) && 3138 !(isExternC(Old) && isExternC(New))) 3139 Old = nullptr; 3140 3141 if (!Old) { 3142 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3143 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3144 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3145 return true; 3146 } 3147 return false; 3148 } 3149 3150 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3151 const FunctionDecl *B) { 3152 assert(A->getNumParams() == B->getNumParams()); 3153 3154 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3155 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3156 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3157 if (AttrA == AttrB) 3158 return true; 3159 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3160 AttrA->isDynamic() == AttrB->isDynamic(); 3161 }; 3162 3163 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3164 } 3165 3166 /// If necessary, adjust the semantic declaration context for a qualified 3167 /// declaration to name the correct inline namespace within the qualifier. 3168 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3169 DeclaratorDecl *OldD) { 3170 // The only case where we need to update the DeclContext is when 3171 // redeclaration lookup for a qualified name finds a declaration 3172 // in an inline namespace within the context named by the qualifier: 3173 // 3174 // inline namespace N { int f(); } 3175 // int ::f(); // Sema DC needs adjusting from :: to N::. 3176 // 3177 // For unqualified declarations, the semantic context *can* change 3178 // along the redeclaration chain (for local extern declarations, 3179 // extern "C" declarations, and friend declarations in particular). 3180 if (!NewD->getQualifier()) 3181 return; 3182 3183 // NewD is probably already in the right context. 3184 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3185 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3186 if (NamedDC->Equals(SemaDC)) 3187 return; 3188 3189 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3190 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3191 "unexpected context for redeclaration"); 3192 3193 auto *LexDC = NewD->getLexicalDeclContext(); 3194 auto FixSemaDC = [=](NamedDecl *D) { 3195 if (!D) 3196 return; 3197 D->setDeclContext(SemaDC); 3198 D->setLexicalDeclContext(LexDC); 3199 }; 3200 3201 FixSemaDC(NewD); 3202 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3203 FixSemaDC(FD->getDescribedFunctionTemplate()); 3204 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3205 FixSemaDC(VD->getDescribedVarTemplate()); 3206 } 3207 3208 /// MergeFunctionDecl - We just parsed a function 'New' from 3209 /// declarator D which has the same name and scope as a previous 3210 /// declaration 'Old'. Figure out how to resolve this situation, 3211 /// merging decls or emitting diagnostics as appropriate. 3212 /// 3213 /// In C++, New and Old must be declarations that are not 3214 /// overloaded. Use IsOverload to determine whether New and Old are 3215 /// overloaded, and to select the Old declaration that New should be 3216 /// merged with. 3217 /// 3218 /// Returns true if there was an error, false otherwise. 3219 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3220 Scope *S, bool MergeTypeWithOld) { 3221 // Verify the old decl was also a function. 3222 FunctionDecl *Old = OldD->getAsFunction(); 3223 if (!Old) { 3224 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3225 if (New->getFriendObjectKind()) { 3226 Diag(New->getLocation(), diag::err_using_decl_friend); 3227 Diag(Shadow->getTargetDecl()->getLocation(), 3228 diag::note_using_decl_target); 3229 Diag(Shadow->getUsingDecl()->getLocation(), 3230 diag::note_using_decl) << 0; 3231 return true; 3232 } 3233 3234 // Check whether the two declarations might declare the same function. 3235 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3236 return true; 3237 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3238 } else { 3239 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3240 << New->getDeclName(); 3241 notePreviousDefinition(OldD, New->getLocation()); 3242 return true; 3243 } 3244 } 3245 3246 // If the old declaration was found in an inline namespace and the new 3247 // declaration was qualified, update the DeclContext to match. 3248 adjustDeclContextForDeclaratorDecl(New, Old); 3249 3250 // If the old declaration is invalid, just give up here. 3251 if (Old->isInvalidDecl()) 3252 return true; 3253 3254 // Disallow redeclaration of some builtins. 3255 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3256 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3257 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3258 << Old << Old->getType(); 3259 return true; 3260 } 3261 3262 diag::kind PrevDiag; 3263 SourceLocation OldLocation; 3264 std::tie(PrevDiag, OldLocation) = 3265 getNoteDiagForInvalidRedeclaration(Old, New); 3266 3267 // Don't complain about this if we're in GNU89 mode and the old function 3268 // is an extern inline function. 3269 // Don't complain about specializations. They are not supposed to have 3270 // storage classes. 3271 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3272 New->getStorageClass() == SC_Static && 3273 Old->hasExternalFormalLinkage() && 3274 !New->getTemplateSpecializationInfo() && 3275 !canRedefineFunction(Old, getLangOpts())) { 3276 if (getLangOpts().MicrosoftExt) { 3277 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3278 Diag(OldLocation, PrevDiag); 3279 } else { 3280 Diag(New->getLocation(), diag::err_static_non_static) << New; 3281 Diag(OldLocation, PrevDiag); 3282 return true; 3283 } 3284 } 3285 3286 if (New->hasAttr<InternalLinkageAttr>() && 3287 !Old->hasAttr<InternalLinkageAttr>()) { 3288 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3289 << New->getDeclName(); 3290 notePreviousDefinition(Old, New->getLocation()); 3291 New->dropAttr<InternalLinkageAttr>(); 3292 } 3293 3294 if (CheckRedeclarationModuleOwnership(New, Old)) 3295 return true; 3296 3297 if (!getLangOpts().CPlusPlus) { 3298 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3299 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3300 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3301 << New << OldOvl; 3302 3303 // Try our best to find a decl that actually has the overloadable 3304 // attribute for the note. In most cases (e.g. programs with only one 3305 // broken declaration/definition), this won't matter. 3306 // 3307 // FIXME: We could do this if we juggled some extra state in 3308 // OverloadableAttr, rather than just removing it. 3309 const Decl *DiagOld = Old; 3310 if (OldOvl) { 3311 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3312 const auto *A = D->getAttr<OverloadableAttr>(); 3313 return A && !A->isImplicit(); 3314 }); 3315 // If we've implicitly added *all* of the overloadable attrs to this 3316 // chain, emitting a "previous redecl" note is pointless. 3317 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3318 } 3319 3320 if (DiagOld) 3321 Diag(DiagOld->getLocation(), 3322 diag::note_attribute_overloadable_prev_overload) 3323 << OldOvl; 3324 3325 if (OldOvl) 3326 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3327 else 3328 New->dropAttr<OverloadableAttr>(); 3329 } 3330 } 3331 3332 // If a function is first declared with a calling convention, but is later 3333 // declared or defined without one, all following decls assume the calling 3334 // convention of the first. 3335 // 3336 // It's OK if a function is first declared without a calling convention, 3337 // but is later declared or defined with the default calling convention. 3338 // 3339 // To test if either decl has an explicit calling convention, we look for 3340 // AttributedType sugar nodes on the type as written. If they are missing or 3341 // were canonicalized away, we assume the calling convention was implicit. 3342 // 3343 // Note also that we DO NOT return at this point, because we still have 3344 // other tests to run. 3345 QualType OldQType = Context.getCanonicalType(Old->getType()); 3346 QualType NewQType = Context.getCanonicalType(New->getType()); 3347 const FunctionType *OldType = cast<FunctionType>(OldQType); 3348 const FunctionType *NewType = cast<FunctionType>(NewQType); 3349 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3350 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3351 bool RequiresAdjustment = false; 3352 3353 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3354 FunctionDecl *First = Old->getFirstDecl(); 3355 const FunctionType *FT = 3356 First->getType().getCanonicalType()->castAs<FunctionType>(); 3357 FunctionType::ExtInfo FI = FT->getExtInfo(); 3358 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3359 if (!NewCCExplicit) { 3360 // Inherit the CC from the previous declaration if it was specified 3361 // there but not here. 3362 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3363 RequiresAdjustment = true; 3364 } else if (Old->getBuiltinID()) { 3365 // Builtin attribute isn't propagated to the new one yet at this point, 3366 // so we check if the old one is a builtin. 3367 3368 // Calling Conventions on a Builtin aren't really useful and setting a 3369 // default calling convention and cdecl'ing some builtin redeclarations is 3370 // common, so warn and ignore the calling convention on the redeclaration. 3371 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3372 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3373 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3374 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3375 RequiresAdjustment = true; 3376 } else { 3377 // Calling conventions aren't compatible, so complain. 3378 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3379 Diag(New->getLocation(), diag::err_cconv_change) 3380 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3381 << !FirstCCExplicit 3382 << (!FirstCCExplicit ? "" : 3383 FunctionType::getNameForCallConv(FI.getCC())); 3384 3385 // Put the note on the first decl, since it is the one that matters. 3386 Diag(First->getLocation(), diag::note_previous_declaration); 3387 return true; 3388 } 3389 } 3390 3391 // FIXME: diagnose the other way around? 3392 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3393 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3394 RequiresAdjustment = true; 3395 } 3396 3397 // Merge regparm attribute. 3398 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3399 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3400 if (NewTypeInfo.getHasRegParm()) { 3401 Diag(New->getLocation(), diag::err_regparm_mismatch) 3402 << NewType->getRegParmType() 3403 << OldType->getRegParmType(); 3404 Diag(OldLocation, diag::note_previous_declaration); 3405 return true; 3406 } 3407 3408 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3409 RequiresAdjustment = true; 3410 } 3411 3412 // Merge ns_returns_retained attribute. 3413 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3414 if (NewTypeInfo.getProducesResult()) { 3415 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3416 << "'ns_returns_retained'"; 3417 Diag(OldLocation, diag::note_previous_declaration); 3418 return true; 3419 } 3420 3421 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3422 RequiresAdjustment = true; 3423 } 3424 3425 if (OldTypeInfo.getNoCallerSavedRegs() != 3426 NewTypeInfo.getNoCallerSavedRegs()) { 3427 if (NewTypeInfo.getNoCallerSavedRegs()) { 3428 AnyX86NoCallerSavedRegistersAttr *Attr = 3429 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3430 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3431 Diag(OldLocation, diag::note_previous_declaration); 3432 return true; 3433 } 3434 3435 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3436 RequiresAdjustment = true; 3437 } 3438 3439 if (RequiresAdjustment) { 3440 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3441 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3442 New->setType(QualType(AdjustedType, 0)); 3443 NewQType = Context.getCanonicalType(New->getType()); 3444 } 3445 3446 // If this redeclaration makes the function inline, we may need to add it to 3447 // UndefinedButUsed. 3448 if (!Old->isInlined() && New->isInlined() && 3449 !New->hasAttr<GNUInlineAttr>() && 3450 !getLangOpts().GNUInline && 3451 Old->isUsed(false) && 3452 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3453 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3454 SourceLocation())); 3455 3456 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3457 // about it. 3458 if (New->hasAttr<GNUInlineAttr>() && 3459 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3460 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3461 } 3462 3463 // If pass_object_size params don't match up perfectly, this isn't a valid 3464 // redeclaration. 3465 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3466 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3467 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3468 << New->getDeclName(); 3469 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3470 return true; 3471 } 3472 3473 if (getLangOpts().CPlusPlus) { 3474 // C++1z [over.load]p2 3475 // Certain function declarations cannot be overloaded: 3476 // -- Function declarations that differ only in the return type, 3477 // the exception specification, or both cannot be overloaded. 3478 3479 // Check the exception specifications match. This may recompute the type of 3480 // both Old and New if it resolved exception specifications, so grab the 3481 // types again after this. Because this updates the type, we do this before 3482 // any of the other checks below, which may update the "de facto" NewQType 3483 // but do not necessarily update the type of New. 3484 if (CheckEquivalentExceptionSpec(Old, New)) 3485 return true; 3486 OldQType = Context.getCanonicalType(Old->getType()); 3487 NewQType = Context.getCanonicalType(New->getType()); 3488 3489 // Go back to the type source info to compare the declared return types, 3490 // per C++1y [dcl.type.auto]p13: 3491 // Redeclarations or specializations of a function or function template 3492 // with a declared return type that uses a placeholder type shall also 3493 // use that placeholder, not a deduced type. 3494 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3495 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3496 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3497 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3498 OldDeclaredReturnType)) { 3499 QualType ResQT; 3500 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3501 OldDeclaredReturnType->isObjCObjectPointerType()) 3502 // FIXME: This does the wrong thing for a deduced return type. 3503 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3504 if (ResQT.isNull()) { 3505 if (New->isCXXClassMember() && New->isOutOfLine()) 3506 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3507 << New << New->getReturnTypeSourceRange(); 3508 else 3509 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3510 << New->getReturnTypeSourceRange(); 3511 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3512 << Old->getReturnTypeSourceRange(); 3513 return true; 3514 } 3515 else 3516 NewQType = ResQT; 3517 } 3518 3519 QualType OldReturnType = OldType->getReturnType(); 3520 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3521 if (OldReturnType != NewReturnType) { 3522 // If this function has a deduced return type and has already been 3523 // defined, copy the deduced value from the old declaration. 3524 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3525 if (OldAT && OldAT->isDeduced()) { 3526 New->setType( 3527 SubstAutoType(New->getType(), 3528 OldAT->isDependentType() ? Context.DependentTy 3529 : OldAT->getDeducedType())); 3530 NewQType = Context.getCanonicalType( 3531 SubstAutoType(NewQType, 3532 OldAT->isDependentType() ? Context.DependentTy 3533 : OldAT->getDeducedType())); 3534 } 3535 } 3536 3537 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3538 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3539 if (OldMethod && NewMethod) { 3540 // Preserve triviality. 3541 NewMethod->setTrivial(OldMethod->isTrivial()); 3542 3543 // MSVC allows explicit template specialization at class scope: 3544 // 2 CXXMethodDecls referring to the same function will be injected. 3545 // We don't want a redeclaration error. 3546 bool IsClassScopeExplicitSpecialization = 3547 OldMethod->isFunctionTemplateSpecialization() && 3548 NewMethod->isFunctionTemplateSpecialization(); 3549 bool isFriend = NewMethod->getFriendObjectKind(); 3550 3551 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3552 !IsClassScopeExplicitSpecialization) { 3553 // -- Member function declarations with the same name and the 3554 // same parameter types cannot be overloaded if any of them 3555 // is a static member function declaration. 3556 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3557 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3558 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3559 return true; 3560 } 3561 3562 // C++ [class.mem]p1: 3563 // [...] A member shall not be declared twice in the 3564 // member-specification, except that a nested class or member 3565 // class template can be declared and then later defined. 3566 if (!inTemplateInstantiation()) { 3567 unsigned NewDiag; 3568 if (isa<CXXConstructorDecl>(OldMethod)) 3569 NewDiag = diag::err_constructor_redeclared; 3570 else if (isa<CXXDestructorDecl>(NewMethod)) 3571 NewDiag = diag::err_destructor_redeclared; 3572 else if (isa<CXXConversionDecl>(NewMethod)) 3573 NewDiag = diag::err_conv_function_redeclared; 3574 else 3575 NewDiag = diag::err_member_redeclared; 3576 3577 Diag(New->getLocation(), NewDiag); 3578 } else { 3579 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3580 << New << New->getType(); 3581 } 3582 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3583 return true; 3584 3585 // Complain if this is an explicit declaration of a special 3586 // member that was initially declared implicitly. 3587 // 3588 // As an exception, it's okay to befriend such methods in order 3589 // to permit the implicit constructor/destructor/operator calls. 3590 } else if (OldMethod->isImplicit()) { 3591 if (isFriend) { 3592 NewMethod->setImplicit(); 3593 } else { 3594 Diag(NewMethod->getLocation(), 3595 diag::err_definition_of_implicitly_declared_member) 3596 << New << getSpecialMember(OldMethod); 3597 return true; 3598 } 3599 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3600 Diag(NewMethod->getLocation(), 3601 diag::err_definition_of_explicitly_defaulted_member) 3602 << getSpecialMember(OldMethod); 3603 return true; 3604 } 3605 } 3606 3607 // C++11 [dcl.attr.noreturn]p1: 3608 // The first declaration of a function shall specify the noreturn 3609 // attribute if any declaration of that function specifies the noreturn 3610 // attribute. 3611 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3612 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3613 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3614 Diag(Old->getFirstDecl()->getLocation(), 3615 diag::note_noreturn_missing_first_decl); 3616 } 3617 3618 // C++11 [dcl.attr.depend]p2: 3619 // The first declaration of a function shall specify the 3620 // carries_dependency attribute for its declarator-id if any declaration 3621 // of the function specifies the carries_dependency attribute. 3622 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3623 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3624 Diag(CDA->getLocation(), 3625 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3626 Diag(Old->getFirstDecl()->getLocation(), 3627 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3628 } 3629 3630 // (C++98 8.3.5p3): 3631 // All declarations for a function shall agree exactly in both the 3632 // return type and the parameter-type-list. 3633 // We also want to respect all the extended bits except noreturn. 3634 3635 // noreturn should now match unless the old type info didn't have it. 3636 QualType OldQTypeForComparison = OldQType; 3637 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3638 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3639 const FunctionType *OldTypeForComparison 3640 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3641 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3642 assert(OldQTypeForComparison.isCanonical()); 3643 } 3644 3645 if (haveIncompatibleLanguageLinkages(Old, New)) { 3646 // As a special case, retain the language linkage from previous 3647 // declarations of a friend function as an extension. 3648 // 3649 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3650 // and is useful because there's otherwise no way to specify language 3651 // linkage within class scope. 3652 // 3653 // Check cautiously as the friend object kind isn't yet complete. 3654 if (New->getFriendObjectKind() != Decl::FOK_None) { 3655 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3656 Diag(OldLocation, PrevDiag); 3657 } else { 3658 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3659 Diag(OldLocation, PrevDiag); 3660 return true; 3661 } 3662 } 3663 3664 // If the function types are compatible, merge the declarations. Ignore the 3665 // exception specifier because it was already checked above in 3666 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3667 // about incompatible types under -fms-compatibility. 3668 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3669 NewQType)) 3670 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3671 3672 // If the types are imprecise (due to dependent constructs in friends or 3673 // local extern declarations), it's OK if they differ. We'll check again 3674 // during instantiation. 3675 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3676 return false; 3677 3678 // Fall through for conflicting redeclarations and redefinitions. 3679 } 3680 3681 // C: Function types need to be compatible, not identical. This handles 3682 // duplicate function decls like "void f(int); void f(enum X);" properly. 3683 if (!getLangOpts().CPlusPlus && 3684 Context.typesAreCompatible(OldQType, NewQType)) { 3685 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3686 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3687 const FunctionProtoType *OldProto = nullptr; 3688 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3689 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3690 // The old declaration provided a function prototype, but the 3691 // new declaration does not. Merge in the prototype. 3692 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3693 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3694 NewQType = 3695 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3696 OldProto->getExtProtoInfo()); 3697 New->setType(NewQType); 3698 New->setHasInheritedPrototype(); 3699 3700 // Synthesize parameters with the same types. 3701 SmallVector<ParmVarDecl*, 16> Params; 3702 for (const auto &ParamType : OldProto->param_types()) { 3703 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3704 SourceLocation(), nullptr, 3705 ParamType, /*TInfo=*/nullptr, 3706 SC_None, nullptr); 3707 Param->setScopeInfo(0, Params.size()); 3708 Param->setImplicit(); 3709 Params.push_back(Param); 3710 } 3711 3712 New->setParams(Params); 3713 } 3714 3715 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3716 } 3717 3718 // Check if the function types are compatible when pointer size address 3719 // spaces are ignored. 3720 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3721 return false; 3722 3723 // GNU C permits a K&R definition to follow a prototype declaration 3724 // if the declared types of the parameters in the K&R definition 3725 // match the types in the prototype declaration, even when the 3726 // promoted types of the parameters from the K&R definition differ 3727 // from the types in the prototype. GCC then keeps the types from 3728 // the prototype. 3729 // 3730 // If a variadic prototype is followed by a non-variadic K&R definition, 3731 // the K&R definition becomes variadic. This is sort of an edge case, but 3732 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3733 // C99 6.9.1p8. 3734 if (!getLangOpts().CPlusPlus && 3735 Old->hasPrototype() && !New->hasPrototype() && 3736 New->getType()->getAs<FunctionProtoType>() && 3737 Old->getNumParams() == New->getNumParams()) { 3738 SmallVector<QualType, 16> ArgTypes; 3739 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3740 const FunctionProtoType *OldProto 3741 = Old->getType()->getAs<FunctionProtoType>(); 3742 const FunctionProtoType *NewProto 3743 = New->getType()->getAs<FunctionProtoType>(); 3744 3745 // Determine whether this is the GNU C extension. 3746 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3747 NewProto->getReturnType()); 3748 bool LooseCompatible = !MergedReturn.isNull(); 3749 for (unsigned Idx = 0, End = Old->getNumParams(); 3750 LooseCompatible && Idx != End; ++Idx) { 3751 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3752 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3753 if (Context.typesAreCompatible(OldParm->getType(), 3754 NewProto->getParamType(Idx))) { 3755 ArgTypes.push_back(NewParm->getType()); 3756 } else if (Context.typesAreCompatible(OldParm->getType(), 3757 NewParm->getType(), 3758 /*CompareUnqualified=*/true)) { 3759 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3760 NewProto->getParamType(Idx) }; 3761 Warnings.push_back(Warn); 3762 ArgTypes.push_back(NewParm->getType()); 3763 } else 3764 LooseCompatible = false; 3765 } 3766 3767 if (LooseCompatible) { 3768 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3769 Diag(Warnings[Warn].NewParm->getLocation(), 3770 diag::ext_param_promoted_not_compatible_with_prototype) 3771 << Warnings[Warn].PromotedType 3772 << Warnings[Warn].OldParm->getType(); 3773 if (Warnings[Warn].OldParm->getLocation().isValid()) 3774 Diag(Warnings[Warn].OldParm->getLocation(), 3775 diag::note_previous_declaration); 3776 } 3777 3778 if (MergeTypeWithOld) 3779 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3780 OldProto->getExtProtoInfo())); 3781 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3782 } 3783 3784 // Fall through to diagnose conflicting types. 3785 } 3786 3787 // A function that has already been declared has been redeclared or 3788 // defined with a different type; show an appropriate diagnostic. 3789 3790 // If the previous declaration was an implicitly-generated builtin 3791 // declaration, then at the very least we should use a specialized note. 3792 unsigned BuiltinID; 3793 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3794 // If it's actually a library-defined builtin function like 'malloc' 3795 // or 'printf', just warn about the incompatible redeclaration. 3796 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3797 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3798 Diag(OldLocation, diag::note_previous_builtin_declaration) 3799 << Old << Old->getType(); 3800 return false; 3801 } 3802 3803 PrevDiag = diag::note_previous_builtin_declaration; 3804 } 3805 3806 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3807 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3808 return true; 3809 } 3810 3811 /// Completes the merge of two function declarations that are 3812 /// known to be compatible. 3813 /// 3814 /// This routine handles the merging of attributes and other 3815 /// properties of function declarations from the old declaration to 3816 /// the new declaration, once we know that New is in fact a 3817 /// redeclaration of Old. 3818 /// 3819 /// \returns false 3820 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3821 Scope *S, bool MergeTypeWithOld) { 3822 // Merge the attributes 3823 mergeDeclAttributes(New, Old); 3824 3825 // Merge "pure" flag. 3826 if (Old->isPure()) 3827 New->setPure(); 3828 3829 // Merge "used" flag. 3830 if (Old->getMostRecentDecl()->isUsed(false)) 3831 New->setIsUsed(); 3832 3833 // Merge attributes from the parameters. These can mismatch with K&R 3834 // declarations. 3835 if (New->getNumParams() == Old->getNumParams()) 3836 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3837 ParmVarDecl *NewParam = New->getParamDecl(i); 3838 ParmVarDecl *OldParam = Old->getParamDecl(i); 3839 mergeParamDeclAttributes(NewParam, OldParam, *this); 3840 mergeParamDeclTypes(NewParam, OldParam, *this); 3841 } 3842 3843 if (getLangOpts().CPlusPlus) 3844 return MergeCXXFunctionDecl(New, Old, S); 3845 3846 // Merge the function types so the we get the composite types for the return 3847 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3848 // was visible. 3849 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3850 if (!Merged.isNull() && MergeTypeWithOld) 3851 New->setType(Merged); 3852 3853 return false; 3854 } 3855 3856 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3857 ObjCMethodDecl *oldMethod) { 3858 // Merge the attributes, including deprecated/unavailable 3859 AvailabilityMergeKind MergeKind = 3860 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3861 ? AMK_ProtocolImplementation 3862 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3863 : AMK_Override; 3864 3865 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3866 3867 // Merge attributes from the parameters. 3868 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3869 oe = oldMethod->param_end(); 3870 for (ObjCMethodDecl::param_iterator 3871 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3872 ni != ne && oi != oe; ++ni, ++oi) 3873 mergeParamDeclAttributes(*ni, *oi, *this); 3874 3875 CheckObjCMethodOverride(newMethod, oldMethod); 3876 } 3877 3878 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3879 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3880 3881 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3882 ? diag::err_redefinition_different_type 3883 : diag::err_redeclaration_different_type) 3884 << New->getDeclName() << New->getType() << Old->getType(); 3885 3886 diag::kind PrevDiag; 3887 SourceLocation OldLocation; 3888 std::tie(PrevDiag, OldLocation) 3889 = getNoteDiagForInvalidRedeclaration(Old, New); 3890 S.Diag(OldLocation, PrevDiag); 3891 New->setInvalidDecl(); 3892 } 3893 3894 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3895 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3896 /// emitting diagnostics as appropriate. 3897 /// 3898 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3899 /// to here in AddInitializerToDecl. We can't check them before the initializer 3900 /// is attached. 3901 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3902 bool MergeTypeWithOld) { 3903 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3904 return; 3905 3906 QualType MergedT; 3907 if (getLangOpts().CPlusPlus) { 3908 if (New->getType()->isUndeducedType()) { 3909 // We don't know what the new type is until the initializer is attached. 3910 return; 3911 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3912 // These could still be something that needs exception specs checked. 3913 return MergeVarDeclExceptionSpecs(New, Old); 3914 } 3915 // C++ [basic.link]p10: 3916 // [...] the types specified by all declarations referring to a given 3917 // object or function shall be identical, except that declarations for an 3918 // array object can specify array types that differ by the presence or 3919 // absence of a major array bound (8.3.4). 3920 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3921 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3922 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3923 3924 // We are merging a variable declaration New into Old. If it has an array 3925 // bound, and that bound differs from Old's bound, we should diagnose the 3926 // mismatch. 3927 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3928 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3929 PrevVD = PrevVD->getPreviousDecl()) { 3930 QualType PrevVDTy = PrevVD->getType(); 3931 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3932 continue; 3933 3934 if (!Context.hasSameType(New->getType(), PrevVDTy)) 3935 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3936 } 3937 } 3938 3939 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3940 if (Context.hasSameType(OldArray->getElementType(), 3941 NewArray->getElementType())) 3942 MergedT = New->getType(); 3943 } 3944 // FIXME: Check visibility. New is hidden but has a complete type. If New 3945 // has no array bound, it should not inherit one from Old, if Old is not 3946 // visible. 3947 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3948 if (Context.hasSameType(OldArray->getElementType(), 3949 NewArray->getElementType())) 3950 MergedT = Old->getType(); 3951 } 3952 } 3953 else if (New->getType()->isObjCObjectPointerType() && 3954 Old->getType()->isObjCObjectPointerType()) { 3955 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3956 Old->getType()); 3957 } 3958 } else { 3959 // C 6.2.7p2: 3960 // All declarations that refer to the same object or function shall have 3961 // compatible type. 3962 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3963 } 3964 if (MergedT.isNull()) { 3965 // It's OK if we couldn't merge types if either type is dependent, for a 3966 // block-scope variable. In other cases (static data members of class 3967 // templates, variable templates, ...), we require the types to be 3968 // equivalent. 3969 // FIXME: The C++ standard doesn't say anything about this. 3970 if ((New->getType()->isDependentType() || 3971 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3972 // If the old type was dependent, we can't merge with it, so the new type 3973 // becomes dependent for now. We'll reproduce the original type when we 3974 // instantiate the TypeSourceInfo for the variable. 3975 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3976 New->setType(Context.DependentTy); 3977 return; 3978 } 3979 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3980 } 3981 3982 // Don't actually update the type on the new declaration if the old 3983 // declaration was an extern declaration in a different scope. 3984 if (MergeTypeWithOld) 3985 New->setType(MergedT); 3986 } 3987 3988 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3989 LookupResult &Previous) { 3990 // C11 6.2.7p4: 3991 // For an identifier with internal or external linkage declared 3992 // in a scope in which a prior declaration of that identifier is 3993 // visible, if the prior declaration specifies internal or 3994 // external linkage, the type of the identifier at the later 3995 // declaration becomes the composite type. 3996 // 3997 // If the variable isn't visible, we do not merge with its type. 3998 if (Previous.isShadowed()) 3999 return false; 4000 4001 if (S.getLangOpts().CPlusPlus) { 4002 // C++11 [dcl.array]p3: 4003 // If there is a preceding declaration of the entity in the same 4004 // scope in which the bound was specified, an omitted array bound 4005 // is taken to be the same as in that earlier declaration. 4006 return NewVD->isPreviousDeclInSameBlockScope() || 4007 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4008 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4009 } else { 4010 // If the old declaration was function-local, don't merge with its 4011 // type unless we're in the same function. 4012 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4013 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4014 } 4015 } 4016 4017 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4018 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4019 /// situation, merging decls or emitting diagnostics as appropriate. 4020 /// 4021 /// Tentative definition rules (C99 6.9.2p2) are checked by 4022 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4023 /// definitions here, since the initializer hasn't been attached. 4024 /// 4025 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4026 // If the new decl is already invalid, don't do any other checking. 4027 if (New->isInvalidDecl()) 4028 return; 4029 4030 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4031 return; 4032 4033 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4034 4035 // Verify the old decl was also a variable or variable template. 4036 VarDecl *Old = nullptr; 4037 VarTemplateDecl *OldTemplate = nullptr; 4038 if (Previous.isSingleResult()) { 4039 if (NewTemplate) { 4040 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4041 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4042 4043 if (auto *Shadow = 4044 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4045 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4046 return New->setInvalidDecl(); 4047 } else { 4048 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4049 4050 if (auto *Shadow = 4051 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4052 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4053 return New->setInvalidDecl(); 4054 } 4055 } 4056 if (!Old) { 4057 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4058 << New->getDeclName(); 4059 notePreviousDefinition(Previous.getRepresentativeDecl(), 4060 New->getLocation()); 4061 return New->setInvalidDecl(); 4062 } 4063 4064 // If the old declaration was found in an inline namespace and the new 4065 // declaration was qualified, update the DeclContext to match. 4066 adjustDeclContextForDeclaratorDecl(New, Old); 4067 4068 // Ensure the template parameters are compatible. 4069 if (NewTemplate && 4070 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4071 OldTemplate->getTemplateParameters(), 4072 /*Complain=*/true, TPL_TemplateMatch)) 4073 return New->setInvalidDecl(); 4074 4075 // C++ [class.mem]p1: 4076 // A member shall not be declared twice in the member-specification [...] 4077 // 4078 // Here, we need only consider static data members. 4079 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4080 Diag(New->getLocation(), diag::err_duplicate_member) 4081 << New->getIdentifier(); 4082 Diag(Old->getLocation(), diag::note_previous_declaration); 4083 New->setInvalidDecl(); 4084 } 4085 4086 mergeDeclAttributes(New, Old); 4087 // Warn if an already-declared variable is made a weak_import in a subsequent 4088 // declaration 4089 if (New->hasAttr<WeakImportAttr>() && 4090 Old->getStorageClass() == SC_None && 4091 !Old->hasAttr<WeakImportAttr>()) { 4092 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4093 notePreviousDefinition(Old, New->getLocation()); 4094 // Remove weak_import attribute on new declaration. 4095 New->dropAttr<WeakImportAttr>(); 4096 } 4097 4098 if (New->hasAttr<InternalLinkageAttr>() && 4099 !Old->hasAttr<InternalLinkageAttr>()) { 4100 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4101 << New->getDeclName(); 4102 notePreviousDefinition(Old, New->getLocation()); 4103 New->dropAttr<InternalLinkageAttr>(); 4104 } 4105 4106 // Merge the types. 4107 VarDecl *MostRecent = Old->getMostRecentDecl(); 4108 if (MostRecent != Old) { 4109 MergeVarDeclTypes(New, MostRecent, 4110 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4111 if (New->isInvalidDecl()) 4112 return; 4113 } 4114 4115 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4116 if (New->isInvalidDecl()) 4117 return; 4118 4119 diag::kind PrevDiag; 4120 SourceLocation OldLocation; 4121 std::tie(PrevDiag, OldLocation) = 4122 getNoteDiagForInvalidRedeclaration(Old, New); 4123 4124 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4125 if (New->getStorageClass() == SC_Static && 4126 !New->isStaticDataMember() && 4127 Old->hasExternalFormalLinkage()) { 4128 if (getLangOpts().MicrosoftExt) { 4129 Diag(New->getLocation(), diag::ext_static_non_static) 4130 << New->getDeclName(); 4131 Diag(OldLocation, PrevDiag); 4132 } else { 4133 Diag(New->getLocation(), diag::err_static_non_static) 4134 << New->getDeclName(); 4135 Diag(OldLocation, PrevDiag); 4136 return New->setInvalidDecl(); 4137 } 4138 } 4139 // C99 6.2.2p4: 4140 // For an identifier declared with the storage-class specifier 4141 // extern in a scope in which a prior declaration of that 4142 // identifier is visible,23) if the prior declaration specifies 4143 // internal or external linkage, the linkage of the identifier at 4144 // the later declaration is the same as the linkage specified at 4145 // the prior declaration. If no prior declaration is visible, or 4146 // if the prior declaration specifies no linkage, then the 4147 // identifier has external linkage. 4148 if (New->hasExternalStorage() && Old->hasLinkage()) 4149 /* Okay */; 4150 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4151 !New->isStaticDataMember() && 4152 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4153 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4154 Diag(OldLocation, PrevDiag); 4155 return New->setInvalidDecl(); 4156 } 4157 4158 // Check if extern is followed by non-extern and vice-versa. 4159 if (New->hasExternalStorage() && 4160 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4161 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4162 Diag(OldLocation, PrevDiag); 4163 return New->setInvalidDecl(); 4164 } 4165 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4166 !New->hasExternalStorage()) { 4167 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4168 Diag(OldLocation, PrevDiag); 4169 return New->setInvalidDecl(); 4170 } 4171 4172 if (CheckRedeclarationModuleOwnership(New, Old)) 4173 return; 4174 4175 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4176 4177 // FIXME: The test for external storage here seems wrong? We still 4178 // need to check for mismatches. 4179 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4180 // Don't complain about out-of-line definitions of static members. 4181 !(Old->getLexicalDeclContext()->isRecord() && 4182 !New->getLexicalDeclContext()->isRecord())) { 4183 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4184 Diag(OldLocation, PrevDiag); 4185 return New->setInvalidDecl(); 4186 } 4187 4188 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4189 if (VarDecl *Def = Old->getDefinition()) { 4190 // C++1z [dcl.fcn.spec]p4: 4191 // If the definition of a variable appears in a translation unit before 4192 // its first declaration as inline, the program is ill-formed. 4193 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4194 Diag(Def->getLocation(), diag::note_previous_definition); 4195 } 4196 } 4197 4198 // If this redeclaration makes the variable inline, we may need to add it to 4199 // UndefinedButUsed. 4200 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4201 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4202 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4203 SourceLocation())); 4204 4205 if (New->getTLSKind() != Old->getTLSKind()) { 4206 if (!Old->getTLSKind()) { 4207 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4208 Diag(OldLocation, PrevDiag); 4209 } else if (!New->getTLSKind()) { 4210 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4211 Diag(OldLocation, PrevDiag); 4212 } else { 4213 // Do not allow redeclaration to change the variable between requiring 4214 // static and dynamic initialization. 4215 // FIXME: GCC allows this, but uses the TLS keyword on the first 4216 // declaration to determine the kind. Do we need to be compatible here? 4217 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4218 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4219 Diag(OldLocation, PrevDiag); 4220 } 4221 } 4222 4223 // C++ doesn't have tentative definitions, so go right ahead and check here. 4224 if (getLangOpts().CPlusPlus && 4225 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4226 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4227 Old->getCanonicalDecl()->isConstexpr()) { 4228 // This definition won't be a definition any more once it's been merged. 4229 Diag(New->getLocation(), 4230 diag::warn_deprecated_redundant_constexpr_static_def); 4231 } else if (VarDecl *Def = Old->getDefinition()) { 4232 if (checkVarDeclRedefinition(Def, New)) 4233 return; 4234 } 4235 } 4236 4237 if (haveIncompatibleLanguageLinkages(Old, New)) { 4238 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4239 Diag(OldLocation, PrevDiag); 4240 New->setInvalidDecl(); 4241 return; 4242 } 4243 4244 // Merge "used" flag. 4245 if (Old->getMostRecentDecl()->isUsed(false)) 4246 New->setIsUsed(); 4247 4248 // Keep a chain of previous declarations. 4249 New->setPreviousDecl(Old); 4250 if (NewTemplate) 4251 NewTemplate->setPreviousDecl(OldTemplate); 4252 4253 // Inherit access appropriately. 4254 New->setAccess(Old->getAccess()); 4255 if (NewTemplate) 4256 NewTemplate->setAccess(New->getAccess()); 4257 4258 if (Old->isInline()) 4259 New->setImplicitlyInline(); 4260 } 4261 4262 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4263 SourceManager &SrcMgr = getSourceManager(); 4264 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4265 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4266 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4267 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4268 auto &HSI = PP.getHeaderSearchInfo(); 4269 StringRef HdrFilename = 4270 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4271 4272 auto noteFromModuleOrInclude = [&](Module *Mod, 4273 SourceLocation IncLoc) -> bool { 4274 // Redefinition errors with modules are common with non modular mapped 4275 // headers, example: a non-modular header H in module A that also gets 4276 // included directly in a TU. Pointing twice to the same header/definition 4277 // is confusing, try to get better diagnostics when modules is on. 4278 if (IncLoc.isValid()) { 4279 if (Mod) { 4280 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4281 << HdrFilename.str() << Mod->getFullModuleName(); 4282 if (!Mod->DefinitionLoc.isInvalid()) 4283 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4284 << Mod->getFullModuleName(); 4285 } else { 4286 Diag(IncLoc, diag::note_redefinition_include_same_file) 4287 << HdrFilename.str(); 4288 } 4289 return true; 4290 } 4291 4292 return false; 4293 }; 4294 4295 // Is it the same file and same offset? Provide more information on why 4296 // this leads to a redefinition error. 4297 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4298 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4299 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4300 bool EmittedDiag = 4301 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4302 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4303 4304 // If the header has no guards, emit a note suggesting one. 4305 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4306 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4307 4308 if (EmittedDiag) 4309 return; 4310 } 4311 4312 // Redefinition coming from different files or couldn't do better above. 4313 if (Old->getLocation().isValid()) 4314 Diag(Old->getLocation(), diag::note_previous_definition); 4315 } 4316 4317 /// We've just determined that \p Old and \p New both appear to be definitions 4318 /// of the same variable. Either diagnose or fix the problem. 4319 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4320 if (!hasVisibleDefinition(Old) && 4321 (New->getFormalLinkage() == InternalLinkage || 4322 New->isInline() || 4323 New->getDescribedVarTemplate() || 4324 New->getNumTemplateParameterLists() || 4325 New->getDeclContext()->isDependentContext())) { 4326 // The previous definition is hidden, and multiple definitions are 4327 // permitted (in separate TUs). Demote this to a declaration. 4328 New->demoteThisDefinitionToDeclaration(); 4329 4330 // Make the canonical definition visible. 4331 if (auto *OldTD = Old->getDescribedVarTemplate()) 4332 makeMergedDefinitionVisible(OldTD); 4333 makeMergedDefinitionVisible(Old); 4334 return false; 4335 } else { 4336 Diag(New->getLocation(), diag::err_redefinition) << New; 4337 notePreviousDefinition(Old, New->getLocation()); 4338 New->setInvalidDecl(); 4339 return true; 4340 } 4341 } 4342 4343 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4344 /// no declarator (e.g. "struct foo;") is parsed. 4345 Decl * 4346 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4347 RecordDecl *&AnonRecord) { 4348 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4349 AnonRecord); 4350 } 4351 4352 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4353 // disambiguate entities defined in different scopes. 4354 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4355 // compatibility. 4356 // We will pick our mangling number depending on which version of MSVC is being 4357 // targeted. 4358 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4359 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4360 ? S->getMSCurManglingNumber() 4361 : S->getMSLastManglingNumber(); 4362 } 4363 4364 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4365 if (!Context.getLangOpts().CPlusPlus) 4366 return; 4367 4368 if (isa<CXXRecordDecl>(Tag->getParent())) { 4369 // If this tag is the direct child of a class, number it if 4370 // it is anonymous. 4371 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4372 return; 4373 MangleNumberingContext &MCtx = 4374 Context.getManglingNumberContext(Tag->getParent()); 4375 Context.setManglingNumber( 4376 Tag, MCtx.getManglingNumber( 4377 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4378 return; 4379 } 4380 4381 // If this tag isn't a direct child of a class, number it if it is local. 4382 MangleNumberingContext *MCtx; 4383 Decl *ManglingContextDecl; 4384 std::tie(MCtx, ManglingContextDecl) = 4385 getCurrentMangleNumberContext(Tag->getDeclContext()); 4386 if (MCtx) { 4387 Context.setManglingNumber( 4388 Tag, MCtx->getManglingNumber( 4389 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4390 } 4391 } 4392 4393 namespace { 4394 struct NonCLikeKind { 4395 enum { 4396 None, 4397 BaseClass, 4398 DefaultMemberInit, 4399 Lambda, 4400 Friend, 4401 OtherMember, 4402 Invalid, 4403 } Kind = None; 4404 SourceRange Range; 4405 4406 explicit operator bool() { return Kind != None; } 4407 }; 4408 } 4409 4410 /// Determine whether a class is C-like, according to the rules of C++ 4411 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4412 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4413 if (RD->isInvalidDecl()) 4414 return {NonCLikeKind::Invalid, {}}; 4415 4416 // C++ [dcl.typedef]p9: [P1766R1] 4417 // An unnamed class with a typedef name for linkage purposes shall not 4418 // 4419 // -- have any base classes 4420 if (RD->getNumBases()) 4421 return {NonCLikeKind::BaseClass, 4422 SourceRange(RD->bases_begin()->getBeginLoc(), 4423 RD->bases_end()[-1].getEndLoc())}; 4424 bool Invalid = false; 4425 for (Decl *D : RD->decls()) { 4426 // Don't complain about things we already diagnosed. 4427 if (D->isInvalidDecl()) { 4428 Invalid = true; 4429 continue; 4430 } 4431 4432 // -- have any [...] default member initializers 4433 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4434 if (FD->hasInClassInitializer()) { 4435 auto *Init = FD->getInClassInitializer(); 4436 return {NonCLikeKind::DefaultMemberInit, 4437 Init ? Init->getSourceRange() : D->getSourceRange()}; 4438 } 4439 continue; 4440 } 4441 4442 // FIXME: We don't allow friend declarations. This violates the wording of 4443 // P1766, but not the intent. 4444 if (isa<FriendDecl>(D)) 4445 return {NonCLikeKind::Friend, D->getSourceRange()}; 4446 4447 // -- declare any members other than non-static data members, member 4448 // enumerations, or member classes, 4449 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4450 isa<EnumDecl>(D)) 4451 continue; 4452 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4453 if (!MemberRD) { 4454 if (D->isImplicit()) 4455 continue; 4456 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4457 } 4458 4459 // -- contain a lambda-expression, 4460 if (MemberRD->isLambda()) 4461 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4462 4463 // and all member classes shall also satisfy these requirements 4464 // (recursively). 4465 if (MemberRD->isThisDeclarationADefinition()) { 4466 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4467 return Kind; 4468 } 4469 } 4470 4471 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4472 } 4473 4474 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4475 TypedefNameDecl *NewTD) { 4476 if (TagFromDeclSpec->isInvalidDecl()) 4477 return; 4478 4479 // Do nothing if the tag already has a name for linkage purposes. 4480 if (TagFromDeclSpec->hasNameForLinkage()) 4481 return; 4482 4483 // A well-formed anonymous tag must always be a TUK_Definition. 4484 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4485 4486 // The type must match the tag exactly; no qualifiers allowed. 4487 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4488 Context.getTagDeclType(TagFromDeclSpec))) { 4489 if (getLangOpts().CPlusPlus) 4490 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4491 return; 4492 } 4493 4494 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4495 // An unnamed class with a typedef name for linkage purposes shall [be 4496 // C-like]. 4497 // 4498 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4499 // shouldn't happen, but there are constructs that the language rule doesn't 4500 // disallow for which we can't reasonably avoid computing linkage early. 4501 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4502 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4503 : NonCLikeKind(); 4504 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4505 if (NonCLike || ChangesLinkage) { 4506 if (NonCLike.Kind == NonCLikeKind::Invalid) 4507 return; 4508 4509 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4510 if (ChangesLinkage) { 4511 // If the linkage changes, we can't accept this as an extension. 4512 if (NonCLike.Kind == NonCLikeKind::None) 4513 DiagID = diag::err_typedef_changes_linkage; 4514 else 4515 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4516 } 4517 4518 SourceLocation FixitLoc = 4519 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4520 llvm::SmallString<40> TextToInsert; 4521 TextToInsert += ' '; 4522 TextToInsert += NewTD->getIdentifier()->getName(); 4523 4524 Diag(FixitLoc, DiagID) 4525 << isa<TypeAliasDecl>(NewTD) 4526 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4527 if (NonCLike.Kind != NonCLikeKind::None) { 4528 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4529 << NonCLike.Kind - 1 << NonCLike.Range; 4530 } 4531 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4532 << NewTD << isa<TypeAliasDecl>(NewTD); 4533 4534 if (ChangesLinkage) 4535 return; 4536 } 4537 4538 // Otherwise, set this as the anon-decl typedef for the tag. 4539 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4540 } 4541 4542 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4543 switch (T) { 4544 case DeclSpec::TST_class: 4545 return 0; 4546 case DeclSpec::TST_struct: 4547 return 1; 4548 case DeclSpec::TST_interface: 4549 return 2; 4550 case DeclSpec::TST_union: 4551 return 3; 4552 case DeclSpec::TST_enum: 4553 return 4; 4554 default: 4555 llvm_unreachable("unexpected type specifier"); 4556 } 4557 } 4558 4559 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4560 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4561 /// parameters to cope with template friend declarations. 4562 Decl * 4563 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4564 MultiTemplateParamsArg TemplateParams, 4565 bool IsExplicitInstantiation, 4566 RecordDecl *&AnonRecord) { 4567 Decl *TagD = nullptr; 4568 TagDecl *Tag = nullptr; 4569 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4570 DS.getTypeSpecType() == DeclSpec::TST_struct || 4571 DS.getTypeSpecType() == DeclSpec::TST_interface || 4572 DS.getTypeSpecType() == DeclSpec::TST_union || 4573 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4574 TagD = DS.getRepAsDecl(); 4575 4576 if (!TagD) // We probably had an error 4577 return nullptr; 4578 4579 // Note that the above type specs guarantee that the 4580 // type rep is a Decl, whereas in many of the others 4581 // it's a Type. 4582 if (isa<TagDecl>(TagD)) 4583 Tag = cast<TagDecl>(TagD); 4584 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4585 Tag = CTD->getTemplatedDecl(); 4586 } 4587 4588 if (Tag) { 4589 handleTagNumbering(Tag, S); 4590 Tag->setFreeStanding(); 4591 if (Tag->isInvalidDecl()) 4592 return Tag; 4593 } 4594 4595 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4596 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4597 // or incomplete types shall not be restrict-qualified." 4598 if (TypeQuals & DeclSpec::TQ_restrict) 4599 Diag(DS.getRestrictSpecLoc(), 4600 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4601 << DS.getSourceRange(); 4602 } 4603 4604 if (DS.isInlineSpecified()) 4605 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4606 << getLangOpts().CPlusPlus17; 4607 4608 if (DS.hasConstexprSpecifier()) { 4609 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4610 // and definitions of functions and variables. 4611 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4612 // the declaration of a function or function template 4613 if (Tag) 4614 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4615 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4616 << static_cast<int>(DS.getConstexprSpecifier()); 4617 else 4618 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4619 << static_cast<int>(DS.getConstexprSpecifier()); 4620 // Don't emit warnings after this error. 4621 return TagD; 4622 } 4623 4624 DiagnoseFunctionSpecifiers(DS); 4625 4626 if (DS.isFriendSpecified()) { 4627 // If we're dealing with a decl but not a TagDecl, assume that 4628 // whatever routines created it handled the friendship aspect. 4629 if (TagD && !Tag) 4630 return nullptr; 4631 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4632 } 4633 4634 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4635 bool IsExplicitSpecialization = 4636 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4637 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4638 !IsExplicitInstantiation && !IsExplicitSpecialization && 4639 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4640 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4641 // nested-name-specifier unless it is an explicit instantiation 4642 // or an explicit specialization. 4643 // 4644 // FIXME: We allow class template partial specializations here too, per the 4645 // obvious intent of DR1819. 4646 // 4647 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4648 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4649 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4650 return nullptr; 4651 } 4652 4653 // Track whether this decl-specifier declares anything. 4654 bool DeclaresAnything = true; 4655 4656 // Handle anonymous struct definitions. 4657 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4658 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4659 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4660 if (getLangOpts().CPlusPlus || 4661 Record->getDeclContext()->isRecord()) { 4662 // If CurContext is a DeclContext that can contain statements, 4663 // RecursiveASTVisitor won't visit the decls that 4664 // BuildAnonymousStructOrUnion() will put into CurContext. 4665 // Also store them here so that they can be part of the 4666 // DeclStmt that gets created in this case. 4667 // FIXME: Also return the IndirectFieldDecls created by 4668 // BuildAnonymousStructOr union, for the same reason? 4669 if (CurContext->isFunctionOrMethod()) 4670 AnonRecord = Record; 4671 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4672 Context.getPrintingPolicy()); 4673 } 4674 4675 DeclaresAnything = false; 4676 } 4677 } 4678 4679 // C11 6.7.2.1p2: 4680 // A struct-declaration that does not declare an anonymous structure or 4681 // anonymous union shall contain a struct-declarator-list. 4682 // 4683 // This rule also existed in C89 and C99; the grammar for struct-declaration 4684 // did not permit a struct-declaration without a struct-declarator-list. 4685 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4686 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4687 // Check for Microsoft C extension: anonymous struct/union member. 4688 // Handle 2 kinds of anonymous struct/union: 4689 // struct STRUCT; 4690 // union UNION; 4691 // and 4692 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4693 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4694 if ((Tag && Tag->getDeclName()) || 4695 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4696 RecordDecl *Record = nullptr; 4697 if (Tag) 4698 Record = dyn_cast<RecordDecl>(Tag); 4699 else if (const RecordType *RT = 4700 DS.getRepAsType().get()->getAsStructureType()) 4701 Record = RT->getDecl(); 4702 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4703 Record = UT->getDecl(); 4704 4705 if (Record && getLangOpts().MicrosoftExt) { 4706 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4707 << Record->isUnion() << DS.getSourceRange(); 4708 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4709 } 4710 4711 DeclaresAnything = false; 4712 } 4713 } 4714 4715 // Skip all the checks below if we have a type error. 4716 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4717 (TagD && TagD->isInvalidDecl())) 4718 return TagD; 4719 4720 if (getLangOpts().CPlusPlus && 4721 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4722 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4723 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4724 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4725 DeclaresAnything = false; 4726 4727 if (!DS.isMissingDeclaratorOk()) { 4728 // Customize diagnostic for a typedef missing a name. 4729 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4730 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4731 << DS.getSourceRange(); 4732 else 4733 DeclaresAnything = false; 4734 } 4735 4736 if (DS.isModulePrivateSpecified() && 4737 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4738 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4739 << Tag->getTagKind() 4740 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4741 4742 ActOnDocumentableDecl(TagD); 4743 4744 // C 6.7/2: 4745 // A declaration [...] shall declare at least a declarator [...], a tag, 4746 // or the members of an enumeration. 4747 // C++ [dcl.dcl]p3: 4748 // [If there are no declarators], and except for the declaration of an 4749 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4750 // names into the program, or shall redeclare a name introduced by a 4751 // previous declaration. 4752 if (!DeclaresAnything) { 4753 // In C, we allow this as a (popular) extension / bug. Don't bother 4754 // producing further diagnostics for redundant qualifiers after this. 4755 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 4756 ? diag::err_no_declarators 4757 : diag::ext_no_declarators) 4758 << DS.getSourceRange(); 4759 return TagD; 4760 } 4761 4762 // C++ [dcl.stc]p1: 4763 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4764 // init-declarator-list of the declaration shall not be empty. 4765 // C++ [dcl.fct.spec]p1: 4766 // If a cv-qualifier appears in a decl-specifier-seq, the 4767 // init-declarator-list of the declaration shall not be empty. 4768 // 4769 // Spurious qualifiers here appear to be valid in C. 4770 unsigned DiagID = diag::warn_standalone_specifier; 4771 if (getLangOpts().CPlusPlus) 4772 DiagID = diag::ext_standalone_specifier; 4773 4774 // Note that a linkage-specification sets a storage class, but 4775 // 'extern "C" struct foo;' is actually valid and not theoretically 4776 // useless. 4777 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4778 if (SCS == DeclSpec::SCS_mutable) 4779 // Since mutable is not a viable storage class specifier in C, there is 4780 // no reason to treat it as an extension. Instead, diagnose as an error. 4781 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4782 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4783 Diag(DS.getStorageClassSpecLoc(), DiagID) 4784 << DeclSpec::getSpecifierName(SCS); 4785 } 4786 4787 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4788 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4789 << DeclSpec::getSpecifierName(TSCS); 4790 if (DS.getTypeQualifiers()) { 4791 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4792 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4793 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4794 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4795 // Restrict is covered above. 4796 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4797 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4798 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4799 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4800 } 4801 4802 // Warn about ignored type attributes, for example: 4803 // __attribute__((aligned)) struct A; 4804 // Attributes should be placed after tag to apply to type declaration. 4805 if (!DS.getAttributes().empty()) { 4806 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4807 if (TypeSpecType == DeclSpec::TST_class || 4808 TypeSpecType == DeclSpec::TST_struct || 4809 TypeSpecType == DeclSpec::TST_interface || 4810 TypeSpecType == DeclSpec::TST_union || 4811 TypeSpecType == DeclSpec::TST_enum) { 4812 for (const ParsedAttr &AL : DS.getAttributes()) 4813 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4814 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4815 } 4816 } 4817 4818 return TagD; 4819 } 4820 4821 /// We are trying to inject an anonymous member into the given scope; 4822 /// check if there's an existing declaration that can't be overloaded. 4823 /// 4824 /// \return true if this is a forbidden redeclaration 4825 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4826 Scope *S, 4827 DeclContext *Owner, 4828 DeclarationName Name, 4829 SourceLocation NameLoc, 4830 bool IsUnion) { 4831 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4832 Sema::ForVisibleRedeclaration); 4833 if (!SemaRef.LookupName(R, S)) return false; 4834 4835 // Pick a representative declaration. 4836 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4837 assert(PrevDecl && "Expected a non-null Decl"); 4838 4839 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4840 return false; 4841 4842 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4843 << IsUnion << Name; 4844 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4845 4846 return true; 4847 } 4848 4849 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4850 /// anonymous struct or union AnonRecord into the owning context Owner 4851 /// and scope S. This routine will be invoked just after we realize 4852 /// that an unnamed union or struct is actually an anonymous union or 4853 /// struct, e.g., 4854 /// 4855 /// @code 4856 /// union { 4857 /// int i; 4858 /// float f; 4859 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4860 /// // f into the surrounding scope.x 4861 /// @endcode 4862 /// 4863 /// This routine is recursive, injecting the names of nested anonymous 4864 /// structs/unions into the owning context and scope as well. 4865 static bool 4866 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4867 RecordDecl *AnonRecord, AccessSpecifier AS, 4868 SmallVectorImpl<NamedDecl *> &Chaining) { 4869 bool Invalid = false; 4870 4871 // Look every FieldDecl and IndirectFieldDecl with a name. 4872 for (auto *D : AnonRecord->decls()) { 4873 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4874 cast<NamedDecl>(D)->getDeclName()) { 4875 ValueDecl *VD = cast<ValueDecl>(D); 4876 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4877 VD->getLocation(), 4878 AnonRecord->isUnion())) { 4879 // C++ [class.union]p2: 4880 // The names of the members of an anonymous union shall be 4881 // distinct from the names of any other entity in the 4882 // scope in which the anonymous union is declared. 4883 Invalid = true; 4884 } else { 4885 // C++ [class.union]p2: 4886 // For the purpose of name lookup, after the anonymous union 4887 // definition, the members of the anonymous union are 4888 // considered to have been defined in the scope in which the 4889 // anonymous union is declared. 4890 unsigned OldChainingSize = Chaining.size(); 4891 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4892 Chaining.append(IF->chain_begin(), IF->chain_end()); 4893 else 4894 Chaining.push_back(VD); 4895 4896 assert(Chaining.size() >= 2); 4897 NamedDecl **NamedChain = 4898 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4899 for (unsigned i = 0; i < Chaining.size(); i++) 4900 NamedChain[i] = Chaining[i]; 4901 4902 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4903 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4904 VD->getType(), {NamedChain, Chaining.size()}); 4905 4906 for (const auto *Attr : VD->attrs()) 4907 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4908 4909 IndirectField->setAccess(AS); 4910 IndirectField->setImplicit(); 4911 SemaRef.PushOnScopeChains(IndirectField, S); 4912 4913 // That includes picking up the appropriate access specifier. 4914 if (AS != AS_none) IndirectField->setAccess(AS); 4915 4916 Chaining.resize(OldChainingSize); 4917 } 4918 } 4919 } 4920 4921 return Invalid; 4922 } 4923 4924 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4925 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4926 /// illegal input values are mapped to SC_None. 4927 static StorageClass 4928 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4929 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4930 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4931 "Parser allowed 'typedef' as storage class VarDecl."); 4932 switch (StorageClassSpec) { 4933 case DeclSpec::SCS_unspecified: return SC_None; 4934 case DeclSpec::SCS_extern: 4935 if (DS.isExternInLinkageSpec()) 4936 return SC_None; 4937 return SC_Extern; 4938 case DeclSpec::SCS_static: return SC_Static; 4939 case DeclSpec::SCS_auto: return SC_Auto; 4940 case DeclSpec::SCS_register: return SC_Register; 4941 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4942 // Illegal SCSs map to None: error reporting is up to the caller. 4943 case DeclSpec::SCS_mutable: // Fall through. 4944 case DeclSpec::SCS_typedef: return SC_None; 4945 } 4946 llvm_unreachable("unknown storage class specifier"); 4947 } 4948 4949 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4950 assert(Record->hasInClassInitializer()); 4951 4952 for (const auto *I : Record->decls()) { 4953 const auto *FD = dyn_cast<FieldDecl>(I); 4954 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4955 FD = IFD->getAnonField(); 4956 if (FD && FD->hasInClassInitializer()) 4957 return FD->getLocation(); 4958 } 4959 4960 llvm_unreachable("couldn't find in-class initializer"); 4961 } 4962 4963 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4964 SourceLocation DefaultInitLoc) { 4965 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4966 return; 4967 4968 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4969 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4970 } 4971 4972 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4973 CXXRecordDecl *AnonUnion) { 4974 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4975 return; 4976 4977 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4978 } 4979 4980 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4981 /// anonymous structure or union. Anonymous unions are a C++ feature 4982 /// (C++ [class.union]) and a C11 feature; anonymous structures 4983 /// are a C11 feature and GNU C++ extension. 4984 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4985 AccessSpecifier AS, 4986 RecordDecl *Record, 4987 const PrintingPolicy &Policy) { 4988 DeclContext *Owner = Record->getDeclContext(); 4989 4990 // Diagnose whether this anonymous struct/union is an extension. 4991 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4992 Diag(Record->getLocation(), diag::ext_anonymous_union); 4993 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4994 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4995 else if (!Record->isUnion() && !getLangOpts().C11) 4996 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4997 4998 // C and C++ require different kinds of checks for anonymous 4999 // structs/unions. 5000 bool Invalid = false; 5001 if (getLangOpts().CPlusPlus) { 5002 const char *PrevSpec = nullptr; 5003 if (Record->isUnion()) { 5004 // C++ [class.union]p6: 5005 // C++17 [class.union.anon]p2: 5006 // Anonymous unions declared in a named namespace or in the 5007 // global namespace shall be declared static. 5008 unsigned DiagID; 5009 DeclContext *OwnerScope = Owner->getRedeclContext(); 5010 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5011 (OwnerScope->isTranslationUnit() || 5012 (OwnerScope->isNamespace() && 5013 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5014 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5015 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5016 5017 // Recover by adding 'static'. 5018 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5019 PrevSpec, DiagID, Policy); 5020 } 5021 // C++ [class.union]p6: 5022 // A storage class is not allowed in a declaration of an 5023 // anonymous union in a class scope. 5024 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5025 isa<RecordDecl>(Owner)) { 5026 Diag(DS.getStorageClassSpecLoc(), 5027 diag::err_anonymous_union_with_storage_spec) 5028 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5029 5030 // Recover by removing the storage specifier. 5031 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5032 SourceLocation(), 5033 PrevSpec, DiagID, Context.getPrintingPolicy()); 5034 } 5035 } 5036 5037 // Ignore const/volatile/restrict qualifiers. 5038 if (DS.getTypeQualifiers()) { 5039 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5040 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5041 << Record->isUnion() << "const" 5042 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5043 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5044 Diag(DS.getVolatileSpecLoc(), 5045 diag::ext_anonymous_struct_union_qualified) 5046 << Record->isUnion() << "volatile" 5047 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5048 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5049 Diag(DS.getRestrictSpecLoc(), 5050 diag::ext_anonymous_struct_union_qualified) 5051 << Record->isUnion() << "restrict" 5052 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5053 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5054 Diag(DS.getAtomicSpecLoc(), 5055 diag::ext_anonymous_struct_union_qualified) 5056 << Record->isUnion() << "_Atomic" 5057 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5058 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5059 Diag(DS.getUnalignedSpecLoc(), 5060 diag::ext_anonymous_struct_union_qualified) 5061 << Record->isUnion() << "__unaligned" 5062 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5063 5064 DS.ClearTypeQualifiers(); 5065 } 5066 5067 // C++ [class.union]p2: 5068 // The member-specification of an anonymous union shall only 5069 // define non-static data members. [Note: nested types and 5070 // functions cannot be declared within an anonymous union. ] 5071 for (auto *Mem : Record->decls()) { 5072 // Ignore invalid declarations; we already diagnosed them. 5073 if (Mem->isInvalidDecl()) 5074 continue; 5075 5076 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5077 // C++ [class.union]p3: 5078 // An anonymous union shall not have private or protected 5079 // members (clause 11). 5080 assert(FD->getAccess() != AS_none); 5081 if (FD->getAccess() != AS_public) { 5082 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5083 << Record->isUnion() << (FD->getAccess() == AS_protected); 5084 Invalid = true; 5085 } 5086 5087 // C++ [class.union]p1 5088 // An object of a class with a non-trivial constructor, a non-trivial 5089 // copy constructor, a non-trivial destructor, or a non-trivial copy 5090 // assignment operator cannot be a member of a union, nor can an 5091 // array of such objects. 5092 if (CheckNontrivialField(FD)) 5093 Invalid = true; 5094 } else if (Mem->isImplicit()) { 5095 // Any implicit members are fine. 5096 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5097 // This is a type that showed up in an 5098 // elaborated-type-specifier inside the anonymous struct or 5099 // union, but which actually declares a type outside of the 5100 // anonymous struct or union. It's okay. 5101 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5102 if (!MemRecord->isAnonymousStructOrUnion() && 5103 MemRecord->getDeclName()) { 5104 // Visual C++ allows type definition in anonymous struct or union. 5105 if (getLangOpts().MicrosoftExt) 5106 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5107 << Record->isUnion(); 5108 else { 5109 // This is a nested type declaration. 5110 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5111 << Record->isUnion(); 5112 Invalid = true; 5113 } 5114 } else { 5115 // This is an anonymous type definition within another anonymous type. 5116 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5117 // not part of standard C++. 5118 Diag(MemRecord->getLocation(), 5119 diag::ext_anonymous_record_with_anonymous_type) 5120 << Record->isUnion(); 5121 } 5122 } else if (isa<AccessSpecDecl>(Mem)) { 5123 // Any access specifier is fine. 5124 } else if (isa<StaticAssertDecl>(Mem)) { 5125 // In C++1z, static_assert declarations are also fine. 5126 } else { 5127 // We have something that isn't a non-static data 5128 // member. Complain about it. 5129 unsigned DK = diag::err_anonymous_record_bad_member; 5130 if (isa<TypeDecl>(Mem)) 5131 DK = diag::err_anonymous_record_with_type; 5132 else if (isa<FunctionDecl>(Mem)) 5133 DK = diag::err_anonymous_record_with_function; 5134 else if (isa<VarDecl>(Mem)) 5135 DK = diag::err_anonymous_record_with_static; 5136 5137 // Visual C++ allows type definition in anonymous struct or union. 5138 if (getLangOpts().MicrosoftExt && 5139 DK == diag::err_anonymous_record_with_type) 5140 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5141 << Record->isUnion(); 5142 else { 5143 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5144 Invalid = true; 5145 } 5146 } 5147 } 5148 5149 // C++11 [class.union]p8 (DR1460): 5150 // At most one variant member of a union may have a 5151 // brace-or-equal-initializer. 5152 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5153 Owner->isRecord()) 5154 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5155 cast<CXXRecordDecl>(Record)); 5156 } 5157 5158 if (!Record->isUnion() && !Owner->isRecord()) { 5159 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5160 << getLangOpts().CPlusPlus; 5161 Invalid = true; 5162 } 5163 5164 // C++ [dcl.dcl]p3: 5165 // [If there are no declarators], and except for the declaration of an 5166 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5167 // names into the program 5168 // C++ [class.mem]p2: 5169 // each such member-declaration shall either declare at least one member 5170 // name of the class or declare at least one unnamed bit-field 5171 // 5172 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5173 if (getLangOpts().CPlusPlus && Record->field_empty()) 5174 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5175 5176 // Mock up a declarator. 5177 Declarator Dc(DS, DeclaratorContext::Member); 5178 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5179 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5180 5181 // Create a declaration for this anonymous struct/union. 5182 NamedDecl *Anon = nullptr; 5183 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5184 Anon = FieldDecl::Create( 5185 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5186 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5187 /*BitWidth=*/nullptr, /*Mutable=*/false, 5188 /*InitStyle=*/ICIS_NoInit); 5189 Anon->setAccess(AS); 5190 ProcessDeclAttributes(S, Anon, Dc); 5191 5192 if (getLangOpts().CPlusPlus) 5193 FieldCollector->Add(cast<FieldDecl>(Anon)); 5194 } else { 5195 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5196 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5197 if (SCSpec == DeclSpec::SCS_mutable) { 5198 // mutable can only appear on non-static class members, so it's always 5199 // an error here 5200 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5201 Invalid = true; 5202 SC = SC_None; 5203 } 5204 5205 assert(DS.getAttributes().empty() && "No attribute expected"); 5206 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5207 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5208 Context.getTypeDeclType(Record), TInfo, SC); 5209 5210 // Default-initialize the implicit variable. This initialization will be 5211 // trivial in almost all cases, except if a union member has an in-class 5212 // initializer: 5213 // union { int n = 0; }; 5214 ActOnUninitializedDecl(Anon); 5215 } 5216 Anon->setImplicit(); 5217 5218 // Mark this as an anonymous struct/union type. 5219 Record->setAnonymousStructOrUnion(true); 5220 5221 // Add the anonymous struct/union object to the current 5222 // context. We'll be referencing this object when we refer to one of 5223 // its members. 5224 Owner->addDecl(Anon); 5225 5226 // Inject the members of the anonymous struct/union into the owning 5227 // context and into the identifier resolver chain for name lookup 5228 // purposes. 5229 SmallVector<NamedDecl*, 2> Chain; 5230 Chain.push_back(Anon); 5231 5232 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5233 Invalid = true; 5234 5235 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5236 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5237 MangleNumberingContext *MCtx; 5238 Decl *ManglingContextDecl; 5239 std::tie(MCtx, ManglingContextDecl) = 5240 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5241 if (MCtx) { 5242 Context.setManglingNumber( 5243 NewVD, MCtx->getManglingNumber( 5244 NewVD, getMSManglingNumber(getLangOpts(), S))); 5245 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5246 } 5247 } 5248 } 5249 5250 if (Invalid) 5251 Anon->setInvalidDecl(); 5252 5253 return Anon; 5254 } 5255 5256 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5257 /// Microsoft C anonymous structure. 5258 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5259 /// Example: 5260 /// 5261 /// struct A { int a; }; 5262 /// struct B { struct A; int b; }; 5263 /// 5264 /// void foo() { 5265 /// B var; 5266 /// var.a = 3; 5267 /// } 5268 /// 5269 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5270 RecordDecl *Record) { 5271 assert(Record && "expected a record!"); 5272 5273 // Mock up a declarator. 5274 Declarator Dc(DS, DeclaratorContext::TypeName); 5275 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5276 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5277 5278 auto *ParentDecl = cast<RecordDecl>(CurContext); 5279 QualType RecTy = Context.getTypeDeclType(Record); 5280 5281 // Create a declaration for this anonymous struct. 5282 NamedDecl *Anon = 5283 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5284 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5285 /*BitWidth=*/nullptr, /*Mutable=*/false, 5286 /*InitStyle=*/ICIS_NoInit); 5287 Anon->setImplicit(); 5288 5289 // Add the anonymous struct object to the current context. 5290 CurContext->addDecl(Anon); 5291 5292 // Inject the members of the anonymous struct into the current 5293 // context and into the identifier resolver chain for name lookup 5294 // purposes. 5295 SmallVector<NamedDecl*, 2> Chain; 5296 Chain.push_back(Anon); 5297 5298 RecordDecl *RecordDef = Record->getDefinition(); 5299 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5300 diag::err_field_incomplete_or_sizeless) || 5301 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5302 AS_none, Chain)) { 5303 Anon->setInvalidDecl(); 5304 ParentDecl->setInvalidDecl(); 5305 } 5306 5307 return Anon; 5308 } 5309 5310 /// GetNameForDeclarator - Determine the full declaration name for the 5311 /// given Declarator. 5312 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5313 return GetNameFromUnqualifiedId(D.getName()); 5314 } 5315 5316 /// Retrieves the declaration name from a parsed unqualified-id. 5317 DeclarationNameInfo 5318 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5319 DeclarationNameInfo NameInfo; 5320 NameInfo.setLoc(Name.StartLocation); 5321 5322 switch (Name.getKind()) { 5323 5324 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5325 case UnqualifiedIdKind::IK_Identifier: 5326 NameInfo.setName(Name.Identifier); 5327 return NameInfo; 5328 5329 case UnqualifiedIdKind::IK_DeductionGuideName: { 5330 // C++ [temp.deduct.guide]p3: 5331 // The simple-template-id shall name a class template specialization. 5332 // The template-name shall be the same identifier as the template-name 5333 // of the simple-template-id. 5334 // These together intend to imply that the template-name shall name a 5335 // class template. 5336 // FIXME: template<typename T> struct X {}; 5337 // template<typename T> using Y = X<T>; 5338 // Y(int) -> Y<int>; 5339 // satisfies these rules but does not name a class template. 5340 TemplateName TN = Name.TemplateName.get().get(); 5341 auto *Template = TN.getAsTemplateDecl(); 5342 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5343 Diag(Name.StartLocation, 5344 diag::err_deduction_guide_name_not_class_template) 5345 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5346 if (Template) 5347 Diag(Template->getLocation(), diag::note_template_decl_here); 5348 return DeclarationNameInfo(); 5349 } 5350 5351 NameInfo.setName( 5352 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5353 return NameInfo; 5354 } 5355 5356 case UnqualifiedIdKind::IK_OperatorFunctionId: 5357 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5358 Name.OperatorFunctionId.Operator)); 5359 NameInfo.setCXXOperatorNameRange(SourceRange( 5360 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5361 return NameInfo; 5362 5363 case UnqualifiedIdKind::IK_LiteralOperatorId: 5364 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5365 Name.Identifier)); 5366 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5367 return NameInfo; 5368 5369 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5370 TypeSourceInfo *TInfo; 5371 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5372 if (Ty.isNull()) 5373 return DeclarationNameInfo(); 5374 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5375 Context.getCanonicalType(Ty))); 5376 NameInfo.setNamedTypeInfo(TInfo); 5377 return NameInfo; 5378 } 5379 5380 case UnqualifiedIdKind::IK_ConstructorName: { 5381 TypeSourceInfo *TInfo; 5382 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5383 if (Ty.isNull()) 5384 return DeclarationNameInfo(); 5385 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5386 Context.getCanonicalType(Ty))); 5387 NameInfo.setNamedTypeInfo(TInfo); 5388 return NameInfo; 5389 } 5390 5391 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5392 // In well-formed code, we can only have a constructor 5393 // template-id that refers to the current context, so go there 5394 // to find the actual type being constructed. 5395 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5396 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5397 return DeclarationNameInfo(); 5398 5399 // Determine the type of the class being constructed. 5400 QualType CurClassType = Context.getTypeDeclType(CurClass); 5401 5402 // FIXME: Check two things: that the template-id names the same type as 5403 // CurClassType, and that the template-id does not occur when the name 5404 // was qualified. 5405 5406 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5407 Context.getCanonicalType(CurClassType))); 5408 // FIXME: should we retrieve TypeSourceInfo? 5409 NameInfo.setNamedTypeInfo(nullptr); 5410 return NameInfo; 5411 } 5412 5413 case UnqualifiedIdKind::IK_DestructorName: { 5414 TypeSourceInfo *TInfo; 5415 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5416 if (Ty.isNull()) 5417 return DeclarationNameInfo(); 5418 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5419 Context.getCanonicalType(Ty))); 5420 NameInfo.setNamedTypeInfo(TInfo); 5421 return NameInfo; 5422 } 5423 5424 case UnqualifiedIdKind::IK_TemplateId: { 5425 TemplateName TName = Name.TemplateId->Template.get(); 5426 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5427 return Context.getNameForTemplate(TName, TNameLoc); 5428 } 5429 5430 } // switch (Name.getKind()) 5431 5432 llvm_unreachable("Unknown name kind"); 5433 } 5434 5435 static QualType getCoreType(QualType Ty) { 5436 do { 5437 if (Ty->isPointerType() || Ty->isReferenceType()) 5438 Ty = Ty->getPointeeType(); 5439 else if (Ty->isArrayType()) 5440 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5441 else 5442 return Ty.withoutLocalFastQualifiers(); 5443 } while (true); 5444 } 5445 5446 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5447 /// and Definition have "nearly" matching parameters. This heuristic is 5448 /// used to improve diagnostics in the case where an out-of-line function 5449 /// definition doesn't match any declaration within the class or namespace. 5450 /// Also sets Params to the list of indices to the parameters that differ 5451 /// between the declaration and the definition. If hasSimilarParameters 5452 /// returns true and Params is empty, then all of the parameters match. 5453 static bool hasSimilarParameters(ASTContext &Context, 5454 FunctionDecl *Declaration, 5455 FunctionDecl *Definition, 5456 SmallVectorImpl<unsigned> &Params) { 5457 Params.clear(); 5458 if (Declaration->param_size() != Definition->param_size()) 5459 return false; 5460 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5461 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5462 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5463 5464 // The parameter types are identical 5465 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5466 continue; 5467 5468 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5469 QualType DefParamBaseTy = getCoreType(DefParamTy); 5470 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5471 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5472 5473 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5474 (DeclTyName && DeclTyName == DefTyName)) 5475 Params.push_back(Idx); 5476 else // The two parameters aren't even close 5477 return false; 5478 } 5479 5480 return true; 5481 } 5482 5483 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5484 /// declarator needs to be rebuilt in the current instantiation. 5485 /// Any bits of declarator which appear before the name are valid for 5486 /// consideration here. That's specifically the type in the decl spec 5487 /// and the base type in any member-pointer chunks. 5488 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5489 DeclarationName Name) { 5490 // The types we specifically need to rebuild are: 5491 // - typenames, typeofs, and decltypes 5492 // - types which will become injected class names 5493 // Of course, we also need to rebuild any type referencing such a 5494 // type. It's safest to just say "dependent", but we call out a 5495 // few cases here. 5496 5497 DeclSpec &DS = D.getMutableDeclSpec(); 5498 switch (DS.getTypeSpecType()) { 5499 case DeclSpec::TST_typename: 5500 case DeclSpec::TST_typeofType: 5501 case DeclSpec::TST_underlyingType: 5502 case DeclSpec::TST_atomic: { 5503 // Grab the type from the parser. 5504 TypeSourceInfo *TSI = nullptr; 5505 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5506 if (T.isNull() || !T->isInstantiationDependentType()) break; 5507 5508 // Make sure there's a type source info. This isn't really much 5509 // of a waste; most dependent types should have type source info 5510 // attached already. 5511 if (!TSI) 5512 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5513 5514 // Rebuild the type in the current instantiation. 5515 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5516 if (!TSI) return true; 5517 5518 // Store the new type back in the decl spec. 5519 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5520 DS.UpdateTypeRep(LocType); 5521 break; 5522 } 5523 5524 case DeclSpec::TST_decltype: 5525 case DeclSpec::TST_typeofExpr: { 5526 Expr *E = DS.getRepAsExpr(); 5527 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5528 if (Result.isInvalid()) return true; 5529 DS.UpdateExprRep(Result.get()); 5530 break; 5531 } 5532 5533 default: 5534 // Nothing to do for these decl specs. 5535 break; 5536 } 5537 5538 // It doesn't matter what order we do this in. 5539 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5540 DeclaratorChunk &Chunk = D.getTypeObject(I); 5541 5542 // The only type information in the declarator which can come 5543 // before the declaration name is the base type of a member 5544 // pointer. 5545 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5546 continue; 5547 5548 // Rebuild the scope specifier in-place. 5549 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5550 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5551 return true; 5552 } 5553 5554 return false; 5555 } 5556 5557 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5558 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 5559 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5560 5561 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5562 Dcl && Dcl->getDeclContext()->isFileContext()) 5563 Dcl->setTopLevelDeclInObjCContainer(); 5564 5565 if (getLangOpts().OpenCL) 5566 setCurrentOpenCLExtensionForDecl(Dcl); 5567 5568 return Dcl; 5569 } 5570 5571 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5572 /// If T is the name of a class, then each of the following shall have a 5573 /// name different from T: 5574 /// - every static data member of class T; 5575 /// - every member function of class T 5576 /// - every member of class T that is itself a type; 5577 /// \returns true if the declaration name violates these rules. 5578 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5579 DeclarationNameInfo NameInfo) { 5580 DeclarationName Name = NameInfo.getName(); 5581 5582 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5583 while (Record && Record->isAnonymousStructOrUnion()) 5584 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5585 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5586 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5587 return true; 5588 } 5589 5590 return false; 5591 } 5592 5593 /// Diagnose a declaration whose declarator-id has the given 5594 /// nested-name-specifier. 5595 /// 5596 /// \param SS The nested-name-specifier of the declarator-id. 5597 /// 5598 /// \param DC The declaration context to which the nested-name-specifier 5599 /// resolves. 5600 /// 5601 /// \param Name The name of the entity being declared. 5602 /// 5603 /// \param Loc The location of the name of the entity being declared. 5604 /// 5605 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5606 /// we're declaring an explicit / partial specialization / instantiation. 5607 /// 5608 /// \returns true if we cannot safely recover from this error, false otherwise. 5609 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5610 DeclarationName Name, 5611 SourceLocation Loc, bool IsTemplateId) { 5612 DeclContext *Cur = CurContext; 5613 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5614 Cur = Cur->getParent(); 5615 5616 // If the user provided a superfluous scope specifier that refers back to the 5617 // class in which the entity is already declared, diagnose and ignore it. 5618 // 5619 // class X { 5620 // void X::f(); 5621 // }; 5622 // 5623 // Note, it was once ill-formed to give redundant qualification in all 5624 // contexts, but that rule was removed by DR482. 5625 if (Cur->Equals(DC)) { 5626 if (Cur->isRecord()) { 5627 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5628 : diag::err_member_extra_qualification) 5629 << Name << FixItHint::CreateRemoval(SS.getRange()); 5630 SS.clear(); 5631 } else { 5632 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5633 } 5634 return false; 5635 } 5636 5637 // Check whether the qualifying scope encloses the scope of the original 5638 // declaration. For a template-id, we perform the checks in 5639 // CheckTemplateSpecializationScope. 5640 if (!Cur->Encloses(DC) && !IsTemplateId) { 5641 if (Cur->isRecord()) 5642 Diag(Loc, diag::err_member_qualification) 5643 << Name << SS.getRange(); 5644 else if (isa<TranslationUnitDecl>(DC)) 5645 Diag(Loc, diag::err_invalid_declarator_global_scope) 5646 << Name << SS.getRange(); 5647 else if (isa<FunctionDecl>(Cur)) 5648 Diag(Loc, diag::err_invalid_declarator_in_function) 5649 << Name << SS.getRange(); 5650 else if (isa<BlockDecl>(Cur)) 5651 Diag(Loc, diag::err_invalid_declarator_in_block) 5652 << Name << SS.getRange(); 5653 else 5654 Diag(Loc, diag::err_invalid_declarator_scope) 5655 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5656 5657 return true; 5658 } 5659 5660 if (Cur->isRecord()) { 5661 // Cannot qualify members within a class. 5662 Diag(Loc, diag::err_member_qualification) 5663 << Name << SS.getRange(); 5664 SS.clear(); 5665 5666 // C++ constructors and destructors with incorrect scopes can break 5667 // our AST invariants by having the wrong underlying types. If 5668 // that's the case, then drop this declaration entirely. 5669 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5670 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5671 !Context.hasSameType(Name.getCXXNameType(), 5672 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5673 return true; 5674 5675 return false; 5676 } 5677 5678 // C++11 [dcl.meaning]p1: 5679 // [...] "The nested-name-specifier of the qualified declarator-id shall 5680 // not begin with a decltype-specifer" 5681 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5682 while (SpecLoc.getPrefix()) 5683 SpecLoc = SpecLoc.getPrefix(); 5684 if (dyn_cast_or_null<DecltypeType>( 5685 SpecLoc.getNestedNameSpecifier()->getAsType())) 5686 Diag(Loc, diag::err_decltype_in_declarator) 5687 << SpecLoc.getTypeLoc().getSourceRange(); 5688 5689 return false; 5690 } 5691 5692 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5693 MultiTemplateParamsArg TemplateParamLists) { 5694 // TODO: consider using NameInfo for diagnostic. 5695 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5696 DeclarationName Name = NameInfo.getName(); 5697 5698 // All of these full declarators require an identifier. If it doesn't have 5699 // one, the ParsedFreeStandingDeclSpec action should be used. 5700 if (D.isDecompositionDeclarator()) { 5701 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5702 } else if (!Name) { 5703 if (!D.isInvalidType()) // Reject this if we think it is valid. 5704 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5705 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5706 return nullptr; 5707 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5708 return nullptr; 5709 5710 // The scope passed in may not be a decl scope. Zip up the scope tree until 5711 // we find one that is. 5712 while ((S->getFlags() & Scope::DeclScope) == 0 || 5713 (S->getFlags() & Scope::TemplateParamScope) != 0) 5714 S = S->getParent(); 5715 5716 DeclContext *DC = CurContext; 5717 if (D.getCXXScopeSpec().isInvalid()) 5718 D.setInvalidType(); 5719 else if (D.getCXXScopeSpec().isSet()) { 5720 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5721 UPPC_DeclarationQualifier)) 5722 return nullptr; 5723 5724 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5725 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5726 if (!DC || isa<EnumDecl>(DC)) { 5727 // If we could not compute the declaration context, it's because the 5728 // declaration context is dependent but does not refer to a class, 5729 // class template, or class template partial specialization. Complain 5730 // and return early, to avoid the coming semantic disaster. 5731 Diag(D.getIdentifierLoc(), 5732 diag::err_template_qualified_declarator_no_match) 5733 << D.getCXXScopeSpec().getScopeRep() 5734 << D.getCXXScopeSpec().getRange(); 5735 return nullptr; 5736 } 5737 bool IsDependentContext = DC->isDependentContext(); 5738 5739 if (!IsDependentContext && 5740 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5741 return nullptr; 5742 5743 // If a class is incomplete, do not parse entities inside it. 5744 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5745 Diag(D.getIdentifierLoc(), 5746 diag::err_member_def_undefined_record) 5747 << Name << DC << D.getCXXScopeSpec().getRange(); 5748 return nullptr; 5749 } 5750 if (!D.getDeclSpec().isFriendSpecified()) { 5751 if (diagnoseQualifiedDeclaration( 5752 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5753 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5754 if (DC->isRecord()) 5755 return nullptr; 5756 5757 D.setInvalidType(); 5758 } 5759 } 5760 5761 // Check whether we need to rebuild the type of the given 5762 // declaration in the current instantiation. 5763 if (EnteringContext && IsDependentContext && 5764 TemplateParamLists.size() != 0) { 5765 ContextRAII SavedContext(*this, DC); 5766 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5767 D.setInvalidType(); 5768 } 5769 } 5770 5771 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5772 QualType R = TInfo->getType(); 5773 5774 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5775 UPPC_DeclarationType)) 5776 D.setInvalidType(); 5777 5778 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5779 forRedeclarationInCurContext()); 5780 5781 // See if this is a redefinition of a variable in the same scope. 5782 if (!D.getCXXScopeSpec().isSet()) { 5783 bool IsLinkageLookup = false; 5784 bool CreateBuiltins = false; 5785 5786 // If the declaration we're planning to build will be a function 5787 // or object with linkage, then look for another declaration with 5788 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5789 // 5790 // If the declaration we're planning to build will be declared with 5791 // external linkage in the translation unit, create any builtin with 5792 // the same name. 5793 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5794 /* Do nothing*/; 5795 else if (CurContext->isFunctionOrMethod() && 5796 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5797 R->isFunctionType())) { 5798 IsLinkageLookup = true; 5799 CreateBuiltins = 5800 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5801 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5802 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5803 CreateBuiltins = true; 5804 5805 if (IsLinkageLookup) { 5806 Previous.clear(LookupRedeclarationWithLinkage); 5807 Previous.setRedeclarationKind(ForExternalRedeclaration); 5808 } 5809 5810 LookupName(Previous, S, CreateBuiltins); 5811 } else { // Something like "int foo::x;" 5812 LookupQualifiedName(Previous, DC); 5813 5814 // C++ [dcl.meaning]p1: 5815 // When the declarator-id is qualified, the declaration shall refer to a 5816 // previously declared member of the class or namespace to which the 5817 // qualifier refers (or, in the case of a namespace, of an element of the 5818 // inline namespace set of that namespace (7.3.1)) or to a specialization 5819 // thereof; [...] 5820 // 5821 // Note that we already checked the context above, and that we do not have 5822 // enough information to make sure that Previous contains the declaration 5823 // we want to match. For example, given: 5824 // 5825 // class X { 5826 // void f(); 5827 // void f(float); 5828 // }; 5829 // 5830 // void X::f(int) { } // ill-formed 5831 // 5832 // In this case, Previous will point to the overload set 5833 // containing the two f's declared in X, but neither of them 5834 // matches. 5835 5836 // C++ [dcl.meaning]p1: 5837 // [...] the member shall not merely have been introduced by a 5838 // using-declaration in the scope of the class or namespace nominated by 5839 // the nested-name-specifier of the declarator-id. 5840 RemoveUsingDecls(Previous); 5841 } 5842 5843 if (Previous.isSingleResult() && 5844 Previous.getFoundDecl()->isTemplateParameter()) { 5845 // Maybe we will complain about the shadowed template parameter. 5846 if (!D.isInvalidType()) 5847 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5848 Previous.getFoundDecl()); 5849 5850 // Just pretend that we didn't see the previous declaration. 5851 Previous.clear(); 5852 } 5853 5854 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5855 // Forget that the previous declaration is the injected-class-name. 5856 Previous.clear(); 5857 5858 // In C++, the previous declaration we find might be a tag type 5859 // (class or enum). In this case, the new declaration will hide the 5860 // tag type. Note that this applies to functions, function templates, and 5861 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5862 if (Previous.isSingleTagDecl() && 5863 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5864 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5865 Previous.clear(); 5866 5867 // Check that there are no default arguments other than in the parameters 5868 // of a function declaration (C++ only). 5869 if (getLangOpts().CPlusPlus) 5870 CheckExtraCXXDefaultArguments(D); 5871 5872 NamedDecl *New; 5873 5874 bool AddToScope = true; 5875 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5876 if (TemplateParamLists.size()) { 5877 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5878 return nullptr; 5879 } 5880 5881 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5882 } else if (R->isFunctionType()) { 5883 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5884 TemplateParamLists, 5885 AddToScope); 5886 } else { 5887 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5888 AddToScope); 5889 } 5890 5891 if (!New) 5892 return nullptr; 5893 5894 // If this has an identifier and is not a function template specialization, 5895 // add it to the scope stack. 5896 if (New->getDeclName() && AddToScope) 5897 PushOnScopeChains(New, S); 5898 5899 if (isInOpenMPDeclareTargetContext()) 5900 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5901 5902 return New; 5903 } 5904 5905 /// Helper method to turn variable array types into constant array 5906 /// types in certain situations which would otherwise be errors (for 5907 /// GCC compatibility). 5908 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5909 ASTContext &Context, 5910 bool &SizeIsNegative, 5911 llvm::APSInt &Oversized) { 5912 // This method tries to turn a variable array into a constant 5913 // array even when the size isn't an ICE. This is necessary 5914 // for compatibility with code that depends on gcc's buggy 5915 // constant expression folding, like struct {char x[(int)(char*)2];} 5916 SizeIsNegative = false; 5917 Oversized = 0; 5918 5919 if (T->isDependentType()) 5920 return QualType(); 5921 5922 QualifierCollector Qs; 5923 const Type *Ty = Qs.strip(T); 5924 5925 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5926 QualType Pointee = PTy->getPointeeType(); 5927 QualType FixedType = 5928 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5929 Oversized); 5930 if (FixedType.isNull()) return FixedType; 5931 FixedType = Context.getPointerType(FixedType); 5932 return Qs.apply(Context, FixedType); 5933 } 5934 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5935 QualType Inner = PTy->getInnerType(); 5936 QualType FixedType = 5937 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5938 Oversized); 5939 if (FixedType.isNull()) return FixedType; 5940 FixedType = Context.getParenType(FixedType); 5941 return Qs.apply(Context, FixedType); 5942 } 5943 5944 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5945 if (!VLATy) 5946 return QualType(); 5947 5948 QualType ElemTy = VLATy->getElementType(); 5949 if (ElemTy->isVariablyModifiedType()) { 5950 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 5951 SizeIsNegative, Oversized); 5952 if (ElemTy.isNull()) 5953 return QualType(); 5954 } 5955 5956 Expr::EvalResult Result; 5957 if (!VLATy->getSizeExpr() || 5958 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5959 return QualType(); 5960 5961 llvm::APSInt Res = Result.Val.getInt(); 5962 5963 // Check whether the array size is negative. 5964 if (Res.isSigned() && Res.isNegative()) { 5965 SizeIsNegative = true; 5966 return QualType(); 5967 } 5968 5969 // Check whether the array is too large to be addressed. 5970 unsigned ActiveSizeBits = 5971 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 5972 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 5973 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 5974 : Res.getActiveBits(); 5975 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5976 Oversized = Res; 5977 return QualType(); 5978 } 5979 5980 QualType FoldedArrayType = Context.getConstantArrayType( 5981 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 5982 return Qs.apply(Context, FoldedArrayType); 5983 } 5984 5985 static void 5986 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5987 SrcTL = SrcTL.getUnqualifiedLoc(); 5988 DstTL = DstTL.getUnqualifiedLoc(); 5989 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5990 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5991 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5992 DstPTL.getPointeeLoc()); 5993 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5994 return; 5995 } 5996 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5997 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5998 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5999 DstPTL.getInnerLoc()); 6000 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 6001 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 6002 return; 6003 } 6004 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6005 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6006 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6007 TypeLoc DstElemTL = DstATL.getElementLoc(); 6008 if (VariableArrayTypeLoc SrcElemATL = 6009 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6010 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6011 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6012 } else { 6013 DstElemTL.initializeFullCopy(SrcElemTL); 6014 } 6015 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6016 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6017 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6018 } 6019 6020 /// Helper method to turn variable array types into constant array 6021 /// types in certain situations which would otherwise be errors (for 6022 /// GCC compatibility). 6023 static TypeSourceInfo* 6024 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6025 ASTContext &Context, 6026 bool &SizeIsNegative, 6027 llvm::APSInt &Oversized) { 6028 QualType FixedTy 6029 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6030 SizeIsNegative, Oversized); 6031 if (FixedTy.isNull()) 6032 return nullptr; 6033 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6034 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6035 FixedTInfo->getTypeLoc()); 6036 return FixedTInfo; 6037 } 6038 6039 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6040 /// true if we were successful. 6041 static bool tryToFixVariablyModifiedVarType(Sema &S, TypeSourceInfo *&TInfo, 6042 QualType &T, SourceLocation Loc, 6043 unsigned FailedFoldDiagID) { 6044 bool SizeIsNegative; 6045 llvm::APSInt Oversized; 6046 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6047 TInfo, S.Context, SizeIsNegative, Oversized); 6048 if (FixedTInfo) { 6049 S.Diag(Loc, diag::ext_vla_folded_to_constant); 6050 TInfo = FixedTInfo; 6051 T = FixedTInfo->getType(); 6052 return true; 6053 } 6054 6055 if (SizeIsNegative) 6056 S.Diag(Loc, diag::err_typecheck_negative_array_size); 6057 else if (Oversized.getBoolValue()) 6058 S.Diag(Loc, diag::err_array_too_large) << Oversized.toString(10); 6059 else if (FailedFoldDiagID) 6060 S.Diag(Loc, FailedFoldDiagID); 6061 return false; 6062 } 6063 6064 /// Register the given locally-scoped extern "C" declaration so 6065 /// that it can be found later for redeclarations. We include any extern "C" 6066 /// declaration that is not visible in the translation unit here, not just 6067 /// function-scope declarations. 6068 void 6069 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6070 if (!getLangOpts().CPlusPlus && 6071 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6072 // Don't need to track declarations in the TU in C. 6073 return; 6074 6075 // Note that we have a locally-scoped external with this name. 6076 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6077 } 6078 6079 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6080 // FIXME: We can have multiple results via __attribute__((overloadable)). 6081 auto Result = Context.getExternCContextDecl()->lookup(Name); 6082 return Result.empty() ? nullptr : *Result.begin(); 6083 } 6084 6085 /// Diagnose function specifiers on a declaration of an identifier that 6086 /// does not identify a function. 6087 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6088 // FIXME: We should probably indicate the identifier in question to avoid 6089 // confusion for constructs like "virtual int a(), b;" 6090 if (DS.isVirtualSpecified()) 6091 Diag(DS.getVirtualSpecLoc(), 6092 diag::err_virtual_non_function); 6093 6094 if (DS.hasExplicitSpecifier()) 6095 Diag(DS.getExplicitSpecLoc(), 6096 diag::err_explicit_non_function); 6097 6098 if (DS.isNoreturnSpecified()) 6099 Diag(DS.getNoreturnSpecLoc(), 6100 diag::err_noreturn_non_function); 6101 } 6102 6103 NamedDecl* 6104 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6105 TypeSourceInfo *TInfo, LookupResult &Previous) { 6106 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6107 if (D.getCXXScopeSpec().isSet()) { 6108 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6109 << D.getCXXScopeSpec().getRange(); 6110 D.setInvalidType(); 6111 // Pretend we didn't see the scope specifier. 6112 DC = CurContext; 6113 Previous.clear(); 6114 } 6115 6116 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6117 6118 if (D.getDeclSpec().isInlineSpecified()) 6119 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6120 << getLangOpts().CPlusPlus17; 6121 if (D.getDeclSpec().hasConstexprSpecifier()) 6122 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6123 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6124 6125 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6126 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6127 Diag(D.getName().StartLocation, 6128 diag::err_deduction_guide_invalid_specifier) 6129 << "typedef"; 6130 else 6131 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6132 << D.getName().getSourceRange(); 6133 return nullptr; 6134 } 6135 6136 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6137 if (!NewTD) return nullptr; 6138 6139 // Handle attributes prior to checking for duplicates in MergeVarDecl 6140 ProcessDeclAttributes(S, NewTD, D); 6141 6142 CheckTypedefForVariablyModifiedType(S, NewTD); 6143 6144 bool Redeclaration = D.isRedeclaration(); 6145 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6146 D.setRedeclaration(Redeclaration); 6147 return ND; 6148 } 6149 6150 void 6151 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6152 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6153 // then it shall have block scope. 6154 // Note that variably modified types must be fixed before merging the decl so 6155 // that redeclarations will match. 6156 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6157 QualType T = TInfo->getType(); 6158 if (T->isVariablyModifiedType()) { 6159 setFunctionHasBranchProtectedScope(); 6160 6161 if (S->getFnParent() == nullptr) { 6162 bool SizeIsNegative; 6163 llvm::APSInt Oversized; 6164 TypeSourceInfo *FixedTInfo = 6165 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6166 SizeIsNegative, 6167 Oversized); 6168 if (FixedTInfo) { 6169 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6170 NewTD->setTypeSourceInfo(FixedTInfo); 6171 } else { 6172 if (SizeIsNegative) 6173 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6174 else if (T->isVariableArrayType()) 6175 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6176 else if (Oversized.getBoolValue()) 6177 Diag(NewTD->getLocation(), diag::err_array_too_large) 6178 << Oversized.toString(10); 6179 else 6180 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6181 NewTD->setInvalidDecl(); 6182 } 6183 } 6184 } 6185 } 6186 6187 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6188 /// declares a typedef-name, either using the 'typedef' type specifier or via 6189 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6190 NamedDecl* 6191 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6192 LookupResult &Previous, bool &Redeclaration) { 6193 6194 // Find the shadowed declaration before filtering for scope. 6195 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6196 6197 // Merge the decl with the existing one if appropriate. If the decl is 6198 // in an outer scope, it isn't the same thing. 6199 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6200 /*AllowInlineNamespace*/false); 6201 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6202 if (!Previous.empty()) { 6203 Redeclaration = true; 6204 MergeTypedefNameDecl(S, NewTD, Previous); 6205 } else { 6206 inferGslPointerAttribute(NewTD); 6207 } 6208 6209 if (ShadowedDecl && !Redeclaration) 6210 CheckShadow(NewTD, ShadowedDecl, Previous); 6211 6212 // If this is the C FILE type, notify the AST context. 6213 if (IdentifierInfo *II = NewTD->getIdentifier()) 6214 if (!NewTD->isInvalidDecl() && 6215 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6216 if (II->isStr("FILE")) 6217 Context.setFILEDecl(NewTD); 6218 else if (II->isStr("jmp_buf")) 6219 Context.setjmp_bufDecl(NewTD); 6220 else if (II->isStr("sigjmp_buf")) 6221 Context.setsigjmp_bufDecl(NewTD); 6222 else if (II->isStr("ucontext_t")) 6223 Context.setucontext_tDecl(NewTD); 6224 } 6225 6226 return NewTD; 6227 } 6228 6229 /// Determines whether the given declaration is an out-of-scope 6230 /// previous declaration. 6231 /// 6232 /// This routine should be invoked when name lookup has found a 6233 /// previous declaration (PrevDecl) that is not in the scope where a 6234 /// new declaration by the same name is being introduced. If the new 6235 /// declaration occurs in a local scope, previous declarations with 6236 /// linkage may still be considered previous declarations (C99 6237 /// 6.2.2p4-5, C++ [basic.link]p6). 6238 /// 6239 /// \param PrevDecl the previous declaration found by name 6240 /// lookup 6241 /// 6242 /// \param DC the context in which the new declaration is being 6243 /// declared. 6244 /// 6245 /// \returns true if PrevDecl is an out-of-scope previous declaration 6246 /// for a new delcaration with the same name. 6247 static bool 6248 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6249 ASTContext &Context) { 6250 if (!PrevDecl) 6251 return false; 6252 6253 if (!PrevDecl->hasLinkage()) 6254 return false; 6255 6256 if (Context.getLangOpts().CPlusPlus) { 6257 // C++ [basic.link]p6: 6258 // If there is a visible declaration of an entity with linkage 6259 // having the same name and type, ignoring entities declared 6260 // outside the innermost enclosing namespace scope, the block 6261 // scope declaration declares that same entity and receives the 6262 // linkage of the previous declaration. 6263 DeclContext *OuterContext = DC->getRedeclContext(); 6264 if (!OuterContext->isFunctionOrMethod()) 6265 // This rule only applies to block-scope declarations. 6266 return false; 6267 6268 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6269 if (PrevOuterContext->isRecord()) 6270 // We found a member function: ignore it. 6271 return false; 6272 6273 // Find the innermost enclosing namespace for the new and 6274 // previous declarations. 6275 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6276 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6277 6278 // The previous declaration is in a different namespace, so it 6279 // isn't the same function. 6280 if (!OuterContext->Equals(PrevOuterContext)) 6281 return false; 6282 } 6283 6284 return true; 6285 } 6286 6287 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6288 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6289 if (!SS.isSet()) return; 6290 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6291 } 6292 6293 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6294 QualType type = decl->getType(); 6295 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6296 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6297 // Various kinds of declaration aren't allowed to be __autoreleasing. 6298 unsigned kind = -1U; 6299 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6300 if (var->hasAttr<BlocksAttr>()) 6301 kind = 0; // __block 6302 else if (!var->hasLocalStorage()) 6303 kind = 1; // global 6304 } else if (isa<ObjCIvarDecl>(decl)) { 6305 kind = 3; // ivar 6306 } else if (isa<FieldDecl>(decl)) { 6307 kind = 2; // field 6308 } 6309 6310 if (kind != -1U) { 6311 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6312 << kind; 6313 } 6314 } else if (lifetime == Qualifiers::OCL_None) { 6315 // Try to infer lifetime. 6316 if (!type->isObjCLifetimeType()) 6317 return false; 6318 6319 lifetime = type->getObjCARCImplicitLifetime(); 6320 type = Context.getLifetimeQualifiedType(type, lifetime); 6321 decl->setType(type); 6322 } 6323 6324 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6325 // Thread-local variables cannot have lifetime. 6326 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6327 var->getTLSKind()) { 6328 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6329 << var->getType(); 6330 return true; 6331 } 6332 } 6333 6334 return false; 6335 } 6336 6337 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6338 if (Decl->getType().hasAddressSpace()) 6339 return; 6340 if (Decl->getType()->isDependentType()) 6341 return; 6342 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6343 QualType Type = Var->getType(); 6344 if (Type->isSamplerT() || Type->isVoidType()) 6345 return; 6346 LangAS ImplAS = LangAS::opencl_private; 6347 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6348 Var->hasGlobalStorage()) 6349 ImplAS = LangAS::opencl_global; 6350 // If the original type from a decayed type is an array type and that array 6351 // type has no address space yet, deduce it now. 6352 if (auto DT = dyn_cast<DecayedType>(Type)) { 6353 auto OrigTy = DT->getOriginalType(); 6354 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6355 // Add the address space to the original array type and then propagate 6356 // that to the element type through `getAsArrayType`. 6357 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6358 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6359 // Re-generate the decayed type. 6360 Type = Context.getDecayedType(OrigTy); 6361 } 6362 } 6363 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6364 // Apply any qualifiers (including address space) from the array type to 6365 // the element type. This implements C99 6.7.3p8: "If the specification of 6366 // an array type includes any type qualifiers, the element type is so 6367 // qualified, not the array type." 6368 if (Type->isArrayType()) 6369 Type = QualType(Context.getAsArrayType(Type), 0); 6370 Decl->setType(Type); 6371 } 6372 } 6373 6374 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6375 // Ensure that an auto decl is deduced otherwise the checks below might cache 6376 // the wrong linkage. 6377 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6378 6379 // 'weak' only applies to declarations with external linkage. 6380 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6381 if (!ND.isExternallyVisible()) { 6382 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6383 ND.dropAttr<WeakAttr>(); 6384 } 6385 } 6386 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6387 if (ND.isExternallyVisible()) { 6388 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6389 ND.dropAttr<WeakRefAttr>(); 6390 ND.dropAttr<AliasAttr>(); 6391 } 6392 } 6393 6394 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6395 if (VD->hasInit()) { 6396 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6397 assert(VD->isThisDeclarationADefinition() && 6398 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6399 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6400 VD->dropAttr<AliasAttr>(); 6401 } 6402 } 6403 } 6404 6405 // 'selectany' only applies to externally visible variable declarations. 6406 // It does not apply to functions. 6407 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6408 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6409 S.Diag(Attr->getLocation(), 6410 diag::err_attribute_selectany_non_extern_data); 6411 ND.dropAttr<SelectAnyAttr>(); 6412 } 6413 } 6414 6415 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6416 auto *VD = dyn_cast<VarDecl>(&ND); 6417 bool IsAnonymousNS = false; 6418 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6419 if (VD) { 6420 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6421 while (NS && !IsAnonymousNS) { 6422 IsAnonymousNS = NS->isAnonymousNamespace(); 6423 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6424 } 6425 } 6426 // dll attributes require external linkage. Static locals may have external 6427 // linkage but still cannot be explicitly imported or exported. 6428 // In Microsoft mode, a variable defined in anonymous namespace must have 6429 // external linkage in order to be exported. 6430 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6431 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6432 (!AnonNSInMicrosoftMode && 6433 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6434 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6435 << &ND << Attr; 6436 ND.setInvalidDecl(); 6437 } 6438 } 6439 6440 // Check the attributes on the function type, if any. 6441 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6442 // Don't declare this variable in the second operand of the for-statement; 6443 // GCC miscompiles that by ending its lifetime before evaluating the 6444 // third operand. See gcc.gnu.org/PR86769. 6445 AttributedTypeLoc ATL; 6446 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6447 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6448 TL = ATL.getModifiedLoc()) { 6449 // The [[lifetimebound]] attribute can be applied to the implicit object 6450 // parameter of a non-static member function (other than a ctor or dtor) 6451 // by applying it to the function type. 6452 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6453 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6454 if (!MD || MD->isStatic()) { 6455 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6456 << !MD << A->getRange(); 6457 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6458 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6459 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6460 } 6461 } 6462 } 6463 } 6464 } 6465 6466 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6467 NamedDecl *NewDecl, 6468 bool IsSpecialization, 6469 bool IsDefinition) { 6470 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6471 return; 6472 6473 bool IsTemplate = false; 6474 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6475 OldDecl = OldTD->getTemplatedDecl(); 6476 IsTemplate = true; 6477 if (!IsSpecialization) 6478 IsDefinition = false; 6479 } 6480 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6481 NewDecl = NewTD->getTemplatedDecl(); 6482 IsTemplate = true; 6483 } 6484 6485 if (!OldDecl || !NewDecl) 6486 return; 6487 6488 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6489 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6490 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6491 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6492 6493 // dllimport and dllexport are inheritable attributes so we have to exclude 6494 // inherited attribute instances. 6495 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6496 (NewExportAttr && !NewExportAttr->isInherited()); 6497 6498 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6499 // the only exception being explicit specializations. 6500 // Implicitly generated declarations are also excluded for now because there 6501 // is no other way to switch these to use dllimport or dllexport. 6502 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6503 6504 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6505 // Allow with a warning for free functions and global variables. 6506 bool JustWarn = false; 6507 if (!OldDecl->isCXXClassMember()) { 6508 auto *VD = dyn_cast<VarDecl>(OldDecl); 6509 if (VD && !VD->getDescribedVarTemplate()) 6510 JustWarn = true; 6511 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6512 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6513 JustWarn = true; 6514 } 6515 6516 // We cannot change a declaration that's been used because IR has already 6517 // been emitted. Dllimported functions will still work though (modulo 6518 // address equality) as they can use the thunk. 6519 if (OldDecl->isUsed()) 6520 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6521 JustWarn = false; 6522 6523 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6524 : diag::err_attribute_dll_redeclaration; 6525 S.Diag(NewDecl->getLocation(), DiagID) 6526 << NewDecl 6527 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6528 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6529 if (!JustWarn) { 6530 NewDecl->setInvalidDecl(); 6531 return; 6532 } 6533 } 6534 6535 // A redeclaration is not allowed to drop a dllimport attribute, the only 6536 // exceptions being inline function definitions (except for function 6537 // templates), local extern declarations, qualified friend declarations or 6538 // special MSVC extension: in the last case, the declaration is treated as if 6539 // it were marked dllexport. 6540 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6541 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 6542 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6543 // Ignore static data because out-of-line definitions are diagnosed 6544 // separately. 6545 IsStaticDataMember = VD->isStaticDataMember(); 6546 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6547 VarDecl::DeclarationOnly; 6548 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6549 IsInline = FD->isInlined(); 6550 IsQualifiedFriend = FD->getQualifier() && 6551 FD->getFriendObjectKind() == Decl::FOK_Declared; 6552 } 6553 6554 if (OldImportAttr && !HasNewAttr && 6555 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 6556 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6557 if (IsMicrosoftABI && IsDefinition) { 6558 S.Diag(NewDecl->getLocation(), 6559 diag::warn_redeclaration_without_import_attribute) 6560 << NewDecl; 6561 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6562 NewDecl->dropAttr<DLLImportAttr>(); 6563 NewDecl->addAttr( 6564 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6565 } else { 6566 S.Diag(NewDecl->getLocation(), 6567 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6568 << NewDecl << OldImportAttr; 6569 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6570 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6571 OldDecl->dropAttr<DLLImportAttr>(); 6572 NewDecl->dropAttr<DLLImportAttr>(); 6573 } 6574 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 6575 // In MinGW, seeing a function declared inline drops the dllimport 6576 // attribute. 6577 OldDecl->dropAttr<DLLImportAttr>(); 6578 NewDecl->dropAttr<DLLImportAttr>(); 6579 S.Diag(NewDecl->getLocation(), 6580 diag::warn_dllimport_dropped_from_inline_function) 6581 << NewDecl << OldImportAttr; 6582 } 6583 6584 // A specialization of a class template member function is processed here 6585 // since it's a redeclaration. If the parent class is dllexport, the 6586 // specialization inherits that attribute. This doesn't happen automatically 6587 // since the parent class isn't instantiated until later. 6588 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6589 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6590 !NewImportAttr && !NewExportAttr) { 6591 if (const DLLExportAttr *ParentExportAttr = 6592 MD->getParent()->getAttr<DLLExportAttr>()) { 6593 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6594 NewAttr->setInherited(true); 6595 NewDecl->addAttr(NewAttr); 6596 } 6597 } 6598 } 6599 } 6600 6601 /// Given that we are within the definition of the given function, 6602 /// will that definition behave like C99's 'inline', where the 6603 /// definition is discarded except for optimization purposes? 6604 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6605 // Try to avoid calling GetGVALinkageForFunction. 6606 6607 // All cases of this require the 'inline' keyword. 6608 if (!FD->isInlined()) return false; 6609 6610 // This is only possible in C++ with the gnu_inline attribute. 6611 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6612 return false; 6613 6614 // Okay, go ahead and call the relatively-more-expensive function. 6615 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6616 } 6617 6618 /// Determine whether a variable is extern "C" prior to attaching 6619 /// an initializer. We can't just call isExternC() here, because that 6620 /// will also compute and cache whether the declaration is externally 6621 /// visible, which might change when we attach the initializer. 6622 /// 6623 /// This can only be used if the declaration is known to not be a 6624 /// redeclaration of an internal linkage declaration. 6625 /// 6626 /// For instance: 6627 /// 6628 /// auto x = []{}; 6629 /// 6630 /// Attaching the initializer here makes this declaration not externally 6631 /// visible, because its type has internal linkage. 6632 /// 6633 /// FIXME: This is a hack. 6634 template<typename T> 6635 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6636 if (S.getLangOpts().CPlusPlus) { 6637 // In C++, the overloadable attribute negates the effects of extern "C". 6638 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6639 return false; 6640 6641 // So do CUDA's host/device attributes. 6642 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6643 D->template hasAttr<CUDAHostAttr>())) 6644 return false; 6645 } 6646 return D->isExternC(); 6647 } 6648 6649 static bool shouldConsiderLinkage(const VarDecl *VD) { 6650 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6651 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6652 isa<OMPDeclareMapperDecl>(DC)) 6653 return VD->hasExternalStorage(); 6654 if (DC->isFileContext()) 6655 return true; 6656 if (DC->isRecord()) 6657 return false; 6658 if (isa<RequiresExprBodyDecl>(DC)) 6659 return false; 6660 llvm_unreachable("Unexpected context"); 6661 } 6662 6663 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6664 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6665 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6666 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6667 return true; 6668 if (DC->isRecord()) 6669 return false; 6670 llvm_unreachable("Unexpected context"); 6671 } 6672 6673 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6674 ParsedAttr::Kind Kind) { 6675 // Check decl attributes on the DeclSpec. 6676 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6677 return true; 6678 6679 // Walk the declarator structure, checking decl attributes that were in a type 6680 // position to the decl itself. 6681 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6682 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6683 return true; 6684 } 6685 6686 // Finally, check attributes on the decl itself. 6687 return PD.getAttributes().hasAttribute(Kind); 6688 } 6689 6690 /// Adjust the \c DeclContext for a function or variable that might be a 6691 /// function-local external declaration. 6692 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6693 if (!DC->isFunctionOrMethod()) 6694 return false; 6695 6696 // If this is a local extern function or variable declared within a function 6697 // template, don't add it into the enclosing namespace scope until it is 6698 // instantiated; it might have a dependent type right now. 6699 if (DC->isDependentContext()) 6700 return true; 6701 6702 // C++11 [basic.link]p7: 6703 // When a block scope declaration of an entity with linkage is not found to 6704 // refer to some other declaration, then that entity is a member of the 6705 // innermost enclosing namespace. 6706 // 6707 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6708 // semantically-enclosing namespace, not a lexically-enclosing one. 6709 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6710 DC = DC->getParent(); 6711 return true; 6712 } 6713 6714 /// Returns true if given declaration has external C language linkage. 6715 static bool isDeclExternC(const Decl *D) { 6716 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6717 return FD->isExternC(); 6718 if (const auto *VD = dyn_cast<VarDecl>(D)) 6719 return VD->isExternC(); 6720 6721 llvm_unreachable("Unknown type of decl!"); 6722 } 6723 /// Returns true if there hasn't been any invalid type diagnosed. 6724 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, 6725 DeclContext *DC, QualType R) { 6726 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6727 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6728 // argument. 6729 if (R->isImageType() || R->isPipeType()) { 6730 Se.Diag(D.getIdentifierLoc(), 6731 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6732 << R; 6733 D.setInvalidType(); 6734 return false; 6735 } 6736 6737 // OpenCL v1.2 s6.9.r: 6738 // The event type cannot be used to declare a program scope variable. 6739 // OpenCL v2.0 s6.9.q: 6740 // The clk_event_t and reserve_id_t types cannot be declared in program 6741 // scope. 6742 if (NULL == S->getParent()) { 6743 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6744 Se.Diag(D.getIdentifierLoc(), 6745 diag::err_invalid_type_for_program_scope_var) 6746 << R; 6747 D.setInvalidType(); 6748 return false; 6749 } 6750 } 6751 6752 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6753 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 6754 Se.getLangOpts())) { 6755 QualType NR = R.getCanonicalType(); 6756 while (NR->isPointerType() || NR->isMemberFunctionPointerType() || 6757 NR->isReferenceType()) { 6758 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || 6759 NR->isFunctionReferenceType()) { 6760 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer) 6761 << NR->isReferenceType(); 6762 D.setInvalidType(); 6763 return false; 6764 } 6765 NR = NR->getPointeeType(); 6766 } 6767 } 6768 6769 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 6770 Se.getLangOpts())) { 6771 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6772 // half array type (unless the cl_khr_fp16 extension is enabled). 6773 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6774 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6775 D.setInvalidType(); 6776 return false; 6777 } 6778 } 6779 6780 // OpenCL v1.2 s6.9.r: 6781 // The event type cannot be used with the __local, __constant and __global 6782 // address space qualifiers. 6783 if (R->isEventT()) { 6784 if (R.getAddressSpace() != LangAS::opencl_private) { 6785 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6786 D.setInvalidType(); 6787 return false; 6788 } 6789 } 6790 6791 // C++ for OpenCL does not allow the thread_local storage qualifier. 6792 // OpenCL C does not support thread_local either, and 6793 // also reject all other thread storage class specifiers. 6794 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6795 if (TSC != TSCS_unspecified) { 6796 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; 6797 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6798 diag::err_opencl_unknown_type_specifier) 6799 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() 6800 << DeclSpec::getSpecifierName(TSC) << 1; 6801 D.setInvalidType(); 6802 return false; 6803 } 6804 6805 if (R->isSamplerT()) { 6806 // OpenCL v1.2 s6.9.b p4: 6807 // The sampler type cannot be used with the __local and __global address 6808 // space qualifiers. 6809 if (R.getAddressSpace() == LangAS::opencl_local || 6810 R.getAddressSpace() == LangAS::opencl_global) { 6811 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6812 D.setInvalidType(); 6813 } 6814 6815 // OpenCL v1.2 s6.12.14.1: 6816 // A global sampler must be declared with either the constant address 6817 // space qualifier or with the const qualifier. 6818 if (DC->isTranslationUnit() && 6819 !(R.getAddressSpace() == LangAS::opencl_constant || 6820 R.isConstQualified())) { 6821 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6822 D.setInvalidType(); 6823 } 6824 if (D.isInvalidType()) 6825 return false; 6826 } 6827 return true; 6828 } 6829 6830 NamedDecl *Sema::ActOnVariableDeclarator( 6831 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6832 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6833 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6834 QualType R = TInfo->getType(); 6835 DeclarationName Name = GetNameForDeclarator(D).getName(); 6836 6837 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6838 6839 if (D.isDecompositionDeclarator()) { 6840 // Take the name of the first declarator as our name for diagnostic 6841 // purposes. 6842 auto &Decomp = D.getDecompositionDeclarator(); 6843 if (!Decomp.bindings().empty()) { 6844 II = Decomp.bindings()[0].Name; 6845 Name = II; 6846 } 6847 } else if (!II) { 6848 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6849 return nullptr; 6850 } 6851 6852 6853 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6854 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6855 6856 // dllimport globals without explicit storage class are treated as extern. We 6857 // have to change the storage class this early to get the right DeclContext. 6858 if (SC == SC_None && !DC->isRecord() && 6859 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6860 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6861 SC = SC_Extern; 6862 6863 DeclContext *OriginalDC = DC; 6864 bool IsLocalExternDecl = SC == SC_Extern && 6865 adjustContextForLocalExternDecl(DC); 6866 6867 if (SCSpec == DeclSpec::SCS_mutable) { 6868 // mutable can only appear on non-static class members, so it's always 6869 // an error here 6870 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6871 D.setInvalidType(); 6872 SC = SC_None; 6873 } 6874 6875 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6876 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6877 D.getDeclSpec().getStorageClassSpecLoc())) { 6878 // In C++11, the 'register' storage class specifier is deprecated. 6879 // Suppress the warning in system macros, it's used in macros in some 6880 // popular C system headers, such as in glibc's htonl() macro. 6881 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6882 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6883 : diag::warn_deprecated_register) 6884 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6885 } 6886 6887 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6888 6889 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6890 // C99 6.9p2: The storage-class specifiers auto and register shall not 6891 // appear in the declaration specifiers in an external declaration. 6892 // Global Register+Asm is a GNU extension we support. 6893 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6894 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6895 D.setInvalidType(); 6896 } 6897 } 6898 6899 // If this variable has a variable-modified type and an initializer, try to 6900 // fold to a constant-sized type. This is otherwise invalid. 6901 if (D.hasInitializer() && R->isVariablyModifiedType()) 6902 tryToFixVariablyModifiedVarType(*this, TInfo, R, D.getIdentifierLoc(), 6903 /*DiagID=*/0); 6904 6905 bool IsMemberSpecialization = false; 6906 bool IsVariableTemplateSpecialization = false; 6907 bool IsPartialSpecialization = false; 6908 bool IsVariableTemplate = false; 6909 VarDecl *NewVD = nullptr; 6910 VarTemplateDecl *NewTemplate = nullptr; 6911 TemplateParameterList *TemplateParams = nullptr; 6912 if (!getLangOpts().CPlusPlus) { 6913 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6914 II, R, TInfo, SC); 6915 6916 if (R->getContainedDeducedType()) 6917 ParsingInitForAutoVars.insert(NewVD); 6918 6919 if (D.isInvalidType()) 6920 NewVD->setInvalidDecl(); 6921 6922 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6923 NewVD->hasLocalStorage()) 6924 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6925 NTCUC_AutoVar, NTCUK_Destruct); 6926 } else { 6927 bool Invalid = false; 6928 6929 if (DC->isRecord() && !CurContext->isRecord()) { 6930 // This is an out-of-line definition of a static data member. 6931 switch (SC) { 6932 case SC_None: 6933 break; 6934 case SC_Static: 6935 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6936 diag::err_static_out_of_line) 6937 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6938 break; 6939 case SC_Auto: 6940 case SC_Register: 6941 case SC_Extern: 6942 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6943 // to names of variables declared in a block or to function parameters. 6944 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6945 // of class members 6946 6947 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6948 diag::err_storage_class_for_static_member) 6949 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6950 break; 6951 case SC_PrivateExtern: 6952 llvm_unreachable("C storage class in c++!"); 6953 } 6954 } 6955 6956 if (SC == SC_Static && CurContext->isRecord()) { 6957 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6958 // Walk up the enclosing DeclContexts to check for any that are 6959 // incompatible with static data members. 6960 const DeclContext *FunctionOrMethod = nullptr; 6961 const CXXRecordDecl *AnonStruct = nullptr; 6962 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 6963 if (Ctxt->isFunctionOrMethod()) { 6964 FunctionOrMethod = Ctxt; 6965 break; 6966 } 6967 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 6968 if (ParentDecl && !ParentDecl->getDeclName()) { 6969 AnonStruct = ParentDecl; 6970 break; 6971 } 6972 } 6973 if (FunctionOrMethod) { 6974 // C++ [class.static.data]p5: A local class shall not have static data 6975 // members. 6976 Diag(D.getIdentifierLoc(), 6977 diag::err_static_data_member_not_allowed_in_local_class) 6978 << Name << RD->getDeclName() << RD->getTagKind(); 6979 } else if (AnonStruct) { 6980 // C++ [class.static.data]p4: Unnamed classes and classes contained 6981 // directly or indirectly within unnamed classes shall not contain 6982 // static data members. 6983 Diag(D.getIdentifierLoc(), 6984 diag::err_static_data_member_not_allowed_in_anon_struct) 6985 << Name << AnonStruct->getTagKind(); 6986 Invalid = true; 6987 } else if (RD->isUnion()) { 6988 // C++98 [class.union]p1: If a union contains a static data member, 6989 // the program is ill-formed. C++11 drops this restriction. 6990 Diag(D.getIdentifierLoc(), 6991 getLangOpts().CPlusPlus11 6992 ? diag::warn_cxx98_compat_static_data_member_in_union 6993 : diag::ext_static_data_member_in_union) << Name; 6994 } 6995 } 6996 } 6997 6998 // Match up the template parameter lists with the scope specifier, then 6999 // determine whether we have a template or a template specialization. 7000 bool InvalidScope = false; 7001 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7002 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7003 D.getCXXScopeSpec(), 7004 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7005 ? D.getName().TemplateId 7006 : nullptr, 7007 TemplateParamLists, 7008 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7009 Invalid |= InvalidScope; 7010 7011 if (TemplateParams) { 7012 if (!TemplateParams->size() && 7013 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7014 // There is an extraneous 'template<>' for this variable. Complain 7015 // about it, but allow the declaration of the variable. 7016 Diag(TemplateParams->getTemplateLoc(), 7017 diag::err_template_variable_noparams) 7018 << II 7019 << SourceRange(TemplateParams->getTemplateLoc(), 7020 TemplateParams->getRAngleLoc()); 7021 TemplateParams = nullptr; 7022 } else { 7023 // Check that we can declare a template here. 7024 if (CheckTemplateDeclScope(S, TemplateParams)) 7025 return nullptr; 7026 7027 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7028 // This is an explicit specialization or a partial specialization. 7029 IsVariableTemplateSpecialization = true; 7030 IsPartialSpecialization = TemplateParams->size() > 0; 7031 } else { // if (TemplateParams->size() > 0) 7032 // This is a template declaration. 7033 IsVariableTemplate = true; 7034 7035 // Only C++1y supports variable templates (N3651). 7036 Diag(D.getIdentifierLoc(), 7037 getLangOpts().CPlusPlus14 7038 ? diag::warn_cxx11_compat_variable_template 7039 : diag::ext_variable_template); 7040 } 7041 } 7042 } else { 7043 // Check that we can declare a member specialization here. 7044 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7045 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7046 return nullptr; 7047 assert((Invalid || 7048 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7049 "should have a 'template<>' for this decl"); 7050 } 7051 7052 if (IsVariableTemplateSpecialization) { 7053 SourceLocation TemplateKWLoc = 7054 TemplateParamLists.size() > 0 7055 ? TemplateParamLists[0]->getTemplateLoc() 7056 : SourceLocation(); 7057 DeclResult Res = ActOnVarTemplateSpecialization( 7058 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7059 IsPartialSpecialization); 7060 if (Res.isInvalid()) 7061 return nullptr; 7062 NewVD = cast<VarDecl>(Res.get()); 7063 AddToScope = false; 7064 } else if (D.isDecompositionDeclarator()) { 7065 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7066 D.getIdentifierLoc(), R, TInfo, SC, 7067 Bindings); 7068 } else 7069 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7070 D.getIdentifierLoc(), II, R, TInfo, SC); 7071 7072 // If this is supposed to be a variable template, create it as such. 7073 if (IsVariableTemplate) { 7074 NewTemplate = 7075 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7076 TemplateParams, NewVD); 7077 NewVD->setDescribedVarTemplate(NewTemplate); 7078 } 7079 7080 // If this decl has an auto type in need of deduction, make a note of the 7081 // Decl so we can diagnose uses of it in its own initializer. 7082 if (R->getContainedDeducedType()) 7083 ParsingInitForAutoVars.insert(NewVD); 7084 7085 if (D.isInvalidType() || Invalid) { 7086 NewVD->setInvalidDecl(); 7087 if (NewTemplate) 7088 NewTemplate->setInvalidDecl(); 7089 } 7090 7091 SetNestedNameSpecifier(*this, NewVD, D); 7092 7093 // If we have any template parameter lists that don't directly belong to 7094 // the variable (matching the scope specifier), store them. 7095 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7096 if (TemplateParamLists.size() > VDTemplateParamLists) 7097 NewVD->setTemplateParameterListsInfo( 7098 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7099 } 7100 7101 if (D.getDeclSpec().isInlineSpecified()) { 7102 if (!getLangOpts().CPlusPlus) { 7103 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7104 << 0; 7105 } else if (CurContext->isFunctionOrMethod()) { 7106 // 'inline' is not allowed on block scope variable declaration. 7107 Diag(D.getDeclSpec().getInlineSpecLoc(), 7108 diag::err_inline_declaration_block_scope) << Name 7109 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7110 } else { 7111 Diag(D.getDeclSpec().getInlineSpecLoc(), 7112 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7113 : diag::ext_inline_variable); 7114 NewVD->setInlineSpecified(); 7115 } 7116 } 7117 7118 // Set the lexical context. If the declarator has a C++ scope specifier, the 7119 // lexical context will be different from the semantic context. 7120 NewVD->setLexicalDeclContext(CurContext); 7121 if (NewTemplate) 7122 NewTemplate->setLexicalDeclContext(CurContext); 7123 7124 if (IsLocalExternDecl) { 7125 if (D.isDecompositionDeclarator()) 7126 for (auto *B : Bindings) 7127 B->setLocalExternDecl(); 7128 else 7129 NewVD->setLocalExternDecl(); 7130 } 7131 7132 bool EmitTLSUnsupportedError = false; 7133 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7134 // C++11 [dcl.stc]p4: 7135 // When thread_local is applied to a variable of block scope the 7136 // storage-class-specifier static is implied if it does not appear 7137 // explicitly. 7138 // Core issue: 'static' is not implied if the variable is declared 7139 // 'extern'. 7140 if (NewVD->hasLocalStorage() && 7141 (SCSpec != DeclSpec::SCS_unspecified || 7142 TSCS != DeclSpec::TSCS_thread_local || 7143 !DC->isFunctionOrMethod())) 7144 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7145 diag::err_thread_non_global) 7146 << DeclSpec::getSpecifierName(TSCS); 7147 else if (!Context.getTargetInfo().isTLSSupported()) { 7148 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7149 getLangOpts().SYCLIsDevice) { 7150 // Postpone error emission until we've collected attributes required to 7151 // figure out whether it's a host or device variable and whether the 7152 // error should be ignored. 7153 EmitTLSUnsupportedError = true; 7154 // We still need to mark the variable as TLS so it shows up in AST with 7155 // proper storage class for other tools to use even if we're not going 7156 // to emit any code for it. 7157 NewVD->setTSCSpec(TSCS); 7158 } else 7159 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7160 diag::err_thread_unsupported); 7161 } else 7162 NewVD->setTSCSpec(TSCS); 7163 } 7164 7165 switch (D.getDeclSpec().getConstexprSpecifier()) { 7166 case ConstexprSpecKind::Unspecified: 7167 break; 7168 7169 case ConstexprSpecKind::Consteval: 7170 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7171 diag::err_constexpr_wrong_decl_kind) 7172 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7173 LLVM_FALLTHROUGH; 7174 7175 case ConstexprSpecKind::Constexpr: 7176 NewVD->setConstexpr(true); 7177 MaybeAddCUDAConstantAttr(NewVD); 7178 // C++1z [dcl.spec.constexpr]p1: 7179 // A static data member declared with the constexpr specifier is 7180 // implicitly an inline variable. 7181 if (NewVD->isStaticDataMember() && 7182 (getLangOpts().CPlusPlus17 || 7183 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7184 NewVD->setImplicitlyInline(); 7185 break; 7186 7187 case ConstexprSpecKind::Constinit: 7188 if (!NewVD->hasGlobalStorage()) 7189 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7190 diag::err_constinit_local_variable); 7191 else 7192 NewVD->addAttr(ConstInitAttr::Create( 7193 Context, D.getDeclSpec().getConstexprSpecLoc(), 7194 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7195 break; 7196 } 7197 7198 // C99 6.7.4p3 7199 // An inline definition of a function with external linkage shall 7200 // not contain a definition of a modifiable object with static or 7201 // thread storage duration... 7202 // We only apply this when the function is required to be defined 7203 // elsewhere, i.e. when the function is not 'extern inline'. Note 7204 // that a local variable with thread storage duration still has to 7205 // be marked 'static'. Also note that it's possible to get these 7206 // semantics in C++ using __attribute__((gnu_inline)). 7207 if (SC == SC_Static && S->getFnParent() != nullptr && 7208 !NewVD->getType().isConstQualified()) { 7209 FunctionDecl *CurFD = getCurFunctionDecl(); 7210 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7211 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7212 diag::warn_static_local_in_extern_inline); 7213 MaybeSuggestAddingStaticToDecl(CurFD); 7214 } 7215 } 7216 7217 if (D.getDeclSpec().isModulePrivateSpecified()) { 7218 if (IsVariableTemplateSpecialization) 7219 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7220 << (IsPartialSpecialization ? 1 : 0) 7221 << FixItHint::CreateRemoval( 7222 D.getDeclSpec().getModulePrivateSpecLoc()); 7223 else if (IsMemberSpecialization) 7224 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7225 << 2 7226 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7227 else if (NewVD->hasLocalStorage()) 7228 Diag(NewVD->getLocation(), diag::err_module_private_local) 7229 << 0 << NewVD 7230 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7231 << FixItHint::CreateRemoval( 7232 D.getDeclSpec().getModulePrivateSpecLoc()); 7233 else { 7234 NewVD->setModulePrivate(); 7235 if (NewTemplate) 7236 NewTemplate->setModulePrivate(); 7237 for (auto *B : Bindings) 7238 B->setModulePrivate(); 7239 } 7240 } 7241 7242 if (getLangOpts().OpenCL) { 7243 7244 deduceOpenCLAddressSpace(NewVD); 7245 7246 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); 7247 } 7248 7249 // Handle attributes prior to checking for duplicates in MergeVarDecl 7250 ProcessDeclAttributes(S, NewVD, D); 7251 7252 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7253 getLangOpts().SYCLIsDevice) { 7254 if (EmitTLSUnsupportedError && 7255 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7256 (getLangOpts().OpenMPIsDevice && 7257 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7258 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7259 diag::err_thread_unsupported); 7260 7261 if (EmitTLSUnsupportedError && 7262 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7263 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7264 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7265 // storage [duration]." 7266 if (SC == SC_None && S->getFnParent() != nullptr && 7267 (NewVD->hasAttr<CUDASharedAttr>() || 7268 NewVD->hasAttr<CUDAConstantAttr>())) { 7269 NewVD->setStorageClass(SC_Static); 7270 } 7271 } 7272 7273 // Ensure that dllimport globals without explicit storage class are treated as 7274 // extern. The storage class is set above using parsed attributes. Now we can 7275 // check the VarDecl itself. 7276 assert(!NewVD->hasAttr<DLLImportAttr>() || 7277 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7278 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7279 7280 // In auto-retain/release, infer strong retension for variables of 7281 // retainable type. 7282 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7283 NewVD->setInvalidDecl(); 7284 7285 // Handle GNU asm-label extension (encoded as an attribute). 7286 if (Expr *E = (Expr*)D.getAsmLabel()) { 7287 // The parser guarantees this is a string. 7288 StringLiteral *SE = cast<StringLiteral>(E); 7289 StringRef Label = SE->getString(); 7290 if (S->getFnParent() != nullptr) { 7291 switch (SC) { 7292 case SC_None: 7293 case SC_Auto: 7294 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7295 break; 7296 case SC_Register: 7297 // Local Named register 7298 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7299 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7300 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7301 break; 7302 case SC_Static: 7303 case SC_Extern: 7304 case SC_PrivateExtern: 7305 break; 7306 } 7307 } else if (SC == SC_Register) { 7308 // Global Named register 7309 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7310 const auto &TI = Context.getTargetInfo(); 7311 bool HasSizeMismatch; 7312 7313 if (!TI.isValidGCCRegisterName(Label)) 7314 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7315 else if (!TI.validateGlobalRegisterVariable(Label, 7316 Context.getTypeSize(R), 7317 HasSizeMismatch)) 7318 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7319 else if (HasSizeMismatch) 7320 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7321 } 7322 7323 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7324 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7325 NewVD->setInvalidDecl(true); 7326 } 7327 } 7328 7329 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7330 /*IsLiteralLabel=*/true, 7331 SE->getStrTokenLoc(0))); 7332 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7333 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7334 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7335 if (I != ExtnameUndeclaredIdentifiers.end()) { 7336 if (isDeclExternC(NewVD)) { 7337 NewVD->addAttr(I->second); 7338 ExtnameUndeclaredIdentifiers.erase(I); 7339 } else 7340 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7341 << /*Variable*/1 << NewVD; 7342 } 7343 } 7344 7345 // Find the shadowed declaration before filtering for scope. 7346 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7347 ? getShadowedDeclaration(NewVD, Previous) 7348 : nullptr; 7349 7350 // Don't consider existing declarations that are in a different 7351 // scope and are out-of-semantic-context declarations (if the new 7352 // declaration has linkage). 7353 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7354 D.getCXXScopeSpec().isNotEmpty() || 7355 IsMemberSpecialization || 7356 IsVariableTemplateSpecialization); 7357 7358 // Check whether the previous declaration is in the same block scope. This 7359 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7360 if (getLangOpts().CPlusPlus && 7361 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7362 NewVD->setPreviousDeclInSameBlockScope( 7363 Previous.isSingleResult() && !Previous.isShadowed() && 7364 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7365 7366 if (!getLangOpts().CPlusPlus) { 7367 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7368 } else { 7369 // If this is an explicit specialization of a static data member, check it. 7370 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7371 CheckMemberSpecialization(NewVD, Previous)) 7372 NewVD->setInvalidDecl(); 7373 7374 // Merge the decl with the existing one if appropriate. 7375 if (!Previous.empty()) { 7376 if (Previous.isSingleResult() && 7377 isa<FieldDecl>(Previous.getFoundDecl()) && 7378 D.getCXXScopeSpec().isSet()) { 7379 // The user tried to define a non-static data member 7380 // out-of-line (C++ [dcl.meaning]p1). 7381 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7382 << D.getCXXScopeSpec().getRange(); 7383 Previous.clear(); 7384 NewVD->setInvalidDecl(); 7385 } 7386 } else if (D.getCXXScopeSpec().isSet()) { 7387 // No previous declaration in the qualifying scope. 7388 Diag(D.getIdentifierLoc(), diag::err_no_member) 7389 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7390 << D.getCXXScopeSpec().getRange(); 7391 NewVD->setInvalidDecl(); 7392 } 7393 7394 if (!IsVariableTemplateSpecialization) 7395 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7396 7397 if (NewTemplate) { 7398 VarTemplateDecl *PrevVarTemplate = 7399 NewVD->getPreviousDecl() 7400 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7401 : nullptr; 7402 7403 // Check the template parameter list of this declaration, possibly 7404 // merging in the template parameter list from the previous variable 7405 // template declaration. 7406 if (CheckTemplateParameterList( 7407 TemplateParams, 7408 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7409 : nullptr, 7410 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7411 DC->isDependentContext()) 7412 ? TPC_ClassTemplateMember 7413 : TPC_VarTemplate)) 7414 NewVD->setInvalidDecl(); 7415 7416 // If we are providing an explicit specialization of a static variable 7417 // template, make a note of that. 7418 if (PrevVarTemplate && 7419 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7420 PrevVarTemplate->setMemberSpecialization(); 7421 } 7422 } 7423 7424 // Diagnose shadowed variables iff this isn't a redeclaration. 7425 if (ShadowedDecl && !D.isRedeclaration()) 7426 CheckShadow(NewVD, ShadowedDecl, Previous); 7427 7428 ProcessPragmaWeak(S, NewVD); 7429 7430 // If this is the first declaration of an extern C variable, update 7431 // the map of such variables. 7432 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7433 isIncompleteDeclExternC(*this, NewVD)) 7434 RegisterLocallyScopedExternCDecl(NewVD, S); 7435 7436 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7437 MangleNumberingContext *MCtx; 7438 Decl *ManglingContextDecl; 7439 std::tie(MCtx, ManglingContextDecl) = 7440 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7441 if (MCtx) { 7442 Context.setManglingNumber( 7443 NewVD, MCtx->getManglingNumber( 7444 NewVD, getMSManglingNumber(getLangOpts(), S))); 7445 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7446 } 7447 } 7448 7449 // Special handling of variable named 'main'. 7450 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7451 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7452 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7453 7454 // C++ [basic.start.main]p3 7455 // A program that declares a variable main at global scope is ill-formed. 7456 if (getLangOpts().CPlusPlus) 7457 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7458 7459 // In C, and external-linkage variable named main results in undefined 7460 // behavior. 7461 else if (NewVD->hasExternalFormalLinkage()) 7462 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7463 } 7464 7465 if (D.isRedeclaration() && !Previous.empty()) { 7466 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7467 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7468 D.isFunctionDefinition()); 7469 } 7470 7471 if (NewTemplate) { 7472 if (NewVD->isInvalidDecl()) 7473 NewTemplate->setInvalidDecl(); 7474 ActOnDocumentableDecl(NewTemplate); 7475 return NewTemplate; 7476 } 7477 7478 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7479 CompleteMemberSpecialization(NewVD, Previous); 7480 7481 return NewVD; 7482 } 7483 7484 /// Enum describing the %select options in diag::warn_decl_shadow. 7485 enum ShadowedDeclKind { 7486 SDK_Local, 7487 SDK_Global, 7488 SDK_StaticMember, 7489 SDK_Field, 7490 SDK_Typedef, 7491 SDK_Using, 7492 SDK_StructuredBinding 7493 }; 7494 7495 /// Determine what kind of declaration we're shadowing. 7496 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7497 const DeclContext *OldDC) { 7498 if (isa<TypeAliasDecl>(ShadowedDecl)) 7499 return SDK_Using; 7500 else if (isa<TypedefDecl>(ShadowedDecl)) 7501 return SDK_Typedef; 7502 else if (isa<BindingDecl>(ShadowedDecl)) 7503 return SDK_StructuredBinding; 7504 else if (isa<RecordDecl>(OldDC)) 7505 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7506 7507 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7508 } 7509 7510 /// Return the location of the capture if the given lambda captures the given 7511 /// variable \p VD, or an invalid source location otherwise. 7512 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7513 const VarDecl *VD) { 7514 for (const Capture &Capture : LSI->Captures) { 7515 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7516 return Capture.getLocation(); 7517 } 7518 return SourceLocation(); 7519 } 7520 7521 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7522 const LookupResult &R) { 7523 // Only diagnose if we're shadowing an unambiguous field or variable. 7524 if (R.getResultKind() != LookupResult::Found) 7525 return false; 7526 7527 // Return false if warning is ignored. 7528 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7529 } 7530 7531 /// Return the declaration shadowed by the given variable \p D, or null 7532 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7533 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7534 const LookupResult &R) { 7535 if (!shouldWarnIfShadowedDecl(Diags, R)) 7536 return nullptr; 7537 7538 // Don't diagnose declarations at file scope. 7539 if (D->hasGlobalStorage()) 7540 return nullptr; 7541 7542 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7543 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7544 : nullptr; 7545 } 7546 7547 /// Return the declaration shadowed by the given typedef \p D, or null 7548 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7549 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7550 const LookupResult &R) { 7551 // Don't warn if typedef declaration is part of a class 7552 if (D->getDeclContext()->isRecord()) 7553 return nullptr; 7554 7555 if (!shouldWarnIfShadowedDecl(Diags, R)) 7556 return nullptr; 7557 7558 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7559 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7560 } 7561 7562 /// Return the declaration shadowed by the given variable \p D, or null 7563 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7564 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, 7565 const LookupResult &R) { 7566 if (!shouldWarnIfShadowedDecl(Diags, R)) 7567 return nullptr; 7568 7569 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7570 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7571 : nullptr; 7572 } 7573 7574 /// Diagnose variable or built-in function shadowing. Implements 7575 /// -Wshadow. 7576 /// 7577 /// This method is called whenever a VarDecl is added to a "useful" 7578 /// scope. 7579 /// 7580 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7581 /// \param R the lookup of the name 7582 /// 7583 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7584 const LookupResult &R) { 7585 DeclContext *NewDC = D->getDeclContext(); 7586 7587 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7588 // Fields are not shadowed by variables in C++ static methods. 7589 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7590 if (MD->isStatic()) 7591 return; 7592 7593 // Fields shadowed by constructor parameters are a special case. Usually 7594 // the constructor initializes the field with the parameter. 7595 if (isa<CXXConstructorDecl>(NewDC)) 7596 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7597 // Remember that this was shadowed so we can either warn about its 7598 // modification or its existence depending on warning settings. 7599 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7600 return; 7601 } 7602 } 7603 7604 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7605 if (shadowedVar->isExternC()) { 7606 // For shadowing external vars, make sure that we point to the global 7607 // declaration, not a locally scoped extern declaration. 7608 for (auto I : shadowedVar->redecls()) 7609 if (I->isFileVarDecl()) { 7610 ShadowedDecl = I; 7611 break; 7612 } 7613 } 7614 7615 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7616 7617 unsigned WarningDiag = diag::warn_decl_shadow; 7618 SourceLocation CaptureLoc; 7619 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7620 isa<CXXMethodDecl>(NewDC)) { 7621 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7622 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7623 if (RD->getLambdaCaptureDefault() == LCD_None) { 7624 // Try to avoid warnings for lambdas with an explicit capture list. 7625 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7626 // Warn only when the lambda captures the shadowed decl explicitly. 7627 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7628 if (CaptureLoc.isInvalid()) 7629 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7630 } else { 7631 // Remember that this was shadowed so we can avoid the warning if the 7632 // shadowed decl isn't captured and the warning settings allow it. 7633 cast<LambdaScopeInfo>(getCurFunction()) 7634 ->ShadowingDecls.push_back( 7635 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7636 return; 7637 } 7638 } 7639 7640 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7641 // A variable can't shadow a local variable in an enclosing scope, if 7642 // they are separated by a non-capturing declaration context. 7643 for (DeclContext *ParentDC = NewDC; 7644 ParentDC && !ParentDC->Equals(OldDC); 7645 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7646 // Only block literals, captured statements, and lambda expressions 7647 // can capture; other scopes don't. 7648 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7649 !isLambdaCallOperator(ParentDC)) { 7650 return; 7651 } 7652 } 7653 } 7654 } 7655 } 7656 7657 // Only warn about certain kinds of shadowing for class members. 7658 if (NewDC && NewDC->isRecord()) { 7659 // In particular, don't warn about shadowing non-class members. 7660 if (!OldDC->isRecord()) 7661 return; 7662 7663 // TODO: should we warn about static data members shadowing 7664 // static data members from base classes? 7665 7666 // TODO: don't diagnose for inaccessible shadowed members. 7667 // This is hard to do perfectly because we might friend the 7668 // shadowing context, but that's just a false negative. 7669 } 7670 7671 7672 DeclarationName Name = R.getLookupName(); 7673 7674 // Emit warning and note. 7675 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7676 return; 7677 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7678 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7679 if (!CaptureLoc.isInvalid()) 7680 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7681 << Name << /*explicitly*/ 1; 7682 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7683 } 7684 7685 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7686 /// when these variables are captured by the lambda. 7687 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7688 for (const auto &Shadow : LSI->ShadowingDecls) { 7689 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7690 // Try to avoid the warning when the shadowed decl isn't captured. 7691 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7692 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7693 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7694 ? diag::warn_decl_shadow_uncaptured_local 7695 : diag::warn_decl_shadow) 7696 << Shadow.VD->getDeclName() 7697 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7698 if (!CaptureLoc.isInvalid()) 7699 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7700 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7701 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7702 } 7703 } 7704 7705 /// Check -Wshadow without the advantage of a previous lookup. 7706 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7707 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7708 return; 7709 7710 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7711 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7712 LookupName(R, S); 7713 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7714 CheckShadow(D, ShadowedDecl, R); 7715 } 7716 7717 /// Check if 'E', which is an expression that is about to be modified, refers 7718 /// to a constructor parameter that shadows a field. 7719 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7720 // Quickly ignore expressions that can't be shadowing ctor parameters. 7721 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7722 return; 7723 E = E->IgnoreParenImpCasts(); 7724 auto *DRE = dyn_cast<DeclRefExpr>(E); 7725 if (!DRE) 7726 return; 7727 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7728 auto I = ShadowingDecls.find(D); 7729 if (I == ShadowingDecls.end()) 7730 return; 7731 const NamedDecl *ShadowedDecl = I->second; 7732 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7733 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7734 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7735 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7736 7737 // Avoid issuing multiple warnings about the same decl. 7738 ShadowingDecls.erase(I); 7739 } 7740 7741 /// Check for conflict between this global or extern "C" declaration and 7742 /// previous global or extern "C" declarations. This is only used in C++. 7743 template<typename T> 7744 static bool checkGlobalOrExternCConflict( 7745 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7746 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7747 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7748 7749 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7750 // The common case: this global doesn't conflict with any extern "C" 7751 // declaration. 7752 return false; 7753 } 7754 7755 if (Prev) { 7756 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7757 // Both the old and new declarations have C language linkage. This is a 7758 // redeclaration. 7759 Previous.clear(); 7760 Previous.addDecl(Prev); 7761 return true; 7762 } 7763 7764 // This is a global, non-extern "C" declaration, and there is a previous 7765 // non-global extern "C" declaration. Diagnose if this is a variable 7766 // declaration. 7767 if (!isa<VarDecl>(ND)) 7768 return false; 7769 } else { 7770 // The declaration is extern "C". Check for any declaration in the 7771 // translation unit which might conflict. 7772 if (IsGlobal) { 7773 // We have already performed the lookup into the translation unit. 7774 IsGlobal = false; 7775 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7776 I != E; ++I) { 7777 if (isa<VarDecl>(*I)) { 7778 Prev = *I; 7779 break; 7780 } 7781 } 7782 } else { 7783 DeclContext::lookup_result R = 7784 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7785 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7786 I != E; ++I) { 7787 if (isa<VarDecl>(*I)) { 7788 Prev = *I; 7789 break; 7790 } 7791 // FIXME: If we have any other entity with this name in global scope, 7792 // the declaration is ill-formed, but that is a defect: it breaks the 7793 // 'stat' hack, for instance. Only variables can have mangled name 7794 // clashes with extern "C" declarations, so only they deserve a 7795 // diagnostic. 7796 } 7797 } 7798 7799 if (!Prev) 7800 return false; 7801 } 7802 7803 // Use the first declaration's location to ensure we point at something which 7804 // is lexically inside an extern "C" linkage-spec. 7805 assert(Prev && "should have found a previous declaration to diagnose"); 7806 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7807 Prev = FD->getFirstDecl(); 7808 else 7809 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7810 7811 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7812 << IsGlobal << ND; 7813 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7814 << IsGlobal; 7815 return false; 7816 } 7817 7818 /// Apply special rules for handling extern "C" declarations. Returns \c true 7819 /// if we have found that this is a redeclaration of some prior entity. 7820 /// 7821 /// Per C++ [dcl.link]p6: 7822 /// Two declarations [for a function or variable] with C language linkage 7823 /// with the same name that appear in different scopes refer to the same 7824 /// [entity]. An entity with C language linkage shall not be declared with 7825 /// the same name as an entity in global scope. 7826 template<typename T> 7827 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7828 LookupResult &Previous) { 7829 if (!S.getLangOpts().CPlusPlus) { 7830 // In C, when declaring a global variable, look for a corresponding 'extern' 7831 // variable declared in function scope. We don't need this in C++, because 7832 // we find local extern decls in the surrounding file-scope DeclContext. 7833 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7834 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7835 Previous.clear(); 7836 Previous.addDecl(Prev); 7837 return true; 7838 } 7839 } 7840 return false; 7841 } 7842 7843 // A declaration in the translation unit can conflict with an extern "C" 7844 // declaration. 7845 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7846 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7847 7848 // An extern "C" declaration can conflict with a declaration in the 7849 // translation unit or can be a redeclaration of an extern "C" declaration 7850 // in another scope. 7851 if (isIncompleteDeclExternC(S,ND)) 7852 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7853 7854 // Neither global nor extern "C": nothing to do. 7855 return false; 7856 } 7857 7858 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7859 // If the decl is already known invalid, don't check it. 7860 if (NewVD->isInvalidDecl()) 7861 return; 7862 7863 QualType T = NewVD->getType(); 7864 7865 // Defer checking an 'auto' type until its initializer is attached. 7866 if (T->isUndeducedType()) 7867 return; 7868 7869 if (NewVD->hasAttrs()) 7870 CheckAlignasUnderalignment(NewVD); 7871 7872 if (T->isObjCObjectType()) { 7873 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7874 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7875 T = Context.getObjCObjectPointerType(T); 7876 NewVD->setType(T); 7877 } 7878 7879 // Emit an error if an address space was applied to decl with local storage. 7880 // This includes arrays of objects with address space qualifiers, but not 7881 // automatic variables that point to other address spaces. 7882 // ISO/IEC TR 18037 S5.1.2 7883 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7884 T.getAddressSpace() != LangAS::Default) { 7885 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7886 NewVD->setInvalidDecl(); 7887 return; 7888 } 7889 7890 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7891 // scope. 7892 if (getLangOpts().OpenCLVersion == 120 && 7893 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", 7894 getLangOpts()) && 7895 NewVD->isStaticLocal()) { 7896 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7897 NewVD->setInvalidDecl(); 7898 return; 7899 } 7900 7901 if (getLangOpts().OpenCL) { 7902 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7903 if (NewVD->hasAttr<BlocksAttr>()) { 7904 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7905 return; 7906 } 7907 7908 if (T->isBlockPointerType()) { 7909 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7910 // can't use 'extern' storage class. 7911 if (!T.isConstQualified()) { 7912 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7913 << 0 /*const*/; 7914 NewVD->setInvalidDecl(); 7915 return; 7916 } 7917 if (NewVD->hasExternalStorage()) { 7918 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7919 NewVD->setInvalidDecl(); 7920 return; 7921 } 7922 } 7923 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7924 // __constant address space. 7925 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7926 // variables inside a function can also be declared in the global 7927 // address space. 7928 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7929 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7930 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7931 NewVD->hasExternalStorage()) { 7932 if (!T->isSamplerT() && 7933 !T->isDependentType() && 7934 !(T.getAddressSpace() == LangAS::opencl_constant || 7935 (T.getAddressSpace() == LangAS::opencl_global && 7936 (getLangOpts().OpenCLVersion == 200 || 7937 getLangOpts().OpenCLCPlusPlus)))) { 7938 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7939 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7940 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7941 << Scope << "global or constant"; 7942 else 7943 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7944 << Scope << "constant"; 7945 NewVD->setInvalidDecl(); 7946 return; 7947 } 7948 } else { 7949 if (T.getAddressSpace() == LangAS::opencl_global) { 7950 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7951 << 1 /*is any function*/ << "global"; 7952 NewVD->setInvalidDecl(); 7953 return; 7954 } 7955 if (T.getAddressSpace() == LangAS::opencl_constant || 7956 T.getAddressSpace() == LangAS::opencl_local) { 7957 FunctionDecl *FD = getCurFunctionDecl(); 7958 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7959 // in functions. 7960 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7961 if (T.getAddressSpace() == LangAS::opencl_constant) 7962 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7963 << 0 /*non-kernel only*/ << "constant"; 7964 else 7965 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7966 << 0 /*non-kernel only*/ << "local"; 7967 NewVD->setInvalidDecl(); 7968 return; 7969 } 7970 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7971 // in the outermost scope of a kernel function. 7972 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7973 if (!getCurScope()->isFunctionScope()) { 7974 if (T.getAddressSpace() == LangAS::opencl_constant) 7975 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7976 << "constant"; 7977 else 7978 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7979 << "local"; 7980 NewVD->setInvalidDecl(); 7981 return; 7982 } 7983 } 7984 } else if (T.getAddressSpace() != LangAS::opencl_private && 7985 // If we are parsing a template we didn't deduce an addr 7986 // space yet. 7987 T.getAddressSpace() != LangAS::Default) { 7988 // Do not allow other address spaces on automatic variable. 7989 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7990 NewVD->setInvalidDecl(); 7991 return; 7992 } 7993 } 7994 } 7995 7996 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7997 && !NewVD->hasAttr<BlocksAttr>()) { 7998 if (getLangOpts().getGC() != LangOptions::NonGC) 7999 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 8000 else { 8001 assert(!getLangOpts().ObjCAutoRefCount); 8002 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 8003 } 8004 } 8005 8006 bool isVM = T->isVariablyModifiedType(); 8007 if (isVM || NewVD->hasAttr<CleanupAttr>() || 8008 NewVD->hasAttr<BlocksAttr>()) 8009 setFunctionHasBranchProtectedScope(); 8010 8011 if ((isVM && NewVD->hasLinkage()) || 8012 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8013 bool SizeIsNegative; 8014 llvm::APSInt Oversized; 8015 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8016 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8017 QualType FixedT; 8018 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8019 FixedT = FixedTInfo->getType(); 8020 else if (FixedTInfo) { 8021 // Type and type-as-written are canonically different. We need to fix up 8022 // both types separately. 8023 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8024 Oversized); 8025 } 8026 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8027 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8028 // FIXME: This won't give the correct result for 8029 // int a[10][n]; 8030 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8031 8032 if (NewVD->isFileVarDecl()) 8033 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8034 << SizeRange; 8035 else if (NewVD->isStaticLocal()) 8036 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8037 << SizeRange; 8038 else 8039 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8040 << SizeRange; 8041 NewVD->setInvalidDecl(); 8042 return; 8043 } 8044 8045 if (!FixedTInfo) { 8046 if (NewVD->isFileVarDecl()) 8047 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8048 else 8049 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8050 NewVD->setInvalidDecl(); 8051 return; 8052 } 8053 8054 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8055 NewVD->setType(FixedT); 8056 NewVD->setTypeSourceInfo(FixedTInfo); 8057 } 8058 8059 if (T->isVoidType()) { 8060 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8061 // of objects and functions. 8062 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8063 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8064 << T; 8065 NewVD->setInvalidDecl(); 8066 return; 8067 } 8068 } 8069 8070 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8071 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8072 NewVD->setInvalidDecl(); 8073 return; 8074 } 8075 8076 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8077 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8078 NewVD->setInvalidDecl(); 8079 return; 8080 } 8081 8082 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8083 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8084 NewVD->setInvalidDecl(); 8085 return; 8086 } 8087 8088 if (NewVD->isConstexpr() && !T->isDependentType() && 8089 RequireLiteralType(NewVD->getLocation(), T, 8090 diag::err_constexpr_var_non_literal)) { 8091 NewVD->setInvalidDecl(); 8092 return; 8093 } 8094 8095 // PPC MMA non-pointer types are not allowed as non-local variable types. 8096 if (Context.getTargetInfo().getTriple().isPPC64() && 8097 !NewVD->isLocalVarDecl() && 8098 CheckPPCMMAType(T, NewVD->getLocation())) { 8099 NewVD->setInvalidDecl(); 8100 return; 8101 } 8102 } 8103 8104 /// Perform semantic checking on a newly-created variable 8105 /// declaration. 8106 /// 8107 /// This routine performs all of the type-checking required for a 8108 /// variable declaration once it has been built. It is used both to 8109 /// check variables after they have been parsed and their declarators 8110 /// have been translated into a declaration, and to check variables 8111 /// that have been instantiated from a template. 8112 /// 8113 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8114 /// 8115 /// Returns true if the variable declaration is a redeclaration. 8116 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8117 CheckVariableDeclarationType(NewVD); 8118 8119 // If the decl is already known invalid, don't check it. 8120 if (NewVD->isInvalidDecl()) 8121 return false; 8122 8123 // If we did not find anything by this name, look for a non-visible 8124 // extern "C" declaration with the same name. 8125 if (Previous.empty() && 8126 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8127 Previous.setShadowed(); 8128 8129 if (!Previous.empty()) { 8130 MergeVarDecl(NewVD, Previous); 8131 return true; 8132 } 8133 return false; 8134 } 8135 8136 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8137 /// and if so, check that it's a valid override and remember it. 8138 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8139 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8140 8141 // Look for methods in base classes that this method might override. 8142 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8143 /*DetectVirtual=*/false); 8144 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8145 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8146 DeclarationName Name = MD->getDeclName(); 8147 8148 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8149 // We really want to find the base class destructor here. 8150 QualType T = Context.getTypeDeclType(BaseRecord); 8151 CanQualType CT = Context.getCanonicalType(T); 8152 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8153 } 8154 8155 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8156 CXXMethodDecl *BaseMD = 8157 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8158 if (!BaseMD || !BaseMD->isVirtual() || 8159 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8160 /*ConsiderCudaAttrs=*/true, 8161 // C++2a [class.virtual]p2 does not consider requires 8162 // clauses when overriding. 8163 /*ConsiderRequiresClauses=*/false)) 8164 continue; 8165 8166 if (Overridden.insert(BaseMD).second) { 8167 MD->addOverriddenMethod(BaseMD); 8168 CheckOverridingFunctionReturnType(MD, BaseMD); 8169 CheckOverridingFunctionAttributes(MD, BaseMD); 8170 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8171 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8172 } 8173 8174 // A method can only override one function from each base class. We 8175 // don't track indirectly overridden methods from bases of bases. 8176 return true; 8177 } 8178 8179 return false; 8180 }; 8181 8182 DC->lookupInBases(VisitBase, Paths); 8183 return !Overridden.empty(); 8184 } 8185 8186 namespace { 8187 // Struct for holding all of the extra arguments needed by 8188 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8189 struct ActOnFDArgs { 8190 Scope *S; 8191 Declarator &D; 8192 MultiTemplateParamsArg TemplateParamLists; 8193 bool AddToScope; 8194 }; 8195 } // end anonymous namespace 8196 8197 namespace { 8198 8199 // Callback to only accept typo corrections that have a non-zero edit distance. 8200 // Also only accept corrections that have the same parent decl. 8201 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8202 public: 8203 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8204 CXXRecordDecl *Parent) 8205 : Context(Context), OriginalFD(TypoFD), 8206 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8207 8208 bool ValidateCandidate(const TypoCorrection &candidate) override { 8209 if (candidate.getEditDistance() == 0) 8210 return false; 8211 8212 SmallVector<unsigned, 1> MismatchedParams; 8213 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8214 CDeclEnd = candidate.end(); 8215 CDecl != CDeclEnd; ++CDecl) { 8216 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8217 8218 if (FD && !FD->hasBody() && 8219 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8220 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8221 CXXRecordDecl *Parent = MD->getParent(); 8222 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8223 return true; 8224 } else if (!ExpectedParent) { 8225 return true; 8226 } 8227 } 8228 } 8229 8230 return false; 8231 } 8232 8233 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8234 return std::make_unique<DifferentNameValidatorCCC>(*this); 8235 } 8236 8237 private: 8238 ASTContext &Context; 8239 FunctionDecl *OriginalFD; 8240 CXXRecordDecl *ExpectedParent; 8241 }; 8242 8243 } // end anonymous namespace 8244 8245 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8246 TypoCorrectedFunctionDefinitions.insert(F); 8247 } 8248 8249 /// Generate diagnostics for an invalid function redeclaration. 8250 /// 8251 /// This routine handles generating the diagnostic messages for an invalid 8252 /// function redeclaration, including finding possible similar declarations 8253 /// or performing typo correction if there are no previous declarations with 8254 /// the same name. 8255 /// 8256 /// Returns a NamedDecl iff typo correction was performed and substituting in 8257 /// the new declaration name does not cause new errors. 8258 static NamedDecl *DiagnoseInvalidRedeclaration( 8259 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8260 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8261 DeclarationName Name = NewFD->getDeclName(); 8262 DeclContext *NewDC = NewFD->getDeclContext(); 8263 SmallVector<unsigned, 1> MismatchedParams; 8264 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8265 TypoCorrection Correction; 8266 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8267 unsigned DiagMsg = 8268 IsLocalFriend ? diag::err_no_matching_local_friend : 8269 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8270 diag::err_member_decl_does_not_match; 8271 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8272 IsLocalFriend ? Sema::LookupLocalFriendName 8273 : Sema::LookupOrdinaryName, 8274 Sema::ForVisibleRedeclaration); 8275 8276 NewFD->setInvalidDecl(); 8277 if (IsLocalFriend) 8278 SemaRef.LookupName(Prev, S); 8279 else 8280 SemaRef.LookupQualifiedName(Prev, NewDC); 8281 assert(!Prev.isAmbiguous() && 8282 "Cannot have an ambiguity in previous-declaration lookup"); 8283 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8284 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8285 MD ? MD->getParent() : nullptr); 8286 if (!Prev.empty()) { 8287 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8288 Func != FuncEnd; ++Func) { 8289 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8290 if (FD && 8291 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8292 // Add 1 to the index so that 0 can mean the mismatch didn't 8293 // involve a parameter 8294 unsigned ParamNum = 8295 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8296 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8297 } 8298 } 8299 // If the qualified name lookup yielded nothing, try typo correction 8300 } else if ((Correction = SemaRef.CorrectTypo( 8301 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8302 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8303 IsLocalFriend ? nullptr : NewDC))) { 8304 // Set up everything for the call to ActOnFunctionDeclarator 8305 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8306 ExtraArgs.D.getIdentifierLoc()); 8307 Previous.clear(); 8308 Previous.setLookupName(Correction.getCorrection()); 8309 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8310 CDeclEnd = Correction.end(); 8311 CDecl != CDeclEnd; ++CDecl) { 8312 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8313 if (FD && !FD->hasBody() && 8314 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8315 Previous.addDecl(FD); 8316 } 8317 } 8318 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8319 8320 NamedDecl *Result; 8321 // Retry building the function declaration with the new previous 8322 // declarations, and with errors suppressed. 8323 { 8324 // Trap errors. 8325 Sema::SFINAETrap Trap(SemaRef); 8326 8327 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8328 // pieces need to verify the typo-corrected C++ declaration and hopefully 8329 // eliminate the need for the parameter pack ExtraArgs. 8330 Result = SemaRef.ActOnFunctionDeclarator( 8331 ExtraArgs.S, ExtraArgs.D, 8332 Correction.getCorrectionDecl()->getDeclContext(), 8333 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8334 ExtraArgs.AddToScope); 8335 8336 if (Trap.hasErrorOccurred()) 8337 Result = nullptr; 8338 } 8339 8340 if (Result) { 8341 // Determine which correction we picked. 8342 Decl *Canonical = Result->getCanonicalDecl(); 8343 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8344 I != E; ++I) 8345 if ((*I)->getCanonicalDecl() == Canonical) 8346 Correction.setCorrectionDecl(*I); 8347 8348 // Let Sema know about the correction. 8349 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8350 SemaRef.diagnoseTypo( 8351 Correction, 8352 SemaRef.PDiag(IsLocalFriend 8353 ? diag::err_no_matching_local_friend_suggest 8354 : diag::err_member_decl_does_not_match_suggest) 8355 << Name << NewDC << IsDefinition); 8356 return Result; 8357 } 8358 8359 // Pretend the typo correction never occurred 8360 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8361 ExtraArgs.D.getIdentifierLoc()); 8362 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8363 Previous.clear(); 8364 Previous.setLookupName(Name); 8365 } 8366 8367 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8368 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8369 8370 bool NewFDisConst = false; 8371 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8372 NewFDisConst = NewMD->isConst(); 8373 8374 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8375 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8376 NearMatch != NearMatchEnd; ++NearMatch) { 8377 FunctionDecl *FD = NearMatch->first; 8378 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8379 bool FDisConst = MD && MD->isConst(); 8380 bool IsMember = MD || !IsLocalFriend; 8381 8382 // FIXME: These notes are poorly worded for the local friend case. 8383 if (unsigned Idx = NearMatch->second) { 8384 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8385 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8386 if (Loc.isInvalid()) Loc = FD->getLocation(); 8387 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8388 : diag::note_local_decl_close_param_match) 8389 << Idx << FDParam->getType() 8390 << NewFD->getParamDecl(Idx - 1)->getType(); 8391 } else if (FDisConst != NewFDisConst) { 8392 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8393 << NewFDisConst << FD->getSourceRange().getEnd(); 8394 } else 8395 SemaRef.Diag(FD->getLocation(), 8396 IsMember ? diag::note_member_def_close_match 8397 : diag::note_local_decl_close_match); 8398 } 8399 return nullptr; 8400 } 8401 8402 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8403 switch (D.getDeclSpec().getStorageClassSpec()) { 8404 default: llvm_unreachable("Unknown storage class!"); 8405 case DeclSpec::SCS_auto: 8406 case DeclSpec::SCS_register: 8407 case DeclSpec::SCS_mutable: 8408 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8409 diag::err_typecheck_sclass_func); 8410 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8411 D.setInvalidType(); 8412 break; 8413 case DeclSpec::SCS_unspecified: break; 8414 case DeclSpec::SCS_extern: 8415 if (D.getDeclSpec().isExternInLinkageSpec()) 8416 return SC_None; 8417 return SC_Extern; 8418 case DeclSpec::SCS_static: { 8419 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8420 // C99 6.7.1p5: 8421 // The declaration of an identifier for a function that has 8422 // block scope shall have no explicit storage-class specifier 8423 // other than extern 8424 // See also (C++ [dcl.stc]p4). 8425 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8426 diag::err_static_block_func); 8427 break; 8428 } else 8429 return SC_Static; 8430 } 8431 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8432 } 8433 8434 // No explicit storage class has already been returned 8435 return SC_None; 8436 } 8437 8438 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8439 DeclContext *DC, QualType &R, 8440 TypeSourceInfo *TInfo, 8441 StorageClass SC, 8442 bool &IsVirtualOkay) { 8443 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8444 DeclarationName Name = NameInfo.getName(); 8445 8446 FunctionDecl *NewFD = nullptr; 8447 bool isInline = D.getDeclSpec().isInlineSpecified(); 8448 8449 if (!SemaRef.getLangOpts().CPlusPlus) { 8450 // Determine whether the function was written with a 8451 // prototype. This true when: 8452 // - there is a prototype in the declarator, or 8453 // - the type R of the function is some kind of typedef or other non- 8454 // attributed reference to a type name (which eventually refers to a 8455 // function type). 8456 bool HasPrototype = 8457 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8458 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8459 8460 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8461 R, TInfo, SC, isInline, HasPrototype, 8462 ConstexprSpecKind::Unspecified, 8463 /*TrailingRequiresClause=*/nullptr); 8464 if (D.isInvalidType()) 8465 NewFD->setInvalidDecl(); 8466 8467 return NewFD; 8468 } 8469 8470 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8471 8472 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8473 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8474 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8475 diag::err_constexpr_wrong_decl_kind) 8476 << static_cast<int>(ConstexprKind); 8477 ConstexprKind = ConstexprSpecKind::Unspecified; 8478 D.getMutableDeclSpec().ClearConstexprSpec(); 8479 } 8480 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8481 8482 // Check that the return type is not an abstract class type. 8483 // For record types, this is done by the AbstractClassUsageDiagnoser once 8484 // the class has been completely parsed. 8485 if (!DC->isRecord() && 8486 SemaRef.RequireNonAbstractType( 8487 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8488 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8489 D.setInvalidType(); 8490 8491 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8492 // This is a C++ constructor declaration. 8493 assert(DC->isRecord() && 8494 "Constructors can only be declared in a member context"); 8495 8496 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8497 return CXXConstructorDecl::Create( 8498 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8499 TInfo, ExplicitSpecifier, isInline, 8500 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8501 TrailingRequiresClause); 8502 8503 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8504 // This is a C++ destructor declaration. 8505 if (DC->isRecord()) { 8506 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8507 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8508 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8509 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8510 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8511 TrailingRequiresClause); 8512 8513 // If the destructor needs an implicit exception specification, set it 8514 // now. FIXME: It'd be nice to be able to create the right type to start 8515 // with, but the type needs to reference the destructor declaration. 8516 if (SemaRef.getLangOpts().CPlusPlus11) 8517 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8518 8519 IsVirtualOkay = true; 8520 return NewDD; 8521 8522 } else { 8523 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8524 D.setInvalidType(); 8525 8526 // Create a FunctionDecl to satisfy the function definition parsing 8527 // code path. 8528 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8529 D.getIdentifierLoc(), Name, R, TInfo, SC, 8530 isInline, 8531 /*hasPrototype=*/true, ConstexprKind, 8532 TrailingRequiresClause); 8533 } 8534 8535 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8536 if (!DC->isRecord()) { 8537 SemaRef.Diag(D.getIdentifierLoc(), 8538 diag::err_conv_function_not_member); 8539 return nullptr; 8540 } 8541 8542 SemaRef.CheckConversionDeclarator(D, R, SC); 8543 if (D.isInvalidType()) 8544 return nullptr; 8545 8546 IsVirtualOkay = true; 8547 return CXXConversionDecl::Create( 8548 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8549 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8550 TrailingRequiresClause); 8551 8552 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8553 if (TrailingRequiresClause) 8554 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8555 diag::err_trailing_requires_clause_on_deduction_guide) 8556 << TrailingRequiresClause->getSourceRange(); 8557 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8558 8559 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8560 ExplicitSpecifier, NameInfo, R, TInfo, 8561 D.getEndLoc()); 8562 } else if (DC->isRecord()) { 8563 // If the name of the function is the same as the name of the record, 8564 // then this must be an invalid constructor that has a return type. 8565 // (The parser checks for a return type and makes the declarator a 8566 // constructor if it has no return type). 8567 if (Name.getAsIdentifierInfo() && 8568 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8569 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8570 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8571 << SourceRange(D.getIdentifierLoc()); 8572 return nullptr; 8573 } 8574 8575 // This is a C++ method declaration. 8576 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8577 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8578 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8579 TrailingRequiresClause); 8580 IsVirtualOkay = !Ret->isStatic(); 8581 return Ret; 8582 } else { 8583 bool isFriend = 8584 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8585 if (!isFriend && SemaRef.CurContext->isRecord()) 8586 return nullptr; 8587 8588 // Determine whether the function was written with a 8589 // prototype. This true when: 8590 // - we're in C++ (where every function has a prototype), 8591 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8592 R, TInfo, SC, isInline, true /*HasPrototype*/, 8593 ConstexprKind, TrailingRequiresClause); 8594 } 8595 } 8596 8597 enum OpenCLParamType { 8598 ValidKernelParam, 8599 PtrPtrKernelParam, 8600 PtrKernelParam, 8601 InvalidAddrSpacePtrKernelParam, 8602 InvalidKernelParam, 8603 RecordKernelParam 8604 }; 8605 8606 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8607 // Size dependent types are just typedefs to normal integer types 8608 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8609 // integers other than by their names. 8610 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8611 8612 // Remove typedefs one by one until we reach a typedef 8613 // for a size dependent type. 8614 QualType DesugaredTy = Ty; 8615 do { 8616 ArrayRef<StringRef> Names(SizeTypeNames); 8617 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8618 if (Names.end() != Match) 8619 return true; 8620 8621 Ty = DesugaredTy; 8622 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8623 } while (DesugaredTy != Ty); 8624 8625 return false; 8626 } 8627 8628 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8629 if (PT->isPointerType()) { 8630 QualType PointeeType = PT->getPointeeType(); 8631 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8632 PointeeType.getAddressSpace() == LangAS::opencl_private || 8633 PointeeType.getAddressSpace() == LangAS::Default) 8634 return InvalidAddrSpacePtrKernelParam; 8635 8636 if (PointeeType->isPointerType()) { 8637 // This is a pointer to pointer parameter. 8638 // Recursively check inner type. 8639 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 8640 if (ParamKind == InvalidAddrSpacePtrKernelParam || 8641 ParamKind == InvalidKernelParam) 8642 return ParamKind; 8643 8644 return PtrPtrKernelParam; 8645 } 8646 return PtrKernelParam; 8647 } 8648 8649 // OpenCL v1.2 s6.9.k: 8650 // Arguments to kernel functions in a program cannot be declared with the 8651 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8652 // uintptr_t or a struct and/or union that contain fields declared to be one 8653 // of these built-in scalar types. 8654 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8655 return InvalidKernelParam; 8656 8657 if (PT->isImageType()) 8658 return PtrKernelParam; 8659 8660 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8661 return InvalidKernelParam; 8662 8663 // OpenCL extension spec v1.2 s9.5: 8664 // This extension adds support for half scalar and vector types as built-in 8665 // types that can be used for arithmetic operations, conversions etc. 8666 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 8667 PT->isHalfType()) 8668 return InvalidKernelParam; 8669 8670 if (PT->isRecordType()) 8671 return RecordKernelParam; 8672 8673 // Look into an array argument to check if it has a forbidden type. 8674 if (PT->isArrayType()) { 8675 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8676 // Call ourself to check an underlying type of an array. Since the 8677 // getPointeeOrArrayElementType returns an innermost type which is not an 8678 // array, this recursive call only happens once. 8679 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8680 } 8681 8682 return ValidKernelParam; 8683 } 8684 8685 static void checkIsValidOpenCLKernelParameter( 8686 Sema &S, 8687 Declarator &D, 8688 ParmVarDecl *Param, 8689 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8690 QualType PT = Param->getType(); 8691 8692 // Cache the valid types we encounter to avoid rechecking structs that are 8693 // used again 8694 if (ValidTypes.count(PT.getTypePtr())) 8695 return; 8696 8697 switch (getOpenCLKernelParameterType(S, PT)) { 8698 case PtrPtrKernelParam: 8699 // OpenCL v3.0 s6.11.a: 8700 // A kernel function argument cannot be declared as a pointer to a pointer 8701 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 8702 if (S.getLangOpts().OpenCLVersion < 120 && 8703 !S.getLangOpts().OpenCLCPlusPlus) { 8704 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8705 D.setInvalidType(); 8706 return; 8707 } 8708 8709 ValidTypes.insert(PT.getTypePtr()); 8710 return; 8711 8712 case InvalidAddrSpacePtrKernelParam: 8713 // OpenCL v1.0 s6.5: 8714 // __kernel function arguments declared to be a pointer of a type can point 8715 // to one of the following address spaces only : __global, __local or 8716 // __constant. 8717 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8718 D.setInvalidType(); 8719 return; 8720 8721 // OpenCL v1.2 s6.9.k: 8722 // Arguments to kernel functions in a program cannot be declared with the 8723 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8724 // uintptr_t or a struct and/or union that contain fields declared to be 8725 // one of these built-in scalar types. 8726 8727 case InvalidKernelParam: 8728 // OpenCL v1.2 s6.8 n: 8729 // A kernel function argument cannot be declared 8730 // of event_t type. 8731 // Do not diagnose half type since it is diagnosed as invalid argument 8732 // type for any function elsewhere. 8733 if (!PT->isHalfType()) { 8734 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8735 8736 // Explain what typedefs are involved. 8737 const TypedefType *Typedef = nullptr; 8738 while ((Typedef = PT->getAs<TypedefType>())) { 8739 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8740 // SourceLocation may be invalid for a built-in type. 8741 if (Loc.isValid()) 8742 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8743 PT = Typedef->desugar(); 8744 } 8745 } 8746 8747 D.setInvalidType(); 8748 return; 8749 8750 case PtrKernelParam: 8751 case ValidKernelParam: 8752 ValidTypes.insert(PT.getTypePtr()); 8753 return; 8754 8755 case RecordKernelParam: 8756 break; 8757 } 8758 8759 // Track nested structs we will inspect 8760 SmallVector<const Decl *, 4> VisitStack; 8761 8762 // Track where we are in the nested structs. Items will migrate from 8763 // VisitStack to HistoryStack as we do the DFS for bad field. 8764 SmallVector<const FieldDecl *, 4> HistoryStack; 8765 HistoryStack.push_back(nullptr); 8766 8767 // At this point we already handled everything except of a RecordType or 8768 // an ArrayType of a RecordType. 8769 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8770 const RecordType *RecTy = 8771 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8772 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8773 8774 VisitStack.push_back(RecTy->getDecl()); 8775 assert(VisitStack.back() && "First decl null?"); 8776 8777 do { 8778 const Decl *Next = VisitStack.pop_back_val(); 8779 if (!Next) { 8780 assert(!HistoryStack.empty()); 8781 // Found a marker, we have gone up a level 8782 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8783 ValidTypes.insert(Hist->getType().getTypePtr()); 8784 8785 continue; 8786 } 8787 8788 // Adds everything except the original parameter declaration (which is not a 8789 // field itself) to the history stack. 8790 const RecordDecl *RD; 8791 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8792 HistoryStack.push_back(Field); 8793 8794 QualType FieldTy = Field->getType(); 8795 // Other field types (known to be valid or invalid) are handled while we 8796 // walk around RecordDecl::fields(). 8797 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8798 "Unexpected type."); 8799 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8800 8801 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8802 } else { 8803 RD = cast<RecordDecl>(Next); 8804 } 8805 8806 // Add a null marker so we know when we've gone back up a level 8807 VisitStack.push_back(nullptr); 8808 8809 for (const auto *FD : RD->fields()) { 8810 QualType QT = FD->getType(); 8811 8812 if (ValidTypes.count(QT.getTypePtr())) 8813 continue; 8814 8815 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8816 if (ParamType == ValidKernelParam) 8817 continue; 8818 8819 if (ParamType == RecordKernelParam) { 8820 VisitStack.push_back(FD); 8821 continue; 8822 } 8823 8824 // OpenCL v1.2 s6.9.p: 8825 // Arguments to kernel functions that are declared to be a struct or union 8826 // do not allow OpenCL objects to be passed as elements of the struct or 8827 // union. 8828 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8829 ParamType == InvalidAddrSpacePtrKernelParam) { 8830 S.Diag(Param->getLocation(), 8831 diag::err_record_with_pointers_kernel_param) 8832 << PT->isUnionType() 8833 << PT; 8834 } else { 8835 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8836 } 8837 8838 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8839 << OrigRecDecl->getDeclName(); 8840 8841 // We have an error, now let's go back up through history and show where 8842 // the offending field came from 8843 for (ArrayRef<const FieldDecl *>::const_iterator 8844 I = HistoryStack.begin() + 1, 8845 E = HistoryStack.end(); 8846 I != E; ++I) { 8847 const FieldDecl *OuterField = *I; 8848 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8849 << OuterField->getType(); 8850 } 8851 8852 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8853 << QT->isPointerType() 8854 << QT; 8855 D.setInvalidType(); 8856 return; 8857 } 8858 } while (!VisitStack.empty()); 8859 } 8860 8861 /// Find the DeclContext in which a tag is implicitly declared if we see an 8862 /// elaborated type specifier in the specified context, and lookup finds 8863 /// nothing. 8864 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8865 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8866 DC = DC->getParent(); 8867 return DC; 8868 } 8869 8870 /// Find the Scope in which a tag is implicitly declared if we see an 8871 /// elaborated type specifier in the specified context, and lookup finds 8872 /// nothing. 8873 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8874 while (S->isClassScope() || 8875 (LangOpts.CPlusPlus && 8876 S->isFunctionPrototypeScope()) || 8877 ((S->getFlags() & Scope::DeclScope) == 0) || 8878 (S->getEntity() && S->getEntity()->isTransparentContext())) 8879 S = S->getParent(); 8880 return S; 8881 } 8882 8883 NamedDecl* 8884 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8885 TypeSourceInfo *TInfo, LookupResult &Previous, 8886 MultiTemplateParamsArg TemplateParamListsRef, 8887 bool &AddToScope) { 8888 QualType R = TInfo->getType(); 8889 8890 assert(R->isFunctionType()); 8891 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 8892 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 8893 8894 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8895 for (TemplateParameterList *TPL : TemplateParamListsRef) 8896 TemplateParamLists.push_back(TPL); 8897 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8898 if (!TemplateParamLists.empty() && 8899 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8900 TemplateParamLists.back() = Invented; 8901 else 8902 TemplateParamLists.push_back(Invented); 8903 } 8904 8905 // TODO: consider using NameInfo for diagnostic. 8906 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8907 DeclarationName Name = NameInfo.getName(); 8908 StorageClass SC = getFunctionStorageClass(*this, D); 8909 8910 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8911 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8912 diag::err_invalid_thread) 8913 << DeclSpec::getSpecifierName(TSCS); 8914 8915 if (D.isFirstDeclarationOfMember()) 8916 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8917 D.getIdentifierLoc()); 8918 8919 bool isFriend = false; 8920 FunctionTemplateDecl *FunctionTemplate = nullptr; 8921 bool isMemberSpecialization = false; 8922 bool isFunctionTemplateSpecialization = false; 8923 8924 bool isDependentClassScopeExplicitSpecialization = false; 8925 bool HasExplicitTemplateArgs = false; 8926 TemplateArgumentListInfo TemplateArgs; 8927 8928 bool isVirtualOkay = false; 8929 8930 DeclContext *OriginalDC = DC; 8931 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8932 8933 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8934 isVirtualOkay); 8935 if (!NewFD) return nullptr; 8936 8937 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8938 NewFD->setTopLevelDeclInObjCContainer(); 8939 8940 // Set the lexical context. If this is a function-scope declaration, or has a 8941 // C++ scope specifier, or is the object of a friend declaration, the lexical 8942 // context will be different from the semantic context. 8943 NewFD->setLexicalDeclContext(CurContext); 8944 8945 if (IsLocalExternDecl) 8946 NewFD->setLocalExternDecl(); 8947 8948 if (getLangOpts().CPlusPlus) { 8949 bool isInline = D.getDeclSpec().isInlineSpecified(); 8950 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8951 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8952 isFriend = D.getDeclSpec().isFriendSpecified(); 8953 if (isFriend && !isInline && D.isFunctionDefinition()) { 8954 // C++ [class.friend]p5 8955 // A function can be defined in a friend declaration of a 8956 // class . . . . Such a function is implicitly inline. 8957 NewFD->setImplicitlyInline(); 8958 } 8959 8960 // If this is a method defined in an __interface, and is not a constructor 8961 // or an overloaded operator, then set the pure flag (isVirtual will already 8962 // return true). 8963 if (const CXXRecordDecl *Parent = 8964 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8965 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8966 NewFD->setPure(true); 8967 8968 // C++ [class.union]p2 8969 // A union can have member functions, but not virtual functions. 8970 if (isVirtual && Parent->isUnion()) 8971 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8972 } 8973 8974 SetNestedNameSpecifier(*this, NewFD, D); 8975 isMemberSpecialization = false; 8976 isFunctionTemplateSpecialization = false; 8977 if (D.isInvalidType()) 8978 NewFD->setInvalidDecl(); 8979 8980 // Match up the template parameter lists with the scope specifier, then 8981 // determine whether we have a template or a template specialization. 8982 bool Invalid = false; 8983 TemplateParameterList *TemplateParams = 8984 MatchTemplateParametersToScopeSpecifier( 8985 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8986 D.getCXXScopeSpec(), 8987 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8988 ? D.getName().TemplateId 8989 : nullptr, 8990 TemplateParamLists, isFriend, isMemberSpecialization, 8991 Invalid); 8992 if (TemplateParams) { 8993 // Check that we can declare a template here. 8994 if (CheckTemplateDeclScope(S, TemplateParams)) 8995 NewFD->setInvalidDecl(); 8996 8997 if (TemplateParams->size() > 0) { 8998 // This is a function template 8999 9000 // A destructor cannot be a template. 9001 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9002 Diag(NewFD->getLocation(), diag::err_destructor_template); 9003 NewFD->setInvalidDecl(); 9004 } 9005 9006 // If we're adding a template to a dependent context, we may need to 9007 // rebuilding some of the types used within the template parameter list, 9008 // now that we know what the current instantiation is. 9009 if (DC->isDependentContext()) { 9010 ContextRAII SavedContext(*this, DC); 9011 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9012 Invalid = true; 9013 } 9014 9015 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9016 NewFD->getLocation(), 9017 Name, TemplateParams, 9018 NewFD); 9019 FunctionTemplate->setLexicalDeclContext(CurContext); 9020 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9021 9022 // For source fidelity, store the other template param lists. 9023 if (TemplateParamLists.size() > 1) { 9024 NewFD->setTemplateParameterListsInfo(Context, 9025 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9026 .drop_back(1)); 9027 } 9028 } else { 9029 // This is a function template specialization. 9030 isFunctionTemplateSpecialization = true; 9031 // For source fidelity, store all the template param lists. 9032 if (TemplateParamLists.size() > 0) 9033 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9034 9035 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9036 if (isFriend) { 9037 // We want to remove the "template<>", found here. 9038 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9039 9040 // If we remove the template<> and the name is not a 9041 // template-id, we're actually silently creating a problem: 9042 // the friend declaration will refer to an untemplated decl, 9043 // and clearly the user wants a template specialization. So 9044 // we need to insert '<>' after the name. 9045 SourceLocation InsertLoc; 9046 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9047 InsertLoc = D.getName().getSourceRange().getEnd(); 9048 InsertLoc = getLocForEndOfToken(InsertLoc); 9049 } 9050 9051 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9052 << Name << RemoveRange 9053 << FixItHint::CreateRemoval(RemoveRange) 9054 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9055 } 9056 } 9057 } else { 9058 // Check that we can declare a template here. 9059 if (!TemplateParamLists.empty() && isMemberSpecialization && 9060 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9061 NewFD->setInvalidDecl(); 9062 9063 // All template param lists were matched against the scope specifier: 9064 // this is NOT (an explicit specialization of) a template. 9065 if (TemplateParamLists.size() > 0) 9066 // For source fidelity, store all the template param lists. 9067 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9068 } 9069 9070 if (Invalid) { 9071 NewFD->setInvalidDecl(); 9072 if (FunctionTemplate) 9073 FunctionTemplate->setInvalidDecl(); 9074 } 9075 9076 // C++ [dcl.fct.spec]p5: 9077 // The virtual specifier shall only be used in declarations of 9078 // nonstatic class member functions that appear within a 9079 // member-specification of a class declaration; see 10.3. 9080 // 9081 if (isVirtual && !NewFD->isInvalidDecl()) { 9082 if (!isVirtualOkay) { 9083 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9084 diag::err_virtual_non_function); 9085 } else if (!CurContext->isRecord()) { 9086 // 'virtual' was specified outside of the class. 9087 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9088 diag::err_virtual_out_of_class) 9089 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9090 } else if (NewFD->getDescribedFunctionTemplate()) { 9091 // C++ [temp.mem]p3: 9092 // A member function template shall not be virtual. 9093 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9094 diag::err_virtual_member_function_template) 9095 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9096 } else { 9097 // Okay: Add virtual to the method. 9098 NewFD->setVirtualAsWritten(true); 9099 } 9100 9101 if (getLangOpts().CPlusPlus14 && 9102 NewFD->getReturnType()->isUndeducedType()) 9103 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9104 } 9105 9106 if (getLangOpts().CPlusPlus14 && 9107 (NewFD->isDependentContext() || 9108 (isFriend && CurContext->isDependentContext())) && 9109 NewFD->getReturnType()->isUndeducedType()) { 9110 // If the function template is referenced directly (for instance, as a 9111 // member of the current instantiation), pretend it has a dependent type. 9112 // This is not really justified by the standard, but is the only sane 9113 // thing to do. 9114 // FIXME: For a friend function, we have not marked the function as being 9115 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9116 const FunctionProtoType *FPT = 9117 NewFD->getType()->castAs<FunctionProtoType>(); 9118 QualType Result = 9119 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9120 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9121 FPT->getExtProtoInfo())); 9122 } 9123 9124 // C++ [dcl.fct.spec]p3: 9125 // The inline specifier shall not appear on a block scope function 9126 // declaration. 9127 if (isInline && !NewFD->isInvalidDecl()) { 9128 if (CurContext->isFunctionOrMethod()) { 9129 // 'inline' is not allowed on block scope function declaration. 9130 Diag(D.getDeclSpec().getInlineSpecLoc(), 9131 diag::err_inline_declaration_block_scope) << Name 9132 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9133 } 9134 } 9135 9136 // C++ [dcl.fct.spec]p6: 9137 // The explicit specifier shall be used only in the declaration of a 9138 // constructor or conversion function within its class definition; 9139 // see 12.3.1 and 12.3.2. 9140 if (hasExplicit && !NewFD->isInvalidDecl() && 9141 !isa<CXXDeductionGuideDecl>(NewFD)) { 9142 if (!CurContext->isRecord()) { 9143 // 'explicit' was specified outside of the class. 9144 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9145 diag::err_explicit_out_of_class) 9146 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9147 } else if (!isa<CXXConstructorDecl>(NewFD) && 9148 !isa<CXXConversionDecl>(NewFD)) { 9149 // 'explicit' was specified on a function that wasn't a constructor 9150 // or conversion function. 9151 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9152 diag::err_explicit_non_ctor_or_conv_function) 9153 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9154 } 9155 } 9156 9157 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9158 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9159 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9160 // are implicitly inline. 9161 NewFD->setImplicitlyInline(); 9162 9163 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9164 // be either constructors or to return a literal type. Therefore, 9165 // destructors cannot be declared constexpr. 9166 if (isa<CXXDestructorDecl>(NewFD) && 9167 (!getLangOpts().CPlusPlus20 || 9168 ConstexprKind == ConstexprSpecKind::Consteval)) { 9169 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9170 << static_cast<int>(ConstexprKind); 9171 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9172 ? ConstexprSpecKind::Unspecified 9173 : ConstexprSpecKind::Constexpr); 9174 } 9175 // C++20 [dcl.constexpr]p2: An allocation function, or a 9176 // deallocation function shall not be declared with the consteval 9177 // specifier. 9178 if (ConstexprKind == ConstexprSpecKind::Consteval && 9179 (NewFD->getOverloadedOperator() == OO_New || 9180 NewFD->getOverloadedOperator() == OO_Array_New || 9181 NewFD->getOverloadedOperator() == OO_Delete || 9182 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9183 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9184 diag::err_invalid_consteval_decl_kind) 9185 << NewFD; 9186 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9187 } 9188 } 9189 9190 // If __module_private__ was specified, mark the function accordingly. 9191 if (D.getDeclSpec().isModulePrivateSpecified()) { 9192 if (isFunctionTemplateSpecialization) { 9193 SourceLocation ModulePrivateLoc 9194 = D.getDeclSpec().getModulePrivateSpecLoc(); 9195 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9196 << 0 9197 << FixItHint::CreateRemoval(ModulePrivateLoc); 9198 } else { 9199 NewFD->setModulePrivate(); 9200 if (FunctionTemplate) 9201 FunctionTemplate->setModulePrivate(); 9202 } 9203 } 9204 9205 if (isFriend) { 9206 if (FunctionTemplate) { 9207 FunctionTemplate->setObjectOfFriendDecl(); 9208 FunctionTemplate->setAccess(AS_public); 9209 } 9210 NewFD->setObjectOfFriendDecl(); 9211 NewFD->setAccess(AS_public); 9212 } 9213 9214 // If a function is defined as defaulted or deleted, mark it as such now. 9215 // We'll do the relevant checks on defaulted / deleted functions later. 9216 switch (D.getFunctionDefinitionKind()) { 9217 case FunctionDefinitionKind::Declaration: 9218 case FunctionDefinitionKind::Definition: 9219 break; 9220 9221 case FunctionDefinitionKind::Defaulted: 9222 NewFD->setDefaulted(); 9223 break; 9224 9225 case FunctionDefinitionKind::Deleted: 9226 NewFD->setDeletedAsWritten(); 9227 break; 9228 } 9229 9230 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9231 D.isFunctionDefinition()) { 9232 // C++ [class.mfct]p2: 9233 // A member function may be defined (8.4) in its class definition, in 9234 // which case it is an inline member function (7.1.2) 9235 NewFD->setImplicitlyInline(); 9236 } 9237 9238 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9239 !CurContext->isRecord()) { 9240 // C++ [class.static]p1: 9241 // A data or function member of a class may be declared static 9242 // in a class definition, in which case it is a static member of 9243 // the class. 9244 9245 // Complain about the 'static' specifier if it's on an out-of-line 9246 // member function definition. 9247 9248 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9249 // member function template declaration and class member template 9250 // declaration (MSVC versions before 2015), warn about this. 9251 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9252 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9253 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9254 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9255 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9256 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9257 } 9258 9259 // C++11 [except.spec]p15: 9260 // A deallocation function with no exception-specification is treated 9261 // as if it were specified with noexcept(true). 9262 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9263 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9264 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9265 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9266 NewFD->setType(Context.getFunctionType( 9267 FPT->getReturnType(), FPT->getParamTypes(), 9268 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9269 } 9270 9271 // Filter out previous declarations that don't match the scope. 9272 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9273 D.getCXXScopeSpec().isNotEmpty() || 9274 isMemberSpecialization || 9275 isFunctionTemplateSpecialization); 9276 9277 // Handle GNU asm-label extension (encoded as an attribute). 9278 if (Expr *E = (Expr*) D.getAsmLabel()) { 9279 // The parser guarantees this is a string. 9280 StringLiteral *SE = cast<StringLiteral>(E); 9281 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9282 /*IsLiteralLabel=*/true, 9283 SE->getStrTokenLoc(0))); 9284 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9285 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9286 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9287 if (I != ExtnameUndeclaredIdentifiers.end()) { 9288 if (isDeclExternC(NewFD)) { 9289 NewFD->addAttr(I->second); 9290 ExtnameUndeclaredIdentifiers.erase(I); 9291 } else 9292 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9293 << /*Variable*/0 << NewFD; 9294 } 9295 } 9296 9297 // Copy the parameter declarations from the declarator D to the function 9298 // declaration NewFD, if they are available. First scavenge them into Params. 9299 SmallVector<ParmVarDecl*, 16> Params; 9300 unsigned FTIIdx; 9301 if (D.isFunctionDeclarator(FTIIdx)) { 9302 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9303 9304 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9305 // function that takes no arguments, not a function that takes a 9306 // single void argument. 9307 // We let through "const void" here because Sema::GetTypeForDeclarator 9308 // already checks for that case. 9309 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9310 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9311 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9312 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9313 Param->setDeclContext(NewFD); 9314 Params.push_back(Param); 9315 9316 if (Param->isInvalidDecl()) 9317 NewFD->setInvalidDecl(); 9318 } 9319 } 9320 9321 if (!getLangOpts().CPlusPlus) { 9322 // In C, find all the tag declarations from the prototype and move them 9323 // into the function DeclContext. Remove them from the surrounding tag 9324 // injection context of the function, which is typically but not always 9325 // the TU. 9326 DeclContext *PrototypeTagContext = 9327 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9328 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9329 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9330 9331 // We don't want to reparent enumerators. Look at their parent enum 9332 // instead. 9333 if (!TD) { 9334 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9335 TD = cast<EnumDecl>(ECD->getDeclContext()); 9336 } 9337 if (!TD) 9338 continue; 9339 DeclContext *TagDC = TD->getLexicalDeclContext(); 9340 if (!TagDC->containsDecl(TD)) 9341 continue; 9342 TagDC->removeDecl(TD); 9343 TD->setDeclContext(NewFD); 9344 NewFD->addDecl(TD); 9345 9346 // Preserve the lexical DeclContext if it is not the surrounding tag 9347 // injection context of the FD. In this example, the semantic context of 9348 // E will be f and the lexical context will be S, while both the 9349 // semantic and lexical contexts of S will be f: 9350 // void f(struct S { enum E { a } f; } s); 9351 if (TagDC != PrototypeTagContext) 9352 TD->setLexicalDeclContext(TagDC); 9353 } 9354 } 9355 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9356 // When we're declaring a function with a typedef, typeof, etc as in the 9357 // following example, we'll need to synthesize (unnamed) 9358 // parameters for use in the declaration. 9359 // 9360 // @code 9361 // typedef void fn(int); 9362 // fn f; 9363 // @endcode 9364 9365 // Synthesize a parameter for each argument type. 9366 for (const auto &AI : FT->param_types()) { 9367 ParmVarDecl *Param = 9368 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9369 Param->setScopeInfo(0, Params.size()); 9370 Params.push_back(Param); 9371 } 9372 } else { 9373 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9374 "Should not need args for typedef of non-prototype fn"); 9375 } 9376 9377 // Finally, we know we have the right number of parameters, install them. 9378 NewFD->setParams(Params); 9379 9380 if (D.getDeclSpec().isNoreturnSpecified()) 9381 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9382 D.getDeclSpec().getNoreturnSpecLoc(), 9383 AttributeCommonInfo::AS_Keyword)); 9384 9385 // Functions returning a variably modified type violate C99 6.7.5.2p2 9386 // because all functions have linkage. 9387 if (!NewFD->isInvalidDecl() && 9388 NewFD->getReturnType()->isVariablyModifiedType()) { 9389 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9390 NewFD->setInvalidDecl(); 9391 } 9392 9393 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9394 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9395 !NewFD->hasAttr<SectionAttr>()) 9396 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9397 Context, PragmaClangTextSection.SectionName, 9398 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9399 9400 // Apply an implicit SectionAttr if #pragma code_seg is active. 9401 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9402 !NewFD->hasAttr<SectionAttr>()) { 9403 NewFD->addAttr(SectionAttr::CreateImplicit( 9404 Context, CodeSegStack.CurrentValue->getString(), 9405 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9406 SectionAttr::Declspec_allocate)); 9407 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9408 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9409 ASTContext::PSF_Read, 9410 NewFD)) 9411 NewFD->dropAttr<SectionAttr>(); 9412 } 9413 9414 // Apply an implicit CodeSegAttr from class declspec or 9415 // apply an implicit SectionAttr from #pragma code_seg if active. 9416 if (!NewFD->hasAttr<CodeSegAttr>()) { 9417 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9418 D.isFunctionDefinition())) { 9419 NewFD->addAttr(SAttr); 9420 } 9421 } 9422 9423 // Handle attributes. 9424 ProcessDeclAttributes(S, NewFD, D); 9425 9426 if (getLangOpts().OpenCL) { 9427 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9428 // type declaration will generate a compilation error. 9429 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9430 if (AddressSpace != LangAS::Default) { 9431 Diag(NewFD->getLocation(), 9432 diag::err_opencl_return_value_with_address_space); 9433 NewFD->setInvalidDecl(); 9434 } 9435 } 9436 9437 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) 9438 checkDeviceDecl(NewFD, D.getBeginLoc()); 9439 9440 if (!getLangOpts().CPlusPlus) { 9441 // Perform semantic checking on the function declaration. 9442 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9443 CheckMain(NewFD, D.getDeclSpec()); 9444 9445 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9446 CheckMSVCRTEntryPoint(NewFD); 9447 9448 if (!NewFD->isInvalidDecl()) 9449 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9450 isMemberSpecialization)); 9451 else if (!Previous.empty()) 9452 // Recover gracefully from an invalid redeclaration. 9453 D.setRedeclaration(true); 9454 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9455 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9456 "previous declaration set still overloaded"); 9457 9458 // Diagnose no-prototype function declarations with calling conventions that 9459 // don't support variadic calls. Only do this in C and do it after merging 9460 // possibly prototyped redeclarations. 9461 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9462 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9463 CallingConv CC = FT->getExtInfo().getCC(); 9464 if (!supportsVariadicCall(CC)) { 9465 // Windows system headers sometimes accidentally use stdcall without 9466 // (void) parameters, so we relax this to a warning. 9467 int DiagID = 9468 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9469 Diag(NewFD->getLocation(), DiagID) 9470 << FunctionType::getNameForCallConv(CC); 9471 } 9472 } 9473 9474 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9475 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9476 checkNonTrivialCUnion(NewFD->getReturnType(), 9477 NewFD->getReturnTypeSourceRange().getBegin(), 9478 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9479 } else { 9480 // C++11 [replacement.functions]p3: 9481 // The program's definitions shall not be specified as inline. 9482 // 9483 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9484 // 9485 // Suppress the diagnostic if the function is __attribute__((used)), since 9486 // that forces an external definition to be emitted. 9487 if (D.getDeclSpec().isInlineSpecified() && 9488 NewFD->isReplaceableGlobalAllocationFunction() && 9489 !NewFD->hasAttr<UsedAttr>()) 9490 Diag(D.getDeclSpec().getInlineSpecLoc(), 9491 diag::ext_operator_new_delete_declared_inline) 9492 << NewFD->getDeclName(); 9493 9494 // If the declarator is a template-id, translate the parser's template 9495 // argument list into our AST format. 9496 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9497 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9498 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9499 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9500 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9501 TemplateId->NumArgs); 9502 translateTemplateArguments(TemplateArgsPtr, 9503 TemplateArgs); 9504 9505 HasExplicitTemplateArgs = true; 9506 9507 if (NewFD->isInvalidDecl()) { 9508 HasExplicitTemplateArgs = false; 9509 } else if (FunctionTemplate) { 9510 // Function template with explicit template arguments. 9511 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9512 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9513 9514 HasExplicitTemplateArgs = false; 9515 } else { 9516 assert((isFunctionTemplateSpecialization || 9517 D.getDeclSpec().isFriendSpecified()) && 9518 "should have a 'template<>' for this decl"); 9519 // "friend void foo<>(int);" is an implicit specialization decl. 9520 isFunctionTemplateSpecialization = true; 9521 } 9522 } else if (isFriend && isFunctionTemplateSpecialization) { 9523 // This combination is only possible in a recovery case; the user 9524 // wrote something like: 9525 // template <> friend void foo(int); 9526 // which we're recovering from as if the user had written: 9527 // friend void foo<>(int); 9528 // Go ahead and fake up a template id. 9529 HasExplicitTemplateArgs = true; 9530 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9531 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9532 } 9533 9534 // We do not add HD attributes to specializations here because 9535 // they may have different constexpr-ness compared to their 9536 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9537 // may end up with different effective targets. Instead, a 9538 // specialization inherits its target attributes from its template 9539 // in the CheckFunctionTemplateSpecialization() call below. 9540 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9541 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9542 9543 // If it's a friend (and only if it's a friend), it's possible 9544 // that either the specialized function type or the specialized 9545 // template is dependent, and therefore matching will fail. In 9546 // this case, don't check the specialization yet. 9547 if (isFunctionTemplateSpecialization && isFriend && 9548 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9549 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 9550 TemplateArgs.arguments()))) { 9551 assert(HasExplicitTemplateArgs && 9552 "friend function specialization without template args"); 9553 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9554 Previous)) 9555 NewFD->setInvalidDecl(); 9556 } else if (isFunctionTemplateSpecialization) { 9557 if (CurContext->isDependentContext() && CurContext->isRecord() 9558 && !isFriend) { 9559 isDependentClassScopeExplicitSpecialization = true; 9560 } else if (!NewFD->isInvalidDecl() && 9561 CheckFunctionTemplateSpecialization( 9562 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9563 Previous)) 9564 NewFD->setInvalidDecl(); 9565 9566 // C++ [dcl.stc]p1: 9567 // A storage-class-specifier shall not be specified in an explicit 9568 // specialization (14.7.3) 9569 FunctionTemplateSpecializationInfo *Info = 9570 NewFD->getTemplateSpecializationInfo(); 9571 if (Info && SC != SC_None) { 9572 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9573 Diag(NewFD->getLocation(), 9574 diag::err_explicit_specialization_inconsistent_storage_class) 9575 << SC 9576 << FixItHint::CreateRemoval( 9577 D.getDeclSpec().getStorageClassSpecLoc()); 9578 9579 else 9580 Diag(NewFD->getLocation(), 9581 diag::ext_explicit_specialization_storage_class) 9582 << FixItHint::CreateRemoval( 9583 D.getDeclSpec().getStorageClassSpecLoc()); 9584 } 9585 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9586 if (CheckMemberSpecialization(NewFD, Previous)) 9587 NewFD->setInvalidDecl(); 9588 } 9589 9590 // Perform semantic checking on the function declaration. 9591 if (!isDependentClassScopeExplicitSpecialization) { 9592 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9593 CheckMain(NewFD, D.getDeclSpec()); 9594 9595 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9596 CheckMSVCRTEntryPoint(NewFD); 9597 9598 if (!NewFD->isInvalidDecl()) 9599 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9600 isMemberSpecialization)); 9601 else if (!Previous.empty()) 9602 // Recover gracefully from an invalid redeclaration. 9603 D.setRedeclaration(true); 9604 } 9605 9606 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9607 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9608 "previous declaration set still overloaded"); 9609 9610 NamedDecl *PrincipalDecl = (FunctionTemplate 9611 ? cast<NamedDecl>(FunctionTemplate) 9612 : NewFD); 9613 9614 if (isFriend && NewFD->getPreviousDecl()) { 9615 AccessSpecifier Access = AS_public; 9616 if (!NewFD->isInvalidDecl()) 9617 Access = NewFD->getPreviousDecl()->getAccess(); 9618 9619 NewFD->setAccess(Access); 9620 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9621 } 9622 9623 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9624 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9625 PrincipalDecl->setNonMemberOperator(); 9626 9627 // If we have a function template, check the template parameter 9628 // list. This will check and merge default template arguments. 9629 if (FunctionTemplate) { 9630 FunctionTemplateDecl *PrevTemplate = 9631 FunctionTemplate->getPreviousDecl(); 9632 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9633 PrevTemplate ? PrevTemplate->getTemplateParameters() 9634 : nullptr, 9635 D.getDeclSpec().isFriendSpecified() 9636 ? (D.isFunctionDefinition() 9637 ? TPC_FriendFunctionTemplateDefinition 9638 : TPC_FriendFunctionTemplate) 9639 : (D.getCXXScopeSpec().isSet() && 9640 DC && DC->isRecord() && 9641 DC->isDependentContext()) 9642 ? TPC_ClassTemplateMember 9643 : TPC_FunctionTemplate); 9644 } 9645 9646 if (NewFD->isInvalidDecl()) { 9647 // Ignore all the rest of this. 9648 } else if (!D.isRedeclaration()) { 9649 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9650 AddToScope }; 9651 // Fake up an access specifier if it's supposed to be a class member. 9652 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9653 NewFD->setAccess(AS_public); 9654 9655 // Qualified decls generally require a previous declaration. 9656 if (D.getCXXScopeSpec().isSet()) { 9657 // ...with the major exception of templated-scope or 9658 // dependent-scope friend declarations. 9659 9660 // TODO: we currently also suppress this check in dependent 9661 // contexts because (1) the parameter depth will be off when 9662 // matching friend templates and (2) we might actually be 9663 // selecting a friend based on a dependent factor. But there 9664 // are situations where these conditions don't apply and we 9665 // can actually do this check immediately. 9666 // 9667 // Unless the scope is dependent, it's always an error if qualified 9668 // redeclaration lookup found nothing at all. Diagnose that now; 9669 // nothing will diagnose that error later. 9670 if (isFriend && 9671 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9672 (!Previous.empty() && CurContext->isDependentContext()))) { 9673 // ignore these 9674 } else { 9675 // The user tried to provide an out-of-line definition for a 9676 // function that is a member of a class or namespace, but there 9677 // was no such member function declared (C++ [class.mfct]p2, 9678 // C++ [namespace.memdef]p2). For example: 9679 // 9680 // class X { 9681 // void f() const; 9682 // }; 9683 // 9684 // void X::f() { } // ill-formed 9685 // 9686 // Complain about this problem, and attempt to suggest close 9687 // matches (e.g., those that differ only in cv-qualifiers and 9688 // whether the parameter types are references). 9689 9690 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9691 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9692 AddToScope = ExtraArgs.AddToScope; 9693 return Result; 9694 } 9695 } 9696 9697 // Unqualified local friend declarations are required to resolve 9698 // to something. 9699 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9700 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9701 *this, Previous, NewFD, ExtraArgs, true, S)) { 9702 AddToScope = ExtraArgs.AddToScope; 9703 return Result; 9704 } 9705 } 9706 } else if (!D.isFunctionDefinition() && 9707 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9708 !isFriend && !isFunctionTemplateSpecialization && 9709 !isMemberSpecialization) { 9710 // An out-of-line member function declaration must also be a 9711 // definition (C++ [class.mfct]p2). 9712 // Note that this is not the case for explicit specializations of 9713 // function templates or member functions of class templates, per 9714 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9715 // extension for compatibility with old SWIG code which likes to 9716 // generate them. 9717 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9718 << D.getCXXScopeSpec().getRange(); 9719 } 9720 } 9721 9722 // If this is the first declaration of a library builtin function, add 9723 // attributes as appropriate. 9724 if (!D.isRedeclaration() && 9725 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 9726 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 9727 if (unsigned BuiltinID = II->getBuiltinID()) { 9728 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 9729 // Validate the type matches unless this builtin is specified as 9730 // matching regardless of its declared type. 9731 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 9732 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9733 } else { 9734 ASTContext::GetBuiltinTypeError Error; 9735 LookupNecessaryTypesForBuiltin(S, BuiltinID); 9736 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 9737 9738 if (!Error && !BuiltinType.isNull() && 9739 Context.hasSameFunctionTypeIgnoringExceptionSpec( 9740 NewFD->getType(), BuiltinType)) 9741 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9742 } 9743 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 9744 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9745 // FIXME: We should consider this a builtin only in the std namespace. 9746 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9747 } 9748 } 9749 } 9750 } 9751 9752 ProcessPragmaWeak(S, NewFD); 9753 checkAttributesAfterMerging(*this, *NewFD); 9754 9755 AddKnownFunctionAttributes(NewFD); 9756 9757 if (NewFD->hasAttr<OverloadableAttr>() && 9758 !NewFD->getType()->getAs<FunctionProtoType>()) { 9759 Diag(NewFD->getLocation(), 9760 diag::err_attribute_overloadable_no_prototype) 9761 << NewFD; 9762 9763 // Turn this into a variadic function with no parameters. 9764 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9765 FunctionProtoType::ExtProtoInfo EPI( 9766 Context.getDefaultCallingConvention(true, false)); 9767 EPI.Variadic = true; 9768 EPI.ExtInfo = FT->getExtInfo(); 9769 9770 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9771 NewFD->setType(R); 9772 } 9773 9774 // If there's a #pragma GCC visibility in scope, and this isn't a class 9775 // member, set the visibility of this function. 9776 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9777 AddPushedVisibilityAttribute(NewFD); 9778 9779 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9780 // marking the function. 9781 AddCFAuditedAttribute(NewFD); 9782 9783 // If this is a function definition, check if we have to apply optnone due to 9784 // a pragma. 9785 if(D.isFunctionDefinition()) 9786 AddRangeBasedOptnone(NewFD); 9787 9788 // If this is the first declaration of an extern C variable, update 9789 // the map of such variables. 9790 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9791 isIncompleteDeclExternC(*this, NewFD)) 9792 RegisterLocallyScopedExternCDecl(NewFD, S); 9793 9794 // Set this FunctionDecl's range up to the right paren. 9795 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9796 9797 if (D.isRedeclaration() && !Previous.empty()) { 9798 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9799 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9800 isMemberSpecialization || 9801 isFunctionTemplateSpecialization, 9802 D.isFunctionDefinition()); 9803 } 9804 9805 if (getLangOpts().CUDA) { 9806 IdentifierInfo *II = NewFD->getIdentifier(); 9807 if (II && II->isStr(getCudaConfigureFuncName()) && 9808 !NewFD->isInvalidDecl() && 9809 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9810 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9811 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9812 << getCudaConfigureFuncName(); 9813 Context.setcudaConfigureCallDecl(NewFD); 9814 } 9815 9816 // Variadic functions, other than a *declaration* of printf, are not allowed 9817 // in device-side CUDA code, unless someone passed 9818 // -fcuda-allow-variadic-functions. 9819 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9820 (NewFD->hasAttr<CUDADeviceAttr>() || 9821 NewFD->hasAttr<CUDAGlobalAttr>()) && 9822 !(II && II->isStr("printf") && NewFD->isExternC() && 9823 !D.isFunctionDefinition())) { 9824 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9825 } 9826 } 9827 9828 MarkUnusedFileScopedDecl(NewFD); 9829 9830 9831 9832 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9833 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9834 if ((getLangOpts().OpenCLVersion >= 120) 9835 && (SC == SC_Static)) { 9836 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9837 D.setInvalidType(); 9838 } 9839 9840 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9841 if (!NewFD->getReturnType()->isVoidType()) { 9842 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9843 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9844 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9845 : FixItHint()); 9846 D.setInvalidType(); 9847 } 9848 9849 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9850 for (auto Param : NewFD->parameters()) 9851 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9852 9853 if (getLangOpts().OpenCLCPlusPlus) { 9854 if (DC->isRecord()) { 9855 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9856 D.setInvalidType(); 9857 } 9858 if (FunctionTemplate) { 9859 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9860 D.setInvalidType(); 9861 } 9862 } 9863 } 9864 9865 if (getLangOpts().CPlusPlus) { 9866 if (FunctionTemplate) { 9867 if (NewFD->isInvalidDecl()) 9868 FunctionTemplate->setInvalidDecl(); 9869 return FunctionTemplate; 9870 } 9871 9872 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9873 CompleteMemberSpecialization(NewFD, Previous); 9874 } 9875 9876 for (const ParmVarDecl *Param : NewFD->parameters()) { 9877 QualType PT = Param->getType(); 9878 9879 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9880 // types. 9881 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9882 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9883 QualType ElemTy = PipeTy->getElementType(); 9884 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9885 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9886 D.setInvalidType(); 9887 } 9888 } 9889 } 9890 } 9891 9892 // Here we have an function template explicit specialization at class scope. 9893 // The actual specialization will be postponed to template instatiation 9894 // time via the ClassScopeFunctionSpecializationDecl node. 9895 if (isDependentClassScopeExplicitSpecialization) { 9896 ClassScopeFunctionSpecializationDecl *NewSpec = 9897 ClassScopeFunctionSpecializationDecl::Create( 9898 Context, CurContext, NewFD->getLocation(), 9899 cast<CXXMethodDecl>(NewFD), 9900 HasExplicitTemplateArgs, TemplateArgs); 9901 CurContext->addDecl(NewSpec); 9902 AddToScope = false; 9903 } 9904 9905 // Diagnose availability attributes. Availability cannot be used on functions 9906 // that are run during load/unload. 9907 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9908 if (NewFD->hasAttr<ConstructorAttr>()) { 9909 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9910 << 1; 9911 NewFD->dropAttr<AvailabilityAttr>(); 9912 } 9913 if (NewFD->hasAttr<DestructorAttr>()) { 9914 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9915 << 2; 9916 NewFD->dropAttr<AvailabilityAttr>(); 9917 } 9918 } 9919 9920 // Diagnose no_builtin attribute on function declaration that are not a 9921 // definition. 9922 // FIXME: We should really be doing this in 9923 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9924 // the FunctionDecl and at this point of the code 9925 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9926 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9927 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9928 switch (D.getFunctionDefinitionKind()) { 9929 case FunctionDefinitionKind::Defaulted: 9930 case FunctionDefinitionKind::Deleted: 9931 Diag(NBA->getLocation(), 9932 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9933 << NBA->getSpelling(); 9934 break; 9935 case FunctionDefinitionKind::Declaration: 9936 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9937 << NBA->getSpelling(); 9938 break; 9939 case FunctionDefinitionKind::Definition: 9940 break; 9941 } 9942 9943 return NewFD; 9944 } 9945 9946 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9947 /// when __declspec(code_seg) "is applied to a class, all member functions of 9948 /// the class and nested classes -- this includes compiler-generated special 9949 /// member functions -- are put in the specified segment." 9950 /// The actual behavior is a little more complicated. The Microsoft compiler 9951 /// won't check outer classes if there is an active value from #pragma code_seg. 9952 /// The CodeSeg is always applied from the direct parent but only from outer 9953 /// classes when the #pragma code_seg stack is empty. See: 9954 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9955 /// available since MS has removed the page. 9956 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9957 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9958 if (!Method) 9959 return nullptr; 9960 const CXXRecordDecl *Parent = Method->getParent(); 9961 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9962 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9963 NewAttr->setImplicit(true); 9964 return NewAttr; 9965 } 9966 9967 // The Microsoft compiler won't check outer classes for the CodeSeg 9968 // when the #pragma code_seg stack is active. 9969 if (S.CodeSegStack.CurrentValue) 9970 return nullptr; 9971 9972 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9973 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9974 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9975 NewAttr->setImplicit(true); 9976 return NewAttr; 9977 } 9978 } 9979 return nullptr; 9980 } 9981 9982 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9983 /// containing class. Otherwise it will return implicit SectionAttr if the 9984 /// function is a definition and there is an active value on CodeSegStack 9985 /// (from the current #pragma code-seg value). 9986 /// 9987 /// \param FD Function being declared. 9988 /// \param IsDefinition Whether it is a definition or just a declarartion. 9989 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9990 /// nullptr if no attribute should be added. 9991 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9992 bool IsDefinition) { 9993 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9994 return A; 9995 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9996 CodeSegStack.CurrentValue) 9997 return SectionAttr::CreateImplicit( 9998 getASTContext(), CodeSegStack.CurrentValue->getString(), 9999 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 10000 SectionAttr::Declspec_allocate); 10001 return nullptr; 10002 } 10003 10004 /// Determines if we can perform a correct type check for \p D as a 10005 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 10006 /// best-effort check. 10007 /// 10008 /// \param NewD The new declaration. 10009 /// \param OldD The old declaration. 10010 /// \param NewT The portion of the type of the new declaration to check. 10011 /// \param OldT The portion of the type of the old declaration to check. 10012 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 10013 QualType NewT, QualType OldT) { 10014 if (!NewD->getLexicalDeclContext()->isDependentContext()) 10015 return true; 10016 10017 // For dependently-typed local extern declarations and friends, we can't 10018 // perform a correct type check in general until instantiation: 10019 // 10020 // int f(); 10021 // template<typename T> void g() { T f(); } 10022 // 10023 // (valid if g() is only instantiated with T = int). 10024 if (NewT->isDependentType() && 10025 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10026 return false; 10027 10028 // Similarly, if the previous declaration was a dependent local extern 10029 // declaration, we don't really know its type yet. 10030 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10031 return false; 10032 10033 return true; 10034 } 10035 10036 /// Checks if the new declaration declared in dependent context must be 10037 /// put in the same redeclaration chain as the specified declaration. 10038 /// 10039 /// \param D Declaration that is checked. 10040 /// \param PrevDecl Previous declaration found with proper lookup method for the 10041 /// same declaration name. 10042 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10043 /// belongs to. 10044 /// 10045 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10046 if (!D->getLexicalDeclContext()->isDependentContext()) 10047 return true; 10048 10049 // Don't chain dependent friend function definitions until instantiation, to 10050 // permit cases like 10051 // 10052 // void func(); 10053 // template<typename T> class C1 { friend void func() {} }; 10054 // template<typename T> class C2 { friend void func() {} }; 10055 // 10056 // ... which is valid if only one of C1 and C2 is ever instantiated. 10057 // 10058 // FIXME: This need only apply to function definitions. For now, we proxy 10059 // this by checking for a file-scope function. We do not want this to apply 10060 // to friend declarations nominating member functions, because that gets in 10061 // the way of access checks. 10062 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10063 return false; 10064 10065 auto *VD = dyn_cast<ValueDecl>(D); 10066 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10067 return !VD || !PrevVD || 10068 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10069 PrevVD->getType()); 10070 } 10071 10072 /// Check the target attribute of the function for MultiVersion 10073 /// validity. 10074 /// 10075 /// Returns true if there was an error, false otherwise. 10076 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10077 const auto *TA = FD->getAttr<TargetAttr>(); 10078 assert(TA && "MultiVersion Candidate requires a target attribute"); 10079 ParsedTargetAttr ParseInfo = TA->parse(); 10080 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10081 enum ErrType { Feature = 0, Architecture = 1 }; 10082 10083 if (!ParseInfo.Architecture.empty() && 10084 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10085 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10086 << Architecture << ParseInfo.Architecture; 10087 return true; 10088 } 10089 10090 for (const auto &Feat : ParseInfo.Features) { 10091 auto BareFeat = StringRef{Feat}.substr(1); 10092 if (Feat[0] == '-') { 10093 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10094 << Feature << ("no-" + BareFeat).str(); 10095 return true; 10096 } 10097 10098 if (!TargetInfo.validateCpuSupports(BareFeat) || 10099 !TargetInfo.isValidFeatureName(BareFeat)) { 10100 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10101 << Feature << BareFeat; 10102 return true; 10103 } 10104 } 10105 return false; 10106 } 10107 10108 // Provide a white-list of attributes that are allowed to be combined with 10109 // multiversion functions. 10110 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10111 MultiVersionKind MVType) { 10112 // Note: this list/diagnosis must match the list in 10113 // checkMultiversionAttributesAllSame. 10114 switch (Kind) { 10115 default: 10116 return false; 10117 case attr::Used: 10118 return MVType == MultiVersionKind::Target; 10119 case attr::NonNull: 10120 case attr::NoThrow: 10121 return true; 10122 } 10123 } 10124 10125 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10126 const FunctionDecl *FD, 10127 const FunctionDecl *CausedFD, 10128 MultiVersionKind MVType) { 10129 bool IsCPUSpecificCPUDispatchMVType = 10130 MVType == MultiVersionKind::CPUDispatch || 10131 MVType == MultiVersionKind::CPUSpecific; 10132 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType]( 10133 Sema &S, const Attr *A) { 10134 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10135 << IsCPUSpecificCPUDispatchMVType << A; 10136 if (CausedFD) 10137 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10138 return true; 10139 }; 10140 10141 for (const Attr *A : FD->attrs()) { 10142 switch (A->getKind()) { 10143 case attr::CPUDispatch: 10144 case attr::CPUSpecific: 10145 if (MVType != MultiVersionKind::CPUDispatch && 10146 MVType != MultiVersionKind::CPUSpecific) 10147 return Diagnose(S, A); 10148 break; 10149 case attr::Target: 10150 if (MVType != MultiVersionKind::Target) 10151 return Diagnose(S, A); 10152 break; 10153 default: 10154 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10155 return Diagnose(S, A); 10156 break; 10157 } 10158 } 10159 return false; 10160 } 10161 10162 bool Sema::areMultiversionVariantFunctionsCompatible( 10163 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10164 const PartialDiagnostic &NoProtoDiagID, 10165 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10166 const PartialDiagnosticAt &NoSupportDiagIDAt, 10167 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10168 bool ConstexprSupported, bool CLinkageMayDiffer) { 10169 enum DoesntSupport { 10170 FuncTemplates = 0, 10171 VirtFuncs = 1, 10172 DeducedReturn = 2, 10173 Constructors = 3, 10174 Destructors = 4, 10175 DeletedFuncs = 5, 10176 DefaultedFuncs = 6, 10177 ConstexprFuncs = 7, 10178 ConstevalFuncs = 8, 10179 }; 10180 enum Different { 10181 CallingConv = 0, 10182 ReturnType = 1, 10183 ConstexprSpec = 2, 10184 InlineSpec = 3, 10185 StorageClass = 4, 10186 Linkage = 5, 10187 }; 10188 10189 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10190 !OldFD->getType()->getAs<FunctionProtoType>()) { 10191 Diag(OldFD->getLocation(), NoProtoDiagID); 10192 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10193 return true; 10194 } 10195 10196 if (NoProtoDiagID.getDiagID() != 0 && 10197 !NewFD->getType()->getAs<FunctionProtoType>()) 10198 return Diag(NewFD->getLocation(), NoProtoDiagID); 10199 10200 if (!TemplatesSupported && 10201 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10202 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10203 << FuncTemplates; 10204 10205 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10206 if (NewCXXFD->isVirtual()) 10207 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10208 << VirtFuncs; 10209 10210 if (isa<CXXConstructorDecl>(NewCXXFD)) 10211 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10212 << Constructors; 10213 10214 if (isa<CXXDestructorDecl>(NewCXXFD)) 10215 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10216 << Destructors; 10217 } 10218 10219 if (NewFD->isDeleted()) 10220 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10221 << DeletedFuncs; 10222 10223 if (NewFD->isDefaulted()) 10224 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10225 << DefaultedFuncs; 10226 10227 if (!ConstexprSupported && NewFD->isConstexpr()) 10228 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10229 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10230 10231 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10232 const auto *NewType = cast<FunctionType>(NewQType); 10233 QualType NewReturnType = NewType->getReturnType(); 10234 10235 if (NewReturnType->isUndeducedType()) 10236 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10237 << DeducedReturn; 10238 10239 // Ensure the return type is identical. 10240 if (OldFD) { 10241 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10242 const auto *OldType = cast<FunctionType>(OldQType); 10243 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10244 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10245 10246 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10247 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10248 10249 QualType OldReturnType = OldType->getReturnType(); 10250 10251 if (OldReturnType != NewReturnType) 10252 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10253 10254 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10255 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10256 10257 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10258 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10259 10260 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10261 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10262 10263 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10264 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10265 10266 if (CheckEquivalentExceptionSpec( 10267 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10268 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10269 return true; 10270 } 10271 return false; 10272 } 10273 10274 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10275 const FunctionDecl *NewFD, 10276 bool CausesMV, 10277 MultiVersionKind MVType) { 10278 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10279 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10280 if (OldFD) 10281 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10282 return true; 10283 } 10284 10285 bool IsCPUSpecificCPUDispatchMVType = 10286 MVType == MultiVersionKind::CPUDispatch || 10287 MVType == MultiVersionKind::CPUSpecific; 10288 10289 if (CausesMV && OldFD && 10290 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType)) 10291 return true; 10292 10293 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType)) 10294 return true; 10295 10296 // Only allow transition to MultiVersion if it hasn't been used. 10297 if (OldFD && CausesMV && OldFD->isUsed(false)) 10298 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10299 10300 return S.areMultiversionVariantFunctionsCompatible( 10301 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10302 PartialDiagnosticAt(NewFD->getLocation(), 10303 S.PDiag(diag::note_multiversioning_caused_here)), 10304 PartialDiagnosticAt(NewFD->getLocation(), 10305 S.PDiag(diag::err_multiversion_doesnt_support) 10306 << IsCPUSpecificCPUDispatchMVType), 10307 PartialDiagnosticAt(NewFD->getLocation(), 10308 S.PDiag(diag::err_multiversion_diff)), 10309 /*TemplatesSupported=*/false, 10310 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10311 /*CLinkageMayDiffer=*/false); 10312 } 10313 10314 /// Check the validity of a multiversion function declaration that is the 10315 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10316 /// 10317 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10318 /// 10319 /// Returns true if there was an error, false otherwise. 10320 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10321 MultiVersionKind MVType, 10322 const TargetAttr *TA) { 10323 assert(MVType != MultiVersionKind::None && 10324 "Function lacks multiversion attribute"); 10325 10326 // Target only causes MV if it is default, otherwise this is a normal 10327 // function. 10328 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10329 return false; 10330 10331 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10332 FD->setInvalidDecl(); 10333 return true; 10334 } 10335 10336 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10337 FD->setInvalidDecl(); 10338 return true; 10339 } 10340 10341 FD->setIsMultiVersion(); 10342 return false; 10343 } 10344 10345 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10346 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10347 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10348 return true; 10349 } 10350 10351 return false; 10352 } 10353 10354 static bool CheckTargetCausesMultiVersioning( 10355 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10356 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10357 LookupResult &Previous) { 10358 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10359 ParsedTargetAttr NewParsed = NewTA->parse(); 10360 // Sort order doesn't matter, it just needs to be consistent. 10361 llvm::sort(NewParsed.Features); 10362 10363 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10364 // to change, this is a simple redeclaration. 10365 if (!NewTA->isDefaultVersion() && 10366 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10367 return false; 10368 10369 // Otherwise, this decl causes MultiVersioning. 10370 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10371 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10372 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10373 NewFD->setInvalidDecl(); 10374 return true; 10375 } 10376 10377 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10378 MultiVersionKind::Target)) { 10379 NewFD->setInvalidDecl(); 10380 return true; 10381 } 10382 10383 if (CheckMultiVersionValue(S, NewFD)) { 10384 NewFD->setInvalidDecl(); 10385 return true; 10386 } 10387 10388 // If this is 'default', permit the forward declaration. 10389 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10390 Redeclaration = true; 10391 OldDecl = OldFD; 10392 OldFD->setIsMultiVersion(); 10393 NewFD->setIsMultiVersion(); 10394 return false; 10395 } 10396 10397 if (CheckMultiVersionValue(S, OldFD)) { 10398 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10399 NewFD->setInvalidDecl(); 10400 return true; 10401 } 10402 10403 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10404 10405 if (OldParsed == NewParsed) { 10406 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10407 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10408 NewFD->setInvalidDecl(); 10409 return true; 10410 } 10411 10412 for (const auto *FD : OldFD->redecls()) { 10413 const auto *CurTA = FD->getAttr<TargetAttr>(); 10414 // We allow forward declarations before ANY multiversioning attributes, but 10415 // nothing after the fact. 10416 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10417 (!CurTA || CurTA->isInherited())) { 10418 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10419 << 0; 10420 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10421 NewFD->setInvalidDecl(); 10422 return true; 10423 } 10424 } 10425 10426 OldFD->setIsMultiVersion(); 10427 NewFD->setIsMultiVersion(); 10428 Redeclaration = false; 10429 MergeTypeWithPrevious = false; 10430 OldDecl = nullptr; 10431 Previous.clear(); 10432 return false; 10433 } 10434 10435 /// Check the validity of a new function declaration being added to an existing 10436 /// multiversioned declaration collection. 10437 static bool CheckMultiVersionAdditionalDecl( 10438 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10439 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10440 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10441 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10442 LookupResult &Previous) { 10443 10444 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10445 // Disallow mixing of multiversioning types. 10446 if ((OldMVType == MultiVersionKind::Target && 10447 NewMVType != MultiVersionKind::Target) || 10448 (NewMVType == MultiVersionKind::Target && 10449 OldMVType != MultiVersionKind::Target)) { 10450 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10451 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10452 NewFD->setInvalidDecl(); 10453 return true; 10454 } 10455 10456 ParsedTargetAttr NewParsed; 10457 if (NewTA) { 10458 NewParsed = NewTA->parse(); 10459 llvm::sort(NewParsed.Features); 10460 } 10461 10462 bool UseMemberUsingDeclRules = 10463 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10464 10465 // Next, check ALL non-overloads to see if this is a redeclaration of a 10466 // previous member of the MultiVersion set. 10467 for (NamedDecl *ND : Previous) { 10468 FunctionDecl *CurFD = ND->getAsFunction(); 10469 if (!CurFD) 10470 continue; 10471 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10472 continue; 10473 10474 if (NewMVType == MultiVersionKind::Target) { 10475 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10476 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10477 NewFD->setIsMultiVersion(); 10478 Redeclaration = true; 10479 OldDecl = ND; 10480 return false; 10481 } 10482 10483 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10484 if (CurParsed == NewParsed) { 10485 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10486 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10487 NewFD->setInvalidDecl(); 10488 return true; 10489 } 10490 } else { 10491 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10492 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10493 // Handle CPUDispatch/CPUSpecific versions. 10494 // Only 1 CPUDispatch function is allowed, this will make it go through 10495 // the redeclaration errors. 10496 if (NewMVType == MultiVersionKind::CPUDispatch && 10497 CurFD->hasAttr<CPUDispatchAttr>()) { 10498 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10499 std::equal( 10500 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10501 NewCPUDisp->cpus_begin(), 10502 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10503 return Cur->getName() == New->getName(); 10504 })) { 10505 NewFD->setIsMultiVersion(); 10506 Redeclaration = true; 10507 OldDecl = ND; 10508 return false; 10509 } 10510 10511 // If the declarations don't match, this is an error condition. 10512 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10513 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10514 NewFD->setInvalidDecl(); 10515 return true; 10516 } 10517 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10518 10519 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10520 std::equal( 10521 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10522 NewCPUSpec->cpus_begin(), 10523 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10524 return Cur->getName() == New->getName(); 10525 })) { 10526 NewFD->setIsMultiVersion(); 10527 Redeclaration = true; 10528 OldDecl = ND; 10529 return false; 10530 } 10531 10532 // Only 1 version of CPUSpecific is allowed for each CPU. 10533 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10534 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10535 if (CurII == NewII) { 10536 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10537 << NewII; 10538 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10539 NewFD->setInvalidDecl(); 10540 return true; 10541 } 10542 } 10543 } 10544 } 10545 // If the two decls aren't the same MVType, there is no possible error 10546 // condition. 10547 } 10548 } 10549 10550 // Else, this is simply a non-redecl case. Checking the 'value' is only 10551 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10552 // handled in the attribute adding step. 10553 if (NewMVType == MultiVersionKind::Target && 10554 CheckMultiVersionValue(S, NewFD)) { 10555 NewFD->setInvalidDecl(); 10556 return true; 10557 } 10558 10559 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10560 !OldFD->isMultiVersion(), NewMVType)) { 10561 NewFD->setInvalidDecl(); 10562 return true; 10563 } 10564 10565 // Permit forward declarations in the case where these two are compatible. 10566 if (!OldFD->isMultiVersion()) { 10567 OldFD->setIsMultiVersion(); 10568 NewFD->setIsMultiVersion(); 10569 Redeclaration = true; 10570 OldDecl = OldFD; 10571 return false; 10572 } 10573 10574 NewFD->setIsMultiVersion(); 10575 Redeclaration = false; 10576 MergeTypeWithPrevious = false; 10577 OldDecl = nullptr; 10578 Previous.clear(); 10579 return false; 10580 } 10581 10582 10583 /// Check the validity of a mulitversion function declaration. 10584 /// Also sets the multiversion'ness' of the function itself. 10585 /// 10586 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10587 /// 10588 /// Returns true if there was an error, false otherwise. 10589 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10590 bool &Redeclaration, NamedDecl *&OldDecl, 10591 bool &MergeTypeWithPrevious, 10592 LookupResult &Previous) { 10593 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10594 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10595 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10596 10597 // Mixing Multiversioning types is prohibited. 10598 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10599 (NewCPUDisp && NewCPUSpec)) { 10600 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10601 NewFD->setInvalidDecl(); 10602 return true; 10603 } 10604 10605 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10606 10607 // Main isn't allowed to become a multiversion function, however it IS 10608 // permitted to have 'main' be marked with the 'target' optimization hint. 10609 if (NewFD->isMain()) { 10610 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10611 MVType == MultiVersionKind::CPUDispatch || 10612 MVType == MultiVersionKind::CPUSpecific) { 10613 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10614 NewFD->setInvalidDecl(); 10615 return true; 10616 } 10617 return false; 10618 } 10619 10620 if (!OldDecl || !OldDecl->getAsFunction() || 10621 OldDecl->getDeclContext()->getRedeclContext() != 10622 NewFD->getDeclContext()->getRedeclContext()) { 10623 // If there's no previous declaration, AND this isn't attempting to cause 10624 // multiversioning, this isn't an error condition. 10625 if (MVType == MultiVersionKind::None) 10626 return false; 10627 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10628 } 10629 10630 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10631 10632 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10633 return false; 10634 10635 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10636 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10637 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10638 NewFD->setInvalidDecl(); 10639 return true; 10640 } 10641 10642 // Handle the target potentially causes multiversioning case. 10643 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10644 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10645 Redeclaration, OldDecl, 10646 MergeTypeWithPrevious, Previous); 10647 10648 // At this point, we have a multiversion function decl (in OldFD) AND an 10649 // appropriate attribute in the current function decl. Resolve that these are 10650 // still compatible with previous declarations. 10651 return CheckMultiVersionAdditionalDecl( 10652 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10653 OldDecl, MergeTypeWithPrevious, Previous); 10654 } 10655 10656 /// Perform semantic checking of a new function declaration. 10657 /// 10658 /// Performs semantic analysis of the new function declaration 10659 /// NewFD. This routine performs all semantic checking that does not 10660 /// require the actual declarator involved in the declaration, and is 10661 /// used both for the declaration of functions as they are parsed 10662 /// (called via ActOnDeclarator) and for the declaration of functions 10663 /// that have been instantiated via C++ template instantiation (called 10664 /// via InstantiateDecl). 10665 /// 10666 /// \param IsMemberSpecialization whether this new function declaration is 10667 /// a member specialization (that replaces any definition provided by the 10668 /// previous declaration). 10669 /// 10670 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10671 /// 10672 /// \returns true if the function declaration is a redeclaration. 10673 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10674 LookupResult &Previous, 10675 bool IsMemberSpecialization) { 10676 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10677 "Variably modified return types are not handled here"); 10678 10679 // Determine whether the type of this function should be merged with 10680 // a previous visible declaration. This never happens for functions in C++, 10681 // and always happens in C if the previous declaration was visible. 10682 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10683 !Previous.isShadowed(); 10684 10685 bool Redeclaration = false; 10686 NamedDecl *OldDecl = nullptr; 10687 bool MayNeedOverloadableChecks = false; 10688 10689 // Merge or overload the declaration with an existing declaration of 10690 // the same name, if appropriate. 10691 if (!Previous.empty()) { 10692 // Determine whether NewFD is an overload of PrevDecl or 10693 // a declaration that requires merging. If it's an overload, 10694 // there's no more work to do here; we'll just add the new 10695 // function to the scope. 10696 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10697 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10698 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10699 Redeclaration = true; 10700 OldDecl = Candidate; 10701 } 10702 } else { 10703 MayNeedOverloadableChecks = true; 10704 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10705 /*NewIsUsingDecl*/ false)) { 10706 case Ovl_Match: 10707 Redeclaration = true; 10708 break; 10709 10710 case Ovl_NonFunction: 10711 Redeclaration = true; 10712 break; 10713 10714 case Ovl_Overload: 10715 Redeclaration = false; 10716 break; 10717 } 10718 } 10719 } 10720 10721 // Check for a previous extern "C" declaration with this name. 10722 if (!Redeclaration && 10723 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10724 if (!Previous.empty()) { 10725 // This is an extern "C" declaration with the same name as a previous 10726 // declaration, and thus redeclares that entity... 10727 Redeclaration = true; 10728 OldDecl = Previous.getFoundDecl(); 10729 MergeTypeWithPrevious = false; 10730 10731 // ... except in the presence of __attribute__((overloadable)). 10732 if (OldDecl->hasAttr<OverloadableAttr>() || 10733 NewFD->hasAttr<OverloadableAttr>()) { 10734 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10735 MayNeedOverloadableChecks = true; 10736 Redeclaration = false; 10737 OldDecl = nullptr; 10738 } 10739 } 10740 } 10741 } 10742 10743 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10744 MergeTypeWithPrevious, Previous)) 10745 return Redeclaration; 10746 10747 // PPC MMA non-pointer types are not allowed as function return types. 10748 if (Context.getTargetInfo().getTriple().isPPC64() && 10749 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 10750 NewFD->setInvalidDecl(); 10751 } 10752 10753 // C++11 [dcl.constexpr]p8: 10754 // A constexpr specifier for a non-static member function that is not 10755 // a constructor declares that member function to be const. 10756 // 10757 // This needs to be delayed until we know whether this is an out-of-line 10758 // definition of a static member function. 10759 // 10760 // This rule is not present in C++1y, so we produce a backwards 10761 // compatibility warning whenever it happens in C++11. 10762 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10763 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10764 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10765 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10766 CXXMethodDecl *OldMD = nullptr; 10767 if (OldDecl) 10768 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10769 if (!OldMD || !OldMD->isStatic()) { 10770 const FunctionProtoType *FPT = 10771 MD->getType()->castAs<FunctionProtoType>(); 10772 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10773 EPI.TypeQuals.addConst(); 10774 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10775 FPT->getParamTypes(), EPI)); 10776 10777 // Warn that we did this, if we're not performing template instantiation. 10778 // In that case, we'll have warned already when the template was defined. 10779 if (!inTemplateInstantiation()) { 10780 SourceLocation AddConstLoc; 10781 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10782 .IgnoreParens().getAs<FunctionTypeLoc>()) 10783 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10784 10785 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10786 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10787 } 10788 } 10789 } 10790 10791 if (Redeclaration) { 10792 // NewFD and OldDecl represent declarations that need to be 10793 // merged. 10794 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10795 NewFD->setInvalidDecl(); 10796 return Redeclaration; 10797 } 10798 10799 Previous.clear(); 10800 Previous.addDecl(OldDecl); 10801 10802 if (FunctionTemplateDecl *OldTemplateDecl = 10803 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10804 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10805 FunctionTemplateDecl *NewTemplateDecl 10806 = NewFD->getDescribedFunctionTemplate(); 10807 assert(NewTemplateDecl && "Template/non-template mismatch"); 10808 10809 // The call to MergeFunctionDecl above may have created some state in 10810 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10811 // can add it as a redeclaration. 10812 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10813 10814 NewFD->setPreviousDeclaration(OldFD); 10815 if (NewFD->isCXXClassMember()) { 10816 NewFD->setAccess(OldTemplateDecl->getAccess()); 10817 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10818 } 10819 10820 // If this is an explicit specialization of a member that is a function 10821 // template, mark it as a member specialization. 10822 if (IsMemberSpecialization && 10823 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10824 NewTemplateDecl->setMemberSpecialization(); 10825 assert(OldTemplateDecl->isMemberSpecialization()); 10826 // Explicit specializations of a member template do not inherit deleted 10827 // status from the parent member template that they are specializing. 10828 if (OldFD->isDeleted()) { 10829 // FIXME: This assert will not hold in the presence of modules. 10830 assert(OldFD->getCanonicalDecl() == OldFD); 10831 // FIXME: We need an update record for this AST mutation. 10832 OldFD->setDeletedAsWritten(false); 10833 } 10834 } 10835 10836 } else { 10837 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10838 auto *OldFD = cast<FunctionDecl>(OldDecl); 10839 // This needs to happen first so that 'inline' propagates. 10840 NewFD->setPreviousDeclaration(OldFD); 10841 if (NewFD->isCXXClassMember()) 10842 NewFD->setAccess(OldFD->getAccess()); 10843 } 10844 } 10845 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10846 !NewFD->getAttr<OverloadableAttr>()) { 10847 assert((Previous.empty() || 10848 llvm::any_of(Previous, 10849 [](const NamedDecl *ND) { 10850 return ND->hasAttr<OverloadableAttr>(); 10851 })) && 10852 "Non-redecls shouldn't happen without overloadable present"); 10853 10854 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10855 const auto *FD = dyn_cast<FunctionDecl>(ND); 10856 return FD && !FD->hasAttr<OverloadableAttr>(); 10857 }); 10858 10859 if (OtherUnmarkedIter != Previous.end()) { 10860 Diag(NewFD->getLocation(), 10861 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10862 Diag((*OtherUnmarkedIter)->getLocation(), 10863 diag::note_attribute_overloadable_prev_overload) 10864 << false; 10865 10866 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10867 } 10868 } 10869 10870 if (LangOpts.OpenMP) 10871 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 10872 10873 // Semantic checking for this function declaration (in isolation). 10874 10875 if (getLangOpts().CPlusPlus) { 10876 // C++-specific checks. 10877 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10878 CheckConstructor(Constructor); 10879 } else if (CXXDestructorDecl *Destructor = 10880 dyn_cast<CXXDestructorDecl>(NewFD)) { 10881 CXXRecordDecl *Record = Destructor->getParent(); 10882 QualType ClassType = Context.getTypeDeclType(Record); 10883 10884 // FIXME: Shouldn't we be able to perform this check even when the class 10885 // type is dependent? Both gcc and edg can handle that. 10886 if (!ClassType->isDependentType()) { 10887 DeclarationName Name 10888 = Context.DeclarationNames.getCXXDestructorName( 10889 Context.getCanonicalType(ClassType)); 10890 if (NewFD->getDeclName() != Name) { 10891 Diag(NewFD->getLocation(), diag::err_destructor_name); 10892 NewFD->setInvalidDecl(); 10893 return Redeclaration; 10894 } 10895 } 10896 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10897 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10898 CheckDeductionGuideTemplate(TD); 10899 10900 // A deduction guide is not on the list of entities that can be 10901 // explicitly specialized. 10902 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10903 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10904 << /*explicit specialization*/ 1; 10905 } 10906 10907 // Find any virtual functions that this function overrides. 10908 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10909 if (!Method->isFunctionTemplateSpecialization() && 10910 !Method->getDescribedFunctionTemplate() && 10911 Method->isCanonicalDecl()) { 10912 AddOverriddenMethods(Method->getParent(), Method); 10913 } 10914 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10915 // C++2a [class.virtual]p6 10916 // A virtual method shall not have a requires-clause. 10917 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10918 diag::err_constrained_virtual_method); 10919 10920 if (Method->isStatic()) 10921 checkThisInStaticMemberFunctionType(Method); 10922 } 10923 10924 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 10925 ActOnConversionDeclarator(Conversion); 10926 10927 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10928 if (NewFD->isOverloadedOperator() && 10929 CheckOverloadedOperatorDeclaration(NewFD)) { 10930 NewFD->setInvalidDecl(); 10931 return Redeclaration; 10932 } 10933 10934 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10935 if (NewFD->getLiteralIdentifier() && 10936 CheckLiteralOperatorDeclaration(NewFD)) { 10937 NewFD->setInvalidDecl(); 10938 return Redeclaration; 10939 } 10940 10941 // In C++, check default arguments now that we have merged decls. Unless 10942 // the lexical context is the class, because in this case this is done 10943 // during delayed parsing anyway. 10944 if (!CurContext->isRecord()) 10945 CheckCXXDefaultArguments(NewFD); 10946 10947 // If this function declares a builtin function, check the type of this 10948 // declaration against the expected type for the builtin. 10949 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10950 ASTContext::GetBuiltinTypeError Error; 10951 LookupNecessaryTypesForBuiltin(S, BuiltinID); 10952 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10953 // If the type of the builtin differs only in its exception 10954 // specification, that's OK. 10955 // FIXME: If the types do differ in this way, it would be better to 10956 // retain the 'noexcept' form of the type. 10957 if (!T.isNull() && 10958 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10959 NewFD->getType())) 10960 // The type of this function differs from the type of the builtin, 10961 // so forget about the builtin entirely. 10962 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10963 } 10964 10965 // If this function is declared as being extern "C", then check to see if 10966 // the function returns a UDT (class, struct, or union type) that is not C 10967 // compatible, and if it does, warn the user. 10968 // But, issue any diagnostic on the first declaration only. 10969 if (Previous.empty() && NewFD->isExternC()) { 10970 QualType R = NewFD->getReturnType(); 10971 if (R->isIncompleteType() && !R->isVoidType()) 10972 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10973 << NewFD << R; 10974 else if (!R.isPODType(Context) && !R->isVoidType() && 10975 !R->isObjCObjectPointerType()) 10976 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10977 } 10978 10979 // C++1z [dcl.fct]p6: 10980 // [...] whether the function has a non-throwing exception-specification 10981 // [is] part of the function type 10982 // 10983 // This results in an ABI break between C++14 and C++17 for functions whose 10984 // declared type includes an exception-specification in a parameter or 10985 // return type. (Exception specifications on the function itself are OK in 10986 // most cases, and exception specifications are not permitted in most other 10987 // contexts where they could make it into a mangling.) 10988 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10989 auto HasNoexcept = [&](QualType T) -> bool { 10990 // Strip off declarator chunks that could be between us and a function 10991 // type. We don't need to look far, exception specifications are very 10992 // restricted prior to C++17. 10993 if (auto *RT = T->getAs<ReferenceType>()) 10994 T = RT->getPointeeType(); 10995 else if (T->isAnyPointerType()) 10996 T = T->getPointeeType(); 10997 else if (auto *MPT = T->getAs<MemberPointerType>()) 10998 T = MPT->getPointeeType(); 10999 if (auto *FPT = T->getAs<FunctionProtoType>()) 11000 if (FPT->isNothrow()) 11001 return true; 11002 return false; 11003 }; 11004 11005 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 11006 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 11007 for (QualType T : FPT->param_types()) 11008 AnyNoexcept |= HasNoexcept(T); 11009 if (AnyNoexcept) 11010 Diag(NewFD->getLocation(), 11011 diag::warn_cxx17_compat_exception_spec_in_signature) 11012 << NewFD; 11013 } 11014 11015 if (!Redeclaration && LangOpts.CUDA) 11016 checkCUDATargetOverload(NewFD, Previous); 11017 } 11018 return Redeclaration; 11019 } 11020 11021 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11022 // C++11 [basic.start.main]p3: 11023 // A program that [...] declares main to be inline, static or 11024 // constexpr is ill-formed. 11025 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11026 // appear in a declaration of main. 11027 // static main is not an error under C99, but we should warn about it. 11028 // We accept _Noreturn main as an extension. 11029 if (FD->getStorageClass() == SC_Static) 11030 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11031 ? diag::err_static_main : diag::warn_static_main) 11032 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11033 if (FD->isInlineSpecified()) 11034 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11035 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11036 if (DS.isNoreturnSpecified()) { 11037 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11038 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11039 Diag(NoreturnLoc, diag::ext_noreturn_main); 11040 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11041 << FixItHint::CreateRemoval(NoreturnRange); 11042 } 11043 if (FD->isConstexpr()) { 11044 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11045 << FD->isConsteval() 11046 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11047 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11048 } 11049 11050 if (getLangOpts().OpenCL) { 11051 Diag(FD->getLocation(), diag::err_opencl_no_main) 11052 << FD->hasAttr<OpenCLKernelAttr>(); 11053 FD->setInvalidDecl(); 11054 return; 11055 } 11056 11057 QualType T = FD->getType(); 11058 assert(T->isFunctionType() && "function decl is not of function type"); 11059 const FunctionType* FT = T->castAs<FunctionType>(); 11060 11061 // Set default calling convention for main() 11062 if (FT->getCallConv() != CC_C) { 11063 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11064 FD->setType(QualType(FT, 0)); 11065 T = Context.getCanonicalType(FD->getType()); 11066 } 11067 11068 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11069 // In C with GNU extensions we allow main() to have non-integer return 11070 // type, but we should warn about the extension, and we disable the 11071 // implicit-return-zero rule. 11072 11073 // GCC in C mode accepts qualified 'int'. 11074 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11075 FD->setHasImplicitReturnZero(true); 11076 else { 11077 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11078 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11079 if (RTRange.isValid()) 11080 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11081 << FixItHint::CreateReplacement(RTRange, "int"); 11082 } 11083 } else { 11084 // In C and C++, main magically returns 0 if you fall off the end; 11085 // set the flag which tells us that. 11086 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11087 11088 // All the standards say that main() should return 'int'. 11089 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11090 FD->setHasImplicitReturnZero(true); 11091 else { 11092 // Otherwise, this is just a flat-out error. 11093 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11094 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11095 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11096 : FixItHint()); 11097 FD->setInvalidDecl(true); 11098 } 11099 } 11100 11101 // Treat protoless main() as nullary. 11102 if (isa<FunctionNoProtoType>(FT)) return; 11103 11104 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11105 unsigned nparams = FTP->getNumParams(); 11106 assert(FD->getNumParams() == nparams); 11107 11108 bool HasExtraParameters = (nparams > 3); 11109 11110 if (FTP->isVariadic()) { 11111 Diag(FD->getLocation(), diag::ext_variadic_main); 11112 // FIXME: if we had information about the location of the ellipsis, we 11113 // could add a FixIt hint to remove it as a parameter. 11114 } 11115 11116 // Darwin passes an undocumented fourth argument of type char**. If 11117 // other platforms start sprouting these, the logic below will start 11118 // getting shifty. 11119 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11120 HasExtraParameters = false; 11121 11122 if (HasExtraParameters) { 11123 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11124 FD->setInvalidDecl(true); 11125 nparams = 3; 11126 } 11127 11128 // FIXME: a lot of the following diagnostics would be improved 11129 // if we had some location information about types. 11130 11131 QualType CharPP = 11132 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11133 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11134 11135 for (unsigned i = 0; i < nparams; ++i) { 11136 QualType AT = FTP->getParamType(i); 11137 11138 bool mismatch = true; 11139 11140 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11141 mismatch = false; 11142 else if (Expected[i] == CharPP) { 11143 // As an extension, the following forms are okay: 11144 // char const ** 11145 // char const * const * 11146 // char * const * 11147 11148 QualifierCollector qs; 11149 const PointerType* PT; 11150 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11151 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11152 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11153 Context.CharTy)) { 11154 qs.removeConst(); 11155 mismatch = !qs.empty(); 11156 } 11157 } 11158 11159 if (mismatch) { 11160 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11161 // TODO: suggest replacing given type with expected type 11162 FD->setInvalidDecl(true); 11163 } 11164 } 11165 11166 if (nparams == 1 && !FD->isInvalidDecl()) { 11167 Diag(FD->getLocation(), diag::warn_main_one_arg); 11168 } 11169 11170 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11171 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11172 FD->setInvalidDecl(); 11173 } 11174 } 11175 11176 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 11177 11178 // Default calling convention for main and wmain is __cdecl 11179 if (FD->getName() == "main" || FD->getName() == "wmain") 11180 return false; 11181 11182 // Default calling convention for MinGW is __cdecl 11183 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 11184 if (T.isWindowsGNUEnvironment()) 11185 return false; 11186 11187 // Default calling convention for WinMain, wWinMain and DllMain 11188 // is __stdcall on 32 bit Windows 11189 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 11190 return true; 11191 11192 return false; 11193 } 11194 11195 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11196 QualType T = FD->getType(); 11197 assert(T->isFunctionType() && "function decl is not of function type"); 11198 const FunctionType *FT = T->castAs<FunctionType>(); 11199 11200 // Set an implicit return of 'zero' if the function can return some integral, 11201 // enumeration, pointer or nullptr type. 11202 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11203 FT->getReturnType()->isAnyPointerType() || 11204 FT->getReturnType()->isNullPtrType()) 11205 // DllMain is exempt because a return value of zero means it failed. 11206 if (FD->getName() != "DllMain") 11207 FD->setHasImplicitReturnZero(true); 11208 11209 // Explicity specified calling conventions are applied to MSVC entry points 11210 if (!hasExplicitCallingConv(T)) { 11211 if (isDefaultStdCall(FD, *this)) { 11212 if (FT->getCallConv() != CC_X86StdCall) { 11213 FT = Context.adjustFunctionType( 11214 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 11215 FD->setType(QualType(FT, 0)); 11216 } 11217 } else if (FT->getCallConv() != CC_C) { 11218 FT = Context.adjustFunctionType(FT, 11219 FT->getExtInfo().withCallingConv(CC_C)); 11220 FD->setType(QualType(FT, 0)); 11221 } 11222 } 11223 11224 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11225 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11226 FD->setInvalidDecl(); 11227 } 11228 } 11229 11230 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11231 // FIXME: Need strict checking. In C89, we need to check for 11232 // any assignment, increment, decrement, function-calls, or 11233 // commas outside of a sizeof. In C99, it's the same list, 11234 // except that the aforementioned are allowed in unevaluated 11235 // expressions. Everything else falls under the 11236 // "may accept other forms of constant expressions" exception. 11237 // 11238 // Regular C++ code will not end up here (exceptions: language extensions, 11239 // OpenCL C++ etc), so the constant expression rules there don't matter. 11240 if (Init->isValueDependent()) { 11241 assert(Init->containsErrors() && 11242 "Dependent code should only occur in error-recovery path."); 11243 return true; 11244 } 11245 const Expr *Culprit; 11246 if (Init->isConstantInitializer(Context, false, &Culprit)) 11247 return false; 11248 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11249 << Culprit->getSourceRange(); 11250 return true; 11251 } 11252 11253 namespace { 11254 // Visits an initialization expression to see if OrigDecl is evaluated in 11255 // its own initialization and throws a warning if it does. 11256 class SelfReferenceChecker 11257 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11258 Sema &S; 11259 Decl *OrigDecl; 11260 bool isRecordType; 11261 bool isPODType; 11262 bool isReferenceType; 11263 11264 bool isInitList; 11265 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11266 11267 public: 11268 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11269 11270 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11271 S(S), OrigDecl(OrigDecl) { 11272 isPODType = false; 11273 isRecordType = false; 11274 isReferenceType = false; 11275 isInitList = false; 11276 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11277 isPODType = VD->getType().isPODType(S.Context); 11278 isRecordType = VD->getType()->isRecordType(); 11279 isReferenceType = VD->getType()->isReferenceType(); 11280 } 11281 } 11282 11283 // For most expressions, just call the visitor. For initializer lists, 11284 // track the index of the field being initialized since fields are 11285 // initialized in order allowing use of previously initialized fields. 11286 void CheckExpr(Expr *E) { 11287 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11288 if (!InitList) { 11289 Visit(E); 11290 return; 11291 } 11292 11293 // Track and increment the index here. 11294 isInitList = true; 11295 InitFieldIndex.push_back(0); 11296 for (auto Child : InitList->children()) { 11297 CheckExpr(cast<Expr>(Child)); 11298 ++InitFieldIndex.back(); 11299 } 11300 InitFieldIndex.pop_back(); 11301 } 11302 11303 // Returns true if MemberExpr is checked and no further checking is needed. 11304 // Returns false if additional checking is required. 11305 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11306 llvm::SmallVector<FieldDecl*, 4> Fields; 11307 Expr *Base = E; 11308 bool ReferenceField = false; 11309 11310 // Get the field members used. 11311 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11312 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11313 if (!FD) 11314 return false; 11315 Fields.push_back(FD); 11316 if (FD->getType()->isReferenceType()) 11317 ReferenceField = true; 11318 Base = ME->getBase()->IgnoreParenImpCasts(); 11319 } 11320 11321 // Keep checking only if the base Decl is the same. 11322 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11323 if (!DRE || DRE->getDecl() != OrigDecl) 11324 return false; 11325 11326 // A reference field can be bound to an unininitialized field. 11327 if (CheckReference && !ReferenceField) 11328 return true; 11329 11330 // Convert FieldDecls to their index number. 11331 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11332 for (const FieldDecl *I : llvm::reverse(Fields)) 11333 UsedFieldIndex.push_back(I->getFieldIndex()); 11334 11335 // See if a warning is needed by checking the first difference in index 11336 // numbers. If field being used has index less than the field being 11337 // initialized, then the use is safe. 11338 for (auto UsedIter = UsedFieldIndex.begin(), 11339 UsedEnd = UsedFieldIndex.end(), 11340 OrigIter = InitFieldIndex.begin(), 11341 OrigEnd = InitFieldIndex.end(); 11342 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11343 if (*UsedIter < *OrigIter) 11344 return true; 11345 if (*UsedIter > *OrigIter) 11346 break; 11347 } 11348 11349 // TODO: Add a different warning which will print the field names. 11350 HandleDeclRefExpr(DRE); 11351 return true; 11352 } 11353 11354 // For most expressions, the cast is directly above the DeclRefExpr. 11355 // For conditional operators, the cast can be outside the conditional 11356 // operator if both expressions are DeclRefExpr's. 11357 void HandleValue(Expr *E) { 11358 E = E->IgnoreParens(); 11359 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11360 HandleDeclRefExpr(DRE); 11361 return; 11362 } 11363 11364 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11365 Visit(CO->getCond()); 11366 HandleValue(CO->getTrueExpr()); 11367 HandleValue(CO->getFalseExpr()); 11368 return; 11369 } 11370 11371 if (BinaryConditionalOperator *BCO = 11372 dyn_cast<BinaryConditionalOperator>(E)) { 11373 Visit(BCO->getCond()); 11374 HandleValue(BCO->getFalseExpr()); 11375 return; 11376 } 11377 11378 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11379 HandleValue(OVE->getSourceExpr()); 11380 return; 11381 } 11382 11383 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11384 if (BO->getOpcode() == BO_Comma) { 11385 Visit(BO->getLHS()); 11386 HandleValue(BO->getRHS()); 11387 return; 11388 } 11389 } 11390 11391 if (isa<MemberExpr>(E)) { 11392 if (isInitList) { 11393 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11394 false /*CheckReference*/)) 11395 return; 11396 } 11397 11398 Expr *Base = E->IgnoreParenImpCasts(); 11399 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11400 // Check for static member variables and don't warn on them. 11401 if (!isa<FieldDecl>(ME->getMemberDecl())) 11402 return; 11403 Base = ME->getBase()->IgnoreParenImpCasts(); 11404 } 11405 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11406 HandleDeclRefExpr(DRE); 11407 return; 11408 } 11409 11410 Visit(E); 11411 } 11412 11413 // Reference types not handled in HandleValue are handled here since all 11414 // uses of references are bad, not just r-value uses. 11415 void VisitDeclRefExpr(DeclRefExpr *E) { 11416 if (isReferenceType) 11417 HandleDeclRefExpr(E); 11418 } 11419 11420 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11421 if (E->getCastKind() == CK_LValueToRValue) { 11422 HandleValue(E->getSubExpr()); 11423 return; 11424 } 11425 11426 Inherited::VisitImplicitCastExpr(E); 11427 } 11428 11429 void VisitMemberExpr(MemberExpr *E) { 11430 if (isInitList) { 11431 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11432 return; 11433 } 11434 11435 // Don't warn on arrays since they can be treated as pointers. 11436 if (E->getType()->canDecayToPointerType()) return; 11437 11438 // Warn when a non-static method call is followed by non-static member 11439 // field accesses, which is followed by a DeclRefExpr. 11440 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11441 bool Warn = (MD && !MD->isStatic()); 11442 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11443 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11444 if (!isa<FieldDecl>(ME->getMemberDecl())) 11445 Warn = false; 11446 Base = ME->getBase()->IgnoreParenImpCasts(); 11447 } 11448 11449 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11450 if (Warn) 11451 HandleDeclRefExpr(DRE); 11452 return; 11453 } 11454 11455 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11456 // Visit that expression. 11457 Visit(Base); 11458 } 11459 11460 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11461 Expr *Callee = E->getCallee(); 11462 11463 if (isa<UnresolvedLookupExpr>(Callee)) 11464 return Inherited::VisitCXXOperatorCallExpr(E); 11465 11466 Visit(Callee); 11467 for (auto Arg: E->arguments()) 11468 HandleValue(Arg->IgnoreParenImpCasts()); 11469 } 11470 11471 void VisitUnaryOperator(UnaryOperator *E) { 11472 // For POD record types, addresses of its own members are well-defined. 11473 if (E->getOpcode() == UO_AddrOf && isRecordType && 11474 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11475 if (!isPODType) 11476 HandleValue(E->getSubExpr()); 11477 return; 11478 } 11479 11480 if (E->isIncrementDecrementOp()) { 11481 HandleValue(E->getSubExpr()); 11482 return; 11483 } 11484 11485 Inherited::VisitUnaryOperator(E); 11486 } 11487 11488 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11489 11490 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11491 if (E->getConstructor()->isCopyConstructor()) { 11492 Expr *ArgExpr = E->getArg(0); 11493 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11494 if (ILE->getNumInits() == 1) 11495 ArgExpr = ILE->getInit(0); 11496 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11497 if (ICE->getCastKind() == CK_NoOp) 11498 ArgExpr = ICE->getSubExpr(); 11499 HandleValue(ArgExpr); 11500 return; 11501 } 11502 Inherited::VisitCXXConstructExpr(E); 11503 } 11504 11505 void VisitCallExpr(CallExpr *E) { 11506 // Treat std::move as a use. 11507 if (E->isCallToStdMove()) { 11508 HandleValue(E->getArg(0)); 11509 return; 11510 } 11511 11512 Inherited::VisitCallExpr(E); 11513 } 11514 11515 void VisitBinaryOperator(BinaryOperator *E) { 11516 if (E->isCompoundAssignmentOp()) { 11517 HandleValue(E->getLHS()); 11518 Visit(E->getRHS()); 11519 return; 11520 } 11521 11522 Inherited::VisitBinaryOperator(E); 11523 } 11524 11525 // A custom visitor for BinaryConditionalOperator is needed because the 11526 // regular visitor would check the condition and true expression separately 11527 // but both point to the same place giving duplicate diagnostics. 11528 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11529 Visit(E->getCond()); 11530 Visit(E->getFalseExpr()); 11531 } 11532 11533 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11534 Decl* ReferenceDecl = DRE->getDecl(); 11535 if (OrigDecl != ReferenceDecl) return; 11536 unsigned diag; 11537 if (isReferenceType) { 11538 diag = diag::warn_uninit_self_reference_in_reference_init; 11539 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11540 diag = diag::warn_static_self_reference_in_init; 11541 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11542 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11543 DRE->getDecl()->getType()->isRecordType()) { 11544 diag = diag::warn_uninit_self_reference_in_init; 11545 } else { 11546 // Local variables will be handled by the CFG analysis. 11547 return; 11548 } 11549 11550 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11551 S.PDiag(diag) 11552 << DRE->getDecl() << OrigDecl->getLocation() 11553 << DRE->getSourceRange()); 11554 } 11555 }; 11556 11557 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11558 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11559 bool DirectInit) { 11560 // Parameters arguments are occassionially constructed with itself, 11561 // for instance, in recursive functions. Skip them. 11562 if (isa<ParmVarDecl>(OrigDecl)) 11563 return; 11564 11565 E = E->IgnoreParens(); 11566 11567 // Skip checking T a = a where T is not a record or reference type. 11568 // Doing so is a way to silence uninitialized warnings. 11569 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11570 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11571 if (ICE->getCastKind() == CK_LValueToRValue) 11572 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11573 if (DRE->getDecl() == OrigDecl) 11574 return; 11575 11576 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11577 } 11578 } // end anonymous namespace 11579 11580 namespace { 11581 // Simple wrapper to add the name of a variable or (if no variable is 11582 // available) a DeclarationName into a diagnostic. 11583 struct VarDeclOrName { 11584 VarDecl *VDecl; 11585 DeclarationName Name; 11586 11587 friend const Sema::SemaDiagnosticBuilder & 11588 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11589 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11590 } 11591 }; 11592 } // end anonymous namespace 11593 11594 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11595 DeclarationName Name, QualType Type, 11596 TypeSourceInfo *TSI, 11597 SourceRange Range, bool DirectInit, 11598 Expr *Init) { 11599 bool IsInitCapture = !VDecl; 11600 assert((!VDecl || !VDecl->isInitCapture()) && 11601 "init captures are expected to be deduced prior to initialization"); 11602 11603 VarDeclOrName VN{VDecl, Name}; 11604 11605 DeducedType *Deduced = Type->getContainedDeducedType(); 11606 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11607 11608 // C++11 [dcl.spec.auto]p3 11609 if (!Init) { 11610 assert(VDecl && "no init for init capture deduction?"); 11611 11612 // Except for class argument deduction, and then for an initializing 11613 // declaration only, i.e. no static at class scope or extern. 11614 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11615 VDecl->hasExternalStorage() || 11616 VDecl->isStaticDataMember()) { 11617 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11618 << VDecl->getDeclName() << Type; 11619 return QualType(); 11620 } 11621 } 11622 11623 ArrayRef<Expr*> DeduceInits; 11624 if (Init) 11625 DeduceInits = Init; 11626 11627 if (DirectInit) { 11628 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11629 DeduceInits = PL->exprs(); 11630 } 11631 11632 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11633 assert(VDecl && "non-auto type for init capture deduction?"); 11634 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11635 InitializationKind Kind = InitializationKind::CreateForInit( 11636 VDecl->getLocation(), DirectInit, Init); 11637 // FIXME: Initialization should not be taking a mutable list of inits. 11638 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11639 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11640 InitsCopy); 11641 } 11642 11643 if (DirectInit) { 11644 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11645 DeduceInits = IL->inits(); 11646 } 11647 11648 // Deduction only works if we have exactly one source expression. 11649 if (DeduceInits.empty()) { 11650 // It isn't possible to write this directly, but it is possible to 11651 // end up in this situation with "auto x(some_pack...);" 11652 Diag(Init->getBeginLoc(), IsInitCapture 11653 ? diag::err_init_capture_no_expression 11654 : diag::err_auto_var_init_no_expression) 11655 << VN << Type << Range; 11656 return QualType(); 11657 } 11658 11659 if (DeduceInits.size() > 1) { 11660 Diag(DeduceInits[1]->getBeginLoc(), 11661 IsInitCapture ? diag::err_init_capture_multiple_expressions 11662 : diag::err_auto_var_init_multiple_expressions) 11663 << VN << Type << Range; 11664 return QualType(); 11665 } 11666 11667 Expr *DeduceInit = DeduceInits[0]; 11668 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11669 Diag(Init->getBeginLoc(), IsInitCapture 11670 ? diag::err_init_capture_paren_braces 11671 : diag::err_auto_var_init_paren_braces) 11672 << isa<InitListExpr>(Init) << VN << Type << Range; 11673 return QualType(); 11674 } 11675 11676 // Expressions default to 'id' when we're in a debugger. 11677 bool DefaultedAnyToId = false; 11678 if (getLangOpts().DebuggerCastResultToId && 11679 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11680 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11681 if (Result.isInvalid()) { 11682 return QualType(); 11683 } 11684 Init = Result.get(); 11685 DefaultedAnyToId = true; 11686 } 11687 11688 // C++ [dcl.decomp]p1: 11689 // If the assignment-expression [...] has array type A and no ref-qualifier 11690 // is present, e has type cv A 11691 if (VDecl && isa<DecompositionDecl>(VDecl) && 11692 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11693 DeduceInit->getType()->isConstantArrayType()) 11694 return Context.getQualifiedType(DeduceInit->getType(), 11695 Type.getQualifiers()); 11696 11697 QualType DeducedType; 11698 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11699 if (!IsInitCapture) 11700 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11701 else if (isa<InitListExpr>(Init)) 11702 Diag(Range.getBegin(), 11703 diag::err_init_capture_deduction_failure_from_init_list) 11704 << VN 11705 << (DeduceInit->getType().isNull() ? TSI->getType() 11706 : DeduceInit->getType()) 11707 << DeduceInit->getSourceRange(); 11708 else 11709 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11710 << VN << TSI->getType() 11711 << (DeduceInit->getType().isNull() ? TSI->getType() 11712 : DeduceInit->getType()) 11713 << DeduceInit->getSourceRange(); 11714 } 11715 11716 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11717 // 'id' instead of a specific object type prevents most of our usual 11718 // checks. 11719 // We only want to warn outside of template instantiations, though: 11720 // inside a template, the 'id' could have come from a parameter. 11721 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11722 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11723 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11724 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11725 } 11726 11727 return DeducedType; 11728 } 11729 11730 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11731 Expr *Init) { 11732 assert(!Init || !Init->containsErrors()); 11733 QualType DeducedType = deduceVarTypeFromInitializer( 11734 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11735 VDecl->getSourceRange(), DirectInit, Init); 11736 if (DeducedType.isNull()) { 11737 VDecl->setInvalidDecl(); 11738 return true; 11739 } 11740 11741 VDecl->setType(DeducedType); 11742 assert(VDecl->isLinkageValid()); 11743 11744 // In ARC, infer lifetime. 11745 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11746 VDecl->setInvalidDecl(); 11747 11748 if (getLangOpts().OpenCL) 11749 deduceOpenCLAddressSpace(VDecl); 11750 11751 // If this is a redeclaration, check that the type we just deduced matches 11752 // the previously declared type. 11753 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11754 // We never need to merge the type, because we cannot form an incomplete 11755 // array of auto, nor deduce such a type. 11756 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11757 } 11758 11759 // Check the deduced type is valid for a variable declaration. 11760 CheckVariableDeclarationType(VDecl); 11761 return VDecl->isInvalidDecl(); 11762 } 11763 11764 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11765 SourceLocation Loc) { 11766 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11767 Init = EWC->getSubExpr(); 11768 11769 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11770 Init = CE->getSubExpr(); 11771 11772 QualType InitType = Init->getType(); 11773 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11774 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11775 "shouldn't be called if type doesn't have a non-trivial C struct"); 11776 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11777 for (auto I : ILE->inits()) { 11778 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11779 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11780 continue; 11781 SourceLocation SL = I->getExprLoc(); 11782 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11783 } 11784 return; 11785 } 11786 11787 if (isa<ImplicitValueInitExpr>(Init)) { 11788 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11789 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11790 NTCUK_Init); 11791 } else { 11792 // Assume all other explicit initializers involving copying some existing 11793 // object. 11794 // TODO: ignore any explicit initializers where we can guarantee 11795 // copy-elision. 11796 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11797 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11798 } 11799 } 11800 11801 namespace { 11802 11803 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11804 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11805 // in the source code or implicitly by the compiler if it is in a union 11806 // defined in a system header and has non-trivial ObjC ownership 11807 // qualifications. We don't want those fields to participate in determining 11808 // whether the containing union is non-trivial. 11809 return FD->hasAttr<UnavailableAttr>(); 11810 } 11811 11812 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11813 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11814 void> { 11815 using Super = 11816 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11817 void>; 11818 11819 DiagNonTrivalCUnionDefaultInitializeVisitor( 11820 QualType OrigTy, SourceLocation OrigLoc, 11821 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11822 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11823 11824 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11825 const FieldDecl *FD, bool InNonTrivialUnion) { 11826 if (const auto *AT = S.Context.getAsArrayType(QT)) 11827 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11828 InNonTrivialUnion); 11829 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11830 } 11831 11832 void visitARCStrong(QualType QT, const FieldDecl *FD, 11833 bool InNonTrivialUnion) { 11834 if (InNonTrivialUnion) 11835 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11836 << 1 << 0 << QT << FD->getName(); 11837 } 11838 11839 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11840 if (InNonTrivialUnion) 11841 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11842 << 1 << 0 << QT << FD->getName(); 11843 } 11844 11845 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11846 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11847 if (RD->isUnion()) { 11848 if (OrigLoc.isValid()) { 11849 bool IsUnion = false; 11850 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11851 IsUnion = OrigRD->isUnion(); 11852 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11853 << 0 << OrigTy << IsUnion << UseContext; 11854 // Reset OrigLoc so that this diagnostic is emitted only once. 11855 OrigLoc = SourceLocation(); 11856 } 11857 InNonTrivialUnion = true; 11858 } 11859 11860 if (InNonTrivialUnion) 11861 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11862 << 0 << 0 << QT.getUnqualifiedType() << ""; 11863 11864 for (const FieldDecl *FD : RD->fields()) 11865 if (!shouldIgnoreForRecordTriviality(FD)) 11866 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11867 } 11868 11869 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11870 11871 // The non-trivial C union type or the struct/union type that contains a 11872 // non-trivial C union. 11873 QualType OrigTy; 11874 SourceLocation OrigLoc; 11875 Sema::NonTrivialCUnionContext UseContext; 11876 Sema &S; 11877 }; 11878 11879 struct DiagNonTrivalCUnionDestructedTypeVisitor 11880 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11881 using Super = 11882 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11883 11884 DiagNonTrivalCUnionDestructedTypeVisitor( 11885 QualType OrigTy, SourceLocation OrigLoc, 11886 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11887 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11888 11889 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11890 const FieldDecl *FD, bool InNonTrivialUnion) { 11891 if (const auto *AT = S.Context.getAsArrayType(QT)) 11892 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11893 InNonTrivialUnion); 11894 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11895 } 11896 11897 void visitARCStrong(QualType QT, const FieldDecl *FD, 11898 bool InNonTrivialUnion) { 11899 if (InNonTrivialUnion) 11900 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11901 << 1 << 1 << QT << FD->getName(); 11902 } 11903 11904 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11905 if (InNonTrivialUnion) 11906 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11907 << 1 << 1 << QT << FD->getName(); 11908 } 11909 11910 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11911 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11912 if (RD->isUnion()) { 11913 if (OrigLoc.isValid()) { 11914 bool IsUnion = false; 11915 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11916 IsUnion = OrigRD->isUnion(); 11917 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11918 << 1 << OrigTy << IsUnion << UseContext; 11919 // Reset OrigLoc so that this diagnostic is emitted only once. 11920 OrigLoc = SourceLocation(); 11921 } 11922 InNonTrivialUnion = true; 11923 } 11924 11925 if (InNonTrivialUnion) 11926 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11927 << 0 << 1 << QT.getUnqualifiedType() << ""; 11928 11929 for (const FieldDecl *FD : RD->fields()) 11930 if (!shouldIgnoreForRecordTriviality(FD)) 11931 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11932 } 11933 11934 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11935 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11936 bool InNonTrivialUnion) {} 11937 11938 // The non-trivial C union type or the struct/union type that contains a 11939 // non-trivial C union. 11940 QualType OrigTy; 11941 SourceLocation OrigLoc; 11942 Sema::NonTrivialCUnionContext UseContext; 11943 Sema &S; 11944 }; 11945 11946 struct DiagNonTrivalCUnionCopyVisitor 11947 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11948 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11949 11950 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11951 Sema::NonTrivialCUnionContext UseContext, 11952 Sema &S) 11953 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11954 11955 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11956 const FieldDecl *FD, bool InNonTrivialUnion) { 11957 if (const auto *AT = S.Context.getAsArrayType(QT)) 11958 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11959 InNonTrivialUnion); 11960 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11961 } 11962 11963 void visitARCStrong(QualType QT, const FieldDecl *FD, 11964 bool InNonTrivialUnion) { 11965 if (InNonTrivialUnion) 11966 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11967 << 1 << 2 << QT << FD->getName(); 11968 } 11969 11970 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11971 if (InNonTrivialUnion) 11972 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11973 << 1 << 2 << QT << FD->getName(); 11974 } 11975 11976 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11977 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11978 if (RD->isUnion()) { 11979 if (OrigLoc.isValid()) { 11980 bool IsUnion = false; 11981 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11982 IsUnion = OrigRD->isUnion(); 11983 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11984 << 2 << OrigTy << IsUnion << UseContext; 11985 // Reset OrigLoc so that this diagnostic is emitted only once. 11986 OrigLoc = SourceLocation(); 11987 } 11988 InNonTrivialUnion = true; 11989 } 11990 11991 if (InNonTrivialUnion) 11992 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11993 << 0 << 2 << QT.getUnqualifiedType() << ""; 11994 11995 for (const FieldDecl *FD : RD->fields()) 11996 if (!shouldIgnoreForRecordTriviality(FD)) 11997 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11998 } 11999 12000 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 12001 const FieldDecl *FD, bool InNonTrivialUnion) {} 12002 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12003 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 12004 bool InNonTrivialUnion) {} 12005 12006 // The non-trivial C union type or the struct/union type that contains a 12007 // non-trivial C union. 12008 QualType OrigTy; 12009 SourceLocation OrigLoc; 12010 Sema::NonTrivialCUnionContext UseContext; 12011 Sema &S; 12012 }; 12013 12014 } // namespace 12015 12016 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 12017 NonTrivialCUnionContext UseContext, 12018 unsigned NonTrivialKind) { 12019 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12020 QT.hasNonTrivialToPrimitiveDestructCUnion() || 12021 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 12022 "shouldn't be called if type doesn't have a non-trivial C union"); 12023 12024 if ((NonTrivialKind & NTCUK_Init) && 12025 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12026 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 12027 .visit(QT, nullptr, false); 12028 if ((NonTrivialKind & NTCUK_Destruct) && 12029 QT.hasNonTrivialToPrimitiveDestructCUnion()) 12030 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 12031 .visit(QT, nullptr, false); 12032 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 12033 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 12034 .visit(QT, nullptr, false); 12035 } 12036 12037 /// AddInitializerToDecl - Adds the initializer Init to the 12038 /// declaration dcl. If DirectInit is true, this is C++ direct 12039 /// initialization rather than copy initialization. 12040 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 12041 // If there is no declaration, there was an error parsing it. Just ignore 12042 // the initializer. 12043 if (!RealDecl || RealDecl->isInvalidDecl()) { 12044 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 12045 return; 12046 } 12047 12048 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 12049 // Pure-specifiers are handled in ActOnPureSpecifier. 12050 Diag(Method->getLocation(), diag::err_member_function_initialization) 12051 << Method->getDeclName() << Init->getSourceRange(); 12052 Method->setInvalidDecl(); 12053 return; 12054 } 12055 12056 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12057 if (!VDecl) { 12058 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 12059 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12060 RealDecl->setInvalidDecl(); 12061 return; 12062 } 12063 12064 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12065 if (VDecl->getType()->isUndeducedType()) { 12066 // Attempt typo correction early so that the type of the init expression can 12067 // be deduced based on the chosen correction if the original init contains a 12068 // TypoExpr. 12069 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12070 if (!Res.isUsable()) { 12071 // There are unresolved typos in Init, just drop them. 12072 // FIXME: improve the recovery strategy to preserve the Init. 12073 RealDecl->setInvalidDecl(); 12074 return; 12075 } 12076 if (Res.get()->containsErrors()) { 12077 // Invalidate the decl as we don't know the type for recovery-expr yet. 12078 RealDecl->setInvalidDecl(); 12079 VDecl->setInit(Res.get()); 12080 return; 12081 } 12082 Init = Res.get(); 12083 12084 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12085 return; 12086 } 12087 12088 // dllimport cannot be used on variable definitions. 12089 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12090 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12091 VDecl->setInvalidDecl(); 12092 return; 12093 } 12094 12095 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12096 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12097 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12098 VDecl->setInvalidDecl(); 12099 return; 12100 } 12101 12102 if (!VDecl->getType()->isDependentType()) { 12103 // A definition must end up with a complete type, which means it must be 12104 // complete with the restriction that an array type might be completed by 12105 // the initializer; note that later code assumes this restriction. 12106 QualType BaseDeclType = VDecl->getType(); 12107 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12108 BaseDeclType = Array->getElementType(); 12109 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12110 diag::err_typecheck_decl_incomplete_type)) { 12111 RealDecl->setInvalidDecl(); 12112 return; 12113 } 12114 12115 // The variable can not have an abstract class type. 12116 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12117 diag::err_abstract_type_in_decl, 12118 AbstractVariableType)) 12119 VDecl->setInvalidDecl(); 12120 } 12121 12122 // If adding the initializer will turn this declaration into a definition, 12123 // and we already have a definition for this variable, diagnose or otherwise 12124 // handle the situation. 12125 VarDecl *Def; 12126 if ((Def = VDecl->getDefinition()) && Def != VDecl && 12127 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12128 !VDecl->isThisDeclarationADemotedDefinition() && 12129 checkVarDeclRedefinition(Def, VDecl)) 12130 return; 12131 12132 if (getLangOpts().CPlusPlus) { 12133 // C++ [class.static.data]p4 12134 // If a static data member is of const integral or const 12135 // enumeration type, its declaration in the class definition can 12136 // specify a constant-initializer which shall be an integral 12137 // constant expression (5.19). In that case, the member can appear 12138 // in integral constant expressions. The member shall still be 12139 // defined in a namespace scope if it is used in the program and the 12140 // namespace scope definition shall not contain an initializer. 12141 // 12142 // We already performed a redefinition check above, but for static 12143 // data members we also need to check whether there was an in-class 12144 // declaration with an initializer. 12145 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12146 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12147 << VDecl->getDeclName(); 12148 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12149 diag::note_previous_initializer) 12150 << 0; 12151 return; 12152 } 12153 12154 if (VDecl->hasLocalStorage()) 12155 setFunctionHasBranchProtectedScope(); 12156 12157 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12158 VDecl->setInvalidDecl(); 12159 return; 12160 } 12161 } 12162 12163 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12164 // a kernel function cannot be initialized." 12165 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12166 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12167 VDecl->setInvalidDecl(); 12168 return; 12169 } 12170 12171 // The LoaderUninitialized attribute acts as a definition (of undef). 12172 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12173 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12174 VDecl->setInvalidDecl(); 12175 return; 12176 } 12177 12178 // Get the decls type and save a reference for later, since 12179 // CheckInitializerTypes may change it. 12180 QualType DclT = VDecl->getType(), SavT = DclT; 12181 12182 // Expressions default to 'id' when we're in a debugger 12183 // and we are assigning it to a variable of Objective-C pointer type. 12184 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12185 Init->getType() == Context.UnknownAnyTy) { 12186 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12187 if (Result.isInvalid()) { 12188 VDecl->setInvalidDecl(); 12189 return; 12190 } 12191 Init = Result.get(); 12192 } 12193 12194 // Perform the initialization. 12195 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12196 if (!VDecl->isInvalidDecl()) { 12197 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12198 InitializationKind Kind = InitializationKind::CreateForInit( 12199 VDecl->getLocation(), DirectInit, Init); 12200 12201 MultiExprArg Args = Init; 12202 if (CXXDirectInit) 12203 Args = MultiExprArg(CXXDirectInit->getExprs(), 12204 CXXDirectInit->getNumExprs()); 12205 12206 // Try to correct any TypoExprs in the initialization arguments. 12207 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12208 ExprResult Res = CorrectDelayedTyposInExpr( 12209 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12210 [this, Entity, Kind](Expr *E) { 12211 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12212 return Init.Failed() ? ExprError() : E; 12213 }); 12214 if (Res.isInvalid()) { 12215 VDecl->setInvalidDecl(); 12216 } else if (Res.get() != Args[Idx]) { 12217 Args[Idx] = Res.get(); 12218 } 12219 } 12220 if (VDecl->isInvalidDecl()) 12221 return; 12222 12223 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12224 /*TopLevelOfInitList=*/false, 12225 /*TreatUnavailableAsInvalid=*/false); 12226 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12227 if (Result.isInvalid()) { 12228 // If the provied initializer fails to initialize the var decl, 12229 // we attach a recovery expr for better recovery. 12230 auto RecoveryExpr = 12231 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12232 if (RecoveryExpr.get()) 12233 VDecl->setInit(RecoveryExpr.get()); 12234 return; 12235 } 12236 12237 Init = Result.getAs<Expr>(); 12238 } 12239 12240 // Check for self-references within variable initializers. 12241 // Variables declared within a function/method body (except for references) 12242 // are handled by a dataflow analysis. 12243 // This is undefined behavior in C++, but valid in C. 12244 if (getLangOpts().CPlusPlus) { 12245 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12246 VDecl->getType()->isReferenceType()) { 12247 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12248 } 12249 } 12250 12251 // If the type changed, it means we had an incomplete type that was 12252 // completed by the initializer. For example: 12253 // int ary[] = { 1, 3, 5 }; 12254 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12255 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12256 VDecl->setType(DclT); 12257 12258 if (!VDecl->isInvalidDecl()) { 12259 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12260 12261 if (VDecl->hasAttr<BlocksAttr>()) 12262 checkRetainCycles(VDecl, Init); 12263 12264 // It is safe to assign a weak reference into a strong variable. 12265 // Although this code can still have problems: 12266 // id x = self.weakProp; 12267 // id y = self.weakProp; 12268 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12269 // paths through the function. This should be revisited if 12270 // -Wrepeated-use-of-weak is made flow-sensitive. 12271 if (FunctionScopeInfo *FSI = getCurFunction()) 12272 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12273 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12274 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12275 Init->getBeginLoc())) 12276 FSI->markSafeWeakUse(Init); 12277 } 12278 12279 // The initialization is usually a full-expression. 12280 // 12281 // FIXME: If this is a braced initialization of an aggregate, it is not 12282 // an expression, and each individual field initializer is a separate 12283 // full-expression. For instance, in: 12284 // 12285 // struct Temp { ~Temp(); }; 12286 // struct S { S(Temp); }; 12287 // struct T { S a, b; } t = { Temp(), Temp() } 12288 // 12289 // we should destroy the first Temp before constructing the second. 12290 ExprResult Result = 12291 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12292 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12293 if (Result.isInvalid()) { 12294 VDecl->setInvalidDecl(); 12295 return; 12296 } 12297 Init = Result.get(); 12298 12299 // Attach the initializer to the decl. 12300 VDecl->setInit(Init); 12301 12302 if (VDecl->isLocalVarDecl()) { 12303 // Don't check the initializer if the declaration is malformed. 12304 if (VDecl->isInvalidDecl()) { 12305 // do nothing 12306 12307 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12308 // This is true even in C++ for OpenCL. 12309 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12310 CheckForConstantInitializer(Init, DclT); 12311 12312 // Otherwise, C++ does not restrict the initializer. 12313 } else if (getLangOpts().CPlusPlus) { 12314 // do nothing 12315 12316 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12317 // static storage duration shall be constant expressions or string literals. 12318 } else if (VDecl->getStorageClass() == SC_Static) { 12319 CheckForConstantInitializer(Init, DclT); 12320 12321 // C89 is stricter than C99 for aggregate initializers. 12322 // C89 6.5.7p3: All the expressions [...] in an initializer list 12323 // for an object that has aggregate or union type shall be 12324 // constant expressions. 12325 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12326 isa<InitListExpr>(Init)) { 12327 const Expr *Culprit; 12328 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12329 Diag(Culprit->getExprLoc(), 12330 diag::ext_aggregate_init_not_constant) 12331 << Culprit->getSourceRange(); 12332 } 12333 } 12334 12335 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12336 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12337 if (VDecl->hasLocalStorage()) 12338 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12339 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12340 VDecl->getLexicalDeclContext()->isRecord()) { 12341 // This is an in-class initialization for a static data member, e.g., 12342 // 12343 // struct S { 12344 // static const int value = 17; 12345 // }; 12346 12347 // C++ [class.mem]p4: 12348 // A member-declarator can contain a constant-initializer only 12349 // if it declares a static member (9.4) of const integral or 12350 // const enumeration type, see 9.4.2. 12351 // 12352 // C++11 [class.static.data]p3: 12353 // If a non-volatile non-inline const static data member is of integral 12354 // or enumeration type, its declaration in the class definition can 12355 // specify a brace-or-equal-initializer in which every initializer-clause 12356 // that is an assignment-expression is a constant expression. A static 12357 // data member of literal type can be declared in the class definition 12358 // with the constexpr specifier; if so, its declaration shall specify a 12359 // brace-or-equal-initializer in which every initializer-clause that is 12360 // an assignment-expression is a constant expression. 12361 12362 // Do nothing on dependent types. 12363 if (DclT->isDependentType()) { 12364 12365 // Allow any 'static constexpr' members, whether or not they are of literal 12366 // type. We separately check that every constexpr variable is of literal 12367 // type. 12368 } else if (VDecl->isConstexpr()) { 12369 12370 // Require constness. 12371 } else if (!DclT.isConstQualified()) { 12372 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12373 << Init->getSourceRange(); 12374 VDecl->setInvalidDecl(); 12375 12376 // We allow integer constant expressions in all cases. 12377 } else if (DclT->isIntegralOrEnumerationType()) { 12378 // Check whether the expression is a constant expression. 12379 SourceLocation Loc; 12380 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12381 // In C++11, a non-constexpr const static data member with an 12382 // in-class initializer cannot be volatile. 12383 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12384 else if (Init->isValueDependent()) 12385 ; // Nothing to check. 12386 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12387 ; // Ok, it's an ICE! 12388 else if (Init->getType()->isScopedEnumeralType() && 12389 Init->isCXX11ConstantExpr(Context)) 12390 ; // Ok, it is a scoped-enum constant expression. 12391 else if (Init->isEvaluatable(Context)) { 12392 // If we can constant fold the initializer through heroics, accept it, 12393 // but report this as a use of an extension for -pedantic. 12394 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12395 << Init->getSourceRange(); 12396 } else { 12397 // Otherwise, this is some crazy unknown case. Report the issue at the 12398 // location provided by the isIntegerConstantExpr failed check. 12399 Diag(Loc, diag::err_in_class_initializer_non_constant) 12400 << Init->getSourceRange(); 12401 VDecl->setInvalidDecl(); 12402 } 12403 12404 // We allow foldable floating-point constants as an extension. 12405 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12406 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12407 // it anyway and provide a fixit to add the 'constexpr'. 12408 if (getLangOpts().CPlusPlus11) { 12409 Diag(VDecl->getLocation(), 12410 diag::ext_in_class_initializer_float_type_cxx11) 12411 << DclT << Init->getSourceRange(); 12412 Diag(VDecl->getBeginLoc(), 12413 diag::note_in_class_initializer_float_type_cxx11) 12414 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12415 } else { 12416 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12417 << DclT << Init->getSourceRange(); 12418 12419 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12420 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12421 << Init->getSourceRange(); 12422 VDecl->setInvalidDecl(); 12423 } 12424 } 12425 12426 // Suggest adding 'constexpr' in C++11 for literal types. 12427 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12428 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12429 << DclT << Init->getSourceRange() 12430 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12431 VDecl->setConstexpr(true); 12432 12433 } else { 12434 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12435 << DclT << Init->getSourceRange(); 12436 VDecl->setInvalidDecl(); 12437 } 12438 } else if (VDecl->isFileVarDecl()) { 12439 // In C, extern is typically used to avoid tentative definitions when 12440 // declaring variables in headers, but adding an intializer makes it a 12441 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12442 // In C++, extern is often used to give implictly static const variables 12443 // external linkage, so don't warn in that case. If selectany is present, 12444 // this might be header code intended for C and C++ inclusion, so apply the 12445 // C++ rules. 12446 if (VDecl->getStorageClass() == SC_Extern && 12447 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12448 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12449 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12450 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12451 Diag(VDecl->getLocation(), diag::warn_extern_init); 12452 12453 // In Microsoft C++ mode, a const variable defined in namespace scope has 12454 // external linkage by default if the variable is declared with 12455 // __declspec(dllexport). 12456 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12457 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12458 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12459 VDecl->setStorageClass(SC_Extern); 12460 12461 // C99 6.7.8p4. All file scoped initializers need to be constant. 12462 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12463 CheckForConstantInitializer(Init, DclT); 12464 } 12465 12466 QualType InitType = Init->getType(); 12467 if (!InitType.isNull() && 12468 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12469 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12470 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12471 12472 // We will represent direct-initialization similarly to copy-initialization: 12473 // int x(1); -as-> int x = 1; 12474 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12475 // 12476 // Clients that want to distinguish between the two forms, can check for 12477 // direct initializer using VarDecl::getInitStyle(). 12478 // A major benefit is that clients that don't particularly care about which 12479 // exactly form was it (like the CodeGen) can handle both cases without 12480 // special case code. 12481 12482 // C++ 8.5p11: 12483 // The form of initialization (using parentheses or '=') is generally 12484 // insignificant, but does matter when the entity being initialized has a 12485 // class type. 12486 if (CXXDirectInit) { 12487 assert(DirectInit && "Call-style initializer must be direct init."); 12488 VDecl->setInitStyle(VarDecl::CallInit); 12489 } else if (DirectInit) { 12490 // This must be list-initialization. No other way is direct-initialization. 12491 VDecl->setInitStyle(VarDecl::ListInit); 12492 } 12493 12494 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12495 DeclsToCheckForDeferredDiags.push_back(VDecl); 12496 CheckCompleteVariableDeclaration(VDecl); 12497 } 12498 12499 /// ActOnInitializerError - Given that there was an error parsing an 12500 /// initializer for the given declaration, try to return to some form 12501 /// of sanity. 12502 void Sema::ActOnInitializerError(Decl *D) { 12503 // Our main concern here is re-establishing invariants like "a 12504 // variable's type is either dependent or complete". 12505 if (!D || D->isInvalidDecl()) return; 12506 12507 VarDecl *VD = dyn_cast<VarDecl>(D); 12508 if (!VD) return; 12509 12510 // Bindings are not usable if we can't make sense of the initializer. 12511 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12512 for (auto *BD : DD->bindings()) 12513 BD->setInvalidDecl(); 12514 12515 // Auto types are meaningless if we can't make sense of the initializer. 12516 if (VD->getType()->isUndeducedType()) { 12517 D->setInvalidDecl(); 12518 return; 12519 } 12520 12521 QualType Ty = VD->getType(); 12522 if (Ty->isDependentType()) return; 12523 12524 // Require a complete type. 12525 if (RequireCompleteType(VD->getLocation(), 12526 Context.getBaseElementType(Ty), 12527 diag::err_typecheck_decl_incomplete_type)) { 12528 VD->setInvalidDecl(); 12529 return; 12530 } 12531 12532 // Require a non-abstract type. 12533 if (RequireNonAbstractType(VD->getLocation(), Ty, 12534 diag::err_abstract_type_in_decl, 12535 AbstractVariableType)) { 12536 VD->setInvalidDecl(); 12537 return; 12538 } 12539 12540 // Don't bother complaining about constructors or destructors, 12541 // though. 12542 } 12543 12544 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12545 // If there is no declaration, there was an error parsing it. Just ignore it. 12546 if (!RealDecl) 12547 return; 12548 12549 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12550 QualType Type = Var->getType(); 12551 12552 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12553 if (isa<DecompositionDecl>(RealDecl)) { 12554 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12555 Var->setInvalidDecl(); 12556 return; 12557 } 12558 12559 if (Type->isUndeducedType() && 12560 DeduceVariableDeclarationType(Var, false, nullptr)) 12561 return; 12562 12563 // C++11 [class.static.data]p3: A static data member can be declared with 12564 // the constexpr specifier; if so, its declaration shall specify 12565 // a brace-or-equal-initializer. 12566 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12567 // the definition of a variable [...] or the declaration of a static data 12568 // member. 12569 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12570 !Var->isThisDeclarationADemotedDefinition()) { 12571 if (Var->isStaticDataMember()) { 12572 // C++1z removes the relevant rule; the in-class declaration is always 12573 // a definition there. 12574 if (!getLangOpts().CPlusPlus17 && 12575 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12576 Diag(Var->getLocation(), 12577 diag::err_constexpr_static_mem_var_requires_init) 12578 << Var; 12579 Var->setInvalidDecl(); 12580 return; 12581 } 12582 } else { 12583 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12584 Var->setInvalidDecl(); 12585 return; 12586 } 12587 } 12588 12589 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12590 // be initialized. 12591 if (!Var->isInvalidDecl() && 12592 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12593 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12594 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12595 Var->setInvalidDecl(); 12596 return; 12597 } 12598 12599 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12600 if (Var->getStorageClass() == SC_Extern) { 12601 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12602 << Var; 12603 Var->setInvalidDecl(); 12604 return; 12605 } 12606 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12607 diag::err_typecheck_decl_incomplete_type)) { 12608 Var->setInvalidDecl(); 12609 return; 12610 } 12611 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12612 if (!RD->hasTrivialDefaultConstructor()) { 12613 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12614 Var->setInvalidDecl(); 12615 return; 12616 } 12617 } 12618 } 12619 12620 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12621 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12622 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12623 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12624 NTCUC_DefaultInitializedObject, NTCUK_Init); 12625 12626 12627 switch (DefKind) { 12628 case VarDecl::Definition: 12629 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12630 break; 12631 12632 // We have an out-of-line definition of a static data member 12633 // that has an in-class initializer, so we type-check this like 12634 // a declaration. 12635 // 12636 LLVM_FALLTHROUGH; 12637 12638 case VarDecl::DeclarationOnly: 12639 // It's only a declaration. 12640 12641 // Block scope. C99 6.7p7: If an identifier for an object is 12642 // declared with no linkage (C99 6.2.2p6), the type for the 12643 // object shall be complete. 12644 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12645 !Var->hasLinkage() && !Var->isInvalidDecl() && 12646 RequireCompleteType(Var->getLocation(), Type, 12647 diag::err_typecheck_decl_incomplete_type)) 12648 Var->setInvalidDecl(); 12649 12650 // Make sure that the type is not abstract. 12651 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12652 RequireNonAbstractType(Var->getLocation(), Type, 12653 diag::err_abstract_type_in_decl, 12654 AbstractVariableType)) 12655 Var->setInvalidDecl(); 12656 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12657 Var->getStorageClass() == SC_PrivateExtern) { 12658 Diag(Var->getLocation(), diag::warn_private_extern); 12659 Diag(Var->getLocation(), diag::note_private_extern); 12660 } 12661 12662 if (Context.getTargetInfo().allowDebugInfoForExternalVar() && 12663 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12664 ExternalDeclarations.push_back(Var); 12665 12666 return; 12667 12668 case VarDecl::TentativeDefinition: 12669 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12670 // object that has file scope without an initializer, and without a 12671 // storage-class specifier or with the storage-class specifier "static", 12672 // constitutes a tentative definition. Note: A tentative definition with 12673 // external linkage is valid (C99 6.2.2p5). 12674 if (!Var->isInvalidDecl()) { 12675 if (const IncompleteArrayType *ArrayT 12676 = Context.getAsIncompleteArrayType(Type)) { 12677 if (RequireCompleteSizedType( 12678 Var->getLocation(), ArrayT->getElementType(), 12679 diag::err_array_incomplete_or_sizeless_type)) 12680 Var->setInvalidDecl(); 12681 } else if (Var->getStorageClass() == SC_Static) { 12682 // C99 6.9.2p3: If the declaration of an identifier for an object is 12683 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12684 // declared type shall not be an incomplete type. 12685 // NOTE: code such as the following 12686 // static struct s; 12687 // struct s { int a; }; 12688 // is accepted by gcc. Hence here we issue a warning instead of 12689 // an error and we do not invalidate the static declaration. 12690 // NOTE: to avoid multiple warnings, only check the first declaration. 12691 if (Var->isFirstDecl()) 12692 RequireCompleteType(Var->getLocation(), Type, 12693 diag::ext_typecheck_decl_incomplete_type); 12694 } 12695 } 12696 12697 // Record the tentative definition; we're done. 12698 if (!Var->isInvalidDecl()) 12699 TentativeDefinitions.push_back(Var); 12700 return; 12701 } 12702 12703 // Provide a specific diagnostic for uninitialized variable 12704 // definitions with incomplete array type. 12705 if (Type->isIncompleteArrayType()) { 12706 Diag(Var->getLocation(), 12707 diag::err_typecheck_incomplete_array_needs_initializer); 12708 Var->setInvalidDecl(); 12709 return; 12710 } 12711 12712 // Provide a specific diagnostic for uninitialized variable 12713 // definitions with reference type. 12714 if (Type->isReferenceType()) { 12715 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12716 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 12717 Var->setInvalidDecl(); 12718 return; 12719 } 12720 12721 // Do not attempt to type-check the default initializer for a 12722 // variable with dependent type. 12723 if (Type->isDependentType()) 12724 return; 12725 12726 if (Var->isInvalidDecl()) 12727 return; 12728 12729 if (!Var->hasAttr<AliasAttr>()) { 12730 if (RequireCompleteType(Var->getLocation(), 12731 Context.getBaseElementType(Type), 12732 diag::err_typecheck_decl_incomplete_type)) { 12733 Var->setInvalidDecl(); 12734 return; 12735 } 12736 } else { 12737 return; 12738 } 12739 12740 // The variable can not have an abstract class type. 12741 if (RequireNonAbstractType(Var->getLocation(), Type, 12742 diag::err_abstract_type_in_decl, 12743 AbstractVariableType)) { 12744 Var->setInvalidDecl(); 12745 return; 12746 } 12747 12748 // Check for jumps past the implicit initializer. C++0x 12749 // clarifies that this applies to a "variable with automatic 12750 // storage duration", not a "local variable". 12751 // C++11 [stmt.dcl]p3 12752 // A program that jumps from a point where a variable with automatic 12753 // storage duration is not in scope to a point where it is in scope is 12754 // ill-formed unless the variable has scalar type, class type with a 12755 // trivial default constructor and a trivial destructor, a cv-qualified 12756 // version of one of these types, or an array of one of the preceding 12757 // types and is declared without an initializer. 12758 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12759 if (const RecordType *Record 12760 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12761 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12762 // Mark the function (if we're in one) for further checking even if the 12763 // looser rules of C++11 do not require such checks, so that we can 12764 // diagnose incompatibilities with C++98. 12765 if (!CXXRecord->isPOD()) 12766 setFunctionHasBranchProtectedScope(); 12767 } 12768 } 12769 // In OpenCL, we can't initialize objects in the __local address space, 12770 // even implicitly, so don't synthesize an implicit initializer. 12771 if (getLangOpts().OpenCL && 12772 Var->getType().getAddressSpace() == LangAS::opencl_local) 12773 return; 12774 // C++03 [dcl.init]p9: 12775 // If no initializer is specified for an object, and the 12776 // object is of (possibly cv-qualified) non-POD class type (or 12777 // array thereof), the object shall be default-initialized; if 12778 // the object is of const-qualified type, the underlying class 12779 // type shall have a user-declared default 12780 // constructor. Otherwise, if no initializer is specified for 12781 // a non- static object, the object and its subobjects, if 12782 // any, have an indeterminate initial value); if the object 12783 // or any of its subobjects are of const-qualified type, the 12784 // program is ill-formed. 12785 // C++0x [dcl.init]p11: 12786 // If no initializer is specified for an object, the object is 12787 // default-initialized; [...]. 12788 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12789 InitializationKind Kind 12790 = InitializationKind::CreateDefault(Var->getLocation()); 12791 12792 InitializationSequence InitSeq(*this, Entity, Kind, None); 12793 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12794 12795 if (Init.get()) { 12796 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12797 // This is important for template substitution. 12798 Var->setInitStyle(VarDecl::CallInit); 12799 } else if (Init.isInvalid()) { 12800 // If default-init fails, attach a recovery-expr initializer to track 12801 // that initialization was attempted and failed. 12802 auto RecoveryExpr = 12803 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12804 if (RecoveryExpr.get()) 12805 Var->setInit(RecoveryExpr.get()); 12806 } 12807 12808 CheckCompleteVariableDeclaration(Var); 12809 } 12810 } 12811 12812 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12813 // If there is no declaration, there was an error parsing it. Ignore it. 12814 if (!D) 12815 return; 12816 12817 VarDecl *VD = dyn_cast<VarDecl>(D); 12818 if (!VD) { 12819 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12820 D->setInvalidDecl(); 12821 return; 12822 } 12823 12824 VD->setCXXForRangeDecl(true); 12825 12826 // for-range-declaration cannot be given a storage class specifier. 12827 int Error = -1; 12828 switch (VD->getStorageClass()) { 12829 case SC_None: 12830 break; 12831 case SC_Extern: 12832 Error = 0; 12833 break; 12834 case SC_Static: 12835 Error = 1; 12836 break; 12837 case SC_PrivateExtern: 12838 Error = 2; 12839 break; 12840 case SC_Auto: 12841 Error = 3; 12842 break; 12843 case SC_Register: 12844 Error = 4; 12845 break; 12846 } 12847 12848 // for-range-declaration cannot be given a storage class specifier con't. 12849 switch (VD->getTSCSpec()) { 12850 case TSCS_thread_local: 12851 Error = 6; 12852 break; 12853 case TSCS___thread: 12854 case TSCS__Thread_local: 12855 case TSCS_unspecified: 12856 break; 12857 } 12858 12859 if (Error != -1) { 12860 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12861 << VD << Error; 12862 D->setInvalidDecl(); 12863 } 12864 } 12865 12866 StmtResult 12867 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12868 IdentifierInfo *Ident, 12869 ParsedAttributes &Attrs, 12870 SourceLocation AttrEnd) { 12871 // C++1y [stmt.iter]p1: 12872 // A range-based for statement of the form 12873 // for ( for-range-identifier : for-range-initializer ) statement 12874 // is equivalent to 12875 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12876 DeclSpec DS(Attrs.getPool().getFactory()); 12877 12878 const char *PrevSpec; 12879 unsigned DiagID; 12880 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12881 getPrintingPolicy()); 12882 12883 Declarator D(DS, DeclaratorContext::ForInit); 12884 D.SetIdentifier(Ident, IdentLoc); 12885 D.takeAttributes(Attrs, AttrEnd); 12886 12887 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12888 IdentLoc); 12889 Decl *Var = ActOnDeclarator(S, D); 12890 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12891 FinalizeDeclaration(Var); 12892 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12893 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12894 } 12895 12896 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12897 if (var->isInvalidDecl()) return; 12898 12899 if (getLangOpts().OpenCL) { 12900 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12901 // initialiser 12902 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12903 !var->hasInit()) { 12904 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12905 << 1 /*Init*/; 12906 var->setInvalidDecl(); 12907 return; 12908 } 12909 } 12910 12911 // In Objective-C, don't allow jumps past the implicit initialization of a 12912 // local retaining variable. 12913 if (getLangOpts().ObjC && 12914 var->hasLocalStorage()) { 12915 switch (var->getType().getObjCLifetime()) { 12916 case Qualifiers::OCL_None: 12917 case Qualifiers::OCL_ExplicitNone: 12918 case Qualifiers::OCL_Autoreleasing: 12919 break; 12920 12921 case Qualifiers::OCL_Weak: 12922 case Qualifiers::OCL_Strong: 12923 setFunctionHasBranchProtectedScope(); 12924 break; 12925 } 12926 } 12927 12928 if (var->hasLocalStorage() && 12929 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12930 setFunctionHasBranchProtectedScope(); 12931 12932 // Warn about externally-visible variables being defined without a 12933 // prior declaration. We only want to do this for global 12934 // declarations, but we also specifically need to avoid doing it for 12935 // class members because the linkage of an anonymous class can 12936 // change if it's later given a typedef name. 12937 if (var->isThisDeclarationADefinition() && 12938 var->getDeclContext()->getRedeclContext()->isFileContext() && 12939 var->isExternallyVisible() && var->hasLinkage() && 12940 !var->isInline() && !var->getDescribedVarTemplate() && 12941 !isa<VarTemplatePartialSpecializationDecl>(var) && 12942 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12943 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12944 var->getLocation())) { 12945 // Find a previous declaration that's not a definition. 12946 VarDecl *prev = var->getPreviousDecl(); 12947 while (prev && prev->isThisDeclarationADefinition()) 12948 prev = prev->getPreviousDecl(); 12949 12950 if (!prev) { 12951 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12952 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12953 << /* variable */ 0; 12954 } 12955 } 12956 12957 // Cache the result of checking for constant initialization. 12958 Optional<bool> CacheHasConstInit; 12959 const Expr *CacheCulprit = nullptr; 12960 auto checkConstInit = [&]() mutable { 12961 if (!CacheHasConstInit) 12962 CacheHasConstInit = var->getInit()->isConstantInitializer( 12963 Context, var->getType()->isReferenceType(), &CacheCulprit); 12964 return *CacheHasConstInit; 12965 }; 12966 12967 if (var->getTLSKind() == VarDecl::TLS_Static) { 12968 if (var->getType().isDestructedType()) { 12969 // GNU C++98 edits for __thread, [basic.start.term]p3: 12970 // The type of an object with thread storage duration shall not 12971 // have a non-trivial destructor. 12972 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12973 if (getLangOpts().CPlusPlus11) 12974 Diag(var->getLocation(), diag::note_use_thread_local); 12975 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12976 if (!checkConstInit()) { 12977 // GNU C++98 edits for __thread, [basic.start.init]p4: 12978 // An object of thread storage duration shall not require dynamic 12979 // initialization. 12980 // FIXME: Need strict checking here. 12981 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12982 << CacheCulprit->getSourceRange(); 12983 if (getLangOpts().CPlusPlus11) 12984 Diag(var->getLocation(), diag::note_use_thread_local); 12985 } 12986 } 12987 } 12988 12989 // Apply section attributes and pragmas to global variables. 12990 bool GlobalStorage = var->hasGlobalStorage(); 12991 if (GlobalStorage && var->isThisDeclarationADefinition() && 12992 !inTemplateInstantiation()) { 12993 PragmaStack<StringLiteral *> *Stack = nullptr; 12994 int SectionFlags = ASTContext::PSF_Read; 12995 if (var->getType().isConstQualified()) 12996 Stack = &ConstSegStack; 12997 else if (!var->getInit()) { 12998 Stack = &BSSSegStack; 12999 SectionFlags |= ASTContext::PSF_Write; 13000 } else { 13001 Stack = &DataSegStack; 13002 SectionFlags |= ASTContext::PSF_Write; 13003 } 13004 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 13005 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 13006 SectionFlags |= ASTContext::PSF_Implicit; 13007 UnifySection(SA->getName(), SectionFlags, var); 13008 } else if (Stack->CurrentValue) { 13009 SectionFlags |= ASTContext::PSF_Implicit; 13010 auto SectionName = Stack->CurrentValue->getString(); 13011 var->addAttr(SectionAttr::CreateImplicit( 13012 Context, SectionName, Stack->CurrentPragmaLocation, 13013 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 13014 if (UnifySection(SectionName, SectionFlags, var)) 13015 var->dropAttr<SectionAttr>(); 13016 } 13017 13018 // Apply the init_seg attribute if this has an initializer. If the 13019 // initializer turns out to not be dynamic, we'll end up ignoring this 13020 // attribute. 13021 if (CurInitSeg && var->getInit()) 13022 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 13023 CurInitSegLoc, 13024 AttributeCommonInfo::AS_Pragma)); 13025 } 13026 13027 if (!var->getType()->isStructureType() && var->hasInit() && 13028 isa<InitListExpr>(var->getInit())) { 13029 const auto *ILE = cast<InitListExpr>(var->getInit()); 13030 unsigned NumInits = ILE->getNumInits(); 13031 if (NumInits > 2) 13032 for (unsigned I = 0; I < NumInits; ++I) { 13033 const auto *Init = ILE->getInit(I); 13034 if (!Init) 13035 break; 13036 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13037 if (!SL) 13038 break; 13039 13040 unsigned NumConcat = SL->getNumConcatenated(); 13041 // Diagnose missing comma in string array initialization. 13042 // Do not warn when all the elements in the initializer are concatenated 13043 // together. Do not warn for macros too. 13044 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 13045 bool OnlyOneMissingComma = true; 13046 for (unsigned J = I + 1; J < NumInits; ++J) { 13047 const auto *Init = ILE->getInit(J); 13048 if (!Init) 13049 break; 13050 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13051 if (!SLJ || SLJ->getNumConcatenated() > 1) { 13052 OnlyOneMissingComma = false; 13053 break; 13054 } 13055 } 13056 13057 if (OnlyOneMissingComma) { 13058 SmallVector<FixItHint, 1> Hints; 13059 for (unsigned i = 0; i < NumConcat - 1; ++i) 13060 Hints.push_back(FixItHint::CreateInsertion( 13061 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13062 13063 Diag(SL->getStrTokenLoc(1), 13064 diag::warn_concatenated_literal_array_init) 13065 << Hints; 13066 Diag(SL->getBeginLoc(), 13067 diag::note_concatenated_string_literal_silence); 13068 } 13069 // In any case, stop now. 13070 break; 13071 } 13072 } 13073 } 13074 13075 // All the following checks are C++ only. 13076 if (!getLangOpts().CPlusPlus) { 13077 // If this variable must be emitted, add it as an initializer for the 13078 // current module. 13079 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13080 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13081 return; 13082 } 13083 13084 QualType type = var->getType(); 13085 13086 if (var->hasAttr<BlocksAttr>()) 13087 getCurFunction()->addByrefBlockVar(var); 13088 13089 Expr *Init = var->getInit(); 13090 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13091 QualType baseType = Context.getBaseElementType(type); 13092 13093 // Check whether the initializer is sufficiently constant. 13094 if (!type->isDependentType() && Init && !Init->isValueDependent() && 13095 (GlobalStorage || var->isConstexpr() || 13096 var->mightBeUsableInConstantExpressions(Context))) { 13097 // If this variable might have a constant initializer or might be usable in 13098 // constant expressions, check whether or not it actually is now. We can't 13099 // do this lazily, because the result might depend on things that change 13100 // later, such as which constexpr functions happen to be defined. 13101 SmallVector<PartialDiagnosticAt, 8> Notes; 13102 bool HasConstInit; 13103 if (!getLangOpts().CPlusPlus11) { 13104 // Prior to C++11, in contexts where a constant initializer is required, 13105 // the set of valid constant initializers is described by syntactic rules 13106 // in [expr.const]p2-6. 13107 // FIXME: Stricter checking for these rules would be useful for constinit / 13108 // -Wglobal-constructors. 13109 HasConstInit = checkConstInit(); 13110 13111 // Compute and cache the constant value, and remember that we have a 13112 // constant initializer. 13113 if (HasConstInit) { 13114 (void)var->checkForConstantInitialization(Notes); 13115 Notes.clear(); 13116 } else if (CacheCulprit) { 13117 Notes.emplace_back(CacheCulprit->getExprLoc(), 13118 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13119 Notes.back().second << CacheCulprit->getSourceRange(); 13120 } 13121 } else { 13122 // Evaluate the initializer to see if it's a constant initializer. 13123 HasConstInit = var->checkForConstantInitialization(Notes); 13124 } 13125 13126 if (HasConstInit) { 13127 // FIXME: Consider replacing the initializer with a ConstantExpr. 13128 } else if (var->isConstexpr()) { 13129 SourceLocation DiagLoc = var->getLocation(); 13130 // If the note doesn't add any useful information other than a source 13131 // location, fold it into the primary diagnostic. 13132 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13133 diag::note_invalid_subexpr_in_const_expr) { 13134 DiagLoc = Notes[0].first; 13135 Notes.clear(); 13136 } 13137 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13138 << var << Init->getSourceRange(); 13139 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13140 Diag(Notes[I].first, Notes[I].second); 13141 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13142 auto *Attr = var->getAttr<ConstInitAttr>(); 13143 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13144 << Init->getSourceRange(); 13145 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13146 << Attr->getRange() << Attr->isConstinit(); 13147 for (auto &it : Notes) 13148 Diag(it.first, it.second); 13149 } else if (IsGlobal && 13150 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13151 var->getLocation())) { 13152 // Warn about globals which don't have a constant initializer. Don't 13153 // warn about globals with a non-trivial destructor because we already 13154 // warned about them. 13155 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13156 if (!(RD && !RD->hasTrivialDestructor())) { 13157 // checkConstInit() here permits trivial default initialization even in 13158 // C++11 onwards, where such an initializer is not a constant initializer 13159 // but nonetheless doesn't require a global constructor. 13160 if (!checkConstInit()) 13161 Diag(var->getLocation(), diag::warn_global_constructor) 13162 << Init->getSourceRange(); 13163 } 13164 } 13165 } 13166 13167 // Require the destructor. 13168 if (!type->isDependentType()) 13169 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13170 FinalizeVarWithDestructor(var, recordType); 13171 13172 // If this variable must be emitted, add it as an initializer for the current 13173 // module. 13174 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13175 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13176 13177 // Build the bindings if this is a structured binding declaration. 13178 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13179 CheckCompleteDecompositionDeclaration(DD); 13180 } 13181 13182 /// Determines if a variable's alignment is dependent. 13183 static bool hasDependentAlignment(VarDecl *VD) { 13184 if (VD->getType()->isDependentType()) 13185 return true; 13186 for (auto *I : VD->specific_attrs<AlignedAttr>()) 13187 if (I->isAlignmentDependent()) 13188 return true; 13189 return false; 13190 } 13191 13192 /// Check if VD needs to be dllexport/dllimport due to being in a 13193 /// dllexport/import function. 13194 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13195 assert(VD->isStaticLocal()); 13196 13197 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13198 13199 // Find outermost function when VD is in lambda function. 13200 while (FD && !getDLLAttr(FD) && 13201 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13202 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13203 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13204 } 13205 13206 if (!FD) 13207 return; 13208 13209 // Static locals inherit dll attributes from their function. 13210 if (Attr *A = getDLLAttr(FD)) { 13211 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13212 NewAttr->setInherited(true); 13213 VD->addAttr(NewAttr); 13214 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13215 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13216 NewAttr->setInherited(true); 13217 VD->addAttr(NewAttr); 13218 13219 // Export this function to enforce exporting this static variable even 13220 // if it is not used in this compilation unit. 13221 if (!FD->hasAttr<DLLExportAttr>()) 13222 FD->addAttr(NewAttr); 13223 13224 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13225 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13226 NewAttr->setInherited(true); 13227 VD->addAttr(NewAttr); 13228 } 13229 } 13230 13231 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13232 /// any semantic actions necessary after any initializer has been attached. 13233 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13234 // Note that we are no longer parsing the initializer for this declaration. 13235 ParsingInitForAutoVars.erase(ThisDecl); 13236 13237 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13238 if (!VD) 13239 return; 13240 13241 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13242 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13243 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13244 if (PragmaClangBSSSection.Valid) 13245 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13246 Context, PragmaClangBSSSection.SectionName, 13247 PragmaClangBSSSection.PragmaLocation, 13248 AttributeCommonInfo::AS_Pragma)); 13249 if (PragmaClangDataSection.Valid) 13250 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13251 Context, PragmaClangDataSection.SectionName, 13252 PragmaClangDataSection.PragmaLocation, 13253 AttributeCommonInfo::AS_Pragma)); 13254 if (PragmaClangRodataSection.Valid) 13255 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13256 Context, PragmaClangRodataSection.SectionName, 13257 PragmaClangRodataSection.PragmaLocation, 13258 AttributeCommonInfo::AS_Pragma)); 13259 if (PragmaClangRelroSection.Valid) 13260 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13261 Context, PragmaClangRelroSection.SectionName, 13262 PragmaClangRelroSection.PragmaLocation, 13263 AttributeCommonInfo::AS_Pragma)); 13264 } 13265 13266 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13267 for (auto *BD : DD->bindings()) { 13268 FinalizeDeclaration(BD); 13269 } 13270 } 13271 13272 checkAttributesAfterMerging(*this, *VD); 13273 13274 // Perform TLS alignment check here after attributes attached to the variable 13275 // which may affect the alignment have been processed. Only perform the check 13276 // if the target has a maximum TLS alignment (zero means no constraints). 13277 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13278 // Protect the check so that it's not performed on dependent types and 13279 // dependent alignments (we can't determine the alignment in that case). 13280 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 13281 !VD->isInvalidDecl()) { 13282 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13283 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13284 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13285 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13286 << (unsigned)MaxAlignChars.getQuantity(); 13287 } 13288 } 13289 } 13290 13291 if (VD->isStaticLocal()) 13292 CheckStaticLocalForDllExport(VD); 13293 13294 // Perform check for initializers of device-side global variables. 13295 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13296 // 7.5). We must also apply the same checks to all __shared__ 13297 // variables whether they are local or not. CUDA also allows 13298 // constant initializers for __constant__ and __device__ variables. 13299 if (getLangOpts().CUDA) 13300 checkAllowedCUDAInitializer(VD); 13301 13302 // Grab the dllimport or dllexport attribute off of the VarDecl. 13303 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13304 13305 // Imported static data members cannot be defined out-of-line. 13306 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13307 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13308 VD->isThisDeclarationADefinition()) { 13309 // We allow definitions of dllimport class template static data members 13310 // with a warning. 13311 CXXRecordDecl *Context = 13312 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13313 bool IsClassTemplateMember = 13314 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13315 Context->getDescribedClassTemplate(); 13316 13317 Diag(VD->getLocation(), 13318 IsClassTemplateMember 13319 ? diag::warn_attribute_dllimport_static_field_definition 13320 : diag::err_attribute_dllimport_static_field_definition); 13321 Diag(IA->getLocation(), diag::note_attribute); 13322 if (!IsClassTemplateMember) 13323 VD->setInvalidDecl(); 13324 } 13325 } 13326 13327 // dllimport/dllexport variables cannot be thread local, their TLS index 13328 // isn't exported with the variable. 13329 if (DLLAttr && VD->getTLSKind()) { 13330 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13331 if (F && getDLLAttr(F)) { 13332 assert(VD->isStaticLocal()); 13333 // But if this is a static local in a dlimport/dllexport function, the 13334 // function will never be inlined, which means the var would never be 13335 // imported, so having it marked import/export is safe. 13336 } else { 13337 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13338 << DLLAttr; 13339 VD->setInvalidDecl(); 13340 } 13341 } 13342 13343 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13344 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13345 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13346 << Attr; 13347 VD->dropAttr<UsedAttr>(); 13348 } 13349 } 13350 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 13351 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13352 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13353 << Attr; 13354 VD->dropAttr<RetainAttr>(); 13355 } 13356 } 13357 13358 const DeclContext *DC = VD->getDeclContext(); 13359 // If there's a #pragma GCC visibility in scope, and this isn't a class 13360 // member, set the visibility of this variable. 13361 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13362 AddPushedVisibilityAttribute(VD); 13363 13364 // FIXME: Warn on unused var template partial specializations. 13365 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13366 MarkUnusedFileScopedDecl(VD); 13367 13368 // Now we have parsed the initializer and can update the table of magic 13369 // tag values. 13370 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13371 !VD->getType()->isIntegralOrEnumerationType()) 13372 return; 13373 13374 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13375 const Expr *MagicValueExpr = VD->getInit(); 13376 if (!MagicValueExpr) { 13377 continue; 13378 } 13379 Optional<llvm::APSInt> MagicValueInt; 13380 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13381 Diag(I->getRange().getBegin(), 13382 diag::err_type_tag_for_datatype_not_ice) 13383 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13384 continue; 13385 } 13386 if (MagicValueInt->getActiveBits() > 64) { 13387 Diag(I->getRange().getBegin(), 13388 diag::err_type_tag_for_datatype_too_large) 13389 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13390 continue; 13391 } 13392 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13393 RegisterTypeTagForDatatype(I->getArgumentKind(), 13394 MagicValue, 13395 I->getMatchingCType(), 13396 I->getLayoutCompatible(), 13397 I->getMustBeNull()); 13398 } 13399 } 13400 13401 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13402 auto *VD = dyn_cast<VarDecl>(DD); 13403 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13404 } 13405 13406 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13407 ArrayRef<Decl *> Group) { 13408 SmallVector<Decl*, 8> Decls; 13409 13410 if (DS.isTypeSpecOwned()) 13411 Decls.push_back(DS.getRepAsDecl()); 13412 13413 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13414 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13415 bool DiagnosedMultipleDecomps = false; 13416 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13417 bool DiagnosedNonDeducedAuto = false; 13418 13419 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13420 if (Decl *D = Group[i]) { 13421 // For declarators, there are some additional syntactic-ish checks we need 13422 // to perform. 13423 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13424 if (!FirstDeclaratorInGroup) 13425 FirstDeclaratorInGroup = DD; 13426 if (!FirstDecompDeclaratorInGroup) 13427 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13428 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13429 !hasDeducedAuto(DD)) 13430 FirstNonDeducedAutoInGroup = DD; 13431 13432 if (FirstDeclaratorInGroup != DD) { 13433 // A decomposition declaration cannot be combined with any other 13434 // declaration in the same group. 13435 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13436 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13437 diag::err_decomp_decl_not_alone) 13438 << FirstDeclaratorInGroup->getSourceRange() 13439 << DD->getSourceRange(); 13440 DiagnosedMultipleDecomps = true; 13441 } 13442 13443 // A declarator that uses 'auto' in any way other than to declare a 13444 // variable with a deduced type cannot be combined with any other 13445 // declarator in the same group. 13446 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13447 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13448 diag::err_auto_non_deduced_not_alone) 13449 << FirstNonDeducedAutoInGroup->getType() 13450 ->hasAutoForTrailingReturnType() 13451 << FirstDeclaratorInGroup->getSourceRange() 13452 << DD->getSourceRange(); 13453 DiagnosedNonDeducedAuto = true; 13454 } 13455 } 13456 } 13457 13458 Decls.push_back(D); 13459 } 13460 } 13461 13462 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13463 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13464 handleTagNumbering(Tag, S); 13465 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13466 getLangOpts().CPlusPlus) 13467 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13468 } 13469 } 13470 13471 return BuildDeclaratorGroup(Decls); 13472 } 13473 13474 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13475 /// group, performing any necessary semantic checking. 13476 Sema::DeclGroupPtrTy 13477 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13478 // C++14 [dcl.spec.auto]p7: (DR1347) 13479 // If the type that replaces the placeholder type is not the same in each 13480 // deduction, the program is ill-formed. 13481 if (Group.size() > 1) { 13482 QualType Deduced; 13483 VarDecl *DeducedDecl = nullptr; 13484 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13485 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13486 if (!D || D->isInvalidDecl()) 13487 break; 13488 DeducedType *DT = D->getType()->getContainedDeducedType(); 13489 if (!DT || DT->getDeducedType().isNull()) 13490 continue; 13491 if (Deduced.isNull()) { 13492 Deduced = DT->getDeducedType(); 13493 DeducedDecl = D; 13494 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13495 auto *AT = dyn_cast<AutoType>(DT); 13496 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13497 diag::err_auto_different_deductions) 13498 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13499 << DeducedDecl->getDeclName() << DT->getDeducedType() 13500 << D->getDeclName(); 13501 if (DeducedDecl->hasInit()) 13502 Dia << DeducedDecl->getInit()->getSourceRange(); 13503 if (D->getInit()) 13504 Dia << D->getInit()->getSourceRange(); 13505 D->setInvalidDecl(); 13506 break; 13507 } 13508 } 13509 } 13510 13511 ActOnDocumentableDecls(Group); 13512 13513 return DeclGroupPtrTy::make( 13514 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13515 } 13516 13517 void Sema::ActOnDocumentableDecl(Decl *D) { 13518 ActOnDocumentableDecls(D); 13519 } 13520 13521 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13522 // Don't parse the comment if Doxygen diagnostics are ignored. 13523 if (Group.empty() || !Group[0]) 13524 return; 13525 13526 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13527 Group[0]->getLocation()) && 13528 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13529 Group[0]->getLocation())) 13530 return; 13531 13532 if (Group.size() >= 2) { 13533 // This is a decl group. Normally it will contain only declarations 13534 // produced from declarator list. But in case we have any definitions or 13535 // additional declaration references: 13536 // 'typedef struct S {} S;' 13537 // 'typedef struct S *S;' 13538 // 'struct S *pS;' 13539 // FinalizeDeclaratorGroup adds these as separate declarations. 13540 Decl *MaybeTagDecl = Group[0]; 13541 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13542 Group = Group.slice(1); 13543 } 13544 } 13545 13546 // FIMXE: We assume every Decl in the group is in the same file. 13547 // This is false when preprocessor constructs the group from decls in 13548 // different files (e. g. macros or #include). 13549 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13550 } 13551 13552 /// Common checks for a parameter-declaration that should apply to both function 13553 /// parameters and non-type template parameters. 13554 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13555 // Check that there are no default arguments inside the type of this 13556 // parameter. 13557 if (getLangOpts().CPlusPlus) 13558 CheckExtraCXXDefaultArguments(D); 13559 13560 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13561 if (D.getCXXScopeSpec().isSet()) { 13562 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13563 << D.getCXXScopeSpec().getRange(); 13564 } 13565 13566 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13567 // simple identifier except [...irrelevant cases...]. 13568 switch (D.getName().getKind()) { 13569 case UnqualifiedIdKind::IK_Identifier: 13570 break; 13571 13572 case UnqualifiedIdKind::IK_OperatorFunctionId: 13573 case UnqualifiedIdKind::IK_ConversionFunctionId: 13574 case UnqualifiedIdKind::IK_LiteralOperatorId: 13575 case UnqualifiedIdKind::IK_ConstructorName: 13576 case UnqualifiedIdKind::IK_DestructorName: 13577 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13578 case UnqualifiedIdKind::IK_DeductionGuideName: 13579 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13580 << GetNameForDeclarator(D).getName(); 13581 break; 13582 13583 case UnqualifiedIdKind::IK_TemplateId: 13584 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13585 // GetNameForDeclarator would not produce a useful name in this case. 13586 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13587 break; 13588 } 13589 } 13590 13591 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13592 /// to introduce parameters into function prototype scope. 13593 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13594 const DeclSpec &DS = D.getDeclSpec(); 13595 13596 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13597 13598 // C++03 [dcl.stc]p2 also permits 'auto'. 13599 StorageClass SC = SC_None; 13600 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13601 SC = SC_Register; 13602 // In C++11, the 'register' storage class specifier is deprecated. 13603 // In C++17, it is not allowed, but we tolerate it as an extension. 13604 if (getLangOpts().CPlusPlus11) { 13605 Diag(DS.getStorageClassSpecLoc(), 13606 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13607 : diag::warn_deprecated_register) 13608 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13609 } 13610 } else if (getLangOpts().CPlusPlus && 13611 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13612 SC = SC_Auto; 13613 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13614 Diag(DS.getStorageClassSpecLoc(), 13615 diag::err_invalid_storage_class_in_func_decl); 13616 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13617 } 13618 13619 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13620 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13621 << DeclSpec::getSpecifierName(TSCS); 13622 if (DS.isInlineSpecified()) 13623 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13624 << getLangOpts().CPlusPlus17; 13625 if (DS.hasConstexprSpecifier()) 13626 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13627 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 13628 13629 DiagnoseFunctionSpecifiers(DS); 13630 13631 CheckFunctionOrTemplateParamDeclarator(S, D); 13632 13633 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13634 QualType parmDeclType = TInfo->getType(); 13635 13636 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13637 IdentifierInfo *II = D.getIdentifier(); 13638 if (II) { 13639 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13640 ForVisibleRedeclaration); 13641 LookupName(R, S); 13642 if (R.isSingleResult()) { 13643 NamedDecl *PrevDecl = R.getFoundDecl(); 13644 if (PrevDecl->isTemplateParameter()) { 13645 // Maybe we will complain about the shadowed template parameter. 13646 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13647 // Just pretend that we didn't see the previous declaration. 13648 PrevDecl = nullptr; 13649 } else if (S->isDeclScope(PrevDecl)) { 13650 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13651 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13652 13653 // Recover by removing the name 13654 II = nullptr; 13655 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13656 D.setInvalidType(true); 13657 } 13658 } 13659 } 13660 13661 // Temporarily put parameter variables in the translation unit, not 13662 // the enclosing context. This prevents them from accidentally 13663 // looking like class members in C++. 13664 ParmVarDecl *New = 13665 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13666 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13667 13668 if (D.isInvalidType()) 13669 New->setInvalidDecl(); 13670 13671 assert(S->isFunctionPrototypeScope()); 13672 assert(S->getFunctionPrototypeDepth() >= 1); 13673 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13674 S->getNextFunctionPrototypeIndex()); 13675 13676 // Add the parameter declaration into this scope. 13677 S->AddDecl(New); 13678 if (II) 13679 IdResolver.AddDecl(New); 13680 13681 ProcessDeclAttributes(S, New, D); 13682 13683 if (D.getDeclSpec().isModulePrivateSpecified()) 13684 Diag(New->getLocation(), diag::err_module_private_local) 13685 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13686 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13687 13688 if (New->hasAttr<BlocksAttr>()) { 13689 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13690 } 13691 13692 if (getLangOpts().OpenCL) 13693 deduceOpenCLAddressSpace(New); 13694 13695 return New; 13696 } 13697 13698 /// Synthesizes a variable for a parameter arising from a 13699 /// typedef. 13700 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13701 SourceLocation Loc, 13702 QualType T) { 13703 /* FIXME: setting StartLoc == Loc. 13704 Would it be worth to modify callers so as to provide proper source 13705 location for the unnamed parameters, embedding the parameter's type? */ 13706 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13707 T, Context.getTrivialTypeSourceInfo(T, Loc), 13708 SC_None, nullptr); 13709 Param->setImplicit(); 13710 return Param; 13711 } 13712 13713 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13714 // Don't diagnose unused-parameter errors in template instantiations; we 13715 // will already have done so in the template itself. 13716 if (inTemplateInstantiation()) 13717 return; 13718 13719 for (const ParmVarDecl *Parameter : Parameters) { 13720 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13721 !Parameter->hasAttr<UnusedAttr>()) { 13722 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13723 << Parameter->getDeclName(); 13724 } 13725 } 13726 } 13727 13728 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13729 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13730 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13731 return; 13732 13733 // Warn if the return value is pass-by-value and larger than the specified 13734 // threshold. 13735 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13736 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13737 if (Size > LangOpts.NumLargeByValueCopy) 13738 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 13739 } 13740 13741 // Warn if any parameter is pass-by-value and larger than the specified 13742 // threshold. 13743 for (const ParmVarDecl *Parameter : Parameters) { 13744 QualType T = Parameter->getType(); 13745 if (T->isDependentType() || !T.isPODType(Context)) 13746 continue; 13747 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13748 if (Size > LangOpts.NumLargeByValueCopy) 13749 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13750 << Parameter << Size; 13751 } 13752 } 13753 13754 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13755 SourceLocation NameLoc, IdentifierInfo *Name, 13756 QualType T, TypeSourceInfo *TSInfo, 13757 StorageClass SC) { 13758 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13759 if (getLangOpts().ObjCAutoRefCount && 13760 T.getObjCLifetime() == Qualifiers::OCL_None && 13761 T->isObjCLifetimeType()) { 13762 13763 Qualifiers::ObjCLifetime lifetime; 13764 13765 // Special cases for arrays: 13766 // - if it's const, use __unsafe_unretained 13767 // - otherwise, it's an error 13768 if (T->isArrayType()) { 13769 if (!T.isConstQualified()) { 13770 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13771 DelayedDiagnostics.add( 13772 sema::DelayedDiagnostic::makeForbiddenType( 13773 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13774 else 13775 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13776 << TSInfo->getTypeLoc().getSourceRange(); 13777 } 13778 lifetime = Qualifiers::OCL_ExplicitNone; 13779 } else { 13780 lifetime = T->getObjCARCImplicitLifetime(); 13781 } 13782 T = Context.getLifetimeQualifiedType(T, lifetime); 13783 } 13784 13785 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13786 Context.getAdjustedParameterType(T), 13787 TSInfo, SC, nullptr); 13788 13789 // Make a note if we created a new pack in the scope of a lambda, so that 13790 // we know that references to that pack must also be expanded within the 13791 // lambda scope. 13792 if (New->isParameterPack()) 13793 if (auto *LSI = getEnclosingLambda()) 13794 LSI->LocalPacks.push_back(New); 13795 13796 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13797 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13798 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13799 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13800 13801 // Parameters can not be abstract class types. 13802 // For record types, this is done by the AbstractClassUsageDiagnoser once 13803 // the class has been completely parsed. 13804 if (!CurContext->isRecord() && 13805 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13806 AbstractParamType)) 13807 New->setInvalidDecl(); 13808 13809 // Parameter declarators cannot be interface types. All ObjC objects are 13810 // passed by reference. 13811 if (T->isObjCObjectType()) { 13812 SourceLocation TypeEndLoc = 13813 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13814 Diag(NameLoc, 13815 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13816 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13817 T = Context.getObjCObjectPointerType(T); 13818 New->setType(T); 13819 } 13820 13821 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13822 // duration shall not be qualified by an address-space qualifier." 13823 // Since all parameters have automatic store duration, they can not have 13824 // an address space. 13825 if (T.getAddressSpace() != LangAS::Default && 13826 // OpenCL allows function arguments declared to be an array of a type 13827 // to be qualified with an address space. 13828 !(getLangOpts().OpenCL && 13829 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13830 Diag(NameLoc, diag::err_arg_with_address_space); 13831 New->setInvalidDecl(); 13832 } 13833 13834 // PPC MMA non-pointer types are not allowed as function argument types. 13835 if (Context.getTargetInfo().getTriple().isPPC64() && 13836 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 13837 New->setInvalidDecl(); 13838 } 13839 13840 return New; 13841 } 13842 13843 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13844 SourceLocation LocAfterDecls) { 13845 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13846 13847 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13848 // for a K&R function. 13849 if (!FTI.hasPrototype) { 13850 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13851 --i; 13852 if (FTI.Params[i].Param == nullptr) { 13853 SmallString<256> Code; 13854 llvm::raw_svector_ostream(Code) 13855 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13856 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13857 << FTI.Params[i].Ident 13858 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13859 13860 // Implicitly declare the argument as type 'int' for lack of a better 13861 // type. 13862 AttributeFactory attrs; 13863 DeclSpec DS(attrs); 13864 const char* PrevSpec; // unused 13865 unsigned DiagID; // unused 13866 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13867 DiagID, Context.getPrintingPolicy()); 13868 // Use the identifier location for the type source range. 13869 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13870 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13871 Declarator ParamD(DS, DeclaratorContext::KNRTypeList); 13872 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13873 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13874 } 13875 } 13876 } 13877 } 13878 13879 Decl * 13880 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13881 MultiTemplateParamsArg TemplateParameterLists, 13882 SkipBodyInfo *SkipBody) { 13883 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13884 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13885 Scope *ParentScope = FnBodyScope->getParent(); 13886 13887 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 13888 // we define a non-templated function definition, we will create a declaration 13889 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 13890 // The base function declaration will have the equivalent of an `omp declare 13891 // variant` annotation which specifies the mangled definition as a 13892 // specialization function under the OpenMP context defined as part of the 13893 // `omp begin declare variant`. 13894 SmallVector<FunctionDecl *, 4> Bases; 13895 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 13896 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 13897 ParentScope, D, TemplateParameterLists, Bases); 13898 13899 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 13900 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13901 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13902 13903 if (!Bases.empty()) 13904 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 13905 13906 return Dcl; 13907 } 13908 13909 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13910 Consumer.HandleInlineFunctionDefinition(D); 13911 } 13912 13913 static bool 13914 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13915 const FunctionDecl *&PossiblePrototype) { 13916 // Don't warn about invalid declarations. 13917 if (FD->isInvalidDecl()) 13918 return false; 13919 13920 // Or declarations that aren't global. 13921 if (!FD->isGlobal()) 13922 return false; 13923 13924 // Don't warn about C++ member functions. 13925 if (isa<CXXMethodDecl>(FD)) 13926 return false; 13927 13928 // Don't warn about 'main'. 13929 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13930 if (IdentifierInfo *II = FD->getIdentifier()) 13931 if (II->isStr("main") || II->isStr("efi_main")) 13932 return false; 13933 13934 // Don't warn about inline functions. 13935 if (FD->isInlined()) 13936 return false; 13937 13938 // Don't warn about function templates. 13939 if (FD->getDescribedFunctionTemplate()) 13940 return false; 13941 13942 // Don't warn about function template specializations. 13943 if (FD->isFunctionTemplateSpecialization()) 13944 return false; 13945 13946 // Don't warn for OpenCL kernels. 13947 if (FD->hasAttr<OpenCLKernelAttr>()) 13948 return false; 13949 13950 // Don't warn on explicitly deleted functions. 13951 if (FD->isDeleted()) 13952 return false; 13953 13954 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13955 Prev; Prev = Prev->getPreviousDecl()) { 13956 // Ignore any declarations that occur in function or method 13957 // scope, because they aren't visible from the header. 13958 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13959 continue; 13960 13961 PossiblePrototype = Prev; 13962 return Prev->getType()->isFunctionNoProtoType(); 13963 } 13964 13965 return true; 13966 } 13967 13968 void 13969 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13970 const FunctionDecl *EffectiveDefinition, 13971 SkipBodyInfo *SkipBody) { 13972 const FunctionDecl *Definition = EffectiveDefinition; 13973 if (!Definition && 13974 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 13975 return; 13976 13977 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 13978 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 13979 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13980 // A merged copy of the same function, instantiated as a member of 13981 // the same class, is OK. 13982 if (declaresSameEntity(OrigFD, OrigDef) && 13983 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 13984 cast<Decl>(FD->getLexicalDeclContext()))) 13985 return; 13986 } 13987 } 13988 } 13989 13990 if (canRedefineFunction(Definition, getLangOpts())) 13991 return; 13992 13993 // Don't emit an error when this is redefinition of a typo-corrected 13994 // definition. 13995 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13996 return; 13997 13998 // If we don't have a visible definition of the function, and it's inline or 13999 // a template, skip the new definition. 14000 if (SkipBody && !hasVisibleDefinition(Definition) && 14001 (Definition->getFormalLinkage() == InternalLinkage || 14002 Definition->isInlined() || 14003 Definition->getDescribedFunctionTemplate() || 14004 Definition->getNumTemplateParameterLists())) { 14005 SkipBody->ShouldSkip = true; 14006 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 14007 if (auto *TD = Definition->getDescribedFunctionTemplate()) 14008 makeMergedDefinitionVisible(TD); 14009 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 14010 return; 14011 } 14012 14013 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 14014 Definition->getStorageClass() == SC_Extern) 14015 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 14016 << FD << getLangOpts().CPlusPlus; 14017 else 14018 Diag(FD->getLocation(), diag::err_redefinition) << FD; 14019 14020 Diag(Definition->getLocation(), diag::note_previous_definition); 14021 FD->setInvalidDecl(); 14022 } 14023 14024 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 14025 Sema &S) { 14026 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 14027 14028 LambdaScopeInfo *LSI = S.PushLambdaScope(); 14029 LSI->CallOperator = CallOperator; 14030 LSI->Lambda = LambdaClass; 14031 LSI->ReturnType = CallOperator->getReturnType(); 14032 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 14033 14034 if (LCD == LCD_None) 14035 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 14036 else if (LCD == LCD_ByCopy) 14037 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 14038 else if (LCD == LCD_ByRef) 14039 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 14040 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 14041 14042 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 14043 LSI->Mutable = !CallOperator->isConst(); 14044 14045 // Add the captures to the LSI so they can be noted as already 14046 // captured within tryCaptureVar. 14047 auto I = LambdaClass->field_begin(); 14048 for (const auto &C : LambdaClass->captures()) { 14049 if (C.capturesVariable()) { 14050 VarDecl *VD = C.getCapturedVar(); 14051 if (VD->isInitCapture()) 14052 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 14053 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 14054 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 14055 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 14056 /*EllipsisLoc*/C.isPackExpansion() 14057 ? C.getEllipsisLoc() : SourceLocation(), 14058 I->getType(), /*Invalid*/false); 14059 14060 } else if (C.capturesThis()) { 14061 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 14062 C.getCaptureKind() == LCK_StarThis); 14063 } else { 14064 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14065 I->getType()); 14066 } 14067 ++I; 14068 } 14069 } 14070 14071 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14072 SkipBodyInfo *SkipBody) { 14073 if (!D) { 14074 // Parsing the function declaration failed in some way. Push on a fake scope 14075 // anyway so we can try to parse the function body. 14076 PushFunctionScope(); 14077 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14078 return D; 14079 } 14080 14081 FunctionDecl *FD = nullptr; 14082 14083 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14084 FD = FunTmpl->getTemplatedDecl(); 14085 else 14086 FD = cast<FunctionDecl>(D); 14087 14088 // Do not push if it is a lambda because one is already pushed when building 14089 // the lambda in ActOnStartOfLambdaDefinition(). 14090 if (!isLambdaCallOperator(FD)) 14091 PushExpressionEvaluationContext( 14092 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14093 : ExprEvalContexts.back().Context); 14094 14095 // Check for defining attributes before the check for redefinition. 14096 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14097 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14098 FD->dropAttr<AliasAttr>(); 14099 FD->setInvalidDecl(); 14100 } 14101 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14102 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14103 FD->dropAttr<IFuncAttr>(); 14104 FD->setInvalidDecl(); 14105 } 14106 14107 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14108 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14109 Ctor->isDefaultConstructor() && 14110 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14111 // If this is an MS ABI dllexport default constructor, instantiate any 14112 // default arguments. 14113 InstantiateDefaultCtorDefaultArgs(Ctor); 14114 } 14115 } 14116 14117 // See if this is a redefinition. If 'will have body' (or similar) is already 14118 // set, then these checks were already performed when it was set. 14119 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14120 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14121 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14122 14123 // If we're skipping the body, we're done. Don't enter the scope. 14124 if (SkipBody && SkipBody->ShouldSkip) 14125 return D; 14126 } 14127 14128 // Mark this function as "will have a body eventually". This lets users to 14129 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14130 // this function. 14131 FD->setWillHaveBody(); 14132 14133 // If we are instantiating a generic lambda call operator, push 14134 // a LambdaScopeInfo onto the function stack. But use the information 14135 // that's already been calculated (ActOnLambdaExpr) to prime the current 14136 // LambdaScopeInfo. 14137 // When the template operator is being specialized, the LambdaScopeInfo, 14138 // has to be properly restored so that tryCaptureVariable doesn't try 14139 // and capture any new variables. In addition when calculating potential 14140 // captures during transformation of nested lambdas, it is necessary to 14141 // have the LSI properly restored. 14142 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14143 assert(inTemplateInstantiation() && 14144 "There should be an active template instantiation on the stack " 14145 "when instantiating a generic lambda!"); 14146 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14147 } else { 14148 // Enter a new function scope 14149 PushFunctionScope(); 14150 } 14151 14152 // Builtin functions cannot be defined. 14153 if (unsigned BuiltinID = FD->getBuiltinID()) { 14154 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14155 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14156 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14157 FD->setInvalidDecl(); 14158 } 14159 } 14160 14161 // The return type of a function definition must be complete 14162 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14163 QualType ResultType = FD->getReturnType(); 14164 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14165 !FD->isInvalidDecl() && 14166 RequireCompleteType(FD->getLocation(), ResultType, 14167 diag::err_func_def_incomplete_result)) 14168 FD->setInvalidDecl(); 14169 14170 if (FnBodyScope) 14171 PushDeclContext(FnBodyScope, FD); 14172 14173 // Check the validity of our function parameters 14174 CheckParmsForFunctionDef(FD->parameters(), 14175 /*CheckParameterNames=*/true); 14176 14177 // Add non-parameter declarations already in the function to the current 14178 // scope. 14179 if (FnBodyScope) { 14180 for (Decl *NPD : FD->decls()) { 14181 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14182 if (!NonParmDecl) 14183 continue; 14184 assert(!isa<ParmVarDecl>(NonParmDecl) && 14185 "parameters should not be in newly created FD yet"); 14186 14187 // If the decl has a name, make it accessible in the current scope. 14188 if (NonParmDecl->getDeclName()) 14189 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14190 14191 // Similarly, dive into enums and fish their constants out, making them 14192 // accessible in this scope. 14193 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14194 for (auto *EI : ED->enumerators()) 14195 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14196 } 14197 } 14198 } 14199 14200 // Introduce our parameters into the function scope 14201 for (auto Param : FD->parameters()) { 14202 Param->setOwningFunction(FD); 14203 14204 // If this has an identifier, add it to the scope stack. 14205 if (Param->getIdentifier() && FnBodyScope) { 14206 CheckShadow(FnBodyScope, Param); 14207 14208 PushOnScopeChains(Param, FnBodyScope); 14209 } 14210 } 14211 14212 // Ensure that the function's exception specification is instantiated. 14213 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14214 ResolveExceptionSpec(D->getLocation(), FPT); 14215 14216 // dllimport cannot be applied to non-inline function definitions. 14217 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14218 !FD->isTemplateInstantiation()) { 14219 assert(!FD->hasAttr<DLLExportAttr>()); 14220 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14221 FD->setInvalidDecl(); 14222 return D; 14223 } 14224 // We want to attach documentation to original Decl (which might be 14225 // a function template). 14226 ActOnDocumentableDecl(D); 14227 if (getCurLexicalContext()->isObjCContainer() && 14228 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14229 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14230 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14231 14232 return D; 14233 } 14234 14235 /// Given the set of return statements within a function body, 14236 /// compute the variables that are subject to the named return value 14237 /// optimization. 14238 /// 14239 /// Each of the variables that is subject to the named return value 14240 /// optimization will be marked as NRVO variables in the AST, and any 14241 /// return statement that has a marked NRVO variable as its NRVO candidate can 14242 /// use the named return value optimization. 14243 /// 14244 /// This function applies a very simplistic algorithm for NRVO: if every return 14245 /// statement in the scope of a variable has the same NRVO candidate, that 14246 /// candidate is an NRVO variable. 14247 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14248 ReturnStmt **Returns = Scope->Returns.data(); 14249 14250 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14251 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14252 if (!NRVOCandidate->isNRVOVariable()) 14253 Returns[I]->setNRVOCandidate(nullptr); 14254 } 14255 } 14256 } 14257 14258 bool Sema::canDelayFunctionBody(const Declarator &D) { 14259 // We can't delay parsing the body of a constexpr function template (yet). 14260 if (D.getDeclSpec().hasConstexprSpecifier()) 14261 return false; 14262 14263 // We can't delay parsing the body of a function template with a deduced 14264 // return type (yet). 14265 if (D.getDeclSpec().hasAutoTypeSpec()) { 14266 // If the placeholder introduces a non-deduced trailing return type, 14267 // we can still delay parsing it. 14268 if (D.getNumTypeObjects()) { 14269 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14270 if (Outer.Kind == DeclaratorChunk::Function && 14271 Outer.Fun.hasTrailingReturnType()) { 14272 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14273 return Ty.isNull() || !Ty->isUndeducedType(); 14274 } 14275 } 14276 return false; 14277 } 14278 14279 return true; 14280 } 14281 14282 bool Sema::canSkipFunctionBody(Decl *D) { 14283 // We cannot skip the body of a function (or function template) which is 14284 // constexpr, since we may need to evaluate its body in order to parse the 14285 // rest of the file. 14286 // We cannot skip the body of a function with an undeduced return type, 14287 // because any callers of that function need to know the type. 14288 if (const FunctionDecl *FD = D->getAsFunction()) { 14289 if (FD->isConstexpr()) 14290 return false; 14291 // We can't simply call Type::isUndeducedType here, because inside template 14292 // auto can be deduced to a dependent type, which is not considered 14293 // "undeduced". 14294 if (FD->getReturnType()->getContainedDeducedType()) 14295 return false; 14296 } 14297 return Consumer.shouldSkipFunctionBody(D); 14298 } 14299 14300 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14301 if (!Decl) 14302 return nullptr; 14303 if (FunctionDecl *FD = Decl->getAsFunction()) 14304 FD->setHasSkippedBody(); 14305 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14306 MD->setHasSkippedBody(); 14307 return Decl; 14308 } 14309 14310 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14311 return ActOnFinishFunctionBody(D, BodyArg, false); 14312 } 14313 14314 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14315 /// body. 14316 class ExitFunctionBodyRAII { 14317 public: 14318 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14319 ~ExitFunctionBodyRAII() { 14320 if (!IsLambda) 14321 S.PopExpressionEvaluationContext(); 14322 } 14323 14324 private: 14325 Sema &S; 14326 bool IsLambda = false; 14327 }; 14328 14329 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14330 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14331 14332 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14333 if (EscapeInfo.count(BD)) 14334 return EscapeInfo[BD]; 14335 14336 bool R = false; 14337 const BlockDecl *CurBD = BD; 14338 14339 do { 14340 R = !CurBD->doesNotEscape(); 14341 if (R) 14342 break; 14343 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14344 } while (CurBD); 14345 14346 return EscapeInfo[BD] = R; 14347 }; 14348 14349 // If the location where 'self' is implicitly retained is inside a escaping 14350 // block, emit a diagnostic. 14351 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14352 S.ImplicitlyRetainedSelfLocs) 14353 if (IsOrNestedInEscapingBlock(P.second)) 14354 S.Diag(P.first, diag::warn_implicitly_retains_self) 14355 << FixItHint::CreateInsertion(P.first, "self->"); 14356 } 14357 14358 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14359 bool IsInstantiation) { 14360 FunctionScopeInfo *FSI = getCurFunction(); 14361 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14362 14363 if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>()) 14364 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14365 14366 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14367 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14368 14369 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14370 CheckCompletedCoroutineBody(FD, Body); 14371 14372 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14373 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14374 // meant to pop the context added in ActOnStartOfFunctionDef(). 14375 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14376 14377 if (FD) { 14378 FD->setBody(Body); 14379 FD->setWillHaveBody(false); 14380 14381 if (getLangOpts().CPlusPlus14) { 14382 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14383 FD->getReturnType()->isUndeducedType()) { 14384 // If the function has a deduced result type but contains no 'return' 14385 // statements, the result type as written must be exactly 'auto', and 14386 // the deduced result type is 'void'. 14387 if (!FD->getReturnType()->getAs<AutoType>()) { 14388 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14389 << FD->getReturnType(); 14390 FD->setInvalidDecl(); 14391 } else { 14392 // Substitute 'void' for the 'auto' in the type. 14393 TypeLoc ResultType = getReturnTypeLoc(FD); 14394 Context.adjustDeducedFunctionResultType( 14395 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14396 } 14397 } 14398 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14399 // In C++11, we don't use 'auto' deduction rules for lambda call 14400 // operators because we don't support return type deduction. 14401 auto *LSI = getCurLambda(); 14402 if (LSI->HasImplicitReturnType) { 14403 deduceClosureReturnType(*LSI); 14404 14405 // C++11 [expr.prim.lambda]p4: 14406 // [...] if there are no return statements in the compound-statement 14407 // [the deduced type is] the type void 14408 QualType RetType = 14409 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14410 14411 // Update the return type to the deduced type. 14412 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14413 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14414 Proto->getExtProtoInfo())); 14415 } 14416 } 14417 14418 // If the function implicitly returns zero (like 'main') or is naked, 14419 // don't complain about missing return statements. 14420 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14421 WP.disableCheckFallThrough(); 14422 14423 // MSVC permits the use of pure specifier (=0) on function definition, 14424 // defined at class scope, warn about this non-standard construct. 14425 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14426 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14427 14428 if (!FD->isInvalidDecl()) { 14429 // Don't diagnose unused parameters of defaulted or deleted functions. 14430 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14431 DiagnoseUnusedParameters(FD->parameters()); 14432 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14433 FD->getReturnType(), FD); 14434 14435 // If this is a structor, we need a vtable. 14436 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14437 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14438 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14439 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14440 14441 // Try to apply the named return value optimization. We have to check 14442 // if we can do this here because lambdas keep return statements around 14443 // to deduce an implicit return type. 14444 if (FD->getReturnType()->isRecordType() && 14445 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14446 computeNRVO(Body, FSI); 14447 } 14448 14449 // GNU warning -Wmissing-prototypes: 14450 // Warn if a global function is defined without a previous 14451 // prototype declaration. This warning is issued even if the 14452 // definition itself provides a prototype. The aim is to detect 14453 // global functions that fail to be declared in header files. 14454 const FunctionDecl *PossiblePrototype = nullptr; 14455 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14456 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14457 14458 if (PossiblePrototype) { 14459 // We found a declaration that is not a prototype, 14460 // but that could be a zero-parameter prototype 14461 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14462 TypeLoc TL = TI->getTypeLoc(); 14463 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14464 Diag(PossiblePrototype->getLocation(), 14465 diag::note_declaration_not_a_prototype) 14466 << (FD->getNumParams() != 0) 14467 << (FD->getNumParams() == 0 14468 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14469 : FixItHint{}); 14470 } 14471 } else { 14472 // Returns true if the token beginning at this Loc is `const`. 14473 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14474 const LangOptions &LangOpts) { 14475 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14476 if (LocInfo.first.isInvalid()) 14477 return false; 14478 14479 bool Invalid = false; 14480 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14481 if (Invalid) 14482 return false; 14483 14484 if (LocInfo.second > Buffer.size()) 14485 return false; 14486 14487 const char *LexStart = Buffer.data() + LocInfo.second; 14488 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14489 14490 return StartTok.consume_front("const") && 14491 (StartTok.empty() || isWhitespace(StartTok[0]) || 14492 StartTok.startswith("/*") || StartTok.startswith("//")); 14493 }; 14494 14495 auto findBeginLoc = [&]() { 14496 // If the return type has `const` qualifier, we want to insert 14497 // `static` before `const` (and not before the typename). 14498 if ((FD->getReturnType()->isAnyPointerType() && 14499 FD->getReturnType()->getPointeeType().isConstQualified()) || 14500 FD->getReturnType().isConstQualified()) { 14501 // But only do this if we can determine where the `const` is. 14502 14503 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14504 getLangOpts())) 14505 14506 return FD->getBeginLoc(); 14507 } 14508 return FD->getTypeSpecStartLoc(); 14509 }; 14510 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14511 << /* function */ 1 14512 << (FD->getStorageClass() == SC_None 14513 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14514 : FixItHint{}); 14515 } 14516 14517 // GNU warning -Wstrict-prototypes 14518 // Warn if K&R function is defined without a previous declaration. 14519 // This warning is issued only if the definition itself does not provide 14520 // a prototype. Only K&R definitions do not provide a prototype. 14521 if (!FD->hasWrittenPrototype()) { 14522 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14523 TypeLoc TL = TI->getTypeLoc(); 14524 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14525 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14526 } 14527 } 14528 14529 // Warn on CPUDispatch with an actual body. 14530 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14531 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14532 if (!CmpndBody->body_empty()) 14533 Diag(CmpndBody->body_front()->getBeginLoc(), 14534 diag::warn_dispatch_body_ignored); 14535 14536 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14537 const CXXMethodDecl *KeyFunction; 14538 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14539 MD->isVirtual() && 14540 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14541 MD == KeyFunction->getCanonicalDecl()) { 14542 // Update the key-function state if necessary for this ABI. 14543 if (FD->isInlined() && 14544 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14545 Context.setNonKeyFunction(MD); 14546 14547 // If the newly-chosen key function is already defined, then we 14548 // need to mark the vtable as used retroactively. 14549 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14550 const FunctionDecl *Definition; 14551 if (KeyFunction && KeyFunction->isDefined(Definition)) 14552 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14553 } else { 14554 // We just defined they key function; mark the vtable as used. 14555 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14556 } 14557 } 14558 } 14559 14560 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14561 "Function parsing confused"); 14562 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14563 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14564 MD->setBody(Body); 14565 if (!MD->isInvalidDecl()) { 14566 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14567 MD->getReturnType(), MD); 14568 14569 if (Body) 14570 computeNRVO(Body, FSI); 14571 } 14572 if (FSI->ObjCShouldCallSuper) { 14573 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14574 << MD->getSelector().getAsString(); 14575 FSI->ObjCShouldCallSuper = false; 14576 } 14577 if (FSI->ObjCWarnForNoDesignatedInitChain) { 14578 const ObjCMethodDecl *InitMethod = nullptr; 14579 bool isDesignated = 14580 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14581 assert(isDesignated && InitMethod); 14582 (void)isDesignated; 14583 14584 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14585 auto IFace = MD->getClassInterface(); 14586 if (!IFace) 14587 return false; 14588 auto SuperD = IFace->getSuperClass(); 14589 if (!SuperD) 14590 return false; 14591 return SuperD->getIdentifier() == 14592 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14593 }; 14594 // Don't issue this warning for unavailable inits or direct subclasses 14595 // of NSObject. 14596 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14597 Diag(MD->getLocation(), 14598 diag::warn_objc_designated_init_missing_super_call); 14599 Diag(InitMethod->getLocation(), 14600 diag::note_objc_designated_init_marked_here); 14601 } 14602 FSI->ObjCWarnForNoDesignatedInitChain = false; 14603 } 14604 if (FSI->ObjCWarnForNoInitDelegation) { 14605 // Don't issue this warning for unavaialable inits. 14606 if (!MD->isUnavailable()) 14607 Diag(MD->getLocation(), 14608 diag::warn_objc_secondary_init_missing_init_call); 14609 FSI->ObjCWarnForNoInitDelegation = false; 14610 } 14611 14612 diagnoseImplicitlyRetainedSelf(*this); 14613 } else { 14614 // Parsing the function declaration failed in some way. Pop the fake scope 14615 // we pushed on. 14616 PopFunctionScopeInfo(ActivePolicy, dcl); 14617 return nullptr; 14618 } 14619 14620 if (Body && FSI->HasPotentialAvailabilityViolations) 14621 DiagnoseUnguardedAvailabilityViolations(dcl); 14622 14623 assert(!FSI->ObjCShouldCallSuper && 14624 "This should only be set for ObjC methods, which should have been " 14625 "handled in the block above."); 14626 14627 // Verify and clean out per-function state. 14628 if (Body && (!FD || !FD->isDefaulted())) { 14629 // C++ constructors that have function-try-blocks can't have return 14630 // statements in the handlers of that block. (C++ [except.handle]p14) 14631 // Verify this. 14632 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14633 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14634 14635 // Verify that gotos and switch cases don't jump into scopes illegally. 14636 if (FSI->NeedsScopeChecking() && 14637 !PP.isCodeCompletionEnabled()) 14638 DiagnoseInvalidJumps(Body); 14639 14640 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14641 if (!Destructor->getParent()->isDependentType()) 14642 CheckDestructor(Destructor); 14643 14644 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14645 Destructor->getParent()); 14646 } 14647 14648 // If any errors have occurred, clear out any temporaries that may have 14649 // been leftover. This ensures that these temporaries won't be picked up for 14650 // deletion in some later function. 14651 if (hasUncompilableErrorOccurred() || 14652 getDiagnostics().getSuppressAllDiagnostics()) { 14653 DiscardCleanupsInEvaluationContext(); 14654 } 14655 if (!hasUncompilableErrorOccurred() && 14656 !isa<FunctionTemplateDecl>(dcl)) { 14657 // Since the body is valid, issue any analysis-based warnings that are 14658 // enabled. 14659 ActivePolicy = &WP; 14660 } 14661 14662 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14663 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14664 FD->setInvalidDecl(); 14665 14666 if (FD && FD->hasAttr<NakedAttr>()) { 14667 for (const Stmt *S : Body->children()) { 14668 // Allow local register variables without initializer as they don't 14669 // require prologue. 14670 bool RegisterVariables = false; 14671 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14672 for (const auto *Decl : DS->decls()) { 14673 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14674 RegisterVariables = 14675 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14676 if (!RegisterVariables) 14677 break; 14678 } 14679 } 14680 } 14681 if (RegisterVariables) 14682 continue; 14683 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14684 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14685 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14686 FD->setInvalidDecl(); 14687 break; 14688 } 14689 } 14690 } 14691 14692 assert(ExprCleanupObjects.size() == 14693 ExprEvalContexts.back().NumCleanupObjects && 14694 "Leftover temporaries in function"); 14695 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14696 assert(MaybeODRUseExprs.empty() && 14697 "Leftover expressions for odr-use checking"); 14698 } 14699 14700 if (!IsInstantiation) 14701 PopDeclContext(); 14702 14703 PopFunctionScopeInfo(ActivePolicy, dcl); 14704 // If any errors have occurred, clear out any temporaries that may have 14705 // been leftover. This ensures that these temporaries won't be picked up for 14706 // deletion in some later function. 14707 if (hasUncompilableErrorOccurred()) { 14708 DiscardCleanupsInEvaluationContext(); 14709 } 14710 14711 if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 14712 auto ES = getEmissionStatus(FD); 14713 if (ES == Sema::FunctionEmissionStatus::Emitted || 14714 ES == Sema::FunctionEmissionStatus::Unknown) 14715 DeclsToCheckForDeferredDiags.push_back(FD); 14716 } 14717 14718 return dcl; 14719 } 14720 14721 /// When we finish delayed parsing of an attribute, we must attach it to the 14722 /// relevant Decl. 14723 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14724 ParsedAttributes &Attrs) { 14725 // Always attach attributes to the underlying decl. 14726 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14727 D = TD->getTemplatedDecl(); 14728 ProcessDeclAttributeList(S, D, Attrs); 14729 14730 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14731 if (Method->isStatic()) 14732 checkThisInStaticMemberFunctionAttributes(Method); 14733 } 14734 14735 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14736 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14737 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14738 IdentifierInfo &II, Scope *S) { 14739 // Find the scope in which the identifier is injected and the corresponding 14740 // DeclContext. 14741 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14742 // In that case, we inject the declaration into the translation unit scope 14743 // instead. 14744 Scope *BlockScope = S; 14745 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14746 BlockScope = BlockScope->getParent(); 14747 14748 Scope *ContextScope = BlockScope; 14749 while (!ContextScope->getEntity()) 14750 ContextScope = ContextScope->getParent(); 14751 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14752 14753 // Before we produce a declaration for an implicitly defined 14754 // function, see whether there was a locally-scoped declaration of 14755 // this name as a function or variable. If so, use that 14756 // (non-visible) declaration, and complain about it. 14757 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14758 if (ExternCPrev) { 14759 // We still need to inject the function into the enclosing block scope so 14760 // that later (non-call) uses can see it. 14761 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14762 14763 // C89 footnote 38: 14764 // If in fact it is not defined as having type "function returning int", 14765 // the behavior is undefined. 14766 if (!isa<FunctionDecl>(ExternCPrev) || 14767 !Context.typesAreCompatible( 14768 cast<FunctionDecl>(ExternCPrev)->getType(), 14769 Context.getFunctionNoProtoType(Context.IntTy))) { 14770 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14771 << ExternCPrev << !getLangOpts().C99; 14772 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14773 return ExternCPrev; 14774 } 14775 } 14776 14777 // Extension in C99. Legal in C90, but warn about it. 14778 unsigned diag_id; 14779 if (II.getName().startswith("__builtin_")) 14780 diag_id = diag::warn_builtin_unknown; 14781 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14782 else if (getLangOpts().OpenCL) 14783 diag_id = diag::err_opencl_implicit_function_decl; 14784 else if (getLangOpts().C99) 14785 diag_id = diag::ext_implicit_function_decl; 14786 else 14787 diag_id = diag::warn_implicit_function_decl; 14788 Diag(Loc, diag_id) << &II; 14789 14790 // If we found a prior declaration of this function, don't bother building 14791 // another one. We've already pushed that one into scope, so there's nothing 14792 // more to do. 14793 if (ExternCPrev) 14794 return ExternCPrev; 14795 14796 // Because typo correction is expensive, only do it if the implicit 14797 // function declaration is going to be treated as an error. 14798 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14799 TypoCorrection Corrected; 14800 DeclFilterCCC<FunctionDecl> CCC{}; 14801 if (S && (Corrected = 14802 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14803 S, nullptr, CCC, CTK_NonError))) 14804 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14805 /*ErrorRecovery*/false); 14806 } 14807 14808 // Set a Declarator for the implicit definition: int foo(); 14809 const char *Dummy; 14810 AttributeFactory attrFactory; 14811 DeclSpec DS(attrFactory); 14812 unsigned DiagID; 14813 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14814 Context.getPrintingPolicy()); 14815 (void)Error; // Silence warning. 14816 assert(!Error && "Error setting up implicit decl!"); 14817 SourceLocation NoLoc; 14818 Declarator D(DS, DeclaratorContext::Block); 14819 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14820 /*IsAmbiguous=*/false, 14821 /*LParenLoc=*/NoLoc, 14822 /*Params=*/nullptr, 14823 /*NumParams=*/0, 14824 /*EllipsisLoc=*/NoLoc, 14825 /*RParenLoc=*/NoLoc, 14826 /*RefQualifierIsLvalueRef=*/true, 14827 /*RefQualifierLoc=*/NoLoc, 14828 /*MutableLoc=*/NoLoc, EST_None, 14829 /*ESpecRange=*/SourceRange(), 14830 /*Exceptions=*/nullptr, 14831 /*ExceptionRanges=*/nullptr, 14832 /*NumExceptions=*/0, 14833 /*NoexceptExpr=*/nullptr, 14834 /*ExceptionSpecTokens=*/nullptr, 14835 /*DeclsInPrototype=*/None, Loc, 14836 Loc, D), 14837 std::move(DS.getAttributes()), SourceLocation()); 14838 D.SetIdentifier(&II, Loc); 14839 14840 // Insert this function into the enclosing block scope. 14841 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14842 FD->setImplicit(); 14843 14844 AddKnownFunctionAttributes(FD); 14845 14846 return FD; 14847 } 14848 14849 /// If this function is a C++ replaceable global allocation function 14850 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14851 /// adds any function attributes that we know a priori based on the standard. 14852 /// 14853 /// We need to check for duplicate attributes both here and where user-written 14854 /// attributes are applied to declarations. 14855 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14856 FunctionDecl *FD) { 14857 if (FD->isInvalidDecl()) 14858 return; 14859 14860 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14861 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14862 return; 14863 14864 Optional<unsigned> AlignmentParam; 14865 bool IsNothrow = false; 14866 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14867 return; 14868 14869 // C++2a [basic.stc.dynamic.allocation]p4: 14870 // An allocation function that has a non-throwing exception specification 14871 // indicates failure by returning a null pointer value. Any other allocation 14872 // function never returns a null pointer value and indicates failure only by 14873 // throwing an exception [...] 14874 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14875 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14876 14877 // C++2a [basic.stc.dynamic.allocation]p2: 14878 // An allocation function attempts to allocate the requested amount of 14879 // storage. [...] If the request succeeds, the value returned by a 14880 // replaceable allocation function is a [...] pointer value p0 different 14881 // from any previously returned value p1 [...] 14882 // 14883 // However, this particular information is being added in codegen, 14884 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14885 14886 // C++2a [basic.stc.dynamic.allocation]p2: 14887 // An allocation function attempts to allocate the requested amount of 14888 // storage. If it is successful, it returns the address of the start of a 14889 // block of storage whose length in bytes is at least as large as the 14890 // requested size. 14891 if (!FD->hasAttr<AllocSizeAttr>()) { 14892 FD->addAttr(AllocSizeAttr::CreateImplicit( 14893 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14894 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14895 } 14896 14897 // C++2a [basic.stc.dynamic.allocation]p3: 14898 // For an allocation function [...], the pointer returned on a successful 14899 // call shall represent the address of storage that is aligned as follows: 14900 // (3.1) If the allocation function takes an argument of type 14901 // std::align_val_t, the storage will have the alignment 14902 // specified by the value of this argument. 14903 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14904 FD->addAttr(AllocAlignAttr::CreateImplicit( 14905 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14906 } 14907 14908 // FIXME: 14909 // C++2a [basic.stc.dynamic.allocation]p3: 14910 // For an allocation function [...], the pointer returned on a successful 14911 // call shall represent the address of storage that is aligned as follows: 14912 // (3.2) Otherwise, if the allocation function is named operator new[], 14913 // the storage is aligned for any object that does not have 14914 // new-extended alignment ([basic.align]) and is no larger than the 14915 // requested size. 14916 // (3.3) Otherwise, the storage is aligned for any object that does not 14917 // have new-extended alignment and is of the requested size. 14918 } 14919 14920 /// Adds any function attributes that we know a priori based on 14921 /// the declaration of this function. 14922 /// 14923 /// These attributes can apply both to implicitly-declared builtins 14924 /// (like __builtin___printf_chk) or to library-declared functions 14925 /// like NSLog or printf. 14926 /// 14927 /// We need to check for duplicate attributes both here and where user-written 14928 /// attributes are applied to declarations. 14929 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14930 if (FD->isInvalidDecl()) 14931 return; 14932 14933 // If this is a built-in function, map its builtin attributes to 14934 // actual attributes. 14935 if (unsigned BuiltinID = FD->getBuiltinID()) { 14936 // Handle printf-formatting attributes. 14937 unsigned FormatIdx; 14938 bool HasVAListArg; 14939 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14940 if (!FD->hasAttr<FormatAttr>()) { 14941 const char *fmt = "printf"; 14942 unsigned int NumParams = FD->getNumParams(); 14943 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14944 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14945 fmt = "NSString"; 14946 FD->addAttr(FormatAttr::CreateImplicit(Context, 14947 &Context.Idents.get(fmt), 14948 FormatIdx+1, 14949 HasVAListArg ? 0 : FormatIdx+2, 14950 FD->getLocation())); 14951 } 14952 } 14953 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14954 HasVAListArg)) { 14955 if (!FD->hasAttr<FormatAttr>()) 14956 FD->addAttr(FormatAttr::CreateImplicit(Context, 14957 &Context.Idents.get("scanf"), 14958 FormatIdx+1, 14959 HasVAListArg ? 0 : FormatIdx+2, 14960 FD->getLocation())); 14961 } 14962 14963 // Handle automatically recognized callbacks. 14964 SmallVector<int, 4> Encoding; 14965 if (!FD->hasAttr<CallbackAttr>() && 14966 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14967 FD->addAttr(CallbackAttr::CreateImplicit( 14968 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14969 14970 // Mark const if we don't care about errno and that is the only thing 14971 // preventing the function from being const. This allows IRgen to use LLVM 14972 // intrinsics for such functions. 14973 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14974 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14975 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14976 14977 // We make "fma" on some platforms const because we know it does not set 14978 // errno in those environments even though it could set errno based on the 14979 // C standard. 14980 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14981 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14982 !FD->hasAttr<ConstAttr>()) { 14983 switch (BuiltinID) { 14984 case Builtin::BI__builtin_fma: 14985 case Builtin::BI__builtin_fmaf: 14986 case Builtin::BI__builtin_fmal: 14987 case Builtin::BIfma: 14988 case Builtin::BIfmaf: 14989 case Builtin::BIfmal: 14990 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14991 break; 14992 default: 14993 break; 14994 } 14995 } 14996 14997 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14998 !FD->hasAttr<ReturnsTwiceAttr>()) 14999 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 15000 FD->getLocation())); 15001 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 15002 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15003 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 15004 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 15005 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 15006 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15007 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 15008 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 15009 // Add the appropriate attribute, depending on the CUDA compilation mode 15010 // and which target the builtin belongs to. For example, during host 15011 // compilation, aux builtins are __device__, while the rest are __host__. 15012 if (getLangOpts().CUDAIsDevice != 15013 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 15014 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 15015 else 15016 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 15017 } 15018 } 15019 15020 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 15021 15022 // If C++ exceptions are enabled but we are told extern "C" functions cannot 15023 // throw, add an implicit nothrow attribute to any extern "C" function we come 15024 // across. 15025 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 15026 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 15027 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 15028 if (!FPT || FPT->getExceptionSpecType() == EST_None) 15029 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15030 } 15031 15032 IdentifierInfo *Name = FD->getIdentifier(); 15033 if (!Name) 15034 return; 15035 if ((!getLangOpts().CPlusPlus && 15036 FD->getDeclContext()->isTranslationUnit()) || 15037 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 15038 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 15039 LinkageSpecDecl::lang_c)) { 15040 // Okay: this could be a libc/libm/Objective-C function we know 15041 // about. 15042 } else 15043 return; 15044 15045 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 15046 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 15047 // target-specific builtins, perhaps? 15048 if (!FD->hasAttr<FormatAttr>()) 15049 FD->addAttr(FormatAttr::CreateImplicit(Context, 15050 &Context.Idents.get("printf"), 2, 15051 Name->isStr("vasprintf") ? 0 : 3, 15052 FD->getLocation())); 15053 } 15054 15055 if (Name->isStr("__CFStringMakeConstantString")) { 15056 // We already have a __builtin___CFStringMakeConstantString, 15057 // but builds that use -fno-constant-cfstrings don't go through that. 15058 if (!FD->hasAttr<FormatArgAttr>()) 15059 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 15060 FD->getLocation())); 15061 } 15062 } 15063 15064 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15065 TypeSourceInfo *TInfo) { 15066 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 15067 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15068 15069 if (!TInfo) { 15070 assert(D.isInvalidType() && "no declarator info for valid type"); 15071 TInfo = Context.getTrivialTypeSourceInfo(T); 15072 } 15073 15074 // Scope manipulation handled by caller. 15075 TypedefDecl *NewTD = 15076 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15077 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15078 15079 // Bail out immediately if we have an invalid declaration. 15080 if (D.isInvalidType()) { 15081 NewTD->setInvalidDecl(); 15082 return NewTD; 15083 } 15084 15085 if (D.getDeclSpec().isModulePrivateSpecified()) { 15086 if (CurContext->isFunctionOrMethod()) 15087 Diag(NewTD->getLocation(), diag::err_module_private_local) 15088 << 2 << NewTD 15089 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15090 << FixItHint::CreateRemoval( 15091 D.getDeclSpec().getModulePrivateSpecLoc()); 15092 else 15093 NewTD->setModulePrivate(); 15094 } 15095 15096 // C++ [dcl.typedef]p8: 15097 // If the typedef declaration defines an unnamed class (or 15098 // enum), the first typedef-name declared by the declaration 15099 // to be that class type (or enum type) is used to denote the 15100 // class type (or enum type) for linkage purposes only. 15101 // We need to check whether the type was declared in the declaration. 15102 switch (D.getDeclSpec().getTypeSpecType()) { 15103 case TST_enum: 15104 case TST_struct: 15105 case TST_interface: 15106 case TST_union: 15107 case TST_class: { 15108 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15109 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15110 break; 15111 } 15112 15113 default: 15114 break; 15115 } 15116 15117 return NewTD; 15118 } 15119 15120 /// Check that this is a valid underlying type for an enum declaration. 15121 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15122 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15123 QualType T = TI->getType(); 15124 15125 if (T->isDependentType()) 15126 return false; 15127 15128 // This doesn't use 'isIntegralType' despite the error message mentioning 15129 // integral type because isIntegralType would also allow enum types in C. 15130 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15131 if (BT->isInteger()) 15132 return false; 15133 15134 if (T->isExtIntType()) 15135 return false; 15136 15137 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15138 } 15139 15140 /// Check whether this is a valid redeclaration of a previous enumeration. 15141 /// \return true if the redeclaration was invalid. 15142 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15143 QualType EnumUnderlyingTy, bool IsFixed, 15144 const EnumDecl *Prev) { 15145 if (IsScoped != Prev->isScoped()) { 15146 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15147 << Prev->isScoped(); 15148 Diag(Prev->getLocation(), diag::note_previous_declaration); 15149 return true; 15150 } 15151 15152 if (IsFixed && Prev->isFixed()) { 15153 if (!EnumUnderlyingTy->isDependentType() && 15154 !Prev->getIntegerType()->isDependentType() && 15155 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15156 Prev->getIntegerType())) { 15157 // TODO: Highlight the underlying type of the redeclaration. 15158 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15159 << EnumUnderlyingTy << Prev->getIntegerType(); 15160 Diag(Prev->getLocation(), diag::note_previous_declaration) 15161 << Prev->getIntegerTypeRange(); 15162 return true; 15163 } 15164 } else if (IsFixed != Prev->isFixed()) { 15165 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15166 << Prev->isFixed(); 15167 Diag(Prev->getLocation(), diag::note_previous_declaration); 15168 return true; 15169 } 15170 15171 return false; 15172 } 15173 15174 /// Get diagnostic %select index for tag kind for 15175 /// redeclaration diagnostic message. 15176 /// WARNING: Indexes apply to particular diagnostics only! 15177 /// 15178 /// \returns diagnostic %select index. 15179 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15180 switch (Tag) { 15181 case TTK_Struct: return 0; 15182 case TTK_Interface: return 1; 15183 case TTK_Class: return 2; 15184 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15185 } 15186 } 15187 15188 /// Determine if tag kind is a class-key compatible with 15189 /// class for redeclaration (class, struct, or __interface). 15190 /// 15191 /// \returns true iff the tag kind is compatible. 15192 static bool isClassCompatTagKind(TagTypeKind Tag) 15193 { 15194 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15195 } 15196 15197 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15198 TagTypeKind TTK) { 15199 if (isa<TypedefDecl>(PrevDecl)) 15200 return NTK_Typedef; 15201 else if (isa<TypeAliasDecl>(PrevDecl)) 15202 return NTK_TypeAlias; 15203 else if (isa<ClassTemplateDecl>(PrevDecl)) 15204 return NTK_Template; 15205 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15206 return NTK_TypeAliasTemplate; 15207 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15208 return NTK_TemplateTemplateArgument; 15209 switch (TTK) { 15210 case TTK_Struct: 15211 case TTK_Interface: 15212 case TTK_Class: 15213 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15214 case TTK_Union: 15215 return NTK_NonUnion; 15216 case TTK_Enum: 15217 return NTK_NonEnum; 15218 } 15219 llvm_unreachable("invalid TTK"); 15220 } 15221 15222 /// Determine whether a tag with a given kind is acceptable 15223 /// as a redeclaration of the given tag declaration. 15224 /// 15225 /// \returns true if the new tag kind is acceptable, false otherwise. 15226 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15227 TagTypeKind NewTag, bool isDefinition, 15228 SourceLocation NewTagLoc, 15229 const IdentifierInfo *Name) { 15230 // C++ [dcl.type.elab]p3: 15231 // The class-key or enum keyword present in the 15232 // elaborated-type-specifier shall agree in kind with the 15233 // declaration to which the name in the elaborated-type-specifier 15234 // refers. This rule also applies to the form of 15235 // elaborated-type-specifier that declares a class-name or 15236 // friend class since it can be construed as referring to the 15237 // definition of the class. Thus, in any 15238 // elaborated-type-specifier, the enum keyword shall be used to 15239 // refer to an enumeration (7.2), the union class-key shall be 15240 // used to refer to a union (clause 9), and either the class or 15241 // struct class-key shall be used to refer to a class (clause 9) 15242 // declared using the class or struct class-key. 15243 TagTypeKind OldTag = Previous->getTagKind(); 15244 if (OldTag != NewTag && 15245 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15246 return false; 15247 15248 // Tags are compatible, but we might still want to warn on mismatched tags. 15249 // Non-class tags can't be mismatched at this point. 15250 if (!isClassCompatTagKind(NewTag)) 15251 return true; 15252 15253 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15254 // by our warning analysis. We don't want to warn about mismatches with (eg) 15255 // declarations in system headers that are designed to be specialized, but if 15256 // a user asks us to warn, we should warn if their code contains mismatched 15257 // declarations. 15258 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15259 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15260 Loc); 15261 }; 15262 if (IsIgnoredLoc(NewTagLoc)) 15263 return true; 15264 15265 auto IsIgnored = [&](const TagDecl *Tag) { 15266 return IsIgnoredLoc(Tag->getLocation()); 15267 }; 15268 while (IsIgnored(Previous)) { 15269 Previous = Previous->getPreviousDecl(); 15270 if (!Previous) 15271 return true; 15272 OldTag = Previous->getTagKind(); 15273 } 15274 15275 bool isTemplate = false; 15276 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15277 isTemplate = Record->getDescribedClassTemplate(); 15278 15279 if (inTemplateInstantiation()) { 15280 if (OldTag != NewTag) { 15281 // In a template instantiation, do not offer fix-its for tag mismatches 15282 // since they usually mess up the template instead of fixing the problem. 15283 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15284 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15285 << getRedeclDiagFromTagKind(OldTag); 15286 // FIXME: Note previous location? 15287 } 15288 return true; 15289 } 15290 15291 if (isDefinition) { 15292 // On definitions, check all previous tags and issue a fix-it for each 15293 // one that doesn't match the current tag. 15294 if (Previous->getDefinition()) { 15295 // Don't suggest fix-its for redefinitions. 15296 return true; 15297 } 15298 15299 bool previousMismatch = false; 15300 for (const TagDecl *I : Previous->redecls()) { 15301 if (I->getTagKind() != NewTag) { 15302 // Ignore previous declarations for which the warning was disabled. 15303 if (IsIgnored(I)) 15304 continue; 15305 15306 if (!previousMismatch) { 15307 previousMismatch = true; 15308 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15309 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15310 << getRedeclDiagFromTagKind(I->getTagKind()); 15311 } 15312 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15313 << getRedeclDiagFromTagKind(NewTag) 15314 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15315 TypeWithKeyword::getTagTypeKindName(NewTag)); 15316 } 15317 } 15318 return true; 15319 } 15320 15321 // Identify the prevailing tag kind: this is the kind of the definition (if 15322 // there is a non-ignored definition), or otherwise the kind of the prior 15323 // (non-ignored) declaration. 15324 const TagDecl *PrevDef = Previous->getDefinition(); 15325 if (PrevDef && IsIgnored(PrevDef)) 15326 PrevDef = nullptr; 15327 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15328 if (Redecl->getTagKind() != NewTag) { 15329 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15330 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15331 << getRedeclDiagFromTagKind(OldTag); 15332 Diag(Redecl->getLocation(), diag::note_previous_use); 15333 15334 // If there is a previous definition, suggest a fix-it. 15335 if (PrevDef) { 15336 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15337 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15338 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15339 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15340 } 15341 } 15342 15343 return true; 15344 } 15345 15346 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15347 /// from an outer enclosing namespace or file scope inside a friend declaration. 15348 /// This should provide the commented out code in the following snippet: 15349 /// namespace N { 15350 /// struct X; 15351 /// namespace M { 15352 /// struct Y { friend struct /*N::*/ X; }; 15353 /// } 15354 /// } 15355 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15356 SourceLocation NameLoc) { 15357 // While the decl is in a namespace, do repeated lookup of that name and see 15358 // if we get the same namespace back. If we do not, continue until 15359 // translation unit scope, at which point we have a fully qualified NNS. 15360 SmallVector<IdentifierInfo *, 4> Namespaces; 15361 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15362 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15363 // This tag should be declared in a namespace, which can only be enclosed by 15364 // other namespaces. Bail if there's an anonymous namespace in the chain. 15365 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15366 if (!Namespace || Namespace->isAnonymousNamespace()) 15367 return FixItHint(); 15368 IdentifierInfo *II = Namespace->getIdentifier(); 15369 Namespaces.push_back(II); 15370 NamedDecl *Lookup = SemaRef.LookupSingleName( 15371 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15372 if (Lookup == Namespace) 15373 break; 15374 } 15375 15376 // Once we have all the namespaces, reverse them to go outermost first, and 15377 // build an NNS. 15378 SmallString<64> Insertion; 15379 llvm::raw_svector_ostream OS(Insertion); 15380 if (DC->isTranslationUnit()) 15381 OS << "::"; 15382 std::reverse(Namespaces.begin(), Namespaces.end()); 15383 for (auto *II : Namespaces) 15384 OS << II->getName() << "::"; 15385 return FixItHint::CreateInsertion(NameLoc, Insertion); 15386 } 15387 15388 /// Determine whether a tag originally declared in context \p OldDC can 15389 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15390 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15391 /// using-declaration). 15392 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15393 DeclContext *NewDC) { 15394 OldDC = OldDC->getRedeclContext(); 15395 NewDC = NewDC->getRedeclContext(); 15396 15397 if (OldDC->Equals(NewDC)) 15398 return true; 15399 15400 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15401 // encloses the other). 15402 if (S.getLangOpts().MSVCCompat && 15403 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15404 return true; 15405 15406 return false; 15407 } 15408 15409 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15410 /// former case, Name will be non-null. In the later case, Name will be null. 15411 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15412 /// reference/declaration/definition of a tag. 15413 /// 15414 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15415 /// trailing-type-specifier) other than one in an alias-declaration. 15416 /// 15417 /// \param SkipBody If non-null, will be set to indicate if the caller should 15418 /// skip the definition of this tag and treat it as if it were a declaration. 15419 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15420 SourceLocation KWLoc, CXXScopeSpec &SS, 15421 IdentifierInfo *Name, SourceLocation NameLoc, 15422 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15423 SourceLocation ModulePrivateLoc, 15424 MultiTemplateParamsArg TemplateParameterLists, 15425 bool &OwnedDecl, bool &IsDependent, 15426 SourceLocation ScopedEnumKWLoc, 15427 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15428 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15429 SkipBodyInfo *SkipBody) { 15430 // If this is not a definition, it must have a name. 15431 IdentifierInfo *OrigName = Name; 15432 assert((Name != nullptr || TUK == TUK_Definition) && 15433 "Nameless record must be a definition!"); 15434 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15435 15436 OwnedDecl = false; 15437 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15438 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15439 15440 // FIXME: Check member specializations more carefully. 15441 bool isMemberSpecialization = false; 15442 bool Invalid = false; 15443 15444 // We only need to do this matching if we have template parameters 15445 // or a scope specifier, which also conveniently avoids this work 15446 // for non-C++ cases. 15447 if (TemplateParameterLists.size() > 0 || 15448 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15449 if (TemplateParameterList *TemplateParams = 15450 MatchTemplateParametersToScopeSpecifier( 15451 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15452 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15453 if (Kind == TTK_Enum) { 15454 Diag(KWLoc, diag::err_enum_template); 15455 return nullptr; 15456 } 15457 15458 if (TemplateParams->size() > 0) { 15459 // This is a declaration or definition of a class template (which may 15460 // be a member of another template). 15461 15462 if (Invalid) 15463 return nullptr; 15464 15465 OwnedDecl = false; 15466 DeclResult Result = CheckClassTemplate( 15467 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15468 AS, ModulePrivateLoc, 15469 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15470 TemplateParameterLists.data(), SkipBody); 15471 return Result.get(); 15472 } else { 15473 // The "template<>" header is extraneous. 15474 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15475 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15476 isMemberSpecialization = true; 15477 } 15478 } 15479 15480 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15481 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15482 return nullptr; 15483 } 15484 15485 // Figure out the underlying type if this a enum declaration. We need to do 15486 // this early, because it's needed to detect if this is an incompatible 15487 // redeclaration. 15488 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15489 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15490 15491 if (Kind == TTK_Enum) { 15492 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15493 // No underlying type explicitly specified, or we failed to parse the 15494 // type, default to int. 15495 EnumUnderlying = Context.IntTy.getTypePtr(); 15496 } else if (UnderlyingType.get()) { 15497 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15498 // integral type; any cv-qualification is ignored. 15499 TypeSourceInfo *TI = nullptr; 15500 GetTypeFromParser(UnderlyingType.get(), &TI); 15501 EnumUnderlying = TI; 15502 15503 if (CheckEnumUnderlyingType(TI)) 15504 // Recover by falling back to int. 15505 EnumUnderlying = Context.IntTy.getTypePtr(); 15506 15507 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15508 UPPC_FixedUnderlyingType)) 15509 EnumUnderlying = Context.IntTy.getTypePtr(); 15510 15511 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15512 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15513 // of 'int'. However, if this is an unfixed forward declaration, don't set 15514 // the underlying type unless the user enables -fms-compatibility. This 15515 // makes unfixed forward declared enums incomplete and is more conforming. 15516 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15517 EnumUnderlying = Context.IntTy.getTypePtr(); 15518 } 15519 } 15520 15521 DeclContext *SearchDC = CurContext; 15522 DeclContext *DC = CurContext; 15523 bool isStdBadAlloc = false; 15524 bool isStdAlignValT = false; 15525 15526 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15527 if (TUK == TUK_Friend || TUK == TUK_Reference) 15528 Redecl = NotForRedeclaration; 15529 15530 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15531 /// implemented asks for structural equivalence checking, the returned decl 15532 /// here is passed back to the parser, allowing the tag body to be parsed. 15533 auto createTagFromNewDecl = [&]() -> TagDecl * { 15534 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15535 // If there is an identifier, use the location of the identifier as the 15536 // location of the decl, otherwise use the location of the struct/union 15537 // keyword. 15538 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15539 TagDecl *New = nullptr; 15540 15541 if (Kind == TTK_Enum) { 15542 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15543 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15544 // If this is an undefined enum, bail. 15545 if (TUK != TUK_Definition && !Invalid) 15546 return nullptr; 15547 if (EnumUnderlying) { 15548 EnumDecl *ED = cast<EnumDecl>(New); 15549 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15550 ED->setIntegerTypeSourceInfo(TI); 15551 else 15552 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15553 ED->setPromotionType(ED->getIntegerType()); 15554 } 15555 } else { // struct/union 15556 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15557 nullptr); 15558 } 15559 15560 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15561 // Add alignment attributes if necessary; these attributes are checked 15562 // when the ASTContext lays out the structure. 15563 // 15564 // It is important for implementing the correct semantics that this 15565 // happen here (in ActOnTag). The #pragma pack stack is 15566 // maintained as a result of parser callbacks which can occur at 15567 // many points during the parsing of a struct declaration (because 15568 // the #pragma tokens are effectively skipped over during the 15569 // parsing of the struct). 15570 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15571 AddAlignmentAttributesForRecord(RD); 15572 AddMsStructLayoutForRecord(RD); 15573 } 15574 } 15575 New->setLexicalDeclContext(CurContext); 15576 return New; 15577 }; 15578 15579 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15580 if (Name && SS.isNotEmpty()) { 15581 // We have a nested-name tag ('struct foo::bar'). 15582 15583 // Check for invalid 'foo::'. 15584 if (SS.isInvalid()) { 15585 Name = nullptr; 15586 goto CreateNewDecl; 15587 } 15588 15589 // If this is a friend or a reference to a class in a dependent 15590 // context, don't try to make a decl for it. 15591 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15592 DC = computeDeclContext(SS, false); 15593 if (!DC) { 15594 IsDependent = true; 15595 return nullptr; 15596 } 15597 } else { 15598 DC = computeDeclContext(SS, true); 15599 if (!DC) { 15600 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15601 << SS.getRange(); 15602 return nullptr; 15603 } 15604 } 15605 15606 if (RequireCompleteDeclContext(SS, DC)) 15607 return nullptr; 15608 15609 SearchDC = DC; 15610 // Look-up name inside 'foo::'. 15611 LookupQualifiedName(Previous, DC); 15612 15613 if (Previous.isAmbiguous()) 15614 return nullptr; 15615 15616 if (Previous.empty()) { 15617 // Name lookup did not find anything. However, if the 15618 // nested-name-specifier refers to the current instantiation, 15619 // and that current instantiation has any dependent base 15620 // classes, we might find something at instantiation time: treat 15621 // this as a dependent elaborated-type-specifier. 15622 // But this only makes any sense for reference-like lookups. 15623 if (Previous.wasNotFoundInCurrentInstantiation() && 15624 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15625 IsDependent = true; 15626 return nullptr; 15627 } 15628 15629 // A tag 'foo::bar' must already exist. 15630 Diag(NameLoc, diag::err_not_tag_in_scope) 15631 << Kind << Name << DC << SS.getRange(); 15632 Name = nullptr; 15633 Invalid = true; 15634 goto CreateNewDecl; 15635 } 15636 } else if (Name) { 15637 // C++14 [class.mem]p14: 15638 // If T is the name of a class, then each of the following shall have a 15639 // name different from T: 15640 // -- every member of class T that is itself a type 15641 if (TUK != TUK_Reference && TUK != TUK_Friend && 15642 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15643 return nullptr; 15644 15645 // If this is a named struct, check to see if there was a previous forward 15646 // declaration or definition. 15647 // FIXME: We're looking into outer scopes here, even when we 15648 // shouldn't be. Doing so can result in ambiguities that we 15649 // shouldn't be diagnosing. 15650 LookupName(Previous, S); 15651 15652 // When declaring or defining a tag, ignore ambiguities introduced 15653 // by types using'ed into this scope. 15654 if (Previous.isAmbiguous() && 15655 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15656 LookupResult::Filter F = Previous.makeFilter(); 15657 while (F.hasNext()) { 15658 NamedDecl *ND = F.next(); 15659 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15660 SearchDC->getRedeclContext())) 15661 F.erase(); 15662 } 15663 F.done(); 15664 } 15665 15666 // C++11 [namespace.memdef]p3: 15667 // If the name in a friend declaration is neither qualified nor 15668 // a template-id and the declaration is a function or an 15669 // elaborated-type-specifier, the lookup to determine whether 15670 // the entity has been previously declared shall not consider 15671 // any scopes outside the innermost enclosing namespace. 15672 // 15673 // MSVC doesn't implement the above rule for types, so a friend tag 15674 // declaration may be a redeclaration of a type declared in an enclosing 15675 // scope. They do implement this rule for friend functions. 15676 // 15677 // Does it matter that this should be by scope instead of by 15678 // semantic context? 15679 if (!Previous.empty() && TUK == TUK_Friend) { 15680 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15681 LookupResult::Filter F = Previous.makeFilter(); 15682 bool FriendSawTagOutsideEnclosingNamespace = false; 15683 while (F.hasNext()) { 15684 NamedDecl *ND = F.next(); 15685 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15686 if (DC->isFileContext() && 15687 !EnclosingNS->Encloses(ND->getDeclContext())) { 15688 if (getLangOpts().MSVCCompat) 15689 FriendSawTagOutsideEnclosingNamespace = true; 15690 else 15691 F.erase(); 15692 } 15693 } 15694 F.done(); 15695 15696 // Diagnose this MSVC extension in the easy case where lookup would have 15697 // unambiguously found something outside the enclosing namespace. 15698 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15699 NamedDecl *ND = Previous.getFoundDecl(); 15700 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15701 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15702 } 15703 } 15704 15705 // Note: there used to be some attempt at recovery here. 15706 if (Previous.isAmbiguous()) 15707 return nullptr; 15708 15709 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15710 // FIXME: This makes sure that we ignore the contexts associated 15711 // with C structs, unions, and enums when looking for a matching 15712 // tag declaration or definition. See the similar lookup tweak 15713 // in Sema::LookupName; is there a better way to deal with this? 15714 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15715 SearchDC = SearchDC->getParent(); 15716 } 15717 } 15718 15719 if (Previous.isSingleResult() && 15720 Previous.getFoundDecl()->isTemplateParameter()) { 15721 // Maybe we will complain about the shadowed template parameter. 15722 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15723 // Just pretend that we didn't see the previous declaration. 15724 Previous.clear(); 15725 } 15726 15727 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15728 DC->Equals(getStdNamespace())) { 15729 if (Name->isStr("bad_alloc")) { 15730 // This is a declaration of or a reference to "std::bad_alloc". 15731 isStdBadAlloc = true; 15732 15733 // If std::bad_alloc has been implicitly declared (but made invisible to 15734 // name lookup), fill in this implicit declaration as the previous 15735 // declaration, so that the declarations get chained appropriately. 15736 if (Previous.empty() && StdBadAlloc) 15737 Previous.addDecl(getStdBadAlloc()); 15738 } else if (Name->isStr("align_val_t")) { 15739 isStdAlignValT = true; 15740 if (Previous.empty() && StdAlignValT) 15741 Previous.addDecl(getStdAlignValT()); 15742 } 15743 } 15744 15745 // If we didn't find a previous declaration, and this is a reference 15746 // (or friend reference), move to the correct scope. In C++, we 15747 // also need to do a redeclaration lookup there, just in case 15748 // there's a shadow friend decl. 15749 if (Name && Previous.empty() && 15750 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15751 if (Invalid) goto CreateNewDecl; 15752 assert(SS.isEmpty()); 15753 15754 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15755 // C++ [basic.scope.pdecl]p5: 15756 // -- for an elaborated-type-specifier of the form 15757 // 15758 // class-key identifier 15759 // 15760 // if the elaborated-type-specifier is used in the 15761 // decl-specifier-seq or parameter-declaration-clause of a 15762 // function defined in namespace scope, the identifier is 15763 // declared as a class-name in the namespace that contains 15764 // the declaration; otherwise, except as a friend 15765 // declaration, the identifier is declared in the smallest 15766 // non-class, non-function-prototype scope that contains the 15767 // declaration. 15768 // 15769 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15770 // C structs and unions. 15771 // 15772 // It is an error in C++ to declare (rather than define) an enum 15773 // type, including via an elaborated type specifier. We'll 15774 // diagnose that later; for now, declare the enum in the same 15775 // scope as we would have picked for any other tag type. 15776 // 15777 // GNU C also supports this behavior as part of its incomplete 15778 // enum types extension, while GNU C++ does not. 15779 // 15780 // Find the context where we'll be declaring the tag. 15781 // FIXME: We would like to maintain the current DeclContext as the 15782 // lexical context, 15783 SearchDC = getTagInjectionContext(SearchDC); 15784 15785 // Find the scope where we'll be declaring the tag. 15786 S = getTagInjectionScope(S, getLangOpts()); 15787 } else { 15788 assert(TUK == TUK_Friend); 15789 // C++ [namespace.memdef]p3: 15790 // If a friend declaration in a non-local class first declares a 15791 // class or function, the friend class or function is a member of 15792 // the innermost enclosing namespace. 15793 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15794 } 15795 15796 // In C++, we need to do a redeclaration lookup to properly 15797 // diagnose some problems. 15798 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15799 // hidden declaration so that we don't get ambiguity errors when using a 15800 // type declared by an elaborated-type-specifier. In C that is not correct 15801 // and we should instead merge compatible types found by lookup. 15802 if (getLangOpts().CPlusPlus) { 15803 // FIXME: This can perform qualified lookups into function contexts, 15804 // which are meaningless. 15805 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15806 LookupQualifiedName(Previous, SearchDC); 15807 } else { 15808 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15809 LookupName(Previous, S); 15810 } 15811 } 15812 15813 // If we have a known previous declaration to use, then use it. 15814 if (Previous.empty() && SkipBody && SkipBody->Previous) 15815 Previous.addDecl(SkipBody->Previous); 15816 15817 if (!Previous.empty()) { 15818 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15819 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15820 15821 // It's okay to have a tag decl in the same scope as a typedef 15822 // which hides a tag decl in the same scope. Finding this 15823 // insanity with a redeclaration lookup can only actually happen 15824 // in C++. 15825 // 15826 // This is also okay for elaborated-type-specifiers, which is 15827 // technically forbidden by the current standard but which is 15828 // okay according to the likely resolution of an open issue; 15829 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15830 if (getLangOpts().CPlusPlus) { 15831 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15832 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15833 TagDecl *Tag = TT->getDecl(); 15834 if (Tag->getDeclName() == Name && 15835 Tag->getDeclContext()->getRedeclContext() 15836 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15837 PrevDecl = Tag; 15838 Previous.clear(); 15839 Previous.addDecl(Tag); 15840 Previous.resolveKind(); 15841 } 15842 } 15843 } 15844 } 15845 15846 // If this is a redeclaration of a using shadow declaration, it must 15847 // declare a tag in the same context. In MSVC mode, we allow a 15848 // redefinition if either context is within the other. 15849 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15850 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15851 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15852 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15853 !(OldTag && isAcceptableTagRedeclContext( 15854 *this, OldTag->getDeclContext(), SearchDC))) { 15855 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15856 Diag(Shadow->getTargetDecl()->getLocation(), 15857 diag::note_using_decl_target); 15858 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15859 << 0; 15860 // Recover by ignoring the old declaration. 15861 Previous.clear(); 15862 goto CreateNewDecl; 15863 } 15864 } 15865 15866 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15867 // If this is a use of a previous tag, or if the tag is already declared 15868 // in the same scope (so that the definition/declaration completes or 15869 // rementions the tag), reuse the decl. 15870 if (TUK == TUK_Reference || TUK == TUK_Friend || 15871 isDeclInScope(DirectPrevDecl, SearchDC, S, 15872 SS.isNotEmpty() || isMemberSpecialization)) { 15873 // Make sure that this wasn't declared as an enum and now used as a 15874 // struct or something similar. 15875 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15876 TUK == TUK_Definition, KWLoc, 15877 Name)) { 15878 bool SafeToContinue 15879 = (PrevTagDecl->getTagKind() != TTK_Enum && 15880 Kind != TTK_Enum); 15881 if (SafeToContinue) 15882 Diag(KWLoc, diag::err_use_with_wrong_tag) 15883 << Name 15884 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15885 PrevTagDecl->getKindName()); 15886 else 15887 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15888 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15889 15890 if (SafeToContinue) 15891 Kind = PrevTagDecl->getTagKind(); 15892 else { 15893 // Recover by making this an anonymous redefinition. 15894 Name = nullptr; 15895 Previous.clear(); 15896 Invalid = true; 15897 } 15898 } 15899 15900 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15901 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15902 if (TUK == TUK_Reference || TUK == TUK_Friend) 15903 return PrevTagDecl; 15904 15905 QualType EnumUnderlyingTy; 15906 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15907 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15908 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15909 EnumUnderlyingTy = QualType(T, 0); 15910 15911 // All conflicts with previous declarations are recovered by 15912 // returning the previous declaration, unless this is a definition, 15913 // in which case we want the caller to bail out. 15914 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15915 ScopedEnum, EnumUnderlyingTy, 15916 IsFixed, PrevEnum)) 15917 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15918 } 15919 15920 // C++11 [class.mem]p1: 15921 // A member shall not be declared twice in the member-specification, 15922 // except that a nested class or member class template can be declared 15923 // and then later defined. 15924 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15925 S->isDeclScope(PrevDecl)) { 15926 Diag(NameLoc, diag::ext_member_redeclared); 15927 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15928 } 15929 15930 if (!Invalid) { 15931 // If this is a use, just return the declaration we found, unless 15932 // we have attributes. 15933 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15934 if (!Attrs.empty()) { 15935 // FIXME: Diagnose these attributes. For now, we create a new 15936 // declaration to hold them. 15937 } else if (TUK == TUK_Reference && 15938 (PrevTagDecl->getFriendObjectKind() == 15939 Decl::FOK_Undeclared || 15940 PrevDecl->getOwningModule() != getCurrentModule()) && 15941 SS.isEmpty()) { 15942 // This declaration is a reference to an existing entity, but 15943 // has different visibility from that entity: it either makes 15944 // a friend visible or it makes a type visible in a new module. 15945 // In either case, create a new declaration. We only do this if 15946 // the declaration would have meant the same thing if no prior 15947 // declaration were found, that is, if it was found in the same 15948 // scope where we would have injected a declaration. 15949 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15950 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15951 return PrevTagDecl; 15952 // This is in the injected scope, create a new declaration in 15953 // that scope. 15954 S = getTagInjectionScope(S, getLangOpts()); 15955 } else { 15956 return PrevTagDecl; 15957 } 15958 } 15959 15960 // Diagnose attempts to redefine a tag. 15961 if (TUK == TUK_Definition) { 15962 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15963 // If we're defining a specialization and the previous definition 15964 // is from an implicit instantiation, don't emit an error 15965 // here; we'll catch this in the general case below. 15966 bool IsExplicitSpecializationAfterInstantiation = false; 15967 if (isMemberSpecialization) { 15968 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15969 IsExplicitSpecializationAfterInstantiation = 15970 RD->getTemplateSpecializationKind() != 15971 TSK_ExplicitSpecialization; 15972 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15973 IsExplicitSpecializationAfterInstantiation = 15974 ED->getTemplateSpecializationKind() != 15975 TSK_ExplicitSpecialization; 15976 } 15977 15978 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15979 // not keep more that one definition around (merge them). However, 15980 // ensure the decl passes the structural compatibility check in 15981 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15982 NamedDecl *Hidden = nullptr; 15983 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15984 // There is a definition of this tag, but it is not visible. We 15985 // explicitly make use of C++'s one definition rule here, and 15986 // assume that this definition is identical to the hidden one 15987 // we already have. Make the existing definition visible and 15988 // use it in place of this one. 15989 if (!getLangOpts().CPlusPlus) { 15990 // Postpone making the old definition visible until after we 15991 // complete parsing the new one and do the structural 15992 // comparison. 15993 SkipBody->CheckSameAsPrevious = true; 15994 SkipBody->New = createTagFromNewDecl(); 15995 SkipBody->Previous = Def; 15996 return Def; 15997 } else { 15998 SkipBody->ShouldSkip = true; 15999 SkipBody->Previous = Def; 16000 makeMergedDefinitionVisible(Hidden); 16001 // Carry on and handle it like a normal definition. We'll 16002 // skip starting the definitiion later. 16003 } 16004 } else if (!IsExplicitSpecializationAfterInstantiation) { 16005 // A redeclaration in function prototype scope in C isn't 16006 // visible elsewhere, so merely issue a warning. 16007 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 16008 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 16009 else 16010 Diag(NameLoc, diag::err_redefinition) << Name; 16011 notePreviousDefinition(Def, 16012 NameLoc.isValid() ? NameLoc : KWLoc); 16013 // If this is a redefinition, recover by making this 16014 // struct be anonymous, which will make any later 16015 // references get the previous definition. 16016 Name = nullptr; 16017 Previous.clear(); 16018 Invalid = true; 16019 } 16020 } else { 16021 // If the type is currently being defined, complain 16022 // about a nested redefinition. 16023 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 16024 if (TD->isBeingDefined()) { 16025 Diag(NameLoc, diag::err_nested_redefinition) << Name; 16026 Diag(PrevTagDecl->getLocation(), 16027 diag::note_previous_definition); 16028 Name = nullptr; 16029 Previous.clear(); 16030 Invalid = true; 16031 } 16032 } 16033 16034 // Okay, this is definition of a previously declared or referenced 16035 // tag. We're going to create a new Decl for it. 16036 } 16037 16038 // Okay, we're going to make a redeclaration. If this is some kind 16039 // of reference, make sure we build the redeclaration in the same DC 16040 // as the original, and ignore the current access specifier. 16041 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16042 SearchDC = PrevTagDecl->getDeclContext(); 16043 AS = AS_none; 16044 } 16045 } 16046 // If we get here we have (another) forward declaration or we 16047 // have a definition. Just create a new decl. 16048 16049 } else { 16050 // If we get here, this is a definition of a new tag type in a nested 16051 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 16052 // new decl/type. We set PrevDecl to NULL so that the entities 16053 // have distinct types. 16054 Previous.clear(); 16055 } 16056 // If we get here, we're going to create a new Decl. If PrevDecl 16057 // is non-NULL, it's a definition of the tag declared by 16058 // PrevDecl. If it's NULL, we have a new definition. 16059 16060 // Otherwise, PrevDecl is not a tag, but was found with tag 16061 // lookup. This is only actually possible in C++, where a few 16062 // things like templates still live in the tag namespace. 16063 } else { 16064 // Use a better diagnostic if an elaborated-type-specifier 16065 // found the wrong kind of type on the first 16066 // (non-redeclaration) lookup. 16067 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16068 !Previous.isForRedeclaration()) { 16069 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16070 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16071 << Kind; 16072 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16073 Invalid = true; 16074 16075 // Otherwise, only diagnose if the declaration is in scope. 16076 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16077 SS.isNotEmpty() || isMemberSpecialization)) { 16078 // do nothing 16079 16080 // Diagnose implicit declarations introduced by elaborated types. 16081 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16082 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16083 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16084 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16085 Invalid = true; 16086 16087 // Otherwise it's a declaration. Call out a particularly common 16088 // case here. 16089 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16090 unsigned Kind = 0; 16091 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16092 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16093 << Name << Kind << TND->getUnderlyingType(); 16094 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16095 Invalid = true; 16096 16097 // Otherwise, diagnose. 16098 } else { 16099 // The tag name clashes with something else in the target scope, 16100 // issue an error and recover by making this tag be anonymous. 16101 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16102 notePreviousDefinition(PrevDecl, NameLoc); 16103 Name = nullptr; 16104 Invalid = true; 16105 } 16106 16107 // The existing declaration isn't relevant to us; we're in a 16108 // new scope, so clear out the previous declaration. 16109 Previous.clear(); 16110 } 16111 } 16112 16113 CreateNewDecl: 16114 16115 TagDecl *PrevDecl = nullptr; 16116 if (Previous.isSingleResult()) 16117 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16118 16119 // If there is an identifier, use the location of the identifier as the 16120 // location of the decl, otherwise use the location of the struct/union 16121 // keyword. 16122 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16123 16124 // Otherwise, create a new declaration. If there is a previous 16125 // declaration of the same entity, the two will be linked via 16126 // PrevDecl. 16127 TagDecl *New; 16128 16129 if (Kind == TTK_Enum) { 16130 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16131 // enum X { A, B, C } D; D should chain to X. 16132 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16133 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16134 ScopedEnumUsesClassTag, IsFixed); 16135 16136 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16137 StdAlignValT = cast<EnumDecl>(New); 16138 16139 // If this is an undefined enum, warn. 16140 if (TUK != TUK_Definition && !Invalid) { 16141 TagDecl *Def; 16142 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16143 // C++0x: 7.2p2: opaque-enum-declaration. 16144 // Conflicts are diagnosed above. Do nothing. 16145 } 16146 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16147 Diag(Loc, diag::ext_forward_ref_enum_def) 16148 << New; 16149 Diag(Def->getLocation(), diag::note_previous_definition); 16150 } else { 16151 unsigned DiagID = diag::ext_forward_ref_enum; 16152 if (getLangOpts().MSVCCompat) 16153 DiagID = diag::ext_ms_forward_ref_enum; 16154 else if (getLangOpts().CPlusPlus) 16155 DiagID = diag::err_forward_ref_enum; 16156 Diag(Loc, DiagID); 16157 } 16158 } 16159 16160 if (EnumUnderlying) { 16161 EnumDecl *ED = cast<EnumDecl>(New); 16162 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16163 ED->setIntegerTypeSourceInfo(TI); 16164 else 16165 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16166 ED->setPromotionType(ED->getIntegerType()); 16167 assert(ED->isComplete() && "enum with type should be complete"); 16168 } 16169 } else { 16170 // struct/union/class 16171 16172 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16173 // struct X { int A; } D; D should chain to X. 16174 if (getLangOpts().CPlusPlus) { 16175 // FIXME: Look for a way to use RecordDecl for simple structs. 16176 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16177 cast_or_null<CXXRecordDecl>(PrevDecl)); 16178 16179 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16180 StdBadAlloc = cast<CXXRecordDecl>(New); 16181 } else 16182 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16183 cast_or_null<RecordDecl>(PrevDecl)); 16184 } 16185 16186 // C++11 [dcl.type]p3: 16187 // A type-specifier-seq shall not define a class or enumeration [...]. 16188 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16189 TUK == TUK_Definition) { 16190 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16191 << Context.getTagDeclType(New); 16192 Invalid = true; 16193 } 16194 16195 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16196 DC->getDeclKind() == Decl::Enum) { 16197 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16198 << Context.getTagDeclType(New); 16199 Invalid = true; 16200 } 16201 16202 // Maybe add qualifier info. 16203 if (SS.isNotEmpty()) { 16204 if (SS.isSet()) { 16205 // If this is either a declaration or a definition, check the 16206 // nested-name-specifier against the current context. 16207 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16208 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16209 isMemberSpecialization)) 16210 Invalid = true; 16211 16212 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16213 if (TemplateParameterLists.size() > 0) { 16214 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16215 } 16216 } 16217 else 16218 Invalid = true; 16219 } 16220 16221 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16222 // Add alignment attributes if necessary; these attributes are checked when 16223 // the ASTContext lays out the structure. 16224 // 16225 // It is important for implementing the correct semantics that this 16226 // happen here (in ActOnTag). The #pragma pack stack is 16227 // maintained as a result of parser callbacks which can occur at 16228 // many points during the parsing of a struct declaration (because 16229 // the #pragma tokens are effectively skipped over during the 16230 // parsing of the struct). 16231 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16232 AddAlignmentAttributesForRecord(RD); 16233 AddMsStructLayoutForRecord(RD); 16234 } 16235 } 16236 16237 if (ModulePrivateLoc.isValid()) { 16238 if (isMemberSpecialization) 16239 Diag(New->getLocation(), diag::err_module_private_specialization) 16240 << 2 16241 << FixItHint::CreateRemoval(ModulePrivateLoc); 16242 // __module_private__ does not apply to local classes. However, we only 16243 // diagnose this as an error when the declaration specifiers are 16244 // freestanding. Here, we just ignore the __module_private__. 16245 else if (!SearchDC->isFunctionOrMethod()) 16246 New->setModulePrivate(); 16247 } 16248 16249 // If this is a specialization of a member class (of a class template), 16250 // check the specialization. 16251 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16252 Invalid = true; 16253 16254 // If we're declaring or defining a tag in function prototype scope in C, 16255 // note that this type can only be used within the function and add it to 16256 // the list of decls to inject into the function definition scope. 16257 if ((Name || Kind == TTK_Enum) && 16258 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16259 if (getLangOpts().CPlusPlus) { 16260 // C++ [dcl.fct]p6: 16261 // Types shall not be defined in return or parameter types. 16262 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16263 Diag(Loc, diag::err_type_defined_in_param_type) 16264 << Name; 16265 Invalid = true; 16266 } 16267 } else if (!PrevDecl) { 16268 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16269 } 16270 } 16271 16272 if (Invalid) 16273 New->setInvalidDecl(); 16274 16275 // Set the lexical context. If the tag has a C++ scope specifier, the 16276 // lexical context will be different from the semantic context. 16277 New->setLexicalDeclContext(CurContext); 16278 16279 // Mark this as a friend decl if applicable. 16280 // In Microsoft mode, a friend declaration also acts as a forward 16281 // declaration so we always pass true to setObjectOfFriendDecl to make 16282 // the tag name visible. 16283 if (TUK == TUK_Friend) 16284 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16285 16286 // Set the access specifier. 16287 if (!Invalid && SearchDC->isRecord()) 16288 SetMemberAccessSpecifier(New, PrevDecl, AS); 16289 16290 if (PrevDecl) 16291 CheckRedeclarationModuleOwnership(New, PrevDecl); 16292 16293 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16294 New->startDefinition(); 16295 16296 ProcessDeclAttributeList(S, New, Attrs); 16297 AddPragmaAttributes(S, New); 16298 16299 // If this has an identifier, add it to the scope stack. 16300 if (TUK == TUK_Friend) { 16301 // We might be replacing an existing declaration in the lookup tables; 16302 // if so, borrow its access specifier. 16303 if (PrevDecl) 16304 New->setAccess(PrevDecl->getAccess()); 16305 16306 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16307 DC->makeDeclVisibleInContext(New); 16308 if (Name) // can be null along some error paths 16309 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16310 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16311 } else if (Name) { 16312 S = getNonFieldDeclScope(S); 16313 PushOnScopeChains(New, S, true); 16314 } else { 16315 CurContext->addDecl(New); 16316 } 16317 16318 // If this is the C FILE type, notify the AST context. 16319 if (IdentifierInfo *II = New->getIdentifier()) 16320 if (!New->isInvalidDecl() && 16321 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16322 II->isStr("FILE")) 16323 Context.setFILEDecl(New); 16324 16325 if (PrevDecl) 16326 mergeDeclAttributes(New, PrevDecl); 16327 16328 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16329 inferGslOwnerPointerAttribute(CXXRD); 16330 16331 // If there's a #pragma GCC visibility in scope, set the visibility of this 16332 // record. 16333 AddPushedVisibilityAttribute(New); 16334 16335 if (isMemberSpecialization && !New->isInvalidDecl()) 16336 CompleteMemberSpecialization(New, Previous); 16337 16338 OwnedDecl = true; 16339 // In C++, don't return an invalid declaration. We can't recover well from 16340 // the cases where we make the type anonymous. 16341 if (Invalid && getLangOpts().CPlusPlus) { 16342 if (New->isBeingDefined()) 16343 if (auto RD = dyn_cast<RecordDecl>(New)) 16344 RD->completeDefinition(); 16345 return nullptr; 16346 } else if (SkipBody && SkipBody->ShouldSkip) { 16347 return SkipBody->Previous; 16348 } else { 16349 return New; 16350 } 16351 } 16352 16353 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16354 AdjustDeclIfTemplate(TagD); 16355 TagDecl *Tag = cast<TagDecl>(TagD); 16356 16357 // Enter the tag context. 16358 PushDeclContext(S, Tag); 16359 16360 ActOnDocumentableDecl(TagD); 16361 16362 // If there's a #pragma GCC visibility in scope, set the visibility of this 16363 // record. 16364 AddPushedVisibilityAttribute(Tag); 16365 } 16366 16367 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16368 SkipBodyInfo &SkipBody) { 16369 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16370 return false; 16371 16372 // Make the previous decl visible. 16373 makeMergedDefinitionVisible(SkipBody.Previous); 16374 return true; 16375 } 16376 16377 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16378 assert(isa<ObjCContainerDecl>(IDecl) && 16379 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16380 DeclContext *OCD = cast<DeclContext>(IDecl); 16381 assert(OCD->getLexicalParent() == CurContext && 16382 "The next DeclContext should be lexically contained in the current one."); 16383 CurContext = OCD; 16384 return IDecl; 16385 } 16386 16387 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16388 SourceLocation FinalLoc, 16389 bool IsFinalSpelledSealed, 16390 SourceLocation LBraceLoc) { 16391 AdjustDeclIfTemplate(TagD); 16392 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16393 16394 FieldCollector->StartClass(); 16395 16396 if (!Record->getIdentifier()) 16397 return; 16398 16399 if (FinalLoc.isValid()) 16400 Record->addAttr(FinalAttr::Create( 16401 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16402 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16403 16404 // C++ [class]p2: 16405 // [...] The class-name is also inserted into the scope of the 16406 // class itself; this is known as the injected-class-name. For 16407 // purposes of access checking, the injected-class-name is treated 16408 // as if it were a public member name. 16409 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16410 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16411 Record->getLocation(), Record->getIdentifier(), 16412 /*PrevDecl=*/nullptr, 16413 /*DelayTypeCreation=*/true); 16414 Context.getTypeDeclType(InjectedClassName, Record); 16415 InjectedClassName->setImplicit(); 16416 InjectedClassName->setAccess(AS_public); 16417 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16418 InjectedClassName->setDescribedClassTemplate(Template); 16419 PushOnScopeChains(InjectedClassName, S); 16420 assert(InjectedClassName->isInjectedClassName() && 16421 "Broken injected-class-name"); 16422 } 16423 16424 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16425 SourceRange BraceRange) { 16426 AdjustDeclIfTemplate(TagD); 16427 TagDecl *Tag = cast<TagDecl>(TagD); 16428 Tag->setBraceRange(BraceRange); 16429 16430 // Make sure we "complete" the definition even it is invalid. 16431 if (Tag->isBeingDefined()) { 16432 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16433 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16434 RD->completeDefinition(); 16435 } 16436 16437 if (isa<CXXRecordDecl>(Tag)) { 16438 FieldCollector->FinishClass(); 16439 } 16440 16441 // Exit this scope of this tag's definition. 16442 PopDeclContext(); 16443 16444 if (getCurLexicalContext()->isObjCContainer() && 16445 Tag->getDeclContext()->isFileContext()) 16446 Tag->setTopLevelDeclInObjCContainer(); 16447 16448 // Notify the consumer that we've defined a tag. 16449 if (!Tag->isInvalidDecl()) 16450 Consumer.HandleTagDeclDefinition(Tag); 16451 } 16452 16453 void Sema::ActOnObjCContainerFinishDefinition() { 16454 // Exit this scope of this interface definition. 16455 PopDeclContext(); 16456 } 16457 16458 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16459 assert(DC == CurContext && "Mismatch of container contexts"); 16460 OriginalLexicalContext = DC; 16461 ActOnObjCContainerFinishDefinition(); 16462 } 16463 16464 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16465 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16466 OriginalLexicalContext = nullptr; 16467 } 16468 16469 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16470 AdjustDeclIfTemplate(TagD); 16471 TagDecl *Tag = cast<TagDecl>(TagD); 16472 Tag->setInvalidDecl(); 16473 16474 // Make sure we "complete" the definition even it is invalid. 16475 if (Tag->isBeingDefined()) { 16476 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16477 RD->completeDefinition(); 16478 } 16479 16480 // We're undoing ActOnTagStartDefinition here, not 16481 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16482 // the FieldCollector. 16483 16484 PopDeclContext(); 16485 } 16486 16487 // Note that FieldName may be null for anonymous bitfields. 16488 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16489 IdentifierInfo *FieldName, 16490 QualType FieldTy, bool IsMsStruct, 16491 Expr *BitWidth, bool *ZeroWidth) { 16492 assert(BitWidth); 16493 if (BitWidth->containsErrors()) 16494 return ExprError(); 16495 16496 // Default to true; that shouldn't confuse checks for emptiness 16497 if (ZeroWidth) 16498 *ZeroWidth = true; 16499 16500 // C99 6.7.2.1p4 - verify the field type. 16501 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16502 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16503 // Handle incomplete and sizeless types with a specific error. 16504 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16505 diag::err_field_incomplete_or_sizeless)) 16506 return ExprError(); 16507 if (FieldName) 16508 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16509 << FieldName << FieldTy << BitWidth->getSourceRange(); 16510 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16511 << FieldTy << BitWidth->getSourceRange(); 16512 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16513 UPPC_BitFieldWidth)) 16514 return ExprError(); 16515 16516 // If the bit-width is type- or value-dependent, don't try to check 16517 // it now. 16518 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16519 return BitWidth; 16520 16521 llvm::APSInt Value; 16522 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 16523 if (ICE.isInvalid()) 16524 return ICE; 16525 BitWidth = ICE.get(); 16526 16527 if (Value != 0 && ZeroWidth) 16528 *ZeroWidth = false; 16529 16530 // Zero-width bitfield is ok for anonymous field. 16531 if (Value == 0 && FieldName) 16532 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16533 16534 if (Value.isSigned() && Value.isNegative()) { 16535 if (FieldName) 16536 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16537 << FieldName << Value.toString(10); 16538 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16539 << Value.toString(10); 16540 } 16541 16542 // The size of the bit-field must not exceed our maximum permitted object 16543 // size. 16544 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 16545 return Diag(FieldLoc, diag::err_bitfield_too_wide) 16546 << !FieldName << FieldName << Value.toString(10); 16547 } 16548 16549 if (!FieldTy->isDependentType()) { 16550 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16551 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16552 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16553 16554 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16555 // ABI. 16556 bool CStdConstraintViolation = 16557 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16558 bool MSBitfieldViolation = 16559 Value.ugt(TypeStorageSize) && 16560 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16561 if (CStdConstraintViolation || MSBitfieldViolation) { 16562 unsigned DiagWidth = 16563 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16564 if (FieldName) 16565 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16566 << FieldName << Value.toString(10) 16567 << !CStdConstraintViolation << DiagWidth; 16568 16569 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16570 << Value.toString(10) << !CStdConstraintViolation 16571 << DiagWidth; 16572 } 16573 16574 // Warn on types where the user might conceivably expect to get all 16575 // specified bits as value bits: that's all integral types other than 16576 // 'bool'. 16577 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 16578 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16579 << FieldName << Value.toString(10) 16580 << (unsigned)TypeWidth; 16581 } 16582 } 16583 16584 return BitWidth; 16585 } 16586 16587 /// ActOnField - Each field of a C struct/union is passed into this in order 16588 /// to create a FieldDecl object for it. 16589 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16590 Declarator &D, Expr *BitfieldWidth) { 16591 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16592 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16593 /*InitStyle=*/ICIS_NoInit, AS_public); 16594 return Res; 16595 } 16596 16597 /// HandleField - Analyze a field of a C struct or a C++ data member. 16598 /// 16599 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16600 SourceLocation DeclStart, 16601 Declarator &D, Expr *BitWidth, 16602 InClassInitStyle InitStyle, 16603 AccessSpecifier AS) { 16604 if (D.isDecompositionDeclarator()) { 16605 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16606 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16607 << Decomp.getSourceRange(); 16608 return nullptr; 16609 } 16610 16611 IdentifierInfo *II = D.getIdentifier(); 16612 SourceLocation Loc = DeclStart; 16613 if (II) Loc = D.getIdentifierLoc(); 16614 16615 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16616 QualType T = TInfo->getType(); 16617 if (getLangOpts().CPlusPlus) { 16618 CheckExtraCXXDefaultArguments(D); 16619 16620 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16621 UPPC_DataMemberType)) { 16622 D.setInvalidType(); 16623 T = Context.IntTy; 16624 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16625 } 16626 } 16627 16628 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16629 16630 if (D.getDeclSpec().isInlineSpecified()) 16631 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16632 << getLangOpts().CPlusPlus17; 16633 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16634 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16635 diag::err_invalid_thread) 16636 << DeclSpec::getSpecifierName(TSCS); 16637 16638 // Check to see if this name was declared as a member previously 16639 NamedDecl *PrevDecl = nullptr; 16640 LookupResult Previous(*this, II, Loc, LookupMemberName, 16641 ForVisibleRedeclaration); 16642 LookupName(Previous, S); 16643 switch (Previous.getResultKind()) { 16644 case LookupResult::Found: 16645 case LookupResult::FoundUnresolvedValue: 16646 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16647 break; 16648 16649 case LookupResult::FoundOverloaded: 16650 PrevDecl = Previous.getRepresentativeDecl(); 16651 break; 16652 16653 case LookupResult::NotFound: 16654 case LookupResult::NotFoundInCurrentInstantiation: 16655 case LookupResult::Ambiguous: 16656 break; 16657 } 16658 Previous.suppressDiagnostics(); 16659 16660 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16661 // Maybe we will complain about the shadowed template parameter. 16662 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16663 // Just pretend that we didn't see the previous declaration. 16664 PrevDecl = nullptr; 16665 } 16666 16667 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16668 PrevDecl = nullptr; 16669 16670 bool Mutable 16671 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16672 SourceLocation TSSL = D.getBeginLoc(); 16673 FieldDecl *NewFD 16674 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16675 TSSL, AS, PrevDecl, &D); 16676 16677 if (NewFD->isInvalidDecl()) 16678 Record->setInvalidDecl(); 16679 16680 if (D.getDeclSpec().isModulePrivateSpecified()) 16681 NewFD->setModulePrivate(); 16682 16683 if (NewFD->isInvalidDecl() && PrevDecl) { 16684 // Don't introduce NewFD into scope; there's already something 16685 // with the same name in the same scope. 16686 } else if (II) { 16687 PushOnScopeChains(NewFD, S); 16688 } else 16689 Record->addDecl(NewFD); 16690 16691 return NewFD; 16692 } 16693 16694 /// Build a new FieldDecl and check its well-formedness. 16695 /// 16696 /// This routine builds a new FieldDecl given the fields name, type, 16697 /// record, etc. \p PrevDecl should refer to any previous declaration 16698 /// with the same name and in the same scope as the field to be 16699 /// created. 16700 /// 16701 /// \returns a new FieldDecl. 16702 /// 16703 /// \todo The Declarator argument is a hack. It will be removed once 16704 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16705 TypeSourceInfo *TInfo, 16706 RecordDecl *Record, SourceLocation Loc, 16707 bool Mutable, Expr *BitWidth, 16708 InClassInitStyle InitStyle, 16709 SourceLocation TSSL, 16710 AccessSpecifier AS, NamedDecl *PrevDecl, 16711 Declarator *D) { 16712 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16713 bool InvalidDecl = false; 16714 if (D) InvalidDecl = D->isInvalidType(); 16715 16716 // If we receive a broken type, recover by assuming 'int' and 16717 // marking this declaration as invalid. 16718 if (T.isNull() || T->containsErrors()) { 16719 InvalidDecl = true; 16720 T = Context.IntTy; 16721 } 16722 16723 QualType EltTy = Context.getBaseElementType(T); 16724 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16725 if (RequireCompleteSizedType(Loc, EltTy, 16726 diag::err_field_incomplete_or_sizeless)) { 16727 // Fields of incomplete type force their record to be invalid. 16728 Record->setInvalidDecl(); 16729 InvalidDecl = true; 16730 } else { 16731 NamedDecl *Def; 16732 EltTy->isIncompleteType(&Def); 16733 if (Def && Def->isInvalidDecl()) { 16734 Record->setInvalidDecl(); 16735 InvalidDecl = true; 16736 } 16737 } 16738 } 16739 16740 // TR 18037 does not allow fields to be declared with address space 16741 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16742 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16743 Diag(Loc, diag::err_field_with_address_space); 16744 Record->setInvalidDecl(); 16745 InvalidDecl = true; 16746 } 16747 16748 if (LangOpts.OpenCL) { 16749 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16750 // used as structure or union field: image, sampler, event or block types. 16751 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16752 T->isBlockPointerType()) { 16753 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16754 Record->setInvalidDecl(); 16755 InvalidDecl = true; 16756 } 16757 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16758 if (BitWidth) { 16759 Diag(Loc, diag::err_opencl_bitfields); 16760 InvalidDecl = true; 16761 } 16762 } 16763 16764 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16765 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16766 T.hasQualifiers()) { 16767 InvalidDecl = true; 16768 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16769 } 16770 16771 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16772 // than a variably modified type. 16773 if (!InvalidDecl && T->isVariablyModifiedType()) { 16774 if (!tryToFixVariablyModifiedVarType( 16775 *this, TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 16776 InvalidDecl = true; 16777 } 16778 16779 // Fields can not have abstract class types 16780 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16781 diag::err_abstract_type_in_decl, 16782 AbstractFieldType)) 16783 InvalidDecl = true; 16784 16785 bool ZeroWidth = false; 16786 if (InvalidDecl) 16787 BitWidth = nullptr; 16788 // If this is declared as a bit-field, check the bit-field. 16789 if (BitWidth) { 16790 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16791 &ZeroWidth).get(); 16792 if (!BitWidth) { 16793 InvalidDecl = true; 16794 BitWidth = nullptr; 16795 ZeroWidth = false; 16796 } 16797 } 16798 16799 // Check that 'mutable' is consistent with the type of the declaration. 16800 if (!InvalidDecl && Mutable) { 16801 unsigned DiagID = 0; 16802 if (T->isReferenceType()) 16803 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16804 : diag::err_mutable_reference; 16805 else if (T.isConstQualified()) 16806 DiagID = diag::err_mutable_const; 16807 16808 if (DiagID) { 16809 SourceLocation ErrLoc = Loc; 16810 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16811 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16812 Diag(ErrLoc, DiagID); 16813 if (DiagID != diag::ext_mutable_reference) { 16814 Mutable = false; 16815 InvalidDecl = true; 16816 } 16817 } 16818 } 16819 16820 // C++11 [class.union]p8 (DR1460): 16821 // At most one variant member of a union may have a 16822 // brace-or-equal-initializer. 16823 if (InitStyle != ICIS_NoInit) 16824 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16825 16826 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16827 BitWidth, Mutable, InitStyle); 16828 if (InvalidDecl) 16829 NewFD->setInvalidDecl(); 16830 16831 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16832 Diag(Loc, diag::err_duplicate_member) << II; 16833 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16834 NewFD->setInvalidDecl(); 16835 } 16836 16837 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16838 if (Record->isUnion()) { 16839 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16840 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16841 if (RDecl->getDefinition()) { 16842 // C++ [class.union]p1: An object of a class with a non-trivial 16843 // constructor, a non-trivial copy constructor, a non-trivial 16844 // destructor, or a non-trivial copy assignment operator 16845 // cannot be a member of a union, nor can an array of such 16846 // objects. 16847 if (CheckNontrivialField(NewFD)) 16848 NewFD->setInvalidDecl(); 16849 } 16850 } 16851 16852 // C++ [class.union]p1: If a union contains a member of reference type, 16853 // the program is ill-formed, except when compiling with MSVC extensions 16854 // enabled. 16855 if (EltTy->isReferenceType()) { 16856 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16857 diag::ext_union_member_of_reference_type : 16858 diag::err_union_member_of_reference_type) 16859 << NewFD->getDeclName() << EltTy; 16860 if (!getLangOpts().MicrosoftExt) 16861 NewFD->setInvalidDecl(); 16862 } 16863 } 16864 } 16865 16866 // FIXME: We need to pass in the attributes given an AST 16867 // representation, not a parser representation. 16868 if (D) { 16869 // FIXME: The current scope is almost... but not entirely... correct here. 16870 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16871 16872 if (NewFD->hasAttrs()) 16873 CheckAlignasUnderalignment(NewFD); 16874 } 16875 16876 // In auto-retain/release, infer strong retension for fields of 16877 // retainable type. 16878 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16879 NewFD->setInvalidDecl(); 16880 16881 if (T.isObjCGCWeak()) 16882 Diag(Loc, diag::warn_attribute_weak_on_field); 16883 16884 // PPC MMA non-pointer types are not allowed as field types. 16885 if (Context.getTargetInfo().getTriple().isPPC64() && 16886 CheckPPCMMAType(T, NewFD->getLocation())) 16887 NewFD->setInvalidDecl(); 16888 16889 NewFD->setAccess(AS); 16890 return NewFD; 16891 } 16892 16893 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16894 assert(FD); 16895 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16896 16897 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16898 return false; 16899 16900 QualType EltTy = Context.getBaseElementType(FD->getType()); 16901 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16902 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16903 if (RDecl->getDefinition()) { 16904 // We check for copy constructors before constructors 16905 // because otherwise we'll never get complaints about 16906 // copy constructors. 16907 16908 CXXSpecialMember member = CXXInvalid; 16909 // We're required to check for any non-trivial constructors. Since the 16910 // implicit default constructor is suppressed if there are any 16911 // user-declared constructors, we just need to check that there is a 16912 // trivial default constructor and a trivial copy constructor. (We don't 16913 // worry about move constructors here, since this is a C++98 check.) 16914 if (RDecl->hasNonTrivialCopyConstructor()) 16915 member = CXXCopyConstructor; 16916 else if (!RDecl->hasTrivialDefaultConstructor()) 16917 member = CXXDefaultConstructor; 16918 else if (RDecl->hasNonTrivialCopyAssignment()) 16919 member = CXXCopyAssignment; 16920 else if (RDecl->hasNonTrivialDestructor()) 16921 member = CXXDestructor; 16922 16923 if (member != CXXInvalid) { 16924 if (!getLangOpts().CPlusPlus11 && 16925 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16926 // Objective-C++ ARC: it is an error to have a non-trivial field of 16927 // a union. However, system headers in Objective-C programs 16928 // occasionally have Objective-C lifetime objects within unions, 16929 // and rather than cause the program to fail, we make those 16930 // members unavailable. 16931 SourceLocation Loc = FD->getLocation(); 16932 if (getSourceManager().isInSystemHeader(Loc)) { 16933 if (!FD->hasAttr<UnavailableAttr>()) 16934 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16935 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16936 return false; 16937 } 16938 } 16939 16940 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16941 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16942 diag::err_illegal_union_or_anon_struct_member) 16943 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16944 DiagnoseNontrivial(RDecl, member); 16945 return !getLangOpts().CPlusPlus11; 16946 } 16947 } 16948 } 16949 16950 return false; 16951 } 16952 16953 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16954 /// AST enum value. 16955 static ObjCIvarDecl::AccessControl 16956 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16957 switch (ivarVisibility) { 16958 default: llvm_unreachable("Unknown visitibility kind"); 16959 case tok::objc_private: return ObjCIvarDecl::Private; 16960 case tok::objc_public: return ObjCIvarDecl::Public; 16961 case tok::objc_protected: return ObjCIvarDecl::Protected; 16962 case tok::objc_package: return ObjCIvarDecl::Package; 16963 } 16964 } 16965 16966 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16967 /// in order to create an IvarDecl object for it. 16968 Decl *Sema::ActOnIvar(Scope *S, 16969 SourceLocation DeclStart, 16970 Declarator &D, Expr *BitfieldWidth, 16971 tok::ObjCKeywordKind Visibility) { 16972 16973 IdentifierInfo *II = D.getIdentifier(); 16974 Expr *BitWidth = (Expr*)BitfieldWidth; 16975 SourceLocation Loc = DeclStart; 16976 if (II) Loc = D.getIdentifierLoc(); 16977 16978 // FIXME: Unnamed fields can be handled in various different ways, for 16979 // example, unnamed unions inject all members into the struct namespace! 16980 16981 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16982 QualType T = TInfo->getType(); 16983 16984 if (BitWidth) { 16985 // 6.7.2.1p3, 6.7.2.1p4 16986 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16987 if (!BitWidth) 16988 D.setInvalidType(); 16989 } else { 16990 // Not a bitfield. 16991 16992 // validate II. 16993 16994 } 16995 if (T->isReferenceType()) { 16996 Diag(Loc, diag::err_ivar_reference_type); 16997 D.setInvalidType(); 16998 } 16999 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17000 // than a variably modified type. 17001 else if (T->isVariablyModifiedType()) { 17002 if (!tryToFixVariablyModifiedVarType( 17003 *this, TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 17004 D.setInvalidType(); 17005 } 17006 17007 // Get the visibility (access control) for this ivar. 17008 ObjCIvarDecl::AccessControl ac = 17009 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 17010 : ObjCIvarDecl::None; 17011 // Must set ivar's DeclContext to its enclosing interface. 17012 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 17013 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 17014 return nullptr; 17015 ObjCContainerDecl *EnclosingContext; 17016 if (ObjCImplementationDecl *IMPDecl = 17017 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17018 if (LangOpts.ObjCRuntime.isFragile()) { 17019 // Case of ivar declared in an implementation. Context is that of its class. 17020 EnclosingContext = IMPDecl->getClassInterface(); 17021 assert(EnclosingContext && "Implementation has no class interface!"); 17022 } 17023 else 17024 EnclosingContext = EnclosingDecl; 17025 } else { 17026 if (ObjCCategoryDecl *CDecl = 17027 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17028 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 17029 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 17030 return nullptr; 17031 } 17032 } 17033 EnclosingContext = EnclosingDecl; 17034 } 17035 17036 // Construct the decl. 17037 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 17038 DeclStart, Loc, II, T, 17039 TInfo, ac, (Expr *)BitfieldWidth); 17040 17041 if (II) { 17042 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 17043 ForVisibleRedeclaration); 17044 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 17045 && !isa<TagDecl>(PrevDecl)) { 17046 Diag(Loc, diag::err_duplicate_member) << II; 17047 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17048 NewID->setInvalidDecl(); 17049 } 17050 } 17051 17052 // Process attributes attached to the ivar. 17053 ProcessDeclAttributes(S, NewID, D); 17054 17055 if (D.isInvalidType()) 17056 NewID->setInvalidDecl(); 17057 17058 // In ARC, infer 'retaining' for ivars of retainable type. 17059 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 17060 NewID->setInvalidDecl(); 17061 17062 if (D.getDeclSpec().isModulePrivateSpecified()) 17063 NewID->setModulePrivate(); 17064 17065 if (II) { 17066 // FIXME: When interfaces are DeclContexts, we'll need to add 17067 // these to the interface. 17068 S->AddDecl(NewID); 17069 IdResolver.AddDecl(NewID); 17070 } 17071 17072 if (LangOpts.ObjCRuntime.isNonFragile() && 17073 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17074 Diag(Loc, diag::warn_ivars_in_interface); 17075 17076 return NewID; 17077 } 17078 17079 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17080 /// class and class extensions. For every class \@interface and class 17081 /// extension \@interface, if the last ivar is a bitfield of any type, 17082 /// then add an implicit `char :0` ivar to the end of that interface. 17083 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17084 SmallVectorImpl<Decl *> &AllIvarDecls) { 17085 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17086 return; 17087 17088 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17089 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17090 17091 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17092 return; 17093 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17094 if (!ID) { 17095 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17096 if (!CD->IsClassExtension()) 17097 return; 17098 } 17099 // No need to add this to end of @implementation. 17100 else 17101 return; 17102 } 17103 // All conditions are met. Add a new bitfield to the tail end of ivars. 17104 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17105 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17106 17107 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17108 DeclLoc, DeclLoc, nullptr, 17109 Context.CharTy, 17110 Context.getTrivialTypeSourceInfo(Context.CharTy, 17111 DeclLoc), 17112 ObjCIvarDecl::Private, BW, 17113 true); 17114 AllIvarDecls.push_back(Ivar); 17115 } 17116 17117 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17118 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17119 SourceLocation RBrac, 17120 const ParsedAttributesView &Attrs) { 17121 assert(EnclosingDecl && "missing record or interface decl"); 17122 17123 // If this is an Objective-C @implementation or category and we have 17124 // new fields here we should reset the layout of the interface since 17125 // it will now change. 17126 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17127 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17128 switch (DC->getKind()) { 17129 default: break; 17130 case Decl::ObjCCategory: 17131 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17132 break; 17133 case Decl::ObjCImplementation: 17134 Context. 17135 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17136 break; 17137 } 17138 } 17139 17140 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17141 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17142 17143 // Start counting up the number of named members; make sure to include 17144 // members of anonymous structs and unions in the total. 17145 unsigned NumNamedMembers = 0; 17146 if (Record) { 17147 for (const auto *I : Record->decls()) { 17148 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17149 if (IFD->getDeclName()) 17150 ++NumNamedMembers; 17151 } 17152 } 17153 17154 // Verify that all the fields are okay. 17155 SmallVector<FieldDecl*, 32> RecFields; 17156 17157 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17158 i != end; ++i) { 17159 FieldDecl *FD = cast<FieldDecl>(*i); 17160 17161 // Get the type for the field. 17162 const Type *FDTy = FD->getType().getTypePtr(); 17163 17164 if (!FD->isAnonymousStructOrUnion()) { 17165 // Remember all fields written by the user. 17166 RecFields.push_back(FD); 17167 } 17168 17169 // If the field is already invalid for some reason, don't emit more 17170 // diagnostics about it. 17171 if (FD->isInvalidDecl()) { 17172 EnclosingDecl->setInvalidDecl(); 17173 continue; 17174 } 17175 17176 // C99 6.7.2.1p2: 17177 // A structure or union shall not contain a member with 17178 // incomplete or function type (hence, a structure shall not 17179 // contain an instance of itself, but may contain a pointer to 17180 // an instance of itself), except that the last member of a 17181 // structure with more than one named member may have incomplete 17182 // array type; such a structure (and any union containing, 17183 // possibly recursively, a member that is such a structure) 17184 // shall not be a member of a structure or an element of an 17185 // array. 17186 bool IsLastField = (i + 1 == Fields.end()); 17187 if (FDTy->isFunctionType()) { 17188 // Field declared as a function. 17189 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17190 << FD->getDeclName(); 17191 FD->setInvalidDecl(); 17192 EnclosingDecl->setInvalidDecl(); 17193 continue; 17194 } else if (FDTy->isIncompleteArrayType() && 17195 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17196 if (Record) { 17197 // Flexible array member. 17198 // Microsoft and g++ is more permissive regarding flexible array. 17199 // It will accept flexible array in union and also 17200 // as the sole element of a struct/class. 17201 unsigned DiagID = 0; 17202 if (!Record->isUnion() && !IsLastField) { 17203 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17204 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17205 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17206 FD->setInvalidDecl(); 17207 EnclosingDecl->setInvalidDecl(); 17208 continue; 17209 } else if (Record->isUnion()) 17210 DiagID = getLangOpts().MicrosoftExt 17211 ? diag::ext_flexible_array_union_ms 17212 : getLangOpts().CPlusPlus 17213 ? diag::ext_flexible_array_union_gnu 17214 : diag::err_flexible_array_union; 17215 else if (NumNamedMembers < 1) 17216 DiagID = getLangOpts().MicrosoftExt 17217 ? diag::ext_flexible_array_empty_aggregate_ms 17218 : getLangOpts().CPlusPlus 17219 ? diag::ext_flexible_array_empty_aggregate_gnu 17220 : diag::err_flexible_array_empty_aggregate; 17221 17222 if (DiagID) 17223 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17224 << Record->getTagKind(); 17225 // While the layout of types that contain virtual bases is not specified 17226 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17227 // virtual bases after the derived members. This would make a flexible 17228 // array member declared at the end of an object not adjacent to the end 17229 // of the type. 17230 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17231 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17232 << FD->getDeclName() << Record->getTagKind(); 17233 if (!getLangOpts().C99) 17234 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17235 << FD->getDeclName() << Record->getTagKind(); 17236 17237 // If the element type has a non-trivial destructor, we would not 17238 // implicitly destroy the elements, so disallow it for now. 17239 // 17240 // FIXME: GCC allows this. We should probably either implicitly delete 17241 // the destructor of the containing class, or just allow this. 17242 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17243 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17244 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17245 << FD->getDeclName() << FD->getType(); 17246 FD->setInvalidDecl(); 17247 EnclosingDecl->setInvalidDecl(); 17248 continue; 17249 } 17250 // Okay, we have a legal flexible array member at the end of the struct. 17251 Record->setHasFlexibleArrayMember(true); 17252 } else { 17253 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17254 // unless they are followed by another ivar. That check is done 17255 // elsewhere, after synthesized ivars are known. 17256 } 17257 } else if (!FDTy->isDependentType() && 17258 RequireCompleteSizedType( 17259 FD->getLocation(), FD->getType(), 17260 diag::err_field_incomplete_or_sizeless)) { 17261 // Incomplete type 17262 FD->setInvalidDecl(); 17263 EnclosingDecl->setInvalidDecl(); 17264 continue; 17265 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17266 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17267 // A type which contains a flexible array member is considered to be a 17268 // flexible array member. 17269 Record->setHasFlexibleArrayMember(true); 17270 if (!Record->isUnion()) { 17271 // If this is a struct/class and this is not the last element, reject 17272 // it. Note that GCC supports variable sized arrays in the middle of 17273 // structures. 17274 if (!IsLastField) 17275 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17276 << FD->getDeclName() << FD->getType(); 17277 else { 17278 // We support flexible arrays at the end of structs in 17279 // other structs as an extension. 17280 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17281 << FD->getDeclName(); 17282 } 17283 } 17284 } 17285 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17286 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17287 diag::err_abstract_type_in_decl, 17288 AbstractIvarType)) { 17289 // Ivars can not have abstract class types 17290 FD->setInvalidDecl(); 17291 } 17292 if (Record && FDTTy->getDecl()->hasObjectMember()) 17293 Record->setHasObjectMember(true); 17294 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17295 Record->setHasVolatileMember(true); 17296 } else if (FDTy->isObjCObjectType()) { 17297 /// A field cannot be an Objective-c object 17298 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17299 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17300 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17301 FD->setType(T); 17302 } else if (Record && Record->isUnion() && 17303 FD->getType().hasNonTrivialObjCLifetime() && 17304 getSourceManager().isInSystemHeader(FD->getLocation()) && 17305 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17306 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17307 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17308 // For backward compatibility, fields of C unions declared in system 17309 // headers that have non-trivial ObjC ownership qualifications are marked 17310 // as unavailable unless the qualifier is explicit and __strong. This can 17311 // break ABI compatibility between programs compiled with ARC and MRR, but 17312 // is a better option than rejecting programs using those unions under 17313 // ARC. 17314 FD->addAttr(UnavailableAttr::CreateImplicit( 17315 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17316 FD->getLocation())); 17317 } else if (getLangOpts().ObjC && 17318 getLangOpts().getGC() != LangOptions::NonGC && Record && 17319 !Record->hasObjectMember()) { 17320 if (FD->getType()->isObjCObjectPointerType() || 17321 FD->getType().isObjCGCStrong()) 17322 Record->setHasObjectMember(true); 17323 else if (Context.getAsArrayType(FD->getType())) { 17324 QualType BaseType = Context.getBaseElementType(FD->getType()); 17325 if (BaseType->isRecordType() && 17326 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17327 Record->setHasObjectMember(true); 17328 else if (BaseType->isObjCObjectPointerType() || 17329 BaseType.isObjCGCStrong()) 17330 Record->setHasObjectMember(true); 17331 } 17332 } 17333 17334 if (Record && !getLangOpts().CPlusPlus && 17335 !shouldIgnoreForRecordTriviality(FD)) { 17336 QualType FT = FD->getType(); 17337 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17338 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17339 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17340 Record->isUnion()) 17341 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17342 } 17343 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17344 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17345 Record->setNonTrivialToPrimitiveCopy(true); 17346 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17347 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17348 } 17349 if (FT.isDestructedType()) { 17350 Record->setNonTrivialToPrimitiveDestroy(true); 17351 Record->setParamDestroyedInCallee(true); 17352 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17353 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17354 } 17355 17356 if (const auto *RT = FT->getAs<RecordType>()) { 17357 if (RT->getDecl()->getArgPassingRestrictions() == 17358 RecordDecl::APK_CanNeverPassInRegs) 17359 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17360 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17361 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17362 } 17363 17364 if (Record && FD->getType().isVolatileQualified()) 17365 Record->setHasVolatileMember(true); 17366 // Keep track of the number of named members. 17367 if (FD->getIdentifier()) 17368 ++NumNamedMembers; 17369 } 17370 17371 // Okay, we successfully defined 'Record'. 17372 if (Record) { 17373 bool Completed = false; 17374 if (CXXRecord) { 17375 if (!CXXRecord->isInvalidDecl()) { 17376 // Set access bits correctly on the directly-declared conversions. 17377 for (CXXRecordDecl::conversion_iterator 17378 I = CXXRecord->conversion_begin(), 17379 E = CXXRecord->conversion_end(); I != E; ++I) 17380 I.setAccess((*I)->getAccess()); 17381 } 17382 17383 // Add any implicitly-declared members to this class. 17384 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17385 17386 if (!CXXRecord->isDependentType()) { 17387 if (!CXXRecord->isInvalidDecl()) { 17388 // If we have virtual base classes, we may end up finding multiple 17389 // final overriders for a given virtual function. Check for this 17390 // problem now. 17391 if (CXXRecord->getNumVBases()) { 17392 CXXFinalOverriderMap FinalOverriders; 17393 CXXRecord->getFinalOverriders(FinalOverriders); 17394 17395 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17396 MEnd = FinalOverriders.end(); 17397 M != MEnd; ++M) { 17398 for (OverridingMethods::iterator SO = M->second.begin(), 17399 SOEnd = M->second.end(); 17400 SO != SOEnd; ++SO) { 17401 assert(SO->second.size() > 0 && 17402 "Virtual function without overriding functions?"); 17403 if (SO->second.size() == 1) 17404 continue; 17405 17406 // C++ [class.virtual]p2: 17407 // In a derived class, if a virtual member function of a base 17408 // class subobject has more than one final overrider the 17409 // program is ill-formed. 17410 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17411 << (const NamedDecl *)M->first << Record; 17412 Diag(M->first->getLocation(), 17413 diag::note_overridden_virtual_function); 17414 for (OverridingMethods::overriding_iterator 17415 OM = SO->second.begin(), 17416 OMEnd = SO->second.end(); 17417 OM != OMEnd; ++OM) 17418 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17419 << (const NamedDecl *)M->first << OM->Method->getParent(); 17420 17421 Record->setInvalidDecl(); 17422 } 17423 } 17424 CXXRecord->completeDefinition(&FinalOverriders); 17425 Completed = true; 17426 } 17427 } 17428 } 17429 } 17430 17431 if (!Completed) 17432 Record->completeDefinition(); 17433 17434 // Handle attributes before checking the layout. 17435 ProcessDeclAttributeList(S, Record, Attrs); 17436 17437 // We may have deferred checking for a deleted destructor. Check now. 17438 if (CXXRecord) { 17439 auto *Dtor = CXXRecord->getDestructor(); 17440 if (Dtor && Dtor->isImplicit() && 17441 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17442 CXXRecord->setImplicitDestructorIsDeleted(); 17443 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17444 } 17445 } 17446 17447 if (Record->hasAttrs()) { 17448 CheckAlignasUnderalignment(Record); 17449 17450 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17451 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17452 IA->getRange(), IA->getBestCase(), 17453 IA->getInheritanceModel()); 17454 } 17455 17456 // Check if the structure/union declaration is a type that can have zero 17457 // size in C. For C this is a language extension, for C++ it may cause 17458 // compatibility problems. 17459 bool CheckForZeroSize; 17460 if (!getLangOpts().CPlusPlus) { 17461 CheckForZeroSize = true; 17462 } else { 17463 // For C++ filter out types that cannot be referenced in C code. 17464 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17465 CheckForZeroSize = 17466 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17467 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 17468 CXXRecord->isCLike(); 17469 } 17470 if (CheckForZeroSize) { 17471 bool ZeroSize = true; 17472 bool IsEmpty = true; 17473 unsigned NonBitFields = 0; 17474 for (RecordDecl::field_iterator I = Record->field_begin(), 17475 E = Record->field_end(); 17476 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17477 IsEmpty = false; 17478 if (I->isUnnamedBitfield()) { 17479 if (!I->isZeroLengthBitField(Context)) 17480 ZeroSize = false; 17481 } else { 17482 ++NonBitFields; 17483 QualType FieldType = I->getType(); 17484 if (FieldType->isIncompleteType() || 17485 !Context.getTypeSizeInChars(FieldType).isZero()) 17486 ZeroSize = false; 17487 } 17488 } 17489 17490 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17491 // allowed in C++, but warn if its declaration is inside 17492 // extern "C" block. 17493 if (ZeroSize) { 17494 Diag(RecLoc, getLangOpts().CPlusPlus ? 17495 diag::warn_zero_size_struct_union_in_extern_c : 17496 diag::warn_zero_size_struct_union_compat) 17497 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17498 } 17499 17500 // Structs without named members are extension in C (C99 6.7.2.1p7), 17501 // but are accepted by GCC. 17502 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17503 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17504 diag::ext_no_named_members_in_struct_union) 17505 << Record->isUnion(); 17506 } 17507 } 17508 } else { 17509 ObjCIvarDecl **ClsFields = 17510 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17511 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17512 ID->setEndOfDefinitionLoc(RBrac); 17513 // Add ivar's to class's DeclContext. 17514 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17515 ClsFields[i]->setLexicalDeclContext(ID); 17516 ID->addDecl(ClsFields[i]); 17517 } 17518 // Must enforce the rule that ivars in the base classes may not be 17519 // duplicates. 17520 if (ID->getSuperClass()) 17521 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17522 } else if (ObjCImplementationDecl *IMPDecl = 17523 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17524 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17525 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17526 // Ivar declared in @implementation never belongs to the implementation. 17527 // Only it is in implementation's lexical context. 17528 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17529 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17530 IMPDecl->setIvarLBraceLoc(LBrac); 17531 IMPDecl->setIvarRBraceLoc(RBrac); 17532 } else if (ObjCCategoryDecl *CDecl = 17533 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17534 // case of ivars in class extension; all other cases have been 17535 // reported as errors elsewhere. 17536 // FIXME. Class extension does not have a LocEnd field. 17537 // CDecl->setLocEnd(RBrac); 17538 // Add ivar's to class extension's DeclContext. 17539 // Diagnose redeclaration of private ivars. 17540 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17541 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17542 if (IDecl) { 17543 if (const ObjCIvarDecl *ClsIvar = 17544 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17545 Diag(ClsFields[i]->getLocation(), 17546 diag::err_duplicate_ivar_declaration); 17547 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17548 continue; 17549 } 17550 for (const auto *Ext : IDecl->known_extensions()) { 17551 if (const ObjCIvarDecl *ClsExtIvar 17552 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17553 Diag(ClsFields[i]->getLocation(), 17554 diag::err_duplicate_ivar_declaration); 17555 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17556 continue; 17557 } 17558 } 17559 } 17560 ClsFields[i]->setLexicalDeclContext(CDecl); 17561 CDecl->addDecl(ClsFields[i]); 17562 } 17563 CDecl->setIvarLBraceLoc(LBrac); 17564 CDecl->setIvarRBraceLoc(RBrac); 17565 } 17566 } 17567 } 17568 17569 /// Determine whether the given integral value is representable within 17570 /// the given type T. 17571 static bool isRepresentableIntegerValue(ASTContext &Context, 17572 llvm::APSInt &Value, 17573 QualType T) { 17574 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17575 "Integral type required!"); 17576 unsigned BitWidth = Context.getIntWidth(T); 17577 17578 if (Value.isUnsigned() || Value.isNonNegative()) { 17579 if (T->isSignedIntegerOrEnumerationType()) 17580 --BitWidth; 17581 return Value.getActiveBits() <= BitWidth; 17582 } 17583 return Value.getMinSignedBits() <= BitWidth; 17584 } 17585 17586 // Given an integral type, return the next larger integral type 17587 // (or a NULL type of no such type exists). 17588 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17589 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17590 // enum checking below. 17591 assert((T->isIntegralType(Context) || 17592 T->isEnumeralType()) && "Integral type required!"); 17593 const unsigned NumTypes = 4; 17594 QualType SignedIntegralTypes[NumTypes] = { 17595 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17596 }; 17597 QualType UnsignedIntegralTypes[NumTypes] = { 17598 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17599 Context.UnsignedLongLongTy 17600 }; 17601 17602 unsigned BitWidth = Context.getTypeSize(T); 17603 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17604 : UnsignedIntegralTypes; 17605 for (unsigned I = 0; I != NumTypes; ++I) 17606 if (Context.getTypeSize(Types[I]) > BitWidth) 17607 return Types[I]; 17608 17609 return QualType(); 17610 } 17611 17612 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17613 EnumConstantDecl *LastEnumConst, 17614 SourceLocation IdLoc, 17615 IdentifierInfo *Id, 17616 Expr *Val) { 17617 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17618 llvm::APSInt EnumVal(IntWidth); 17619 QualType EltTy; 17620 17621 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17622 Val = nullptr; 17623 17624 if (Val) 17625 Val = DefaultLvalueConversion(Val).get(); 17626 17627 if (Val) { 17628 if (Enum->isDependentType() || Val->isTypeDependent()) 17629 EltTy = Context.DependentTy; 17630 else { 17631 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 17632 // underlying type, but do allow it in all other contexts. 17633 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17634 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17635 // constant-expression in the enumerator-definition shall be a converted 17636 // constant expression of the underlying type. 17637 EltTy = Enum->getIntegerType(); 17638 ExprResult Converted = 17639 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17640 CCEK_Enumerator); 17641 if (Converted.isInvalid()) 17642 Val = nullptr; 17643 else 17644 Val = Converted.get(); 17645 } else if (!Val->isValueDependent() && 17646 !(Val = 17647 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 17648 .get())) { 17649 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17650 } else { 17651 if (Enum->isComplete()) { 17652 EltTy = Enum->getIntegerType(); 17653 17654 // In Obj-C and Microsoft mode, require the enumeration value to be 17655 // representable in the underlying type of the enumeration. In C++11, 17656 // we perform a non-narrowing conversion as part of converted constant 17657 // expression checking. 17658 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17659 if (Context.getTargetInfo() 17660 .getTriple() 17661 .isWindowsMSVCEnvironment()) { 17662 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17663 } else { 17664 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17665 } 17666 } 17667 17668 // Cast to the underlying type. 17669 Val = ImpCastExprToType(Val, EltTy, 17670 EltTy->isBooleanType() ? CK_IntegralToBoolean 17671 : CK_IntegralCast) 17672 .get(); 17673 } else if (getLangOpts().CPlusPlus) { 17674 // C++11 [dcl.enum]p5: 17675 // If the underlying type is not fixed, the type of each enumerator 17676 // is the type of its initializing value: 17677 // - If an initializer is specified for an enumerator, the 17678 // initializing value has the same type as the expression. 17679 EltTy = Val->getType(); 17680 } else { 17681 // C99 6.7.2.2p2: 17682 // The expression that defines the value of an enumeration constant 17683 // shall be an integer constant expression that has a value 17684 // representable as an int. 17685 17686 // Complain if the value is not representable in an int. 17687 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17688 Diag(IdLoc, diag::ext_enum_value_not_int) 17689 << EnumVal.toString(10) << Val->getSourceRange() 17690 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17691 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17692 // Force the type of the expression to 'int'. 17693 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17694 } 17695 EltTy = Val->getType(); 17696 } 17697 } 17698 } 17699 } 17700 17701 if (!Val) { 17702 if (Enum->isDependentType()) 17703 EltTy = Context.DependentTy; 17704 else if (!LastEnumConst) { 17705 // C++0x [dcl.enum]p5: 17706 // If the underlying type is not fixed, the type of each enumerator 17707 // is the type of its initializing value: 17708 // - If no initializer is specified for the first enumerator, the 17709 // initializing value has an unspecified integral type. 17710 // 17711 // GCC uses 'int' for its unspecified integral type, as does 17712 // C99 6.7.2.2p3. 17713 if (Enum->isFixed()) { 17714 EltTy = Enum->getIntegerType(); 17715 } 17716 else { 17717 EltTy = Context.IntTy; 17718 } 17719 } else { 17720 // Assign the last value + 1. 17721 EnumVal = LastEnumConst->getInitVal(); 17722 ++EnumVal; 17723 EltTy = LastEnumConst->getType(); 17724 17725 // Check for overflow on increment. 17726 if (EnumVal < LastEnumConst->getInitVal()) { 17727 // C++0x [dcl.enum]p5: 17728 // If the underlying type is not fixed, the type of each enumerator 17729 // is the type of its initializing value: 17730 // 17731 // - Otherwise the type of the initializing value is the same as 17732 // the type of the initializing value of the preceding enumerator 17733 // unless the incremented value is not representable in that type, 17734 // in which case the type is an unspecified integral type 17735 // sufficient to contain the incremented value. If no such type 17736 // exists, the program is ill-formed. 17737 QualType T = getNextLargerIntegralType(Context, EltTy); 17738 if (T.isNull() || Enum->isFixed()) { 17739 // There is no integral type larger enough to represent this 17740 // value. Complain, then allow the value to wrap around. 17741 EnumVal = LastEnumConst->getInitVal(); 17742 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17743 ++EnumVal; 17744 if (Enum->isFixed()) 17745 // When the underlying type is fixed, this is ill-formed. 17746 Diag(IdLoc, diag::err_enumerator_wrapped) 17747 << EnumVal.toString(10) 17748 << EltTy; 17749 else 17750 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17751 << EnumVal.toString(10); 17752 } else { 17753 EltTy = T; 17754 } 17755 17756 // Retrieve the last enumerator's value, extent that type to the 17757 // type that is supposed to be large enough to represent the incremented 17758 // value, then increment. 17759 EnumVal = LastEnumConst->getInitVal(); 17760 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17761 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17762 ++EnumVal; 17763 17764 // If we're not in C++, diagnose the overflow of enumerator values, 17765 // which in C99 means that the enumerator value is not representable in 17766 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17767 // permits enumerator values that are representable in some larger 17768 // integral type. 17769 if (!getLangOpts().CPlusPlus && !T.isNull()) 17770 Diag(IdLoc, diag::warn_enum_value_overflow); 17771 } else if (!getLangOpts().CPlusPlus && 17772 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17773 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17774 Diag(IdLoc, diag::ext_enum_value_not_int) 17775 << EnumVal.toString(10) << 1; 17776 } 17777 } 17778 } 17779 17780 if (!EltTy->isDependentType()) { 17781 // Make the enumerator value match the signedness and size of the 17782 // enumerator's type. 17783 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17784 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17785 } 17786 17787 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17788 Val, EnumVal); 17789 } 17790 17791 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17792 SourceLocation IILoc) { 17793 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17794 !getLangOpts().CPlusPlus) 17795 return SkipBodyInfo(); 17796 17797 // We have an anonymous enum definition. Look up the first enumerator to 17798 // determine if we should merge the definition with an existing one and 17799 // skip the body. 17800 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17801 forRedeclarationInCurContext()); 17802 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17803 if (!PrevECD) 17804 return SkipBodyInfo(); 17805 17806 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17807 NamedDecl *Hidden; 17808 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17809 SkipBodyInfo Skip; 17810 Skip.Previous = Hidden; 17811 return Skip; 17812 } 17813 17814 return SkipBodyInfo(); 17815 } 17816 17817 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17818 SourceLocation IdLoc, IdentifierInfo *Id, 17819 const ParsedAttributesView &Attrs, 17820 SourceLocation EqualLoc, Expr *Val) { 17821 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17822 EnumConstantDecl *LastEnumConst = 17823 cast_or_null<EnumConstantDecl>(lastEnumConst); 17824 17825 // The scope passed in may not be a decl scope. Zip up the scope tree until 17826 // we find one that is. 17827 S = getNonFieldDeclScope(S); 17828 17829 // Verify that there isn't already something declared with this name in this 17830 // scope. 17831 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17832 LookupName(R, S); 17833 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17834 17835 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17836 // Maybe we will complain about the shadowed template parameter. 17837 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17838 // Just pretend that we didn't see the previous declaration. 17839 PrevDecl = nullptr; 17840 } 17841 17842 // C++ [class.mem]p15: 17843 // If T is the name of a class, then each of the following shall have a name 17844 // different from T: 17845 // - every enumerator of every member of class T that is an unscoped 17846 // enumerated type 17847 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17848 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17849 DeclarationNameInfo(Id, IdLoc)); 17850 17851 EnumConstantDecl *New = 17852 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17853 if (!New) 17854 return nullptr; 17855 17856 if (PrevDecl) { 17857 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17858 // Check for other kinds of shadowing not already handled. 17859 CheckShadow(New, PrevDecl, R); 17860 } 17861 17862 // When in C++, we may get a TagDecl with the same name; in this case the 17863 // enum constant will 'hide' the tag. 17864 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17865 "Received TagDecl when not in C++!"); 17866 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17867 if (isa<EnumConstantDecl>(PrevDecl)) 17868 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17869 else 17870 Diag(IdLoc, diag::err_redefinition) << Id; 17871 notePreviousDefinition(PrevDecl, IdLoc); 17872 return nullptr; 17873 } 17874 } 17875 17876 // Process attributes. 17877 ProcessDeclAttributeList(S, New, Attrs); 17878 AddPragmaAttributes(S, New); 17879 17880 // Register this decl in the current scope stack. 17881 New->setAccess(TheEnumDecl->getAccess()); 17882 PushOnScopeChains(New, S); 17883 17884 ActOnDocumentableDecl(New); 17885 17886 return New; 17887 } 17888 17889 // Returns true when the enum initial expression does not trigger the 17890 // duplicate enum warning. A few common cases are exempted as follows: 17891 // Element2 = Element1 17892 // Element2 = Element1 + 1 17893 // Element2 = Element1 - 1 17894 // Where Element2 and Element1 are from the same enum. 17895 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17896 Expr *InitExpr = ECD->getInitExpr(); 17897 if (!InitExpr) 17898 return true; 17899 InitExpr = InitExpr->IgnoreImpCasts(); 17900 17901 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17902 if (!BO->isAdditiveOp()) 17903 return true; 17904 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17905 if (!IL) 17906 return true; 17907 if (IL->getValue() != 1) 17908 return true; 17909 17910 InitExpr = BO->getLHS(); 17911 } 17912 17913 // This checks if the elements are from the same enum. 17914 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17915 if (!DRE) 17916 return true; 17917 17918 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17919 if (!EnumConstant) 17920 return true; 17921 17922 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17923 Enum) 17924 return true; 17925 17926 return false; 17927 } 17928 17929 // Emits a warning when an element is implicitly set a value that 17930 // a previous element has already been set to. 17931 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17932 EnumDecl *Enum, QualType EnumType) { 17933 // Avoid anonymous enums 17934 if (!Enum->getIdentifier()) 17935 return; 17936 17937 // Only check for small enums. 17938 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17939 return; 17940 17941 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17942 return; 17943 17944 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17945 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17946 17947 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17948 17949 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 17950 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17951 17952 // Use int64_t as a key to avoid needing special handling for map keys. 17953 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17954 llvm::APSInt Val = D->getInitVal(); 17955 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17956 }; 17957 17958 DuplicatesVector DupVector; 17959 ValueToVectorMap EnumMap; 17960 17961 // Populate the EnumMap with all values represented by enum constants without 17962 // an initializer. 17963 for (auto *Element : Elements) { 17964 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17965 17966 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17967 // this constant. Skip this enum since it may be ill-formed. 17968 if (!ECD) { 17969 return; 17970 } 17971 17972 // Constants with initalizers are handled in the next loop. 17973 if (ECD->getInitExpr()) 17974 continue; 17975 17976 // Duplicate values are handled in the next loop. 17977 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17978 } 17979 17980 if (EnumMap.size() == 0) 17981 return; 17982 17983 // Create vectors for any values that has duplicates. 17984 for (auto *Element : Elements) { 17985 // The last loop returned if any constant was null. 17986 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17987 if (!ValidDuplicateEnum(ECD, Enum)) 17988 continue; 17989 17990 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17991 if (Iter == EnumMap.end()) 17992 continue; 17993 17994 DeclOrVector& Entry = Iter->second; 17995 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17996 // Ensure constants are different. 17997 if (D == ECD) 17998 continue; 17999 18000 // Create new vector and push values onto it. 18001 auto Vec = std::make_unique<ECDVector>(); 18002 Vec->push_back(D); 18003 Vec->push_back(ECD); 18004 18005 // Update entry to point to the duplicates vector. 18006 Entry = Vec.get(); 18007 18008 // Store the vector somewhere we can consult later for quick emission of 18009 // diagnostics. 18010 DupVector.emplace_back(std::move(Vec)); 18011 continue; 18012 } 18013 18014 ECDVector *Vec = Entry.get<ECDVector*>(); 18015 // Make sure constants are not added more than once. 18016 if (*Vec->begin() == ECD) 18017 continue; 18018 18019 Vec->push_back(ECD); 18020 } 18021 18022 // Emit diagnostics. 18023 for (const auto &Vec : DupVector) { 18024 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 18025 18026 // Emit warning for one enum constant. 18027 auto *FirstECD = Vec->front(); 18028 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 18029 << FirstECD << FirstECD->getInitVal().toString(10) 18030 << FirstECD->getSourceRange(); 18031 18032 // Emit one note for each of the remaining enum constants with 18033 // the same value. 18034 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 18035 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 18036 << ECD << ECD->getInitVal().toString(10) 18037 << ECD->getSourceRange(); 18038 } 18039 } 18040 18041 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 18042 bool AllowMask) const { 18043 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 18044 assert(ED->isCompleteDefinition() && "expected enum definition"); 18045 18046 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 18047 llvm::APInt &FlagBits = R.first->second; 18048 18049 if (R.second) { 18050 for (auto *E : ED->enumerators()) { 18051 const auto &EVal = E->getInitVal(); 18052 // Only single-bit enumerators introduce new flag values. 18053 if (EVal.isPowerOf2()) 18054 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 18055 } 18056 } 18057 18058 // A value is in a flag enum if either its bits are a subset of the enum's 18059 // flag bits (the first condition) or we are allowing masks and the same is 18060 // true of its complement (the second condition). When masks are allowed, we 18061 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 18062 // 18063 // While it's true that any value could be used as a mask, the assumption is 18064 // that a mask will have all of the insignificant bits set. Anything else is 18065 // likely a logic error. 18066 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18067 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18068 } 18069 18070 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18071 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18072 const ParsedAttributesView &Attrs) { 18073 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18074 QualType EnumType = Context.getTypeDeclType(Enum); 18075 18076 ProcessDeclAttributeList(S, Enum, Attrs); 18077 18078 if (Enum->isDependentType()) { 18079 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18080 EnumConstantDecl *ECD = 18081 cast_or_null<EnumConstantDecl>(Elements[i]); 18082 if (!ECD) continue; 18083 18084 ECD->setType(EnumType); 18085 } 18086 18087 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18088 return; 18089 } 18090 18091 // TODO: If the result value doesn't fit in an int, it must be a long or long 18092 // long value. ISO C does not support this, but GCC does as an extension, 18093 // emit a warning. 18094 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18095 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18096 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18097 18098 // Verify that all the values are okay, compute the size of the values, and 18099 // reverse the list. 18100 unsigned NumNegativeBits = 0; 18101 unsigned NumPositiveBits = 0; 18102 18103 // Keep track of whether all elements have type int. 18104 bool AllElementsInt = true; 18105 18106 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18107 EnumConstantDecl *ECD = 18108 cast_or_null<EnumConstantDecl>(Elements[i]); 18109 if (!ECD) continue; // Already issued a diagnostic. 18110 18111 const llvm::APSInt &InitVal = ECD->getInitVal(); 18112 18113 // Keep track of the size of positive and negative values. 18114 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18115 NumPositiveBits = std::max(NumPositiveBits, 18116 (unsigned)InitVal.getActiveBits()); 18117 else 18118 NumNegativeBits = std::max(NumNegativeBits, 18119 (unsigned)InitVal.getMinSignedBits()); 18120 18121 // Keep track of whether every enum element has type int (very common). 18122 if (AllElementsInt) 18123 AllElementsInt = ECD->getType() == Context.IntTy; 18124 } 18125 18126 // Figure out the type that should be used for this enum. 18127 QualType BestType; 18128 unsigned BestWidth; 18129 18130 // C++0x N3000 [conv.prom]p3: 18131 // An rvalue of an unscoped enumeration type whose underlying 18132 // type is not fixed can be converted to an rvalue of the first 18133 // of the following types that can represent all the values of 18134 // the enumeration: int, unsigned int, long int, unsigned long 18135 // int, long long int, or unsigned long long int. 18136 // C99 6.4.4.3p2: 18137 // An identifier declared as an enumeration constant has type int. 18138 // The C99 rule is modified by a gcc extension 18139 QualType BestPromotionType; 18140 18141 bool Packed = Enum->hasAttr<PackedAttr>(); 18142 // -fshort-enums is the equivalent to specifying the packed attribute on all 18143 // enum definitions. 18144 if (LangOpts.ShortEnums) 18145 Packed = true; 18146 18147 // If the enum already has a type because it is fixed or dictated by the 18148 // target, promote that type instead of analyzing the enumerators. 18149 if (Enum->isComplete()) { 18150 BestType = Enum->getIntegerType(); 18151 if (BestType->isPromotableIntegerType()) 18152 BestPromotionType = Context.getPromotedIntegerType(BestType); 18153 else 18154 BestPromotionType = BestType; 18155 18156 BestWidth = Context.getIntWidth(BestType); 18157 } 18158 else if (NumNegativeBits) { 18159 // If there is a negative value, figure out the smallest integer type (of 18160 // int/long/longlong) that fits. 18161 // If it's packed, check also if it fits a char or a short. 18162 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18163 BestType = Context.SignedCharTy; 18164 BestWidth = CharWidth; 18165 } else if (Packed && NumNegativeBits <= ShortWidth && 18166 NumPositiveBits < ShortWidth) { 18167 BestType = Context.ShortTy; 18168 BestWidth = ShortWidth; 18169 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18170 BestType = Context.IntTy; 18171 BestWidth = IntWidth; 18172 } else { 18173 BestWidth = Context.getTargetInfo().getLongWidth(); 18174 18175 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18176 BestType = Context.LongTy; 18177 } else { 18178 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18179 18180 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18181 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18182 BestType = Context.LongLongTy; 18183 } 18184 } 18185 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18186 } else { 18187 // If there is no negative value, figure out the smallest type that fits 18188 // all of the enumerator values. 18189 // If it's packed, check also if it fits a char or a short. 18190 if (Packed && NumPositiveBits <= CharWidth) { 18191 BestType = Context.UnsignedCharTy; 18192 BestPromotionType = Context.IntTy; 18193 BestWidth = CharWidth; 18194 } else if (Packed && NumPositiveBits <= ShortWidth) { 18195 BestType = Context.UnsignedShortTy; 18196 BestPromotionType = Context.IntTy; 18197 BestWidth = ShortWidth; 18198 } else if (NumPositiveBits <= IntWidth) { 18199 BestType = Context.UnsignedIntTy; 18200 BestWidth = IntWidth; 18201 BestPromotionType 18202 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18203 ? Context.UnsignedIntTy : Context.IntTy; 18204 } else if (NumPositiveBits <= 18205 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18206 BestType = Context.UnsignedLongTy; 18207 BestPromotionType 18208 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18209 ? Context.UnsignedLongTy : Context.LongTy; 18210 } else { 18211 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18212 assert(NumPositiveBits <= BestWidth && 18213 "How could an initializer get larger than ULL?"); 18214 BestType = Context.UnsignedLongLongTy; 18215 BestPromotionType 18216 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18217 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18218 } 18219 } 18220 18221 // Loop over all of the enumerator constants, changing their types to match 18222 // the type of the enum if needed. 18223 for (auto *D : Elements) { 18224 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18225 if (!ECD) continue; // Already issued a diagnostic. 18226 18227 // Standard C says the enumerators have int type, but we allow, as an 18228 // extension, the enumerators to be larger than int size. If each 18229 // enumerator value fits in an int, type it as an int, otherwise type it the 18230 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18231 // that X has type 'int', not 'unsigned'. 18232 18233 // Determine whether the value fits into an int. 18234 llvm::APSInt InitVal = ECD->getInitVal(); 18235 18236 // If it fits into an integer type, force it. Otherwise force it to match 18237 // the enum decl type. 18238 QualType NewTy; 18239 unsigned NewWidth; 18240 bool NewSign; 18241 if (!getLangOpts().CPlusPlus && 18242 !Enum->isFixed() && 18243 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18244 NewTy = Context.IntTy; 18245 NewWidth = IntWidth; 18246 NewSign = true; 18247 } else if (ECD->getType() == BestType) { 18248 // Already the right type! 18249 if (getLangOpts().CPlusPlus) 18250 // C++ [dcl.enum]p4: Following the closing brace of an 18251 // enum-specifier, each enumerator has the type of its 18252 // enumeration. 18253 ECD->setType(EnumType); 18254 continue; 18255 } else { 18256 NewTy = BestType; 18257 NewWidth = BestWidth; 18258 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18259 } 18260 18261 // Adjust the APSInt value. 18262 InitVal = InitVal.extOrTrunc(NewWidth); 18263 InitVal.setIsSigned(NewSign); 18264 ECD->setInitVal(InitVal); 18265 18266 // Adjust the Expr initializer and type. 18267 if (ECD->getInitExpr() && 18268 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18269 ECD->setInitExpr(ImplicitCastExpr::Create( 18270 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18271 /*base paths*/ nullptr, VK_RValue, FPOptionsOverride())); 18272 if (getLangOpts().CPlusPlus) 18273 // C++ [dcl.enum]p4: Following the closing brace of an 18274 // enum-specifier, each enumerator has the type of its 18275 // enumeration. 18276 ECD->setType(EnumType); 18277 else 18278 ECD->setType(NewTy); 18279 } 18280 18281 Enum->completeDefinition(BestType, BestPromotionType, 18282 NumPositiveBits, NumNegativeBits); 18283 18284 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18285 18286 if (Enum->isClosedFlag()) { 18287 for (Decl *D : Elements) { 18288 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18289 if (!ECD) continue; // Already issued a diagnostic. 18290 18291 llvm::APSInt InitVal = ECD->getInitVal(); 18292 if (InitVal != 0 && !InitVal.isPowerOf2() && 18293 !IsValueInFlagEnum(Enum, InitVal, true)) 18294 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18295 << ECD << Enum; 18296 } 18297 } 18298 18299 // Now that the enum type is defined, ensure it's not been underaligned. 18300 if (Enum->hasAttrs()) 18301 CheckAlignasUnderalignment(Enum); 18302 } 18303 18304 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18305 SourceLocation StartLoc, 18306 SourceLocation EndLoc) { 18307 StringLiteral *AsmString = cast<StringLiteral>(expr); 18308 18309 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18310 AsmString, StartLoc, 18311 EndLoc); 18312 CurContext->addDecl(New); 18313 return New; 18314 } 18315 18316 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18317 IdentifierInfo* AliasName, 18318 SourceLocation PragmaLoc, 18319 SourceLocation NameLoc, 18320 SourceLocation AliasNameLoc) { 18321 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18322 LookupOrdinaryName); 18323 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18324 AttributeCommonInfo::AS_Pragma); 18325 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18326 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18327 18328 // If a declaration that: 18329 // 1) declares a function or a variable 18330 // 2) has external linkage 18331 // already exists, add a label attribute to it. 18332 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18333 if (isDeclExternC(PrevDecl)) 18334 PrevDecl->addAttr(Attr); 18335 else 18336 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18337 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18338 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18339 } else 18340 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18341 } 18342 18343 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18344 SourceLocation PragmaLoc, 18345 SourceLocation NameLoc) { 18346 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18347 18348 if (PrevDecl) { 18349 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18350 } else { 18351 (void)WeakUndeclaredIdentifiers.insert( 18352 std::pair<IdentifierInfo*,WeakInfo> 18353 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18354 } 18355 } 18356 18357 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18358 IdentifierInfo* AliasName, 18359 SourceLocation PragmaLoc, 18360 SourceLocation NameLoc, 18361 SourceLocation AliasNameLoc) { 18362 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18363 LookupOrdinaryName); 18364 WeakInfo W = WeakInfo(Name, NameLoc); 18365 18366 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18367 if (!PrevDecl->hasAttr<AliasAttr>()) 18368 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18369 DeclApplyPragmaWeak(TUScope, ND, W); 18370 } else { 18371 (void)WeakUndeclaredIdentifiers.insert( 18372 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18373 } 18374 } 18375 18376 Decl *Sema::getObjCDeclContext() const { 18377 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18378 } 18379 18380 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18381 bool Final) { 18382 assert(FD && "Expected non-null FunctionDecl"); 18383 18384 // SYCL functions can be template, so we check if they have appropriate 18385 // attribute prior to checking if it is a template. 18386 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18387 return FunctionEmissionStatus::Emitted; 18388 18389 // Templates are emitted when they're instantiated. 18390 if (FD->isDependentContext()) 18391 return FunctionEmissionStatus::TemplateDiscarded; 18392 18393 // Check whether this function is an externally visible definition. 18394 auto IsEmittedForExternalSymbol = [this, FD]() { 18395 // We have to check the GVA linkage of the function's *definition* -- if we 18396 // only have a declaration, we don't know whether or not the function will 18397 // be emitted, because (say) the definition could include "inline". 18398 FunctionDecl *Def = FD->getDefinition(); 18399 18400 return Def && !isDiscardableGVALinkage( 18401 getASTContext().GetGVALinkageForFunction(Def)); 18402 }; 18403 18404 if (LangOpts.OpenMPIsDevice) { 18405 // In OpenMP device mode we will not emit host only functions, or functions 18406 // we don't need due to their linkage. 18407 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18408 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18409 // DevTy may be changed later by 18410 // #pragma omp declare target to(*) device_type(*). 18411 // Therefore DevTyhaving no value does not imply host. The emission status 18412 // will be checked again at the end of compilation unit with Final = true. 18413 if (DevTy.hasValue()) 18414 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18415 return FunctionEmissionStatus::OMPDiscarded; 18416 // If we have an explicit value for the device type, or we are in a target 18417 // declare context, we need to emit all extern and used symbols. 18418 if (isInOpenMPDeclareTargetContext() || DevTy.hasValue()) 18419 if (IsEmittedForExternalSymbol()) 18420 return FunctionEmissionStatus::Emitted; 18421 // Device mode only emits what it must, if it wasn't tagged yet and needed, 18422 // we'll omit it. 18423 if (Final) 18424 return FunctionEmissionStatus::OMPDiscarded; 18425 } else if (LangOpts.OpenMP > 45) { 18426 // In OpenMP host compilation prior to 5.0 everything was an emitted host 18427 // function. In 5.0, no_host was introduced which might cause a function to 18428 // be ommitted. 18429 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18430 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18431 if (DevTy.hasValue()) 18432 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 18433 return FunctionEmissionStatus::OMPDiscarded; 18434 } 18435 18436 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 18437 return FunctionEmissionStatus::Emitted; 18438 18439 if (LangOpts.CUDA) { 18440 // When compiling for device, host functions are never emitted. Similarly, 18441 // when compiling for host, device and global functions are never emitted. 18442 // (Technically, we do emit a host-side stub for global functions, but this 18443 // doesn't count for our purposes here.) 18444 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18445 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18446 return FunctionEmissionStatus::CUDADiscarded; 18447 if (!LangOpts.CUDAIsDevice && 18448 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18449 return FunctionEmissionStatus::CUDADiscarded; 18450 18451 if (IsEmittedForExternalSymbol()) 18452 return FunctionEmissionStatus::Emitted; 18453 } 18454 18455 // Otherwise, the function is known-emitted if it's in our set of 18456 // known-emitted functions. 18457 return FunctionEmissionStatus::Unknown; 18458 } 18459 18460 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18461 // Host-side references to a __global__ function refer to the stub, so the 18462 // function itself is never emitted and therefore should not be marked. 18463 // If we have host fn calls kernel fn calls host+device, the HD function 18464 // does not get instantiated on the host. We model this by omitting at the 18465 // call to the kernel from the callgraph. This ensures that, when compiling 18466 // for host, only HD functions actually called from the host get marked as 18467 // known-emitted. 18468 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18469 IdentifyCUDATarget(Callee) == CFT_Global; 18470 } 18471