1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TypeLocBuilder.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/CommentDiagnostic.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclTemplate.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/StmtCXX.h" 27 #include "clang/Basic/Builtins.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 35 #include "clang/Sema/CXXFieldCollector.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaInternal.h" 44 #include "clang/Sema/Template.h" 45 #include "llvm/ADT/SmallString.h" 46 #include "llvm/ADT/Triple.h" 47 #include <algorithm> 48 #include <cstring> 49 #include <functional> 50 51 using namespace clang; 52 using namespace sema; 53 54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 55 if (OwnedType) { 56 Decl *Group[2] = { OwnedType, Ptr }; 57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 58 } 59 60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 61 } 62 63 namespace { 64 65 class TypeNameValidatorCCC : public CorrectionCandidateCallback { 66 public: 67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 68 bool AllowTemplates = false, 69 bool AllowNonTemplates = true) 70 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 71 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 72 WantExpressionKeywords = false; 73 WantCXXNamedCasts = false; 74 WantRemainingKeywords = false; 75 } 76 77 bool ValidateCandidate(const TypoCorrection &candidate) override { 78 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 79 if (!AllowInvalidDecl && ND->isInvalidDecl()) 80 return false; 81 82 if (getAsTypeTemplateDecl(ND)) 83 return AllowTemplates; 84 85 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 86 if (!IsType) 87 return false; 88 89 if (AllowNonTemplates) 90 return true; 91 92 // An injected-class-name of a class template (specialization) is valid 93 // as a template or as a non-template. 94 if (AllowTemplates) { 95 auto *RD = dyn_cast<CXXRecordDecl>(ND); 96 if (!RD || !RD->isInjectedClassName()) 97 return false; 98 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 99 return RD->getDescribedClassTemplate() || 100 isa<ClassTemplateSpecializationDecl>(RD); 101 } 102 103 return false; 104 } 105 106 return !WantClassName && candidate.isKeyword(); 107 } 108 109 private: 110 bool AllowInvalidDecl; 111 bool WantClassName; 112 bool AllowTemplates; 113 bool AllowNonTemplates; 114 }; 115 116 } // end anonymous namespace 117 118 /// \brief Determine whether the token kind starts a simple-type-specifier. 119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 120 switch (Kind) { 121 // FIXME: Take into account the current language when deciding whether a 122 // token kind is a valid type specifier 123 case tok::kw_short: 124 case tok::kw_long: 125 case tok::kw___int64: 126 case tok::kw___int128: 127 case tok::kw_signed: 128 case tok::kw_unsigned: 129 case tok::kw_void: 130 case tok::kw_char: 131 case tok::kw_int: 132 case tok::kw_half: 133 case tok::kw_float: 134 case tok::kw_double: 135 case tok::kw___float128: 136 case tok::kw_wchar_t: 137 case tok::kw_bool: 138 case tok::kw___underlying_type: 139 case tok::kw___auto_type: 140 return true; 141 142 case tok::annot_typename: 143 case tok::kw_char16_t: 144 case tok::kw_char32_t: 145 case tok::kw_typeof: 146 case tok::annot_decltype: 147 case tok::kw_decltype: 148 return getLangOpts().CPlusPlus; 149 150 default: 151 break; 152 } 153 154 return false; 155 } 156 157 namespace { 158 enum class UnqualifiedTypeNameLookupResult { 159 NotFound, 160 FoundNonType, 161 FoundType 162 }; 163 } // end anonymous namespace 164 165 /// \brief Tries to perform unqualified lookup of the type decls in bases for 166 /// dependent class. 167 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 168 /// type decl, \a FoundType if only type decls are found. 169 static UnqualifiedTypeNameLookupResult 170 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 171 SourceLocation NameLoc, 172 const CXXRecordDecl *RD) { 173 if (!RD->hasDefinition()) 174 return UnqualifiedTypeNameLookupResult::NotFound; 175 // Look for type decls in base classes. 176 UnqualifiedTypeNameLookupResult FoundTypeDecl = 177 UnqualifiedTypeNameLookupResult::NotFound; 178 for (const auto &Base : RD->bases()) { 179 const CXXRecordDecl *BaseRD = nullptr; 180 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 181 BaseRD = BaseTT->getAsCXXRecordDecl(); 182 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 183 // Look for type decls in dependent base classes that have known primary 184 // templates. 185 if (!TST || !TST->isDependentType()) 186 continue; 187 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 188 if (!TD) 189 continue; 190 if (auto *BasePrimaryTemplate = 191 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 192 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 193 BaseRD = BasePrimaryTemplate; 194 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 195 if (const ClassTemplatePartialSpecializationDecl *PS = 196 CTD->findPartialSpecialization(Base.getType())) 197 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 198 BaseRD = PS; 199 } 200 } 201 } 202 if (BaseRD) { 203 for (NamedDecl *ND : BaseRD->lookup(&II)) { 204 if (!isa<TypeDecl>(ND)) 205 return UnqualifiedTypeNameLookupResult::FoundNonType; 206 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 207 } 208 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 209 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 210 case UnqualifiedTypeNameLookupResult::FoundNonType: 211 return UnqualifiedTypeNameLookupResult::FoundNonType; 212 case UnqualifiedTypeNameLookupResult::FoundType: 213 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 214 break; 215 case UnqualifiedTypeNameLookupResult::NotFound: 216 break; 217 } 218 } 219 } 220 } 221 222 return FoundTypeDecl; 223 } 224 225 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 226 const IdentifierInfo &II, 227 SourceLocation NameLoc) { 228 // Lookup in the parent class template context, if any. 229 const CXXRecordDecl *RD = nullptr; 230 UnqualifiedTypeNameLookupResult FoundTypeDecl = 231 UnqualifiedTypeNameLookupResult::NotFound; 232 for (DeclContext *DC = S.CurContext; 233 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 234 DC = DC->getParent()) { 235 // Look for type decls in dependent base classes that have known primary 236 // templates. 237 RD = dyn_cast<CXXRecordDecl>(DC); 238 if (RD && RD->getDescribedClassTemplate()) 239 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 240 } 241 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 242 return nullptr; 243 244 // We found some types in dependent base classes. Recover as if the user 245 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 246 // lookup during template instantiation. 247 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 248 249 ASTContext &Context = S.Context; 250 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 251 cast<Type>(Context.getRecordType(RD))); 252 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 253 254 CXXScopeSpec SS; 255 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 256 257 TypeLocBuilder Builder; 258 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 259 DepTL.setNameLoc(NameLoc); 260 DepTL.setElaboratedKeywordLoc(SourceLocation()); 261 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 262 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 263 } 264 265 /// \brief If the identifier refers to a type name within this scope, 266 /// return the declaration of that type. 267 /// 268 /// This routine performs ordinary name lookup of the identifier II 269 /// within the given scope, with optional C++ scope specifier SS, to 270 /// determine whether the name refers to a type. If so, returns an 271 /// opaque pointer (actually a QualType) corresponding to that 272 /// type. Otherwise, returns NULL. 273 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 274 Scope *S, CXXScopeSpec *SS, 275 bool isClassName, bool HasTrailingDot, 276 ParsedType ObjectTypePtr, 277 bool IsCtorOrDtorName, 278 bool WantNontrivialTypeSourceInfo, 279 bool IsClassTemplateDeductionContext, 280 IdentifierInfo **CorrectedII) { 281 // FIXME: Consider allowing this outside C++1z mode as an extension. 282 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 283 getLangOpts().CPlusPlus1z && !IsCtorOrDtorName && 284 !isClassName && !HasTrailingDot; 285 286 // Determine where we will perform name lookup. 287 DeclContext *LookupCtx = nullptr; 288 if (ObjectTypePtr) { 289 QualType ObjectType = ObjectTypePtr.get(); 290 if (ObjectType->isRecordType()) 291 LookupCtx = computeDeclContext(ObjectType); 292 } else if (SS && SS->isNotEmpty()) { 293 LookupCtx = computeDeclContext(*SS, false); 294 295 if (!LookupCtx) { 296 if (isDependentScopeSpecifier(*SS)) { 297 // C++ [temp.res]p3: 298 // A qualified-id that refers to a type and in which the 299 // nested-name-specifier depends on a template-parameter (14.6.2) 300 // shall be prefixed by the keyword typename to indicate that the 301 // qualified-id denotes a type, forming an 302 // elaborated-type-specifier (7.1.5.3). 303 // 304 // We therefore do not perform any name lookup if the result would 305 // refer to a member of an unknown specialization. 306 if (!isClassName && !IsCtorOrDtorName) 307 return nullptr; 308 309 // We know from the grammar that this name refers to a type, 310 // so build a dependent node to describe the type. 311 if (WantNontrivialTypeSourceInfo) 312 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 313 314 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 315 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 316 II, NameLoc); 317 return ParsedType::make(T); 318 } 319 320 return nullptr; 321 } 322 323 if (!LookupCtx->isDependentContext() && 324 RequireCompleteDeclContext(*SS, LookupCtx)) 325 return nullptr; 326 } 327 328 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 329 // lookup for class-names. 330 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 331 LookupOrdinaryName; 332 LookupResult Result(*this, &II, NameLoc, Kind); 333 if (LookupCtx) { 334 // Perform "qualified" name lookup into the declaration context we 335 // computed, which is either the type of the base of a member access 336 // expression or the declaration context associated with a prior 337 // nested-name-specifier. 338 LookupQualifiedName(Result, LookupCtx); 339 340 if (ObjectTypePtr && Result.empty()) { 341 // C++ [basic.lookup.classref]p3: 342 // If the unqualified-id is ~type-name, the type-name is looked up 343 // in the context of the entire postfix-expression. If the type T of 344 // the object expression is of a class type C, the type-name is also 345 // looked up in the scope of class C. At least one of the lookups shall 346 // find a name that refers to (possibly cv-qualified) T. 347 LookupName(Result, S); 348 } 349 } else { 350 // Perform unqualified name lookup. 351 LookupName(Result, S); 352 353 // For unqualified lookup in a class template in MSVC mode, look into 354 // dependent base classes where the primary class template is known. 355 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 356 if (ParsedType TypeInBase = 357 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 358 return TypeInBase; 359 } 360 } 361 362 NamedDecl *IIDecl = nullptr; 363 switch (Result.getResultKind()) { 364 case LookupResult::NotFound: 365 case LookupResult::NotFoundInCurrentInstantiation: 366 if (CorrectedII) { 367 TypoCorrection Correction = 368 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, 369 llvm::make_unique<TypeNameValidatorCCC>( 370 true, isClassName, AllowDeducedTemplate), 371 CTK_ErrorRecovery); 372 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 373 TemplateTy Template; 374 bool MemberOfUnknownSpecialization; 375 UnqualifiedId TemplateName; 376 TemplateName.setIdentifier(NewII, NameLoc); 377 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 378 CXXScopeSpec NewSS, *NewSSPtr = SS; 379 if (SS && NNS) { 380 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 381 NewSSPtr = &NewSS; 382 } 383 if (Correction && (NNS || NewII != &II) && 384 // Ignore a correction to a template type as the to-be-corrected 385 // identifier is not a template (typo correction for template names 386 // is handled elsewhere). 387 !(getLangOpts().CPlusPlus && NewSSPtr && 388 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 389 Template, MemberOfUnknownSpecialization))) { 390 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 391 isClassName, HasTrailingDot, ObjectTypePtr, 392 IsCtorOrDtorName, 393 WantNontrivialTypeSourceInfo, 394 IsClassTemplateDeductionContext); 395 if (Ty) { 396 diagnoseTypo(Correction, 397 PDiag(diag::err_unknown_type_or_class_name_suggest) 398 << Result.getLookupName() << isClassName); 399 if (SS && NNS) 400 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 401 *CorrectedII = NewII; 402 return Ty; 403 } 404 } 405 } 406 // If typo correction failed or was not performed, fall through 407 case LookupResult::FoundOverloaded: 408 case LookupResult::FoundUnresolvedValue: 409 Result.suppressDiagnostics(); 410 return nullptr; 411 412 case LookupResult::Ambiguous: 413 // Recover from type-hiding ambiguities by hiding the type. We'll 414 // do the lookup again when looking for an object, and we can 415 // diagnose the error then. If we don't do this, then the error 416 // about hiding the type will be immediately followed by an error 417 // that only makes sense if the identifier was treated like a type. 418 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 419 Result.suppressDiagnostics(); 420 return nullptr; 421 } 422 423 // Look to see if we have a type anywhere in the list of results. 424 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 425 Res != ResEnd; ++Res) { 426 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 427 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 428 if (!IIDecl || 429 (*Res)->getLocation().getRawEncoding() < 430 IIDecl->getLocation().getRawEncoding()) 431 IIDecl = *Res; 432 } 433 } 434 435 if (!IIDecl) { 436 // None of the entities we found is a type, so there is no way 437 // to even assume that the result is a type. In this case, don't 438 // complain about the ambiguity. The parser will either try to 439 // perform this lookup again (e.g., as an object name), which 440 // will produce the ambiguity, or will complain that it expected 441 // a type name. 442 Result.suppressDiagnostics(); 443 return nullptr; 444 } 445 446 // We found a type within the ambiguous lookup; diagnose the 447 // ambiguity and then return that type. This might be the right 448 // answer, or it might not be, but it suppresses any attempt to 449 // perform the name lookup again. 450 break; 451 452 case LookupResult::Found: 453 IIDecl = Result.getFoundDecl(); 454 break; 455 } 456 457 assert(IIDecl && "Didn't find decl"); 458 459 QualType T; 460 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 461 // C++ [class.qual]p2: A lookup that would find the injected-class-name 462 // instead names the constructors of the class, except when naming a class. 463 // This is ill-formed when we're not actually forming a ctor or dtor name. 464 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 465 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 466 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 467 FoundRD->isInjectedClassName() && 468 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 469 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 470 << &II << /*Type*/1; 471 472 DiagnoseUseOfDecl(IIDecl, NameLoc); 473 474 T = Context.getTypeDeclType(TD); 475 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 476 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 477 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 478 if (!HasTrailingDot) 479 T = Context.getObjCInterfaceType(IDecl); 480 } else if (AllowDeducedTemplate) { 481 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 482 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 483 QualType(), false); 484 } 485 486 if (T.isNull()) { 487 // If it's not plausibly a type, suppress diagnostics. 488 Result.suppressDiagnostics(); 489 return nullptr; 490 } 491 492 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 493 // constructor or destructor name (in such a case, the scope specifier 494 // will be attached to the enclosing Expr or Decl node). 495 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 496 !isa<ObjCInterfaceDecl>(IIDecl)) { 497 if (WantNontrivialTypeSourceInfo) { 498 // Construct a type with type-source information. 499 TypeLocBuilder Builder; 500 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 501 502 T = getElaboratedType(ETK_None, *SS, T); 503 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 504 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 505 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 506 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 507 } else { 508 T = getElaboratedType(ETK_None, *SS, T); 509 } 510 } 511 512 return ParsedType::make(T); 513 } 514 515 // Builds a fake NNS for the given decl context. 516 static NestedNameSpecifier * 517 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 518 for (;; DC = DC->getLookupParent()) { 519 DC = DC->getPrimaryContext(); 520 auto *ND = dyn_cast<NamespaceDecl>(DC); 521 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 522 return NestedNameSpecifier::Create(Context, nullptr, ND); 523 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 524 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 525 RD->getTypeForDecl()); 526 else if (isa<TranslationUnitDecl>(DC)) 527 return NestedNameSpecifier::GlobalSpecifier(Context); 528 } 529 llvm_unreachable("something isn't in TU scope?"); 530 } 531 532 /// Find the parent class with dependent bases of the innermost enclosing method 533 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 534 /// up allowing unqualified dependent type names at class-level, which MSVC 535 /// correctly rejects. 536 static const CXXRecordDecl * 537 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 538 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 539 DC = DC->getPrimaryContext(); 540 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 541 if (MD->getParent()->hasAnyDependentBases()) 542 return MD->getParent(); 543 } 544 return nullptr; 545 } 546 547 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 548 SourceLocation NameLoc, 549 bool IsTemplateTypeArg) { 550 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 551 552 NestedNameSpecifier *NNS = nullptr; 553 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 554 // If we weren't able to parse a default template argument, delay lookup 555 // until instantiation time by making a non-dependent DependentTypeName. We 556 // pretend we saw a NestedNameSpecifier referring to the current scope, and 557 // lookup is retried. 558 // FIXME: This hurts our diagnostic quality, since we get errors like "no 559 // type named 'Foo' in 'current_namespace'" when the user didn't write any 560 // name specifiers. 561 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 562 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 563 } else if (const CXXRecordDecl *RD = 564 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 565 // Build a DependentNameType that will perform lookup into RD at 566 // instantiation time. 567 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 568 RD->getTypeForDecl()); 569 570 // Diagnose that this identifier was undeclared, and retry the lookup during 571 // template instantiation. 572 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 573 << RD; 574 } else { 575 // This is not a situation that we should recover from. 576 return ParsedType(); 577 } 578 579 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 580 581 // Build type location information. We synthesized the qualifier, so we have 582 // to build a fake NestedNameSpecifierLoc. 583 NestedNameSpecifierLocBuilder NNSLocBuilder; 584 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 585 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 586 587 TypeLocBuilder Builder; 588 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 589 DepTL.setNameLoc(NameLoc); 590 DepTL.setElaboratedKeywordLoc(SourceLocation()); 591 DepTL.setQualifierLoc(QualifierLoc); 592 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 593 } 594 595 /// isTagName() - This method is called *for error recovery purposes only* 596 /// to determine if the specified name is a valid tag name ("struct foo"). If 597 /// so, this returns the TST for the tag corresponding to it (TST_enum, 598 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 599 /// cases in C where the user forgot to specify the tag. 600 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 601 // Do a tag name lookup in this scope. 602 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 603 LookupName(R, S, false); 604 R.suppressDiagnostics(); 605 if (R.getResultKind() == LookupResult::Found) 606 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 607 switch (TD->getTagKind()) { 608 case TTK_Struct: return DeclSpec::TST_struct; 609 case TTK_Interface: return DeclSpec::TST_interface; 610 case TTK_Union: return DeclSpec::TST_union; 611 case TTK_Class: return DeclSpec::TST_class; 612 case TTK_Enum: return DeclSpec::TST_enum; 613 } 614 } 615 616 return DeclSpec::TST_unspecified; 617 } 618 619 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 620 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 621 /// then downgrade the missing typename error to a warning. 622 /// This is needed for MSVC compatibility; Example: 623 /// @code 624 /// template<class T> class A { 625 /// public: 626 /// typedef int TYPE; 627 /// }; 628 /// template<class T> class B : public A<T> { 629 /// public: 630 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 631 /// }; 632 /// @endcode 633 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 634 if (CurContext->isRecord()) { 635 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 636 return true; 637 638 const Type *Ty = SS->getScopeRep()->getAsType(); 639 640 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 641 for (const auto &Base : RD->bases()) 642 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 643 return true; 644 return S->isFunctionPrototypeScope(); 645 } 646 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 647 } 648 649 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 650 SourceLocation IILoc, 651 Scope *S, 652 CXXScopeSpec *SS, 653 ParsedType &SuggestedType, 654 bool IsTemplateName) { 655 // Don't report typename errors for editor placeholders. 656 if (II->isEditorPlaceholder()) 657 return; 658 // We don't have anything to suggest (yet). 659 SuggestedType = nullptr; 660 661 // There may have been a typo in the name of the type. Look up typo 662 // results, in case we have something that we can suggest. 663 if (TypoCorrection Corrected = 664 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 665 llvm::make_unique<TypeNameValidatorCCC>( 666 false, false, IsTemplateName, !IsTemplateName), 667 CTK_ErrorRecovery)) { 668 // FIXME: Support error recovery for the template-name case. 669 bool CanRecover = !IsTemplateName; 670 if (Corrected.isKeyword()) { 671 // We corrected to a keyword. 672 diagnoseTypo(Corrected, 673 PDiag(IsTemplateName ? diag::err_no_template_suggest 674 : diag::err_unknown_typename_suggest) 675 << II); 676 II = Corrected.getCorrectionAsIdentifierInfo(); 677 } else { 678 // We found a similarly-named type or interface; suggest that. 679 if (!SS || !SS->isSet()) { 680 diagnoseTypo(Corrected, 681 PDiag(IsTemplateName ? diag::err_no_template_suggest 682 : diag::err_unknown_typename_suggest) 683 << II, CanRecover); 684 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 685 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 686 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 687 II->getName().equals(CorrectedStr); 688 diagnoseTypo(Corrected, 689 PDiag(IsTemplateName 690 ? diag::err_no_member_template_suggest 691 : diag::err_unknown_nested_typename_suggest) 692 << II << DC << DroppedSpecifier << SS->getRange(), 693 CanRecover); 694 } else { 695 llvm_unreachable("could not have corrected a typo here"); 696 } 697 698 if (!CanRecover) 699 return; 700 701 CXXScopeSpec tmpSS; 702 if (Corrected.getCorrectionSpecifier()) 703 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 704 SourceRange(IILoc)); 705 // FIXME: Support class template argument deduction here. 706 SuggestedType = 707 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 708 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 709 /*IsCtorOrDtorName=*/false, 710 /*NonTrivialTypeSourceInfo=*/true); 711 } 712 return; 713 } 714 715 if (getLangOpts().CPlusPlus && !IsTemplateName) { 716 // See if II is a class template that the user forgot to pass arguments to. 717 UnqualifiedId Name; 718 Name.setIdentifier(II, IILoc); 719 CXXScopeSpec EmptySS; 720 TemplateTy TemplateResult; 721 bool MemberOfUnknownSpecialization; 722 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 723 Name, nullptr, true, TemplateResult, 724 MemberOfUnknownSpecialization) == TNK_Type_template) { 725 TemplateName TplName = TemplateResult.get(); 726 Diag(IILoc, diag::err_template_missing_args) 727 << (int)getTemplateNameKindForDiagnostics(TplName) << TplName; 728 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 729 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 730 << TplDecl->getTemplateParameters()->getSourceRange(); 731 } 732 return; 733 } 734 } 735 736 // FIXME: Should we move the logic that tries to recover from a missing tag 737 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 738 739 if (!SS || (!SS->isSet() && !SS->isInvalid())) 740 Diag(IILoc, IsTemplateName ? diag::err_no_template 741 : diag::err_unknown_typename) 742 << II; 743 else if (DeclContext *DC = computeDeclContext(*SS, false)) 744 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 745 : diag::err_typename_nested_not_found) 746 << II << DC << SS->getRange(); 747 else if (isDependentScopeSpecifier(*SS)) { 748 unsigned DiagID = diag::err_typename_missing; 749 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 750 DiagID = diag::ext_typename_missing; 751 752 Diag(SS->getRange().getBegin(), DiagID) 753 << SS->getScopeRep() << II->getName() 754 << SourceRange(SS->getRange().getBegin(), IILoc) 755 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 756 SuggestedType = ActOnTypenameType(S, SourceLocation(), 757 *SS, *II, IILoc).get(); 758 } else { 759 assert(SS && SS->isInvalid() && 760 "Invalid scope specifier has already been diagnosed"); 761 } 762 } 763 764 /// \brief Determine whether the given result set contains either a type name 765 /// or 766 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 767 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 768 NextToken.is(tok::less); 769 770 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 771 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 772 return true; 773 774 if (CheckTemplate && isa<TemplateDecl>(*I)) 775 return true; 776 } 777 778 return false; 779 } 780 781 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 782 Scope *S, CXXScopeSpec &SS, 783 IdentifierInfo *&Name, 784 SourceLocation NameLoc) { 785 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 786 SemaRef.LookupParsedName(R, S, &SS); 787 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 788 StringRef FixItTagName; 789 switch (Tag->getTagKind()) { 790 case TTK_Class: 791 FixItTagName = "class "; 792 break; 793 794 case TTK_Enum: 795 FixItTagName = "enum "; 796 break; 797 798 case TTK_Struct: 799 FixItTagName = "struct "; 800 break; 801 802 case TTK_Interface: 803 FixItTagName = "__interface "; 804 break; 805 806 case TTK_Union: 807 FixItTagName = "union "; 808 break; 809 } 810 811 StringRef TagName = FixItTagName.drop_back(); 812 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 813 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 814 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 815 816 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 817 I != IEnd; ++I) 818 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 819 << Name << TagName; 820 821 // Replace lookup results with just the tag decl. 822 Result.clear(Sema::LookupTagName); 823 SemaRef.LookupParsedName(Result, S, &SS); 824 return true; 825 } 826 827 return false; 828 } 829 830 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 831 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 832 QualType T, SourceLocation NameLoc) { 833 ASTContext &Context = S.Context; 834 835 TypeLocBuilder Builder; 836 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 837 838 T = S.getElaboratedType(ETK_None, SS, T); 839 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 840 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 841 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 842 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 843 } 844 845 Sema::NameClassification 846 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 847 SourceLocation NameLoc, const Token &NextToken, 848 bool IsAddressOfOperand, 849 std::unique_ptr<CorrectionCandidateCallback> CCC) { 850 DeclarationNameInfo NameInfo(Name, NameLoc); 851 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 852 853 if (NextToken.is(tok::coloncolon)) { 854 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 855 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); 856 } else if (getLangOpts().CPlusPlus && SS.isSet() && 857 isCurrentClassName(*Name, S, &SS)) { 858 // Per [class.qual]p2, this names the constructors of SS, not the 859 // injected-class-name. We don't have a classification for that. 860 // There's not much point caching this result, since the parser 861 // will reject it later. 862 return NameClassification::Unknown(); 863 } 864 865 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 866 LookupParsedName(Result, S, &SS, !CurMethod); 867 868 // For unqualified lookup in a class template in MSVC mode, look into 869 // dependent base classes where the primary class template is known. 870 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 871 if (ParsedType TypeInBase = 872 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 873 return TypeInBase; 874 } 875 876 // Perform lookup for Objective-C instance variables (including automatically 877 // synthesized instance variables), if we're in an Objective-C method. 878 // FIXME: This lookup really, really needs to be folded in to the normal 879 // unqualified lookup mechanism. 880 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 881 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 882 if (E.get() || E.isInvalid()) 883 return E; 884 } 885 886 bool SecondTry = false; 887 bool IsFilteredTemplateName = false; 888 889 Corrected: 890 switch (Result.getResultKind()) { 891 case LookupResult::NotFound: 892 // If an unqualified-id is followed by a '(', then we have a function 893 // call. 894 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 895 // In C++, this is an ADL-only call. 896 // FIXME: Reference? 897 if (getLangOpts().CPlusPlus) 898 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 899 900 // C90 6.3.2.2: 901 // If the expression that precedes the parenthesized argument list in a 902 // function call consists solely of an identifier, and if no 903 // declaration is visible for this identifier, the identifier is 904 // implicitly declared exactly as if, in the innermost block containing 905 // the function call, the declaration 906 // 907 // extern int identifier (); 908 // 909 // appeared. 910 // 911 // We also allow this in C99 as an extension. 912 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 913 Result.addDecl(D); 914 Result.resolveKind(); 915 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 916 } 917 } 918 919 // In C, we first see whether there is a tag type by the same name, in 920 // which case it's likely that the user just forgot to write "enum", 921 // "struct", or "union". 922 if (!getLangOpts().CPlusPlus && !SecondTry && 923 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 924 break; 925 } 926 927 // Perform typo correction to determine if there is another name that is 928 // close to this name. 929 if (!SecondTry && CCC) { 930 SecondTry = true; 931 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 932 Result.getLookupKind(), S, 933 &SS, std::move(CCC), 934 CTK_ErrorRecovery)) { 935 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 936 unsigned QualifiedDiag = diag::err_no_member_suggest; 937 938 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 939 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 940 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 941 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 942 UnqualifiedDiag = diag::err_no_template_suggest; 943 QualifiedDiag = diag::err_no_member_template_suggest; 944 } else if (UnderlyingFirstDecl && 945 (isa<TypeDecl>(UnderlyingFirstDecl) || 946 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 947 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 948 UnqualifiedDiag = diag::err_unknown_typename_suggest; 949 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 950 } 951 952 if (SS.isEmpty()) { 953 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 954 } else {// FIXME: is this even reachable? Test it. 955 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 956 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 957 Name->getName().equals(CorrectedStr); 958 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 959 << Name << computeDeclContext(SS, false) 960 << DroppedSpecifier << SS.getRange()); 961 } 962 963 // Update the name, so that the caller has the new name. 964 Name = Corrected.getCorrectionAsIdentifierInfo(); 965 966 // Typo correction corrected to a keyword. 967 if (Corrected.isKeyword()) 968 return Name; 969 970 // Also update the LookupResult... 971 // FIXME: This should probably go away at some point 972 Result.clear(); 973 Result.setLookupName(Corrected.getCorrection()); 974 if (FirstDecl) 975 Result.addDecl(FirstDecl); 976 977 // If we found an Objective-C instance variable, let 978 // LookupInObjCMethod build the appropriate expression to 979 // reference the ivar. 980 // FIXME: This is a gross hack. 981 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 982 Result.clear(); 983 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 984 return E; 985 } 986 987 goto Corrected; 988 } 989 } 990 991 // We failed to correct; just fall through and let the parser deal with it. 992 Result.suppressDiagnostics(); 993 return NameClassification::Unknown(); 994 995 case LookupResult::NotFoundInCurrentInstantiation: { 996 // We performed name lookup into the current instantiation, and there were 997 // dependent bases, so we treat this result the same way as any other 998 // dependent nested-name-specifier. 999 1000 // C++ [temp.res]p2: 1001 // A name used in a template declaration or definition and that is 1002 // dependent on a template-parameter is assumed not to name a type 1003 // unless the applicable name lookup finds a type name or the name is 1004 // qualified by the keyword typename. 1005 // 1006 // FIXME: If the next token is '<', we might want to ask the parser to 1007 // perform some heroics to see if we actually have a 1008 // template-argument-list, which would indicate a missing 'template' 1009 // keyword here. 1010 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1011 NameInfo, IsAddressOfOperand, 1012 /*TemplateArgs=*/nullptr); 1013 } 1014 1015 case LookupResult::Found: 1016 case LookupResult::FoundOverloaded: 1017 case LookupResult::FoundUnresolvedValue: 1018 break; 1019 1020 case LookupResult::Ambiguous: 1021 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1022 hasAnyAcceptableTemplateNames(Result)) { 1023 // C++ [temp.local]p3: 1024 // A lookup that finds an injected-class-name (10.2) can result in an 1025 // ambiguity in certain cases (for example, if it is found in more than 1026 // one base class). If all of the injected-class-names that are found 1027 // refer to specializations of the same class template, and if the name 1028 // is followed by a template-argument-list, the reference refers to the 1029 // class template itself and not a specialization thereof, and is not 1030 // ambiguous. 1031 // 1032 // This filtering can make an ambiguous result into an unambiguous one, 1033 // so try again after filtering out template names. 1034 FilterAcceptableTemplateNames(Result); 1035 if (!Result.isAmbiguous()) { 1036 IsFilteredTemplateName = true; 1037 break; 1038 } 1039 } 1040 1041 // Diagnose the ambiguity and return an error. 1042 return NameClassification::Error(); 1043 } 1044 1045 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1046 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 1047 // C++ [temp.names]p3: 1048 // After name lookup (3.4) finds that a name is a template-name or that 1049 // an operator-function-id or a literal- operator-id refers to a set of 1050 // overloaded functions any member of which is a function template if 1051 // this is followed by a <, the < is always taken as the delimiter of a 1052 // template-argument-list and never as the less-than operator. 1053 if (!IsFilteredTemplateName) 1054 FilterAcceptableTemplateNames(Result); 1055 1056 if (!Result.empty()) { 1057 bool IsFunctionTemplate; 1058 bool IsVarTemplate; 1059 TemplateName Template; 1060 if (Result.end() - Result.begin() > 1) { 1061 IsFunctionTemplate = true; 1062 Template = Context.getOverloadedTemplateName(Result.begin(), 1063 Result.end()); 1064 } else { 1065 TemplateDecl *TD 1066 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 1067 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1068 IsVarTemplate = isa<VarTemplateDecl>(TD); 1069 1070 if (SS.isSet() && !SS.isInvalid()) 1071 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 1072 /*TemplateKeyword=*/false, 1073 TD); 1074 else 1075 Template = TemplateName(TD); 1076 } 1077 1078 if (IsFunctionTemplate) { 1079 // Function templates always go through overload resolution, at which 1080 // point we'll perform the various checks (e.g., accessibility) we need 1081 // to based on which function we selected. 1082 Result.suppressDiagnostics(); 1083 1084 return NameClassification::FunctionTemplate(Template); 1085 } 1086 1087 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1088 : NameClassification::TypeTemplate(Template); 1089 } 1090 } 1091 1092 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1093 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1094 DiagnoseUseOfDecl(Type, NameLoc); 1095 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1096 QualType T = Context.getTypeDeclType(Type); 1097 if (SS.isNotEmpty()) 1098 return buildNestedType(*this, SS, T, NameLoc); 1099 return ParsedType::make(T); 1100 } 1101 1102 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1103 if (!Class) { 1104 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1105 if (ObjCCompatibleAliasDecl *Alias = 1106 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1107 Class = Alias->getClassInterface(); 1108 } 1109 1110 if (Class) { 1111 DiagnoseUseOfDecl(Class, NameLoc); 1112 1113 if (NextToken.is(tok::period)) { 1114 // Interface. <something> is parsed as a property reference expression. 1115 // Just return "unknown" as a fall-through for now. 1116 Result.suppressDiagnostics(); 1117 return NameClassification::Unknown(); 1118 } 1119 1120 QualType T = Context.getObjCInterfaceType(Class); 1121 return ParsedType::make(T); 1122 } 1123 1124 // We can have a type template here if we're classifying a template argument. 1125 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1126 !isa<VarTemplateDecl>(FirstDecl)) 1127 return NameClassification::TypeTemplate( 1128 TemplateName(cast<TemplateDecl>(FirstDecl))); 1129 1130 // Check for a tag type hidden by a non-type decl in a few cases where it 1131 // seems likely a type is wanted instead of the non-type that was found. 1132 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1133 if ((NextToken.is(tok::identifier) || 1134 (NextIsOp && 1135 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1136 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1137 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1138 DiagnoseUseOfDecl(Type, NameLoc); 1139 QualType T = Context.getTypeDeclType(Type); 1140 if (SS.isNotEmpty()) 1141 return buildNestedType(*this, SS, T, NameLoc); 1142 return ParsedType::make(T); 1143 } 1144 1145 if (FirstDecl->isCXXClassMember()) 1146 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1147 nullptr, S); 1148 1149 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1150 return BuildDeclarationNameExpr(SS, Result, ADL); 1151 } 1152 1153 Sema::TemplateNameKindForDiagnostics 1154 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1155 auto *TD = Name.getAsTemplateDecl(); 1156 if (!TD) 1157 return TemplateNameKindForDiagnostics::DependentTemplate; 1158 if (isa<ClassTemplateDecl>(TD)) 1159 return TemplateNameKindForDiagnostics::ClassTemplate; 1160 if (isa<FunctionTemplateDecl>(TD)) 1161 return TemplateNameKindForDiagnostics::FunctionTemplate; 1162 if (isa<VarTemplateDecl>(TD)) 1163 return TemplateNameKindForDiagnostics::VarTemplate; 1164 if (isa<TypeAliasTemplateDecl>(TD)) 1165 return TemplateNameKindForDiagnostics::AliasTemplate; 1166 if (isa<TemplateTemplateParmDecl>(TD)) 1167 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1168 return TemplateNameKindForDiagnostics::DependentTemplate; 1169 } 1170 1171 // Determines the context to return to after temporarily entering a 1172 // context. This depends in an unnecessarily complicated way on the 1173 // exact ordering of callbacks from the parser. 1174 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1175 1176 // Functions defined inline within classes aren't parsed until we've 1177 // finished parsing the top-level class, so the top-level class is 1178 // the context we'll need to return to. 1179 // A Lambda call operator whose parent is a class must not be treated 1180 // as an inline member function. A Lambda can be used legally 1181 // either as an in-class member initializer or a default argument. These 1182 // are parsed once the class has been marked complete and so the containing 1183 // context would be the nested class (when the lambda is defined in one); 1184 // If the class is not complete, then the lambda is being used in an 1185 // ill-formed fashion (such as to specify the width of a bit-field, or 1186 // in an array-bound) - in which case we still want to return the 1187 // lexically containing DC (which could be a nested class). 1188 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1189 DC = DC->getLexicalParent(); 1190 1191 // A function not defined within a class will always return to its 1192 // lexical context. 1193 if (!isa<CXXRecordDecl>(DC)) 1194 return DC; 1195 1196 // A C++ inline method/friend is parsed *after* the topmost class 1197 // it was declared in is fully parsed ("complete"); the topmost 1198 // class is the context we need to return to. 1199 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1200 DC = RD; 1201 1202 // Return the declaration context of the topmost class the inline method is 1203 // declared in. 1204 return DC; 1205 } 1206 1207 return DC->getLexicalParent(); 1208 } 1209 1210 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1211 assert(getContainingDC(DC) == CurContext && 1212 "The next DeclContext should be lexically contained in the current one."); 1213 CurContext = DC; 1214 S->setEntity(DC); 1215 } 1216 1217 void Sema::PopDeclContext() { 1218 assert(CurContext && "DeclContext imbalance!"); 1219 1220 CurContext = getContainingDC(CurContext); 1221 assert(CurContext && "Popped translation unit!"); 1222 } 1223 1224 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1225 Decl *D) { 1226 // Unlike PushDeclContext, the context to which we return is not necessarily 1227 // the containing DC of TD, because the new context will be some pre-existing 1228 // TagDecl definition instead of a fresh one. 1229 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1230 CurContext = cast<TagDecl>(D)->getDefinition(); 1231 assert(CurContext && "skipping definition of undefined tag"); 1232 // Start lookups from the parent of the current context; we don't want to look 1233 // into the pre-existing complete definition. 1234 S->setEntity(CurContext->getLookupParent()); 1235 return Result; 1236 } 1237 1238 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1239 CurContext = static_cast<decltype(CurContext)>(Context); 1240 } 1241 1242 /// EnterDeclaratorContext - Used when we must lookup names in the context 1243 /// of a declarator's nested name specifier. 1244 /// 1245 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1246 // C++0x [basic.lookup.unqual]p13: 1247 // A name used in the definition of a static data member of class 1248 // X (after the qualified-id of the static member) is looked up as 1249 // if the name was used in a member function of X. 1250 // C++0x [basic.lookup.unqual]p14: 1251 // If a variable member of a namespace is defined outside of the 1252 // scope of its namespace then any name used in the definition of 1253 // the variable member (after the declarator-id) is looked up as 1254 // if the definition of the variable member occurred in its 1255 // namespace. 1256 // Both of these imply that we should push a scope whose context 1257 // is the semantic context of the declaration. We can't use 1258 // PushDeclContext here because that context is not necessarily 1259 // lexically contained in the current context. Fortunately, 1260 // the containing scope should have the appropriate information. 1261 1262 assert(!S->getEntity() && "scope already has entity"); 1263 1264 #ifndef NDEBUG 1265 Scope *Ancestor = S->getParent(); 1266 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1267 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1268 #endif 1269 1270 CurContext = DC; 1271 S->setEntity(DC); 1272 } 1273 1274 void Sema::ExitDeclaratorContext(Scope *S) { 1275 assert(S->getEntity() == CurContext && "Context imbalance!"); 1276 1277 // Switch back to the lexical context. The safety of this is 1278 // enforced by an assert in EnterDeclaratorContext. 1279 Scope *Ancestor = S->getParent(); 1280 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1281 CurContext = Ancestor->getEntity(); 1282 1283 // We don't need to do anything with the scope, which is going to 1284 // disappear. 1285 } 1286 1287 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1288 // We assume that the caller has already called 1289 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1290 FunctionDecl *FD = D->getAsFunction(); 1291 if (!FD) 1292 return; 1293 1294 // Same implementation as PushDeclContext, but enters the context 1295 // from the lexical parent, rather than the top-level class. 1296 assert(CurContext == FD->getLexicalParent() && 1297 "The next DeclContext should be lexically contained in the current one."); 1298 CurContext = FD; 1299 S->setEntity(CurContext); 1300 1301 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1302 ParmVarDecl *Param = FD->getParamDecl(P); 1303 // If the parameter has an identifier, then add it to the scope 1304 if (Param->getIdentifier()) { 1305 S->AddDecl(Param); 1306 IdResolver.AddDecl(Param); 1307 } 1308 } 1309 } 1310 1311 void Sema::ActOnExitFunctionContext() { 1312 // Same implementation as PopDeclContext, but returns to the lexical parent, 1313 // rather than the top-level class. 1314 assert(CurContext && "DeclContext imbalance!"); 1315 CurContext = CurContext->getLexicalParent(); 1316 assert(CurContext && "Popped translation unit!"); 1317 } 1318 1319 /// \brief Determine whether we allow overloading of the function 1320 /// PrevDecl with another declaration. 1321 /// 1322 /// This routine determines whether overloading is possible, not 1323 /// whether some new function is actually an overload. It will return 1324 /// true in C++ (where we can always provide overloads) or, as an 1325 /// extension, in C when the previous function is already an 1326 /// overloaded function declaration or has the "overloadable" 1327 /// attribute. 1328 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1329 ASTContext &Context) { 1330 if (Context.getLangOpts().CPlusPlus) 1331 return true; 1332 1333 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1334 return true; 1335 1336 return (Previous.getResultKind() == LookupResult::Found 1337 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1338 } 1339 1340 /// Add this decl to the scope shadowed decl chains. 1341 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1342 // Move up the scope chain until we find the nearest enclosing 1343 // non-transparent context. The declaration will be introduced into this 1344 // scope. 1345 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1346 S = S->getParent(); 1347 1348 // Add scoped declarations into their context, so that they can be 1349 // found later. Declarations without a context won't be inserted 1350 // into any context. 1351 if (AddToContext) 1352 CurContext->addDecl(D); 1353 1354 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1355 // are function-local declarations. 1356 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1357 !D->getDeclContext()->getRedeclContext()->Equals( 1358 D->getLexicalDeclContext()->getRedeclContext()) && 1359 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1360 return; 1361 1362 // Template instantiations should also not be pushed into scope. 1363 if (isa<FunctionDecl>(D) && 1364 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1365 return; 1366 1367 // If this replaces anything in the current scope, 1368 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1369 IEnd = IdResolver.end(); 1370 for (; I != IEnd; ++I) { 1371 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1372 S->RemoveDecl(*I); 1373 IdResolver.RemoveDecl(*I); 1374 1375 // Should only need to replace one decl. 1376 break; 1377 } 1378 } 1379 1380 S->AddDecl(D); 1381 1382 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1383 // Implicitly-generated labels may end up getting generated in an order that 1384 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1385 // the label at the appropriate place in the identifier chain. 1386 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1387 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1388 if (IDC == CurContext) { 1389 if (!S->isDeclScope(*I)) 1390 continue; 1391 } else if (IDC->Encloses(CurContext)) 1392 break; 1393 } 1394 1395 IdResolver.InsertDeclAfter(I, D); 1396 } else { 1397 IdResolver.AddDecl(D); 1398 } 1399 } 1400 1401 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1402 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1403 TUScope->AddDecl(D); 1404 } 1405 1406 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1407 bool AllowInlineNamespace) { 1408 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1409 } 1410 1411 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1412 DeclContext *TargetDC = DC->getPrimaryContext(); 1413 do { 1414 if (DeclContext *ScopeDC = S->getEntity()) 1415 if (ScopeDC->getPrimaryContext() == TargetDC) 1416 return S; 1417 } while ((S = S->getParent())); 1418 1419 return nullptr; 1420 } 1421 1422 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1423 DeclContext*, 1424 ASTContext&); 1425 1426 /// Filters out lookup results that don't fall within the given scope 1427 /// as determined by isDeclInScope. 1428 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1429 bool ConsiderLinkage, 1430 bool AllowInlineNamespace) { 1431 LookupResult::Filter F = R.makeFilter(); 1432 while (F.hasNext()) { 1433 NamedDecl *D = F.next(); 1434 1435 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1436 continue; 1437 1438 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1439 continue; 1440 1441 F.erase(); 1442 } 1443 1444 F.done(); 1445 } 1446 1447 static bool isUsingDecl(NamedDecl *D) { 1448 return isa<UsingShadowDecl>(D) || 1449 isa<UnresolvedUsingTypenameDecl>(D) || 1450 isa<UnresolvedUsingValueDecl>(D); 1451 } 1452 1453 /// Removes using shadow declarations from the lookup results. 1454 static void RemoveUsingDecls(LookupResult &R) { 1455 LookupResult::Filter F = R.makeFilter(); 1456 while (F.hasNext()) 1457 if (isUsingDecl(F.next())) 1458 F.erase(); 1459 1460 F.done(); 1461 } 1462 1463 /// \brief Check for this common pattern: 1464 /// @code 1465 /// class S { 1466 /// S(const S&); // DO NOT IMPLEMENT 1467 /// void operator=(const S&); // DO NOT IMPLEMENT 1468 /// }; 1469 /// @endcode 1470 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1471 // FIXME: Should check for private access too but access is set after we get 1472 // the decl here. 1473 if (D->doesThisDeclarationHaveABody()) 1474 return false; 1475 1476 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1477 return CD->isCopyConstructor(); 1478 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1479 return Method->isCopyAssignmentOperator(); 1480 return false; 1481 } 1482 1483 // We need this to handle 1484 // 1485 // typedef struct { 1486 // void *foo() { return 0; } 1487 // } A; 1488 // 1489 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1490 // for example. If 'A', foo will have external linkage. If we have '*A', 1491 // foo will have no linkage. Since we can't know until we get to the end 1492 // of the typedef, this function finds out if D might have non-external linkage. 1493 // Callers should verify at the end of the TU if it D has external linkage or 1494 // not. 1495 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1496 const DeclContext *DC = D->getDeclContext(); 1497 while (!DC->isTranslationUnit()) { 1498 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1499 if (!RD->hasNameForLinkage()) 1500 return true; 1501 } 1502 DC = DC->getParent(); 1503 } 1504 1505 return !D->isExternallyVisible(); 1506 } 1507 1508 // FIXME: This needs to be refactored; some other isInMainFile users want 1509 // these semantics. 1510 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1511 if (S.TUKind != TU_Complete) 1512 return false; 1513 return S.SourceMgr.isInMainFile(Loc); 1514 } 1515 1516 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1517 assert(D); 1518 1519 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1520 return false; 1521 1522 // Ignore all entities declared within templates, and out-of-line definitions 1523 // of members of class templates. 1524 if (D->getDeclContext()->isDependentContext() || 1525 D->getLexicalDeclContext()->isDependentContext()) 1526 return false; 1527 1528 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1529 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1530 return false; 1531 // A non-out-of-line declaration of a member specialization was implicitly 1532 // instantiated; it's the out-of-line declaration that we're interested in. 1533 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1534 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1535 return false; 1536 1537 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1538 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1539 return false; 1540 } else { 1541 // 'static inline' functions are defined in headers; don't warn. 1542 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1543 return false; 1544 } 1545 1546 if (FD->doesThisDeclarationHaveABody() && 1547 Context.DeclMustBeEmitted(FD)) 1548 return false; 1549 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1550 // Constants and utility variables are defined in headers with internal 1551 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1552 // like "inline".) 1553 if (!isMainFileLoc(*this, VD->getLocation())) 1554 return false; 1555 1556 if (Context.DeclMustBeEmitted(VD)) 1557 return false; 1558 1559 if (VD->isStaticDataMember() && 1560 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1561 return false; 1562 if (VD->isStaticDataMember() && 1563 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1564 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1565 return false; 1566 1567 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1568 return false; 1569 } else { 1570 return false; 1571 } 1572 1573 // Only warn for unused decls internal to the translation unit. 1574 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1575 // for inline functions defined in the main source file, for instance. 1576 return mightHaveNonExternalLinkage(D); 1577 } 1578 1579 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1580 if (!D) 1581 return; 1582 1583 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1584 const FunctionDecl *First = FD->getFirstDecl(); 1585 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1586 return; // First should already be in the vector. 1587 } 1588 1589 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1590 const VarDecl *First = VD->getFirstDecl(); 1591 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1592 return; // First should already be in the vector. 1593 } 1594 1595 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1596 UnusedFileScopedDecls.push_back(D); 1597 } 1598 1599 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1600 if (D->isInvalidDecl()) 1601 return false; 1602 1603 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1604 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1605 return false; 1606 1607 if (isa<LabelDecl>(D)) 1608 return true; 1609 1610 // Except for labels, we only care about unused decls that are local to 1611 // functions. 1612 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1613 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1614 // For dependent types, the diagnostic is deferred. 1615 WithinFunction = 1616 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1617 if (!WithinFunction) 1618 return false; 1619 1620 if (isa<TypedefNameDecl>(D)) 1621 return true; 1622 1623 // White-list anything that isn't a local variable. 1624 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1625 return false; 1626 1627 // Types of valid local variables should be complete, so this should succeed. 1628 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1629 1630 // White-list anything with an __attribute__((unused)) type. 1631 const auto *Ty = VD->getType().getTypePtr(); 1632 1633 // Only look at the outermost level of typedef. 1634 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1635 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1636 return false; 1637 } 1638 1639 // If we failed to complete the type for some reason, or if the type is 1640 // dependent, don't diagnose the variable. 1641 if (Ty->isIncompleteType() || Ty->isDependentType()) 1642 return false; 1643 1644 // Look at the element type to ensure that the warning behaviour is 1645 // consistent for both scalars and arrays. 1646 Ty = Ty->getBaseElementTypeUnsafe(); 1647 1648 if (const TagType *TT = Ty->getAs<TagType>()) { 1649 const TagDecl *Tag = TT->getDecl(); 1650 if (Tag->hasAttr<UnusedAttr>()) 1651 return false; 1652 1653 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1654 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1655 return false; 1656 1657 if (const Expr *Init = VD->getInit()) { 1658 if (const ExprWithCleanups *Cleanups = 1659 dyn_cast<ExprWithCleanups>(Init)) 1660 Init = Cleanups->getSubExpr(); 1661 const CXXConstructExpr *Construct = 1662 dyn_cast<CXXConstructExpr>(Init); 1663 if (Construct && !Construct->isElidable()) { 1664 CXXConstructorDecl *CD = Construct->getConstructor(); 1665 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1666 return false; 1667 } 1668 } 1669 } 1670 } 1671 1672 // TODO: __attribute__((unused)) templates? 1673 } 1674 1675 return true; 1676 } 1677 1678 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1679 FixItHint &Hint) { 1680 if (isa<LabelDecl>(D)) { 1681 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1682 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1683 if (AfterColon.isInvalid()) 1684 return; 1685 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1686 getCharRange(D->getLocStart(), AfterColon)); 1687 } 1688 } 1689 1690 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1691 if (D->getTypeForDecl()->isDependentType()) 1692 return; 1693 1694 for (auto *TmpD : D->decls()) { 1695 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1696 DiagnoseUnusedDecl(T); 1697 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1698 DiagnoseUnusedNestedTypedefs(R); 1699 } 1700 } 1701 1702 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1703 /// unless they are marked attr(unused). 1704 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1705 if (!ShouldDiagnoseUnusedDecl(D)) 1706 return; 1707 1708 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1709 // typedefs can be referenced later on, so the diagnostics are emitted 1710 // at end-of-translation-unit. 1711 UnusedLocalTypedefNameCandidates.insert(TD); 1712 return; 1713 } 1714 1715 FixItHint Hint; 1716 GenerateFixForUnusedDecl(D, Context, Hint); 1717 1718 unsigned DiagID; 1719 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1720 DiagID = diag::warn_unused_exception_param; 1721 else if (isa<LabelDecl>(D)) 1722 DiagID = diag::warn_unused_label; 1723 else 1724 DiagID = diag::warn_unused_variable; 1725 1726 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1727 } 1728 1729 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1730 // Verify that we have no forward references left. If so, there was a goto 1731 // or address of a label taken, but no definition of it. Label fwd 1732 // definitions are indicated with a null substmt which is also not a resolved 1733 // MS inline assembly label name. 1734 bool Diagnose = false; 1735 if (L->isMSAsmLabel()) 1736 Diagnose = !L->isResolvedMSAsmLabel(); 1737 else 1738 Diagnose = L->getStmt() == nullptr; 1739 if (Diagnose) 1740 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1741 } 1742 1743 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1744 S->mergeNRVOIntoParent(); 1745 1746 if (S->decl_empty()) return; 1747 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1748 "Scope shouldn't contain decls!"); 1749 1750 for (auto *TmpD : S->decls()) { 1751 assert(TmpD && "This decl didn't get pushed??"); 1752 1753 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1754 NamedDecl *D = cast<NamedDecl>(TmpD); 1755 1756 if (!D->getDeclName()) continue; 1757 1758 // Diagnose unused variables in this scope. 1759 if (!S->hasUnrecoverableErrorOccurred()) { 1760 DiagnoseUnusedDecl(D); 1761 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1762 DiagnoseUnusedNestedTypedefs(RD); 1763 } 1764 1765 // If this was a forward reference to a label, verify it was defined. 1766 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1767 CheckPoppedLabel(LD, *this); 1768 1769 // Remove this name from our lexical scope, and warn on it if we haven't 1770 // already. 1771 IdResolver.RemoveDecl(D); 1772 auto ShadowI = ShadowingDecls.find(D); 1773 if (ShadowI != ShadowingDecls.end()) { 1774 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1775 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1776 << D << FD << FD->getParent(); 1777 Diag(FD->getLocation(), diag::note_previous_declaration); 1778 } 1779 ShadowingDecls.erase(ShadowI); 1780 } 1781 } 1782 } 1783 1784 /// \brief Look for an Objective-C class in the translation unit. 1785 /// 1786 /// \param Id The name of the Objective-C class we're looking for. If 1787 /// typo-correction fixes this name, the Id will be updated 1788 /// to the fixed name. 1789 /// 1790 /// \param IdLoc The location of the name in the translation unit. 1791 /// 1792 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1793 /// if there is no class with the given name. 1794 /// 1795 /// \returns The declaration of the named Objective-C class, or NULL if the 1796 /// class could not be found. 1797 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1798 SourceLocation IdLoc, 1799 bool DoTypoCorrection) { 1800 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1801 // creation from this context. 1802 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1803 1804 if (!IDecl && DoTypoCorrection) { 1805 // Perform typo correction at the given location, but only if we 1806 // find an Objective-C class name. 1807 if (TypoCorrection C = CorrectTypo( 1808 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1809 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1810 CTK_ErrorRecovery)) { 1811 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1812 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1813 Id = IDecl->getIdentifier(); 1814 } 1815 } 1816 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1817 // This routine must always return a class definition, if any. 1818 if (Def && Def->getDefinition()) 1819 Def = Def->getDefinition(); 1820 return Def; 1821 } 1822 1823 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1824 /// from S, where a non-field would be declared. This routine copes 1825 /// with the difference between C and C++ scoping rules in structs and 1826 /// unions. For example, the following code is well-formed in C but 1827 /// ill-formed in C++: 1828 /// @code 1829 /// struct S6 { 1830 /// enum { BAR } e; 1831 /// }; 1832 /// 1833 /// void test_S6() { 1834 /// struct S6 a; 1835 /// a.e = BAR; 1836 /// } 1837 /// @endcode 1838 /// For the declaration of BAR, this routine will return a different 1839 /// scope. The scope S will be the scope of the unnamed enumeration 1840 /// within S6. In C++, this routine will return the scope associated 1841 /// with S6, because the enumeration's scope is a transparent 1842 /// context but structures can contain non-field names. In C, this 1843 /// routine will return the translation unit scope, since the 1844 /// enumeration's scope is a transparent context and structures cannot 1845 /// contain non-field names. 1846 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1847 while (((S->getFlags() & Scope::DeclScope) == 0) || 1848 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1849 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1850 S = S->getParent(); 1851 return S; 1852 } 1853 1854 /// \brief Looks up the declaration of "struct objc_super" and 1855 /// saves it for later use in building builtin declaration of 1856 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1857 /// pre-existing declaration exists no action takes place. 1858 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1859 IdentifierInfo *II) { 1860 if (!II->isStr("objc_msgSendSuper")) 1861 return; 1862 ASTContext &Context = ThisSema.Context; 1863 1864 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1865 SourceLocation(), Sema::LookupTagName); 1866 ThisSema.LookupName(Result, S); 1867 if (Result.getResultKind() == LookupResult::Found) 1868 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1869 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1870 } 1871 1872 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1873 switch (Error) { 1874 case ASTContext::GE_None: 1875 return ""; 1876 case ASTContext::GE_Missing_stdio: 1877 return "stdio.h"; 1878 case ASTContext::GE_Missing_setjmp: 1879 return "setjmp.h"; 1880 case ASTContext::GE_Missing_ucontext: 1881 return "ucontext.h"; 1882 } 1883 llvm_unreachable("unhandled error kind"); 1884 } 1885 1886 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1887 /// file scope. lazily create a decl for it. ForRedeclaration is true 1888 /// if we're creating this built-in in anticipation of redeclaring the 1889 /// built-in. 1890 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1891 Scope *S, bool ForRedeclaration, 1892 SourceLocation Loc) { 1893 LookupPredefedObjCSuperType(*this, S, II); 1894 1895 ASTContext::GetBuiltinTypeError Error; 1896 QualType R = Context.GetBuiltinType(ID, Error); 1897 if (Error) { 1898 if (ForRedeclaration) 1899 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1900 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1901 return nullptr; 1902 } 1903 1904 if (!ForRedeclaration && 1905 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1906 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1907 Diag(Loc, diag::ext_implicit_lib_function_decl) 1908 << Context.BuiltinInfo.getName(ID) << R; 1909 if (Context.BuiltinInfo.getHeaderName(ID) && 1910 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1911 Diag(Loc, diag::note_include_header_or_declare) 1912 << Context.BuiltinInfo.getHeaderName(ID) 1913 << Context.BuiltinInfo.getName(ID); 1914 } 1915 1916 if (R.isNull()) 1917 return nullptr; 1918 1919 DeclContext *Parent = Context.getTranslationUnitDecl(); 1920 if (getLangOpts().CPlusPlus) { 1921 LinkageSpecDecl *CLinkageDecl = 1922 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1923 LinkageSpecDecl::lang_c, false); 1924 CLinkageDecl->setImplicit(); 1925 Parent->addDecl(CLinkageDecl); 1926 Parent = CLinkageDecl; 1927 } 1928 1929 FunctionDecl *New = FunctionDecl::Create(Context, 1930 Parent, 1931 Loc, Loc, II, R, /*TInfo=*/nullptr, 1932 SC_Extern, 1933 false, 1934 R->isFunctionProtoType()); 1935 New->setImplicit(); 1936 1937 // Create Decl objects for each parameter, adding them to the 1938 // FunctionDecl. 1939 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1940 SmallVector<ParmVarDecl*, 16> Params; 1941 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1942 ParmVarDecl *parm = 1943 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1944 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1945 SC_None, nullptr); 1946 parm->setScopeInfo(0, i); 1947 Params.push_back(parm); 1948 } 1949 New->setParams(Params); 1950 } 1951 1952 AddKnownFunctionAttributes(New); 1953 RegisterLocallyScopedExternCDecl(New, S); 1954 1955 // TUScope is the translation-unit scope to insert this function into. 1956 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1957 // relate Scopes to DeclContexts, and probably eliminate CurContext 1958 // entirely, but we're not there yet. 1959 DeclContext *SavedContext = CurContext; 1960 CurContext = Parent; 1961 PushOnScopeChains(New, TUScope); 1962 CurContext = SavedContext; 1963 return New; 1964 } 1965 1966 /// Typedef declarations don't have linkage, but they still denote the same 1967 /// entity if their types are the same. 1968 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1969 /// isSameEntity. 1970 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 1971 TypedefNameDecl *Decl, 1972 LookupResult &Previous) { 1973 // This is only interesting when modules are enabled. 1974 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 1975 return; 1976 1977 // Empty sets are uninteresting. 1978 if (Previous.empty()) 1979 return; 1980 1981 LookupResult::Filter Filter = Previous.makeFilter(); 1982 while (Filter.hasNext()) { 1983 NamedDecl *Old = Filter.next(); 1984 1985 // Non-hidden declarations are never ignored. 1986 if (S.isVisible(Old)) 1987 continue; 1988 1989 // Declarations of the same entity are not ignored, even if they have 1990 // different linkages. 1991 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1992 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 1993 Decl->getUnderlyingType())) 1994 continue; 1995 1996 // If both declarations give a tag declaration a typedef name for linkage 1997 // purposes, then they declare the same entity. 1998 if (S.getLangOpts().CPlusPlus && 1999 OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2000 Decl->getAnonDeclWithTypedefName()) 2001 continue; 2002 } 2003 2004 Filter.erase(); 2005 } 2006 2007 Filter.done(); 2008 } 2009 2010 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2011 QualType OldType; 2012 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2013 OldType = OldTypedef->getUnderlyingType(); 2014 else 2015 OldType = Context.getTypeDeclType(Old); 2016 QualType NewType = New->getUnderlyingType(); 2017 2018 if (NewType->isVariablyModifiedType()) { 2019 // Must not redefine a typedef with a variably-modified type. 2020 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2021 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2022 << Kind << NewType; 2023 if (Old->getLocation().isValid()) 2024 notePreviousDefinition(Old->getLocation(), New->getLocation()); 2025 New->setInvalidDecl(); 2026 return true; 2027 } 2028 2029 if (OldType != NewType && 2030 !OldType->isDependentType() && 2031 !NewType->isDependentType() && 2032 !Context.hasSameType(OldType, NewType)) { 2033 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2034 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2035 << Kind << NewType << OldType; 2036 if (Old->getLocation().isValid()) 2037 notePreviousDefinition(Old->getLocation(), New->getLocation()); 2038 New->setInvalidDecl(); 2039 return true; 2040 } 2041 return false; 2042 } 2043 2044 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2045 /// same name and scope as a previous declaration 'Old'. Figure out 2046 /// how to resolve this situation, merging decls or emitting 2047 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2048 /// 2049 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2050 LookupResult &OldDecls) { 2051 // If the new decl is known invalid already, don't bother doing any 2052 // merging checks. 2053 if (New->isInvalidDecl()) return; 2054 2055 // Allow multiple definitions for ObjC built-in typedefs. 2056 // FIXME: Verify the underlying types are equivalent! 2057 if (getLangOpts().ObjC1) { 2058 const IdentifierInfo *TypeID = New->getIdentifier(); 2059 switch (TypeID->getLength()) { 2060 default: break; 2061 case 2: 2062 { 2063 if (!TypeID->isStr("id")) 2064 break; 2065 QualType T = New->getUnderlyingType(); 2066 if (!T->isPointerType()) 2067 break; 2068 if (!T->isVoidPointerType()) { 2069 QualType PT = T->getAs<PointerType>()->getPointeeType(); 2070 if (!PT->isStructureType()) 2071 break; 2072 } 2073 Context.setObjCIdRedefinitionType(T); 2074 // Install the built-in type for 'id', ignoring the current definition. 2075 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2076 return; 2077 } 2078 case 5: 2079 if (!TypeID->isStr("Class")) 2080 break; 2081 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2082 // Install the built-in type for 'Class', ignoring the current definition. 2083 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2084 return; 2085 case 3: 2086 if (!TypeID->isStr("SEL")) 2087 break; 2088 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2089 // Install the built-in type for 'SEL', ignoring the current definition. 2090 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2091 return; 2092 } 2093 // Fall through - the typedef name was not a builtin type. 2094 } 2095 2096 // Verify the old decl was also a type. 2097 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2098 if (!Old) { 2099 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2100 << New->getDeclName(); 2101 2102 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2103 if (OldD->getLocation().isValid()) 2104 notePreviousDefinition(OldD->getLocation(), New->getLocation()); 2105 2106 return New->setInvalidDecl(); 2107 } 2108 2109 // If the old declaration is invalid, just give up here. 2110 if (Old->isInvalidDecl()) 2111 return New->setInvalidDecl(); 2112 2113 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2114 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2115 auto *NewTag = New->getAnonDeclWithTypedefName(); 2116 NamedDecl *Hidden = nullptr; 2117 if (getLangOpts().CPlusPlus && OldTag && NewTag && 2118 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2119 !hasVisibleDefinition(OldTag, &Hidden)) { 2120 // There is a definition of this tag, but it is not visible. Use it 2121 // instead of our tag. 2122 New->setTypeForDecl(OldTD->getTypeForDecl()); 2123 if (OldTD->isModed()) 2124 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2125 OldTD->getUnderlyingType()); 2126 else 2127 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2128 2129 // Make the old tag definition visible. 2130 makeMergedDefinitionVisible(Hidden); 2131 2132 // If this was an unscoped enumeration, yank all of its enumerators 2133 // out of the scope. 2134 if (isa<EnumDecl>(NewTag)) { 2135 Scope *EnumScope = getNonFieldDeclScope(S); 2136 for (auto *D : NewTag->decls()) { 2137 auto *ED = cast<EnumConstantDecl>(D); 2138 assert(EnumScope->isDeclScope(ED)); 2139 EnumScope->RemoveDecl(ED); 2140 IdResolver.RemoveDecl(ED); 2141 ED->getLexicalDeclContext()->removeDecl(ED); 2142 } 2143 } 2144 } 2145 } 2146 2147 // If the typedef types are not identical, reject them in all languages and 2148 // with any extensions enabled. 2149 if (isIncompatibleTypedef(Old, New)) 2150 return; 2151 2152 // The types match. Link up the redeclaration chain and merge attributes if 2153 // the old declaration was a typedef. 2154 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2155 New->setPreviousDecl(Typedef); 2156 mergeDeclAttributes(New, Old); 2157 } 2158 2159 if (getLangOpts().MicrosoftExt) 2160 return; 2161 2162 if (getLangOpts().CPlusPlus) { 2163 // C++ [dcl.typedef]p2: 2164 // In a given non-class scope, a typedef specifier can be used to 2165 // redefine the name of any type declared in that scope to refer 2166 // to the type to which it already refers. 2167 if (!isa<CXXRecordDecl>(CurContext)) 2168 return; 2169 2170 // C++0x [dcl.typedef]p4: 2171 // In a given class scope, a typedef specifier can be used to redefine 2172 // any class-name declared in that scope that is not also a typedef-name 2173 // to refer to the type to which it already refers. 2174 // 2175 // This wording came in via DR424, which was a correction to the 2176 // wording in DR56, which accidentally banned code like: 2177 // 2178 // struct S { 2179 // typedef struct A { } A; 2180 // }; 2181 // 2182 // in the C++03 standard. We implement the C++0x semantics, which 2183 // allow the above but disallow 2184 // 2185 // struct S { 2186 // typedef int I; 2187 // typedef int I; 2188 // }; 2189 // 2190 // since that was the intent of DR56. 2191 if (!isa<TypedefNameDecl>(Old)) 2192 return; 2193 2194 Diag(New->getLocation(), diag::err_redefinition) 2195 << New->getDeclName(); 2196 notePreviousDefinition(Old->getLocation(), New->getLocation()); 2197 return New->setInvalidDecl(); 2198 } 2199 2200 // Modules always permit redefinition of typedefs, as does C11. 2201 if (getLangOpts().Modules || getLangOpts().C11) 2202 return; 2203 2204 // If we have a redefinition of a typedef in C, emit a warning. This warning 2205 // is normally mapped to an error, but can be controlled with 2206 // -Wtypedef-redefinition. If either the original or the redefinition is 2207 // in a system header, don't emit this for compatibility with GCC. 2208 if (getDiagnostics().getSuppressSystemWarnings() && 2209 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2210 (Old->isImplicit() || 2211 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2212 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2213 return; 2214 2215 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2216 << New->getDeclName(); 2217 notePreviousDefinition(Old->getLocation(), New->getLocation()); 2218 } 2219 2220 /// DeclhasAttr - returns true if decl Declaration already has the target 2221 /// attribute. 2222 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2223 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2224 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2225 for (const auto *i : D->attrs()) 2226 if (i->getKind() == A->getKind()) { 2227 if (Ann) { 2228 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2229 return true; 2230 continue; 2231 } 2232 // FIXME: Don't hardcode this check 2233 if (OA && isa<OwnershipAttr>(i)) 2234 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2235 return true; 2236 } 2237 2238 return false; 2239 } 2240 2241 static bool isAttributeTargetADefinition(Decl *D) { 2242 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2243 return VD->isThisDeclarationADefinition(); 2244 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2245 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2246 return true; 2247 } 2248 2249 /// Merge alignment attributes from \p Old to \p New, taking into account the 2250 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2251 /// 2252 /// \return \c true if any attributes were added to \p New. 2253 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2254 // Look for alignas attributes on Old, and pick out whichever attribute 2255 // specifies the strictest alignment requirement. 2256 AlignedAttr *OldAlignasAttr = nullptr; 2257 AlignedAttr *OldStrictestAlignAttr = nullptr; 2258 unsigned OldAlign = 0; 2259 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2260 // FIXME: We have no way of representing inherited dependent alignments 2261 // in a case like: 2262 // template<int A, int B> struct alignas(A) X; 2263 // template<int A, int B> struct alignas(B) X {}; 2264 // For now, we just ignore any alignas attributes which are not on the 2265 // definition in such a case. 2266 if (I->isAlignmentDependent()) 2267 return false; 2268 2269 if (I->isAlignas()) 2270 OldAlignasAttr = I; 2271 2272 unsigned Align = I->getAlignment(S.Context); 2273 if (Align > OldAlign) { 2274 OldAlign = Align; 2275 OldStrictestAlignAttr = I; 2276 } 2277 } 2278 2279 // Look for alignas attributes on New. 2280 AlignedAttr *NewAlignasAttr = nullptr; 2281 unsigned NewAlign = 0; 2282 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2283 if (I->isAlignmentDependent()) 2284 return false; 2285 2286 if (I->isAlignas()) 2287 NewAlignasAttr = I; 2288 2289 unsigned Align = I->getAlignment(S.Context); 2290 if (Align > NewAlign) 2291 NewAlign = Align; 2292 } 2293 2294 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2295 // Both declarations have 'alignas' attributes. We require them to match. 2296 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2297 // fall short. (If two declarations both have alignas, they must both match 2298 // every definition, and so must match each other if there is a definition.) 2299 2300 // If either declaration only contains 'alignas(0)' specifiers, then it 2301 // specifies the natural alignment for the type. 2302 if (OldAlign == 0 || NewAlign == 0) { 2303 QualType Ty; 2304 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2305 Ty = VD->getType(); 2306 else 2307 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2308 2309 if (OldAlign == 0) 2310 OldAlign = S.Context.getTypeAlign(Ty); 2311 if (NewAlign == 0) 2312 NewAlign = S.Context.getTypeAlign(Ty); 2313 } 2314 2315 if (OldAlign != NewAlign) { 2316 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2317 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2318 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2319 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2320 } 2321 } 2322 2323 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2324 // C++11 [dcl.align]p6: 2325 // if any declaration of an entity has an alignment-specifier, 2326 // every defining declaration of that entity shall specify an 2327 // equivalent alignment. 2328 // C11 6.7.5/7: 2329 // If the definition of an object does not have an alignment 2330 // specifier, any other declaration of that object shall also 2331 // have no alignment specifier. 2332 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2333 << OldAlignasAttr; 2334 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2335 << OldAlignasAttr; 2336 } 2337 2338 bool AnyAdded = false; 2339 2340 // Ensure we have an attribute representing the strictest alignment. 2341 if (OldAlign > NewAlign) { 2342 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2343 Clone->setInherited(true); 2344 New->addAttr(Clone); 2345 AnyAdded = true; 2346 } 2347 2348 // Ensure we have an alignas attribute if the old declaration had one. 2349 if (OldAlignasAttr && !NewAlignasAttr && 2350 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2351 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2352 Clone->setInherited(true); 2353 New->addAttr(Clone); 2354 AnyAdded = true; 2355 } 2356 2357 return AnyAdded; 2358 } 2359 2360 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2361 const InheritableAttr *Attr, 2362 Sema::AvailabilityMergeKind AMK) { 2363 // This function copies an attribute Attr from a previous declaration to the 2364 // new declaration D if the new declaration doesn't itself have that attribute 2365 // yet or if that attribute allows duplicates. 2366 // If you're adding a new attribute that requires logic different from 2367 // "use explicit attribute on decl if present, else use attribute from 2368 // previous decl", for example if the attribute needs to be consistent 2369 // between redeclarations, you need to call a custom merge function here. 2370 InheritableAttr *NewAttr = nullptr; 2371 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2372 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2373 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2374 AA->isImplicit(), AA->getIntroduced(), 2375 AA->getDeprecated(), 2376 AA->getObsoleted(), AA->getUnavailable(), 2377 AA->getMessage(), AA->getStrict(), 2378 AA->getReplacement(), AMK, 2379 AttrSpellingListIndex); 2380 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2381 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2382 AttrSpellingListIndex); 2383 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2384 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2385 AttrSpellingListIndex); 2386 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2387 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2388 AttrSpellingListIndex); 2389 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2390 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2391 AttrSpellingListIndex); 2392 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2393 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2394 FA->getFormatIdx(), FA->getFirstArg(), 2395 AttrSpellingListIndex); 2396 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2397 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2398 AttrSpellingListIndex); 2399 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2400 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2401 AttrSpellingListIndex, 2402 IA->getSemanticSpelling()); 2403 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2404 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2405 &S.Context.Idents.get(AA->getSpelling()), 2406 AttrSpellingListIndex); 2407 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2408 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2409 isa<CUDAGlobalAttr>(Attr))) { 2410 // CUDA target attributes are part of function signature for 2411 // overloading purposes and must not be merged. 2412 return false; 2413 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2414 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2415 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2416 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2417 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2418 NewAttr = S.mergeInternalLinkageAttr( 2419 D, InternalLinkageA->getRange(), 2420 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2421 AttrSpellingListIndex); 2422 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2423 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2424 &S.Context.Idents.get(CommonA->getSpelling()), 2425 AttrSpellingListIndex); 2426 else if (isa<AlignedAttr>(Attr)) 2427 // AlignedAttrs are handled separately, because we need to handle all 2428 // such attributes on a declaration at the same time. 2429 NewAttr = nullptr; 2430 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2431 (AMK == Sema::AMK_Override || 2432 AMK == Sema::AMK_ProtocolImplementation)) 2433 NewAttr = nullptr; 2434 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2435 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2436 UA->getGuid()); 2437 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2438 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2439 2440 if (NewAttr) { 2441 NewAttr->setInherited(true); 2442 D->addAttr(NewAttr); 2443 if (isa<MSInheritanceAttr>(NewAttr)) 2444 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2445 return true; 2446 } 2447 2448 return false; 2449 } 2450 2451 static const Decl *getDefinition(const Decl *D) { 2452 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2453 return TD->getDefinition(); 2454 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2455 const VarDecl *Def = VD->getDefinition(); 2456 if (Def) 2457 return Def; 2458 return VD->getActingDefinition(); 2459 } 2460 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2461 return FD->getDefinition(); 2462 return nullptr; 2463 } 2464 2465 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2466 for (const auto *Attribute : D->attrs()) 2467 if (Attribute->getKind() == Kind) 2468 return true; 2469 return false; 2470 } 2471 2472 /// checkNewAttributesAfterDef - If we already have a definition, check that 2473 /// there are no new attributes in this declaration. 2474 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2475 if (!New->hasAttrs()) 2476 return; 2477 2478 const Decl *Def = getDefinition(Old); 2479 if (!Def || Def == New) 2480 return; 2481 2482 AttrVec &NewAttributes = New->getAttrs(); 2483 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2484 const Attr *NewAttribute = NewAttributes[I]; 2485 2486 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2487 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2488 Sema::SkipBodyInfo SkipBody; 2489 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2490 2491 // If we're skipping this definition, drop the "alias" attribute. 2492 if (SkipBody.ShouldSkip) { 2493 NewAttributes.erase(NewAttributes.begin() + I); 2494 --E; 2495 continue; 2496 } 2497 } else { 2498 VarDecl *VD = cast<VarDecl>(New); 2499 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2500 VarDecl::TentativeDefinition 2501 ? diag::err_alias_after_tentative 2502 : diag::err_redefinition; 2503 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2504 if (Diag == diag::err_redefinition) 2505 S.notePreviousDefinition(Def->getLocation(), VD->getLocation()); 2506 else 2507 S.Diag(Def->getLocation(), diag::note_previous_definition); 2508 VD->setInvalidDecl(); 2509 } 2510 ++I; 2511 continue; 2512 } 2513 2514 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2515 // Tentative definitions are only interesting for the alias check above. 2516 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2517 ++I; 2518 continue; 2519 } 2520 } 2521 2522 if (hasAttribute(Def, NewAttribute->getKind())) { 2523 ++I; 2524 continue; // regular attr merging will take care of validating this. 2525 } 2526 2527 if (isa<C11NoReturnAttr>(NewAttribute)) { 2528 // C's _Noreturn is allowed to be added to a function after it is defined. 2529 ++I; 2530 continue; 2531 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2532 if (AA->isAlignas()) { 2533 // C++11 [dcl.align]p6: 2534 // if any declaration of an entity has an alignment-specifier, 2535 // every defining declaration of that entity shall specify an 2536 // equivalent alignment. 2537 // C11 6.7.5/7: 2538 // If the definition of an object does not have an alignment 2539 // specifier, any other declaration of that object shall also 2540 // have no alignment specifier. 2541 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2542 << AA; 2543 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2544 << AA; 2545 NewAttributes.erase(NewAttributes.begin() + I); 2546 --E; 2547 continue; 2548 } 2549 } 2550 2551 S.Diag(NewAttribute->getLocation(), 2552 diag::warn_attribute_precede_definition); 2553 S.Diag(Def->getLocation(), diag::note_previous_definition); 2554 NewAttributes.erase(NewAttributes.begin() + I); 2555 --E; 2556 } 2557 } 2558 2559 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2560 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2561 AvailabilityMergeKind AMK) { 2562 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2563 UsedAttr *NewAttr = OldAttr->clone(Context); 2564 NewAttr->setInherited(true); 2565 New->addAttr(NewAttr); 2566 } 2567 2568 if (!Old->hasAttrs() && !New->hasAttrs()) 2569 return; 2570 2571 // Attributes declared post-definition are currently ignored. 2572 checkNewAttributesAfterDef(*this, New, Old); 2573 2574 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2575 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2576 if (OldA->getLabel() != NewA->getLabel()) { 2577 // This redeclaration changes __asm__ label. 2578 Diag(New->getLocation(), diag::err_different_asm_label); 2579 Diag(OldA->getLocation(), diag::note_previous_declaration); 2580 } 2581 } else if (Old->isUsed()) { 2582 // This redeclaration adds an __asm__ label to a declaration that has 2583 // already been ODR-used. 2584 Diag(New->getLocation(), diag::err_late_asm_label_name) 2585 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2586 } 2587 } 2588 2589 // Re-declaration cannot add abi_tag's. 2590 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2591 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2592 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2593 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2594 NewTag) == OldAbiTagAttr->tags_end()) { 2595 Diag(NewAbiTagAttr->getLocation(), 2596 diag::err_new_abi_tag_on_redeclaration) 2597 << NewTag; 2598 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2599 } 2600 } 2601 } else { 2602 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2603 Diag(Old->getLocation(), diag::note_previous_declaration); 2604 } 2605 } 2606 2607 if (!Old->hasAttrs()) 2608 return; 2609 2610 bool foundAny = New->hasAttrs(); 2611 2612 // Ensure that any moving of objects within the allocated map is done before 2613 // we process them. 2614 if (!foundAny) New->setAttrs(AttrVec()); 2615 2616 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2617 // Ignore deprecated/unavailable/availability attributes if requested. 2618 AvailabilityMergeKind LocalAMK = AMK_None; 2619 if (isa<DeprecatedAttr>(I) || 2620 isa<UnavailableAttr>(I) || 2621 isa<AvailabilityAttr>(I)) { 2622 switch (AMK) { 2623 case AMK_None: 2624 continue; 2625 2626 case AMK_Redeclaration: 2627 case AMK_Override: 2628 case AMK_ProtocolImplementation: 2629 LocalAMK = AMK; 2630 break; 2631 } 2632 } 2633 2634 // Already handled. 2635 if (isa<UsedAttr>(I)) 2636 continue; 2637 2638 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2639 foundAny = true; 2640 } 2641 2642 if (mergeAlignedAttrs(*this, New, Old)) 2643 foundAny = true; 2644 2645 if (!foundAny) New->dropAttrs(); 2646 } 2647 2648 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2649 /// to the new one. 2650 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2651 const ParmVarDecl *oldDecl, 2652 Sema &S) { 2653 // C++11 [dcl.attr.depend]p2: 2654 // The first declaration of a function shall specify the 2655 // carries_dependency attribute for its declarator-id if any declaration 2656 // of the function specifies the carries_dependency attribute. 2657 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2658 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2659 S.Diag(CDA->getLocation(), 2660 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2661 // Find the first declaration of the parameter. 2662 // FIXME: Should we build redeclaration chains for function parameters? 2663 const FunctionDecl *FirstFD = 2664 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2665 const ParmVarDecl *FirstVD = 2666 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2667 S.Diag(FirstVD->getLocation(), 2668 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2669 } 2670 2671 if (!oldDecl->hasAttrs()) 2672 return; 2673 2674 bool foundAny = newDecl->hasAttrs(); 2675 2676 // Ensure that any moving of objects within the allocated map is 2677 // done before we process them. 2678 if (!foundAny) newDecl->setAttrs(AttrVec()); 2679 2680 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2681 if (!DeclHasAttr(newDecl, I)) { 2682 InheritableAttr *newAttr = 2683 cast<InheritableParamAttr>(I->clone(S.Context)); 2684 newAttr->setInherited(true); 2685 newDecl->addAttr(newAttr); 2686 foundAny = true; 2687 } 2688 } 2689 2690 if (!foundAny) newDecl->dropAttrs(); 2691 } 2692 2693 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2694 const ParmVarDecl *OldParam, 2695 Sema &S) { 2696 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2697 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2698 if (*Oldnullability != *Newnullability) { 2699 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2700 << DiagNullabilityKind( 2701 *Newnullability, 2702 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2703 != 0)) 2704 << DiagNullabilityKind( 2705 *Oldnullability, 2706 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2707 != 0)); 2708 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2709 } 2710 } else { 2711 QualType NewT = NewParam->getType(); 2712 NewT = S.Context.getAttributedType( 2713 AttributedType::getNullabilityAttrKind(*Oldnullability), 2714 NewT, NewT); 2715 NewParam->setType(NewT); 2716 } 2717 } 2718 } 2719 2720 namespace { 2721 2722 /// Used in MergeFunctionDecl to keep track of function parameters in 2723 /// C. 2724 struct GNUCompatibleParamWarning { 2725 ParmVarDecl *OldParm; 2726 ParmVarDecl *NewParm; 2727 QualType PromotedType; 2728 }; 2729 2730 } // end anonymous namespace 2731 2732 /// getSpecialMember - get the special member enum for a method. 2733 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2734 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2735 if (Ctor->isDefaultConstructor()) 2736 return Sema::CXXDefaultConstructor; 2737 2738 if (Ctor->isCopyConstructor()) 2739 return Sema::CXXCopyConstructor; 2740 2741 if (Ctor->isMoveConstructor()) 2742 return Sema::CXXMoveConstructor; 2743 } else if (isa<CXXDestructorDecl>(MD)) { 2744 return Sema::CXXDestructor; 2745 } else if (MD->isCopyAssignmentOperator()) { 2746 return Sema::CXXCopyAssignment; 2747 } else if (MD->isMoveAssignmentOperator()) { 2748 return Sema::CXXMoveAssignment; 2749 } 2750 2751 return Sema::CXXInvalid; 2752 } 2753 2754 // Determine whether the previous declaration was a definition, implicit 2755 // declaration, or a declaration. 2756 template <typename T> 2757 static std::pair<diag::kind, SourceLocation> 2758 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2759 diag::kind PrevDiag; 2760 SourceLocation OldLocation = Old->getLocation(); 2761 if (Old->isThisDeclarationADefinition()) 2762 PrevDiag = diag::note_previous_definition; 2763 else if (Old->isImplicit()) { 2764 PrevDiag = diag::note_previous_implicit_declaration; 2765 if (OldLocation.isInvalid()) 2766 OldLocation = New->getLocation(); 2767 } else 2768 PrevDiag = diag::note_previous_declaration; 2769 return std::make_pair(PrevDiag, OldLocation); 2770 } 2771 2772 /// canRedefineFunction - checks if a function can be redefined. Currently, 2773 /// only extern inline functions can be redefined, and even then only in 2774 /// GNU89 mode. 2775 static bool canRedefineFunction(const FunctionDecl *FD, 2776 const LangOptions& LangOpts) { 2777 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2778 !LangOpts.CPlusPlus && 2779 FD->isInlineSpecified() && 2780 FD->getStorageClass() == SC_Extern); 2781 } 2782 2783 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2784 const AttributedType *AT = T->getAs<AttributedType>(); 2785 while (AT && !AT->isCallingConv()) 2786 AT = AT->getModifiedType()->getAs<AttributedType>(); 2787 return AT; 2788 } 2789 2790 template <typename T> 2791 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2792 const DeclContext *DC = Old->getDeclContext(); 2793 if (DC->isRecord()) 2794 return false; 2795 2796 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2797 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2798 return true; 2799 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2800 return true; 2801 return false; 2802 } 2803 2804 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2805 static bool isExternC(VarTemplateDecl *) { return false; } 2806 2807 /// \brief Check whether a redeclaration of an entity introduced by a 2808 /// using-declaration is valid, given that we know it's not an overload 2809 /// (nor a hidden tag declaration). 2810 template<typename ExpectedDecl> 2811 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2812 ExpectedDecl *New) { 2813 // C++11 [basic.scope.declarative]p4: 2814 // Given a set of declarations in a single declarative region, each of 2815 // which specifies the same unqualified name, 2816 // -- they shall all refer to the same entity, or all refer to functions 2817 // and function templates; or 2818 // -- exactly one declaration shall declare a class name or enumeration 2819 // name that is not a typedef name and the other declarations shall all 2820 // refer to the same variable or enumerator, or all refer to functions 2821 // and function templates; in this case the class name or enumeration 2822 // name is hidden (3.3.10). 2823 2824 // C++11 [namespace.udecl]p14: 2825 // If a function declaration in namespace scope or block scope has the 2826 // same name and the same parameter-type-list as a function introduced 2827 // by a using-declaration, and the declarations do not declare the same 2828 // function, the program is ill-formed. 2829 2830 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2831 if (Old && 2832 !Old->getDeclContext()->getRedeclContext()->Equals( 2833 New->getDeclContext()->getRedeclContext()) && 2834 !(isExternC(Old) && isExternC(New))) 2835 Old = nullptr; 2836 2837 if (!Old) { 2838 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2839 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2840 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2841 return true; 2842 } 2843 return false; 2844 } 2845 2846 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2847 const FunctionDecl *B) { 2848 assert(A->getNumParams() == B->getNumParams()); 2849 2850 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2851 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2852 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2853 if (AttrA == AttrB) 2854 return true; 2855 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2856 }; 2857 2858 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2859 } 2860 2861 /// MergeFunctionDecl - We just parsed a function 'New' from 2862 /// declarator D which has the same name and scope as a previous 2863 /// declaration 'Old'. Figure out how to resolve this situation, 2864 /// merging decls or emitting diagnostics as appropriate. 2865 /// 2866 /// In C++, New and Old must be declarations that are not 2867 /// overloaded. Use IsOverload to determine whether New and Old are 2868 /// overloaded, and to select the Old declaration that New should be 2869 /// merged with. 2870 /// 2871 /// Returns true if there was an error, false otherwise. 2872 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2873 Scope *S, bool MergeTypeWithOld) { 2874 // Verify the old decl was also a function. 2875 FunctionDecl *Old = OldD->getAsFunction(); 2876 if (!Old) { 2877 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2878 if (New->getFriendObjectKind()) { 2879 Diag(New->getLocation(), diag::err_using_decl_friend); 2880 Diag(Shadow->getTargetDecl()->getLocation(), 2881 diag::note_using_decl_target); 2882 Diag(Shadow->getUsingDecl()->getLocation(), 2883 diag::note_using_decl) << 0; 2884 return true; 2885 } 2886 2887 // Check whether the two declarations might declare the same function. 2888 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 2889 return true; 2890 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 2891 } else { 2892 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2893 << New->getDeclName(); 2894 notePreviousDefinition(OldD->getLocation(), New->getLocation()); 2895 return true; 2896 } 2897 } 2898 2899 // If the old declaration is invalid, just give up here. 2900 if (Old->isInvalidDecl()) 2901 return true; 2902 2903 diag::kind PrevDiag; 2904 SourceLocation OldLocation; 2905 std::tie(PrevDiag, OldLocation) = 2906 getNoteDiagForInvalidRedeclaration(Old, New); 2907 2908 // Don't complain about this if we're in GNU89 mode and the old function 2909 // is an extern inline function. 2910 // Don't complain about specializations. They are not supposed to have 2911 // storage classes. 2912 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2913 New->getStorageClass() == SC_Static && 2914 Old->hasExternalFormalLinkage() && 2915 !New->getTemplateSpecializationInfo() && 2916 !canRedefineFunction(Old, getLangOpts())) { 2917 if (getLangOpts().MicrosoftExt) { 2918 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2919 Diag(OldLocation, PrevDiag); 2920 } else { 2921 Diag(New->getLocation(), diag::err_static_non_static) << New; 2922 Diag(OldLocation, PrevDiag); 2923 return true; 2924 } 2925 } 2926 2927 if (New->hasAttr<InternalLinkageAttr>() && 2928 !Old->hasAttr<InternalLinkageAttr>()) { 2929 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 2930 << New->getDeclName(); 2931 notePreviousDefinition(Old->getLocation(), New->getLocation()); 2932 New->dropAttr<InternalLinkageAttr>(); 2933 } 2934 2935 // If a function is first declared with a calling convention, but is later 2936 // declared or defined without one, all following decls assume the calling 2937 // convention of the first. 2938 // 2939 // It's OK if a function is first declared without a calling convention, 2940 // but is later declared or defined with the default calling convention. 2941 // 2942 // To test if either decl has an explicit calling convention, we look for 2943 // AttributedType sugar nodes on the type as written. If they are missing or 2944 // were canonicalized away, we assume the calling convention was implicit. 2945 // 2946 // Note also that we DO NOT return at this point, because we still have 2947 // other tests to run. 2948 QualType OldQType = Context.getCanonicalType(Old->getType()); 2949 QualType NewQType = Context.getCanonicalType(New->getType()); 2950 const FunctionType *OldType = cast<FunctionType>(OldQType); 2951 const FunctionType *NewType = cast<FunctionType>(NewQType); 2952 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2953 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2954 bool RequiresAdjustment = false; 2955 2956 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2957 FunctionDecl *First = Old->getFirstDecl(); 2958 const FunctionType *FT = 2959 First->getType().getCanonicalType()->castAs<FunctionType>(); 2960 FunctionType::ExtInfo FI = FT->getExtInfo(); 2961 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2962 if (!NewCCExplicit) { 2963 // Inherit the CC from the previous declaration if it was specified 2964 // there but not here. 2965 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2966 RequiresAdjustment = true; 2967 } else { 2968 // Calling conventions aren't compatible, so complain. 2969 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2970 Diag(New->getLocation(), diag::err_cconv_change) 2971 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2972 << !FirstCCExplicit 2973 << (!FirstCCExplicit ? "" : 2974 FunctionType::getNameForCallConv(FI.getCC())); 2975 2976 // Put the note on the first decl, since it is the one that matters. 2977 Diag(First->getLocation(), diag::note_previous_declaration); 2978 return true; 2979 } 2980 } 2981 2982 // FIXME: diagnose the other way around? 2983 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2984 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2985 RequiresAdjustment = true; 2986 } 2987 2988 // Merge regparm attribute. 2989 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2990 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2991 if (NewTypeInfo.getHasRegParm()) { 2992 Diag(New->getLocation(), diag::err_regparm_mismatch) 2993 << NewType->getRegParmType() 2994 << OldType->getRegParmType(); 2995 Diag(OldLocation, diag::note_previous_declaration); 2996 return true; 2997 } 2998 2999 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3000 RequiresAdjustment = true; 3001 } 3002 3003 // Merge ns_returns_retained attribute. 3004 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3005 if (NewTypeInfo.getProducesResult()) { 3006 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3007 << "'ns_returns_retained'"; 3008 Diag(OldLocation, diag::note_previous_declaration); 3009 return true; 3010 } 3011 3012 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3013 RequiresAdjustment = true; 3014 } 3015 3016 if (OldTypeInfo.getNoCallerSavedRegs() != 3017 NewTypeInfo.getNoCallerSavedRegs()) { 3018 if (NewTypeInfo.getNoCallerSavedRegs()) { 3019 AnyX86NoCallerSavedRegistersAttr *Attr = 3020 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3021 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3022 Diag(OldLocation, diag::note_previous_declaration); 3023 return true; 3024 } 3025 3026 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3027 RequiresAdjustment = true; 3028 } 3029 3030 if (RequiresAdjustment) { 3031 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3032 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3033 New->setType(QualType(AdjustedType, 0)); 3034 NewQType = Context.getCanonicalType(New->getType()); 3035 NewType = cast<FunctionType>(NewQType); 3036 } 3037 3038 // If this redeclaration makes the function inline, we may need to add it to 3039 // UndefinedButUsed. 3040 if (!Old->isInlined() && New->isInlined() && 3041 !New->hasAttr<GNUInlineAttr>() && 3042 !getLangOpts().GNUInline && 3043 Old->isUsed(false) && 3044 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3045 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3046 SourceLocation())); 3047 3048 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3049 // about it. 3050 if (New->hasAttr<GNUInlineAttr>() && 3051 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3052 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3053 } 3054 3055 // If pass_object_size params don't match up perfectly, this isn't a valid 3056 // redeclaration. 3057 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3058 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3059 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3060 << New->getDeclName(); 3061 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3062 return true; 3063 } 3064 3065 if (getLangOpts().CPlusPlus) { 3066 // C++1z [over.load]p2 3067 // Certain function declarations cannot be overloaded: 3068 // -- Function declarations that differ only in the return type, 3069 // the exception specification, or both cannot be overloaded. 3070 3071 // Check the exception specifications match. This may recompute the type of 3072 // both Old and New if it resolved exception specifications, so grab the 3073 // types again after this. Because this updates the type, we do this before 3074 // any of the other checks below, which may update the "de facto" NewQType 3075 // but do not necessarily update the type of New. 3076 if (CheckEquivalentExceptionSpec(Old, New)) 3077 return true; 3078 OldQType = Context.getCanonicalType(Old->getType()); 3079 NewQType = Context.getCanonicalType(New->getType()); 3080 3081 // Go back to the type source info to compare the declared return types, 3082 // per C++1y [dcl.type.auto]p13: 3083 // Redeclarations or specializations of a function or function template 3084 // with a declared return type that uses a placeholder type shall also 3085 // use that placeholder, not a deduced type. 3086 QualType OldDeclaredReturnType = 3087 (Old->getTypeSourceInfo() 3088 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3089 : OldType)->getReturnType(); 3090 QualType NewDeclaredReturnType = 3091 (New->getTypeSourceInfo() 3092 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3093 : NewType)->getReturnType(); 3094 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3095 !((NewQType->isDependentType() || OldQType->isDependentType()) && 3096 New->isLocalExternDecl())) { 3097 QualType ResQT; 3098 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3099 OldDeclaredReturnType->isObjCObjectPointerType()) 3100 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3101 if (ResQT.isNull()) { 3102 if (New->isCXXClassMember() && New->isOutOfLine()) 3103 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3104 << New << New->getReturnTypeSourceRange(); 3105 else 3106 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3107 << New->getReturnTypeSourceRange(); 3108 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3109 << Old->getReturnTypeSourceRange(); 3110 return true; 3111 } 3112 else 3113 NewQType = ResQT; 3114 } 3115 3116 QualType OldReturnType = OldType->getReturnType(); 3117 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3118 if (OldReturnType != NewReturnType) { 3119 // If this function has a deduced return type and has already been 3120 // defined, copy the deduced value from the old declaration. 3121 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3122 if (OldAT && OldAT->isDeduced()) { 3123 New->setType( 3124 SubstAutoType(New->getType(), 3125 OldAT->isDependentType() ? Context.DependentTy 3126 : OldAT->getDeducedType())); 3127 NewQType = Context.getCanonicalType( 3128 SubstAutoType(NewQType, 3129 OldAT->isDependentType() ? Context.DependentTy 3130 : OldAT->getDeducedType())); 3131 } 3132 } 3133 3134 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3135 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3136 if (OldMethod && NewMethod) { 3137 // Preserve triviality. 3138 NewMethod->setTrivial(OldMethod->isTrivial()); 3139 3140 // MSVC allows explicit template specialization at class scope: 3141 // 2 CXXMethodDecls referring to the same function will be injected. 3142 // We don't want a redeclaration error. 3143 bool IsClassScopeExplicitSpecialization = 3144 OldMethod->isFunctionTemplateSpecialization() && 3145 NewMethod->isFunctionTemplateSpecialization(); 3146 bool isFriend = NewMethod->getFriendObjectKind(); 3147 3148 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3149 !IsClassScopeExplicitSpecialization) { 3150 // -- Member function declarations with the same name and the 3151 // same parameter types cannot be overloaded if any of them 3152 // is a static member function declaration. 3153 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3154 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3155 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3156 return true; 3157 } 3158 3159 // C++ [class.mem]p1: 3160 // [...] A member shall not be declared twice in the 3161 // member-specification, except that a nested class or member 3162 // class template can be declared and then later defined. 3163 if (!inTemplateInstantiation()) { 3164 unsigned NewDiag; 3165 if (isa<CXXConstructorDecl>(OldMethod)) 3166 NewDiag = diag::err_constructor_redeclared; 3167 else if (isa<CXXDestructorDecl>(NewMethod)) 3168 NewDiag = diag::err_destructor_redeclared; 3169 else if (isa<CXXConversionDecl>(NewMethod)) 3170 NewDiag = diag::err_conv_function_redeclared; 3171 else 3172 NewDiag = diag::err_member_redeclared; 3173 3174 Diag(New->getLocation(), NewDiag); 3175 } else { 3176 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3177 << New << New->getType(); 3178 } 3179 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3180 return true; 3181 3182 // Complain if this is an explicit declaration of a special 3183 // member that was initially declared implicitly. 3184 // 3185 // As an exception, it's okay to befriend such methods in order 3186 // to permit the implicit constructor/destructor/operator calls. 3187 } else if (OldMethod->isImplicit()) { 3188 if (isFriend) { 3189 NewMethod->setImplicit(); 3190 } else { 3191 Diag(NewMethod->getLocation(), 3192 diag::err_definition_of_implicitly_declared_member) 3193 << New << getSpecialMember(OldMethod); 3194 return true; 3195 } 3196 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3197 Diag(NewMethod->getLocation(), 3198 diag::err_definition_of_explicitly_defaulted_member) 3199 << getSpecialMember(OldMethod); 3200 return true; 3201 } 3202 } 3203 3204 // C++11 [dcl.attr.noreturn]p1: 3205 // The first declaration of a function shall specify the noreturn 3206 // attribute if any declaration of that function specifies the noreturn 3207 // attribute. 3208 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3209 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3210 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3211 Diag(Old->getFirstDecl()->getLocation(), 3212 diag::note_noreturn_missing_first_decl); 3213 } 3214 3215 // C++11 [dcl.attr.depend]p2: 3216 // The first declaration of a function shall specify the 3217 // carries_dependency attribute for its declarator-id if any declaration 3218 // of the function specifies the carries_dependency attribute. 3219 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3220 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3221 Diag(CDA->getLocation(), 3222 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3223 Diag(Old->getFirstDecl()->getLocation(), 3224 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3225 } 3226 3227 // (C++98 8.3.5p3): 3228 // All declarations for a function shall agree exactly in both the 3229 // return type and the parameter-type-list. 3230 // We also want to respect all the extended bits except noreturn. 3231 3232 // noreturn should now match unless the old type info didn't have it. 3233 QualType OldQTypeForComparison = OldQType; 3234 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3235 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3236 const FunctionType *OldTypeForComparison 3237 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3238 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3239 assert(OldQTypeForComparison.isCanonical()); 3240 } 3241 3242 if (haveIncompatibleLanguageLinkages(Old, New)) { 3243 // As a special case, retain the language linkage from previous 3244 // declarations of a friend function as an extension. 3245 // 3246 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3247 // and is useful because there's otherwise no way to specify language 3248 // linkage within class scope. 3249 // 3250 // Check cautiously as the friend object kind isn't yet complete. 3251 if (New->getFriendObjectKind() != Decl::FOK_None) { 3252 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3253 Diag(OldLocation, PrevDiag); 3254 } else { 3255 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3256 Diag(OldLocation, PrevDiag); 3257 return true; 3258 } 3259 } 3260 3261 if (OldQTypeForComparison == NewQType) 3262 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3263 3264 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3265 New->isLocalExternDecl()) { 3266 // It's OK if we couldn't merge types for a local function declaraton 3267 // if either the old or new type is dependent. We'll merge the types 3268 // when we instantiate the function. 3269 return false; 3270 } 3271 3272 // Fall through for conflicting redeclarations and redefinitions. 3273 } 3274 3275 // C: Function types need to be compatible, not identical. This handles 3276 // duplicate function decls like "void f(int); void f(enum X);" properly. 3277 if (!getLangOpts().CPlusPlus && 3278 Context.typesAreCompatible(OldQType, NewQType)) { 3279 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3280 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3281 const FunctionProtoType *OldProto = nullptr; 3282 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3283 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3284 // The old declaration provided a function prototype, but the 3285 // new declaration does not. Merge in the prototype. 3286 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3287 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3288 NewQType = 3289 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3290 OldProto->getExtProtoInfo()); 3291 New->setType(NewQType); 3292 New->setHasInheritedPrototype(); 3293 3294 // Synthesize parameters with the same types. 3295 SmallVector<ParmVarDecl*, 16> Params; 3296 for (const auto &ParamType : OldProto->param_types()) { 3297 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3298 SourceLocation(), nullptr, 3299 ParamType, /*TInfo=*/nullptr, 3300 SC_None, nullptr); 3301 Param->setScopeInfo(0, Params.size()); 3302 Param->setImplicit(); 3303 Params.push_back(Param); 3304 } 3305 3306 New->setParams(Params); 3307 } 3308 3309 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3310 } 3311 3312 // GNU C permits a K&R definition to follow a prototype declaration 3313 // if the declared types of the parameters in the K&R definition 3314 // match the types in the prototype declaration, even when the 3315 // promoted types of the parameters from the K&R definition differ 3316 // from the types in the prototype. GCC then keeps the types from 3317 // the prototype. 3318 // 3319 // If a variadic prototype is followed by a non-variadic K&R definition, 3320 // the K&R definition becomes variadic. This is sort of an edge case, but 3321 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3322 // C99 6.9.1p8. 3323 if (!getLangOpts().CPlusPlus && 3324 Old->hasPrototype() && !New->hasPrototype() && 3325 New->getType()->getAs<FunctionProtoType>() && 3326 Old->getNumParams() == New->getNumParams()) { 3327 SmallVector<QualType, 16> ArgTypes; 3328 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3329 const FunctionProtoType *OldProto 3330 = Old->getType()->getAs<FunctionProtoType>(); 3331 const FunctionProtoType *NewProto 3332 = New->getType()->getAs<FunctionProtoType>(); 3333 3334 // Determine whether this is the GNU C extension. 3335 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3336 NewProto->getReturnType()); 3337 bool LooseCompatible = !MergedReturn.isNull(); 3338 for (unsigned Idx = 0, End = Old->getNumParams(); 3339 LooseCompatible && Idx != End; ++Idx) { 3340 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3341 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3342 if (Context.typesAreCompatible(OldParm->getType(), 3343 NewProto->getParamType(Idx))) { 3344 ArgTypes.push_back(NewParm->getType()); 3345 } else if (Context.typesAreCompatible(OldParm->getType(), 3346 NewParm->getType(), 3347 /*CompareUnqualified=*/true)) { 3348 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3349 NewProto->getParamType(Idx) }; 3350 Warnings.push_back(Warn); 3351 ArgTypes.push_back(NewParm->getType()); 3352 } else 3353 LooseCompatible = false; 3354 } 3355 3356 if (LooseCompatible) { 3357 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3358 Diag(Warnings[Warn].NewParm->getLocation(), 3359 diag::ext_param_promoted_not_compatible_with_prototype) 3360 << Warnings[Warn].PromotedType 3361 << Warnings[Warn].OldParm->getType(); 3362 if (Warnings[Warn].OldParm->getLocation().isValid()) 3363 Diag(Warnings[Warn].OldParm->getLocation(), 3364 diag::note_previous_declaration); 3365 } 3366 3367 if (MergeTypeWithOld) 3368 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3369 OldProto->getExtProtoInfo())); 3370 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3371 } 3372 3373 // Fall through to diagnose conflicting types. 3374 } 3375 3376 // A function that has already been declared has been redeclared or 3377 // defined with a different type; show an appropriate diagnostic. 3378 3379 // If the previous declaration was an implicitly-generated builtin 3380 // declaration, then at the very least we should use a specialized note. 3381 unsigned BuiltinID; 3382 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3383 // If it's actually a library-defined builtin function like 'malloc' 3384 // or 'printf', just warn about the incompatible redeclaration. 3385 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3386 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3387 Diag(OldLocation, diag::note_previous_builtin_declaration) 3388 << Old << Old->getType(); 3389 3390 // If this is a global redeclaration, just forget hereafter 3391 // about the "builtin-ness" of the function. 3392 // 3393 // Doing this for local extern declarations is problematic. If 3394 // the builtin declaration remains visible, a second invalid 3395 // local declaration will produce a hard error; if it doesn't 3396 // remain visible, a single bogus local redeclaration (which is 3397 // actually only a warning) could break all the downstream code. 3398 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3399 New->getIdentifier()->revertBuiltin(); 3400 3401 return false; 3402 } 3403 3404 PrevDiag = diag::note_previous_builtin_declaration; 3405 } 3406 3407 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3408 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3409 return true; 3410 } 3411 3412 /// \brief Completes the merge of two function declarations that are 3413 /// known to be compatible. 3414 /// 3415 /// This routine handles the merging of attributes and other 3416 /// properties of function declarations from the old declaration to 3417 /// the new declaration, once we know that New is in fact a 3418 /// redeclaration of Old. 3419 /// 3420 /// \returns false 3421 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3422 Scope *S, bool MergeTypeWithOld) { 3423 // Merge the attributes 3424 mergeDeclAttributes(New, Old); 3425 3426 // Merge "pure" flag. 3427 if (Old->isPure()) 3428 New->setPure(); 3429 3430 // Merge "used" flag. 3431 if (Old->getMostRecentDecl()->isUsed(false)) 3432 New->setIsUsed(); 3433 3434 // Merge attributes from the parameters. These can mismatch with K&R 3435 // declarations. 3436 if (New->getNumParams() == Old->getNumParams()) 3437 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3438 ParmVarDecl *NewParam = New->getParamDecl(i); 3439 ParmVarDecl *OldParam = Old->getParamDecl(i); 3440 mergeParamDeclAttributes(NewParam, OldParam, *this); 3441 mergeParamDeclTypes(NewParam, OldParam, *this); 3442 } 3443 3444 if (getLangOpts().CPlusPlus) 3445 return MergeCXXFunctionDecl(New, Old, S); 3446 3447 // Merge the function types so the we get the composite types for the return 3448 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3449 // was visible. 3450 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3451 if (!Merged.isNull() && MergeTypeWithOld) 3452 New->setType(Merged); 3453 3454 return false; 3455 } 3456 3457 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3458 ObjCMethodDecl *oldMethod) { 3459 // Merge the attributes, including deprecated/unavailable 3460 AvailabilityMergeKind MergeKind = 3461 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3462 ? AMK_ProtocolImplementation 3463 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3464 : AMK_Override; 3465 3466 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3467 3468 // Merge attributes from the parameters. 3469 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3470 oe = oldMethod->param_end(); 3471 for (ObjCMethodDecl::param_iterator 3472 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3473 ni != ne && oi != oe; ++ni, ++oi) 3474 mergeParamDeclAttributes(*ni, *oi, *this); 3475 3476 CheckObjCMethodOverride(newMethod, oldMethod); 3477 } 3478 3479 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3480 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3481 3482 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3483 ? diag::err_redefinition_different_type 3484 : diag::err_redeclaration_different_type) 3485 << New->getDeclName() << New->getType() << Old->getType(); 3486 3487 diag::kind PrevDiag; 3488 SourceLocation OldLocation; 3489 std::tie(PrevDiag, OldLocation) 3490 = getNoteDiagForInvalidRedeclaration(Old, New); 3491 S.Diag(OldLocation, PrevDiag); 3492 New->setInvalidDecl(); 3493 } 3494 3495 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3496 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3497 /// emitting diagnostics as appropriate. 3498 /// 3499 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3500 /// to here in AddInitializerToDecl. We can't check them before the initializer 3501 /// is attached. 3502 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3503 bool MergeTypeWithOld) { 3504 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3505 return; 3506 3507 QualType MergedT; 3508 if (getLangOpts().CPlusPlus) { 3509 if (New->getType()->isUndeducedType()) { 3510 // We don't know what the new type is until the initializer is attached. 3511 return; 3512 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3513 // These could still be something that needs exception specs checked. 3514 return MergeVarDeclExceptionSpecs(New, Old); 3515 } 3516 // C++ [basic.link]p10: 3517 // [...] the types specified by all declarations referring to a given 3518 // object or function shall be identical, except that declarations for an 3519 // array object can specify array types that differ by the presence or 3520 // absence of a major array bound (8.3.4). 3521 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3522 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3523 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3524 3525 // We are merging a variable declaration New into Old. If it has an array 3526 // bound, and that bound differs from Old's bound, we should diagnose the 3527 // mismatch. 3528 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3529 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3530 PrevVD = PrevVD->getPreviousDecl()) { 3531 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3532 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3533 continue; 3534 3535 if (!Context.hasSameType(NewArray, PrevVDTy)) 3536 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3537 } 3538 } 3539 3540 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3541 if (Context.hasSameType(OldArray->getElementType(), 3542 NewArray->getElementType())) 3543 MergedT = New->getType(); 3544 } 3545 // FIXME: Check visibility. New is hidden but has a complete type. If New 3546 // has no array bound, it should not inherit one from Old, if Old is not 3547 // visible. 3548 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3549 if (Context.hasSameType(OldArray->getElementType(), 3550 NewArray->getElementType())) 3551 MergedT = Old->getType(); 3552 } 3553 } 3554 else if (New->getType()->isObjCObjectPointerType() && 3555 Old->getType()->isObjCObjectPointerType()) { 3556 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3557 Old->getType()); 3558 } 3559 } else { 3560 // C 6.2.7p2: 3561 // All declarations that refer to the same object or function shall have 3562 // compatible type. 3563 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3564 } 3565 if (MergedT.isNull()) { 3566 // It's OK if we couldn't merge types if either type is dependent, for a 3567 // block-scope variable. In other cases (static data members of class 3568 // templates, variable templates, ...), we require the types to be 3569 // equivalent. 3570 // FIXME: The C++ standard doesn't say anything about this. 3571 if ((New->getType()->isDependentType() || 3572 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3573 // If the old type was dependent, we can't merge with it, so the new type 3574 // becomes dependent for now. We'll reproduce the original type when we 3575 // instantiate the TypeSourceInfo for the variable. 3576 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3577 New->setType(Context.DependentTy); 3578 return; 3579 } 3580 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3581 } 3582 3583 // Don't actually update the type on the new declaration if the old 3584 // declaration was an extern declaration in a different scope. 3585 if (MergeTypeWithOld) 3586 New->setType(MergedT); 3587 } 3588 3589 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3590 LookupResult &Previous) { 3591 // C11 6.2.7p4: 3592 // For an identifier with internal or external linkage declared 3593 // in a scope in which a prior declaration of that identifier is 3594 // visible, if the prior declaration specifies internal or 3595 // external linkage, the type of the identifier at the later 3596 // declaration becomes the composite type. 3597 // 3598 // If the variable isn't visible, we do not merge with its type. 3599 if (Previous.isShadowed()) 3600 return false; 3601 3602 if (S.getLangOpts().CPlusPlus) { 3603 // C++11 [dcl.array]p3: 3604 // If there is a preceding declaration of the entity in the same 3605 // scope in which the bound was specified, an omitted array bound 3606 // is taken to be the same as in that earlier declaration. 3607 return NewVD->isPreviousDeclInSameBlockScope() || 3608 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3609 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3610 } else { 3611 // If the old declaration was function-local, don't merge with its 3612 // type unless we're in the same function. 3613 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3614 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3615 } 3616 } 3617 3618 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3619 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3620 /// situation, merging decls or emitting diagnostics as appropriate. 3621 /// 3622 /// Tentative definition rules (C99 6.9.2p2) are checked by 3623 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3624 /// definitions here, since the initializer hasn't been attached. 3625 /// 3626 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3627 // If the new decl is already invalid, don't do any other checking. 3628 if (New->isInvalidDecl()) 3629 return; 3630 3631 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3632 return; 3633 3634 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3635 3636 // Verify the old decl was also a variable or variable template. 3637 VarDecl *Old = nullptr; 3638 VarTemplateDecl *OldTemplate = nullptr; 3639 if (Previous.isSingleResult()) { 3640 if (NewTemplate) { 3641 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3642 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3643 3644 if (auto *Shadow = 3645 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3646 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3647 return New->setInvalidDecl(); 3648 } else { 3649 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3650 3651 if (auto *Shadow = 3652 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3653 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3654 return New->setInvalidDecl(); 3655 } 3656 } 3657 if (!Old) { 3658 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3659 << New->getDeclName(); 3660 notePreviousDefinition(Previous.getRepresentativeDecl()->getLocation(), 3661 New->getLocation()); 3662 return New->setInvalidDecl(); 3663 } 3664 3665 // Ensure the template parameters are compatible. 3666 if (NewTemplate && 3667 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3668 OldTemplate->getTemplateParameters(), 3669 /*Complain=*/true, TPL_TemplateMatch)) 3670 return New->setInvalidDecl(); 3671 3672 // C++ [class.mem]p1: 3673 // A member shall not be declared twice in the member-specification [...] 3674 // 3675 // Here, we need only consider static data members. 3676 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3677 Diag(New->getLocation(), diag::err_duplicate_member) 3678 << New->getIdentifier(); 3679 Diag(Old->getLocation(), diag::note_previous_declaration); 3680 New->setInvalidDecl(); 3681 } 3682 3683 mergeDeclAttributes(New, Old); 3684 // Warn if an already-declared variable is made a weak_import in a subsequent 3685 // declaration 3686 if (New->hasAttr<WeakImportAttr>() && 3687 Old->getStorageClass() == SC_None && 3688 !Old->hasAttr<WeakImportAttr>()) { 3689 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3690 notePreviousDefinition(Old->getLocation(), New->getLocation()); 3691 // Remove weak_import attribute on new declaration. 3692 New->dropAttr<WeakImportAttr>(); 3693 } 3694 3695 if (New->hasAttr<InternalLinkageAttr>() && 3696 !Old->hasAttr<InternalLinkageAttr>()) { 3697 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3698 << New->getDeclName(); 3699 notePreviousDefinition(Old->getLocation(), New->getLocation()); 3700 New->dropAttr<InternalLinkageAttr>(); 3701 } 3702 3703 // Merge the types. 3704 VarDecl *MostRecent = Old->getMostRecentDecl(); 3705 if (MostRecent != Old) { 3706 MergeVarDeclTypes(New, MostRecent, 3707 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3708 if (New->isInvalidDecl()) 3709 return; 3710 } 3711 3712 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3713 if (New->isInvalidDecl()) 3714 return; 3715 3716 diag::kind PrevDiag; 3717 SourceLocation OldLocation; 3718 std::tie(PrevDiag, OldLocation) = 3719 getNoteDiagForInvalidRedeclaration(Old, New); 3720 3721 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3722 if (New->getStorageClass() == SC_Static && 3723 !New->isStaticDataMember() && 3724 Old->hasExternalFormalLinkage()) { 3725 if (getLangOpts().MicrosoftExt) { 3726 Diag(New->getLocation(), diag::ext_static_non_static) 3727 << New->getDeclName(); 3728 Diag(OldLocation, PrevDiag); 3729 } else { 3730 Diag(New->getLocation(), diag::err_static_non_static) 3731 << New->getDeclName(); 3732 Diag(OldLocation, PrevDiag); 3733 return New->setInvalidDecl(); 3734 } 3735 } 3736 // C99 6.2.2p4: 3737 // For an identifier declared with the storage-class specifier 3738 // extern in a scope in which a prior declaration of that 3739 // identifier is visible,23) if the prior declaration specifies 3740 // internal or external linkage, the linkage of the identifier at 3741 // the later declaration is the same as the linkage specified at 3742 // the prior declaration. If no prior declaration is visible, or 3743 // if the prior declaration specifies no linkage, then the 3744 // identifier has external linkage. 3745 if (New->hasExternalStorage() && Old->hasLinkage()) 3746 /* Okay */; 3747 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3748 !New->isStaticDataMember() && 3749 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3750 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3751 Diag(OldLocation, PrevDiag); 3752 return New->setInvalidDecl(); 3753 } 3754 3755 // Check if extern is followed by non-extern and vice-versa. 3756 if (New->hasExternalStorage() && 3757 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3758 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3759 Diag(OldLocation, PrevDiag); 3760 return New->setInvalidDecl(); 3761 } 3762 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3763 !New->hasExternalStorage()) { 3764 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3765 Diag(OldLocation, PrevDiag); 3766 return New->setInvalidDecl(); 3767 } 3768 3769 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3770 3771 // FIXME: The test for external storage here seems wrong? We still 3772 // need to check for mismatches. 3773 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3774 // Don't complain about out-of-line definitions of static members. 3775 !(Old->getLexicalDeclContext()->isRecord() && 3776 !New->getLexicalDeclContext()->isRecord())) { 3777 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3778 Diag(OldLocation, PrevDiag); 3779 return New->setInvalidDecl(); 3780 } 3781 3782 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3783 if (VarDecl *Def = Old->getDefinition()) { 3784 // C++1z [dcl.fcn.spec]p4: 3785 // If the definition of a variable appears in a translation unit before 3786 // its first declaration as inline, the program is ill-formed. 3787 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3788 Diag(Def->getLocation(), diag::note_previous_definition); 3789 } 3790 } 3791 3792 // If this redeclaration makes the function inline, we may need to add it to 3793 // UndefinedButUsed. 3794 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3795 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3796 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3797 SourceLocation())); 3798 3799 if (New->getTLSKind() != Old->getTLSKind()) { 3800 if (!Old->getTLSKind()) { 3801 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3802 Diag(OldLocation, PrevDiag); 3803 } else if (!New->getTLSKind()) { 3804 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3805 Diag(OldLocation, PrevDiag); 3806 } else { 3807 // Do not allow redeclaration to change the variable between requiring 3808 // static and dynamic initialization. 3809 // FIXME: GCC allows this, but uses the TLS keyword on the first 3810 // declaration to determine the kind. Do we need to be compatible here? 3811 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3812 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3813 Diag(OldLocation, PrevDiag); 3814 } 3815 } 3816 3817 // C++ doesn't have tentative definitions, so go right ahead and check here. 3818 if (getLangOpts().CPlusPlus && 3819 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3820 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 3821 Old->getCanonicalDecl()->isConstexpr()) { 3822 // This definition won't be a definition any more once it's been merged. 3823 Diag(New->getLocation(), 3824 diag::warn_deprecated_redundant_constexpr_static_def); 3825 } else if (VarDecl *Def = Old->getDefinition()) { 3826 if (checkVarDeclRedefinition(Def, New)) 3827 return; 3828 } 3829 } 3830 3831 if (haveIncompatibleLanguageLinkages(Old, New)) { 3832 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3833 Diag(OldLocation, PrevDiag); 3834 New->setInvalidDecl(); 3835 return; 3836 } 3837 3838 // Merge "used" flag. 3839 if (Old->getMostRecentDecl()->isUsed(false)) 3840 New->setIsUsed(); 3841 3842 // Keep a chain of previous declarations. 3843 New->setPreviousDecl(Old); 3844 if (NewTemplate) 3845 NewTemplate->setPreviousDecl(OldTemplate); 3846 3847 // Inherit access appropriately. 3848 New->setAccess(Old->getAccess()); 3849 if (NewTemplate) 3850 NewTemplate->setAccess(New->getAccess()); 3851 3852 if (Old->isInline()) 3853 New->setImplicitlyInline(); 3854 } 3855 3856 void Sema::notePreviousDefinition(SourceLocation Old, SourceLocation New) { 3857 SourceManager &SrcMgr = getSourceManager(); 3858 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 3859 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old); 3860 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 3861 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 3862 auto &HSI = PP.getHeaderSearchInfo(); 3863 StringRef HdrFilename = SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old)); 3864 3865 auto noteFromModuleOrInclude = [&](SourceLocation &Loc, 3866 SourceLocation &IncLoc) -> bool { 3867 Module *Mod = nullptr; 3868 // Redefinition errors with modules are common with non modular mapped 3869 // headers, example: a non-modular header H in module A that also gets 3870 // included directly in a TU. Pointing twice to the same header/definition 3871 // is confusing, try to get better diagnostics when modules is on. 3872 if (getLangOpts().Modules) { 3873 auto ModLoc = SrcMgr.getModuleImportLoc(Old); 3874 if (!ModLoc.first.isInvalid()) 3875 Mod = HSI.getModuleMap().inferModuleFromLocation( 3876 FullSourceLoc(Loc, SrcMgr)); 3877 } 3878 3879 if (IncLoc.isValid()) { 3880 if (Mod) { 3881 Diag(IncLoc, diag::note_redefinition_modules_same_file) 3882 << HdrFilename.str() << Mod->getFullModuleName(); 3883 if (!Mod->DefinitionLoc.isInvalid()) 3884 Diag(Mod->DefinitionLoc, diag::note_defined_here) 3885 << Mod->getFullModuleName(); 3886 } else { 3887 Diag(IncLoc, diag::note_redefinition_include_same_file) 3888 << HdrFilename.str(); 3889 } 3890 return true; 3891 } 3892 3893 return false; 3894 }; 3895 3896 // Is it the same file and same offset? Provide more information on why 3897 // this leads to a redefinition error. 3898 bool EmittedDiag = false; 3899 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 3900 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 3901 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 3902 EmittedDiag = noteFromModuleOrInclude(Old, OldIncLoc); 3903 EmittedDiag |= noteFromModuleOrInclude(New, NewIncLoc); 3904 3905 // If the header has no guards, emit a note suggesting one. 3906 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 3907 Diag(Old, diag::note_use_ifdef_guards); 3908 3909 if (EmittedDiag) 3910 return; 3911 } 3912 3913 // Redefinition coming from different files or couldn't do better above. 3914 Diag(Old, diag::note_previous_definition); 3915 } 3916 3917 /// We've just determined that \p Old and \p New both appear to be definitions 3918 /// of the same variable. Either diagnose or fix the problem. 3919 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 3920 if (!hasVisibleDefinition(Old) && 3921 (New->getFormalLinkage() == InternalLinkage || 3922 New->isInline() || 3923 New->getDescribedVarTemplate() || 3924 New->getNumTemplateParameterLists() || 3925 New->getDeclContext()->isDependentContext())) { 3926 // The previous definition is hidden, and multiple definitions are 3927 // permitted (in separate TUs). Demote this to a declaration. 3928 New->demoteThisDefinitionToDeclaration(); 3929 3930 // Make the canonical definition visible. 3931 if (auto *OldTD = Old->getDescribedVarTemplate()) 3932 makeMergedDefinitionVisible(OldTD); 3933 makeMergedDefinitionVisible(Old); 3934 return false; 3935 } else { 3936 Diag(New->getLocation(), diag::err_redefinition) << New; 3937 notePreviousDefinition(Old->getLocation(), New->getLocation()); 3938 New->setInvalidDecl(); 3939 return true; 3940 } 3941 } 3942 3943 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3944 /// no declarator (e.g. "struct foo;") is parsed. 3945 Decl * 3946 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3947 RecordDecl *&AnonRecord) { 3948 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 3949 AnonRecord); 3950 } 3951 3952 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 3953 // disambiguate entities defined in different scopes. 3954 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 3955 // compatibility. 3956 // We will pick our mangling number depending on which version of MSVC is being 3957 // targeted. 3958 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 3959 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 3960 ? S->getMSCurManglingNumber() 3961 : S->getMSLastManglingNumber(); 3962 } 3963 3964 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 3965 if (!Context.getLangOpts().CPlusPlus) 3966 return; 3967 3968 if (isa<CXXRecordDecl>(Tag->getParent())) { 3969 // If this tag is the direct child of a class, number it if 3970 // it is anonymous. 3971 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3972 return; 3973 MangleNumberingContext &MCtx = 3974 Context.getManglingNumberContext(Tag->getParent()); 3975 Context.setManglingNumber( 3976 Tag, MCtx.getManglingNumber( 3977 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3978 return; 3979 } 3980 3981 // If this tag isn't a direct child of a class, number it if it is local. 3982 Decl *ManglingContextDecl; 3983 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 3984 Tag->getDeclContext(), ManglingContextDecl)) { 3985 Context.setManglingNumber( 3986 Tag, MCtx->getManglingNumber( 3987 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3988 } 3989 } 3990 3991 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 3992 TypedefNameDecl *NewTD) { 3993 if (TagFromDeclSpec->isInvalidDecl()) 3994 return; 3995 3996 // Do nothing if the tag already has a name for linkage purposes. 3997 if (TagFromDeclSpec->hasNameForLinkage()) 3998 return; 3999 4000 // A well-formed anonymous tag must always be a TUK_Definition. 4001 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4002 4003 // The type must match the tag exactly; no qualifiers allowed. 4004 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4005 Context.getTagDeclType(TagFromDeclSpec))) { 4006 if (getLangOpts().CPlusPlus) 4007 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4008 return; 4009 } 4010 4011 // If we've already computed linkage for the anonymous tag, then 4012 // adding a typedef name for the anonymous decl can change that 4013 // linkage, which might be a serious problem. Diagnose this as 4014 // unsupported and ignore the typedef name. TODO: we should 4015 // pursue this as a language defect and establish a formal rule 4016 // for how to handle it. 4017 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4018 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4019 4020 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4021 tagLoc = getLocForEndOfToken(tagLoc); 4022 4023 llvm::SmallString<40> textToInsert; 4024 textToInsert += ' '; 4025 textToInsert += NewTD->getIdentifier()->getName(); 4026 Diag(tagLoc, diag::note_typedef_changes_linkage) 4027 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4028 return; 4029 } 4030 4031 // Otherwise, set this is the anon-decl typedef for the tag. 4032 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4033 } 4034 4035 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4036 switch (T) { 4037 case DeclSpec::TST_class: 4038 return 0; 4039 case DeclSpec::TST_struct: 4040 return 1; 4041 case DeclSpec::TST_interface: 4042 return 2; 4043 case DeclSpec::TST_union: 4044 return 3; 4045 case DeclSpec::TST_enum: 4046 return 4; 4047 default: 4048 llvm_unreachable("unexpected type specifier"); 4049 } 4050 } 4051 4052 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4053 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4054 /// parameters to cope with template friend declarations. 4055 Decl * 4056 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4057 MultiTemplateParamsArg TemplateParams, 4058 bool IsExplicitInstantiation, 4059 RecordDecl *&AnonRecord) { 4060 Decl *TagD = nullptr; 4061 TagDecl *Tag = nullptr; 4062 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4063 DS.getTypeSpecType() == DeclSpec::TST_struct || 4064 DS.getTypeSpecType() == DeclSpec::TST_interface || 4065 DS.getTypeSpecType() == DeclSpec::TST_union || 4066 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4067 TagD = DS.getRepAsDecl(); 4068 4069 if (!TagD) // We probably had an error 4070 return nullptr; 4071 4072 // Note that the above type specs guarantee that the 4073 // type rep is a Decl, whereas in many of the others 4074 // it's a Type. 4075 if (isa<TagDecl>(TagD)) 4076 Tag = cast<TagDecl>(TagD); 4077 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4078 Tag = CTD->getTemplatedDecl(); 4079 } 4080 4081 if (Tag) { 4082 handleTagNumbering(Tag, S); 4083 Tag->setFreeStanding(); 4084 if (Tag->isInvalidDecl()) 4085 return Tag; 4086 } 4087 4088 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4089 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4090 // or incomplete types shall not be restrict-qualified." 4091 if (TypeQuals & DeclSpec::TQ_restrict) 4092 Diag(DS.getRestrictSpecLoc(), 4093 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4094 << DS.getSourceRange(); 4095 } 4096 4097 if (DS.isInlineSpecified()) 4098 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4099 << getLangOpts().CPlusPlus1z; 4100 4101 if (DS.isConstexprSpecified()) { 4102 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4103 // and definitions of functions and variables. 4104 if (Tag) 4105 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4106 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 4107 else 4108 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 4109 // Don't emit warnings after this error. 4110 return TagD; 4111 } 4112 4113 if (DS.isConceptSpecified()) { 4114 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to 4115 // either a function concept and its definition or a variable concept and 4116 // its initializer. 4117 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 4118 return TagD; 4119 } 4120 4121 DiagnoseFunctionSpecifiers(DS); 4122 4123 if (DS.isFriendSpecified()) { 4124 // If we're dealing with a decl but not a TagDecl, assume that 4125 // whatever routines created it handled the friendship aspect. 4126 if (TagD && !Tag) 4127 return nullptr; 4128 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4129 } 4130 4131 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4132 bool IsExplicitSpecialization = 4133 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4134 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4135 !IsExplicitInstantiation && !IsExplicitSpecialization && 4136 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4137 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4138 // nested-name-specifier unless it is an explicit instantiation 4139 // or an explicit specialization. 4140 // 4141 // FIXME: We allow class template partial specializations here too, per the 4142 // obvious intent of DR1819. 4143 // 4144 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4145 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4146 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4147 return nullptr; 4148 } 4149 4150 // Track whether this decl-specifier declares anything. 4151 bool DeclaresAnything = true; 4152 4153 // Handle anonymous struct definitions. 4154 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4155 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4156 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4157 if (getLangOpts().CPlusPlus || 4158 Record->getDeclContext()->isRecord()) { 4159 // If CurContext is a DeclContext that can contain statements, 4160 // RecursiveASTVisitor won't visit the decls that 4161 // BuildAnonymousStructOrUnion() will put into CurContext. 4162 // Also store them here so that they can be part of the 4163 // DeclStmt that gets created in this case. 4164 // FIXME: Also return the IndirectFieldDecls created by 4165 // BuildAnonymousStructOr union, for the same reason? 4166 if (CurContext->isFunctionOrMethod()) 4167 AnonRecord = Record; 4168 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4169 Context.getPrintingPolicy()); 4170 } 4171 4172 DeclaresAnything = false; 4173 } 4174 } 4175 4176 // C11 6.7.2.1p2: 4177 // A struct-declaration that does not declare an anonymous structure or 4178 // anonymous union shall contain a struct-declarator-list. 4179 // 4180 // This rule also existed in C89 and C99; the grammar for struct-declaration 4181 // did not permit a struct-declaration without a struct-declarator-list. 4182 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4183 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4184 // Check for Microsoft C extension: anonymous struct/union member. 4185 // Handle 2 kinds of anonymous struct/union: 4186 // struct STRUCT; 4187 // union UNION; 4188 // and 4189 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4190 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4191 if ((Tag && Tag->getDeclName()) || 4192 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4193 RecordDecl *Record = nullptr; 4194 if (Tag) 4195 Record = dyn_cast<RecordDecl>(Tag); 4196 else if (const RecordType *RT = 4197 DS.getRepAsType().get()->getAsStructureType()) 4198 Record = RT->getDecl(); 4199 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4200 Record = UT->getDecl(); 4201 4202 if (Record && getLangOpts().MicrosoftExt) { 4203 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 4204 << Record->isUnion() << DS.getSourceRange(); 4205 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4206 } 4207 4208 DeclaresAnything = false; 4209 } 4210 } 4211 4212 // Skip all the checks below if we have a type error. 4213 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4214 (TagD && TagD->isInvalidDecl())) 4215 return TagD; 4216 4217 if (getLangOpts().CPlusPlus && 4218 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4219 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4220 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4221 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4222 DeclaresAnything = false; 4223 4224 if (!DS.isMissingDeclaratorOk()) { 4225 // Customize diagnostic for a typedef missing a name. 4226 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4227 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 4228 << DS.getSourceRange(); 4229 else 4230 DeclaresAnything = false; 4231 } 4232 4233 if (DS.isModulePrivateSpecified() && 4234 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4235 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4236 << Tag->getTagKind() 4237 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4238 4239 ActOnDocumentableDecl(TagD); 4240 4241 // C 6.7/2: 4242 // A declaration [...] shall declare at least a declarator [...], a tag, 4243 // or the members of an enumeration. 4244 // C++ [dcl.dcl]p3: 4245 // [If there are no declarators], and except for the declaration of an 4246 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4247 // names into the program, or shall redeclare a name introduced by a 4248 // previous declaration. 4249 if (!DeclaresAnything) { 4250 // In C, we allow this as a (popular) extension / bug. Don't bother 4251 // producing further diagnostics for redundant qualifiers after this. 4252 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 4253 return TagD; 4254 } 4255 4256 // C++ [dcl.stc]p1: 4257 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4258 // init-declarator-list of the declaration shall not be empty. 4259 // C++ [dcl.fct.spec]p1: 4260 // If a cv-qualifier appears in a decl-specifier-seq, the 4261 // init-declarator-list of the declaration shall not be empty. 4262 // 4263 // Spurious qualifiers here appear to be valid in C. 4264 unsigned DiagID = diag::warn_standalone_specifier; 4265 if (getLangOpts().CPlusPlus) 4266 DiagID = diag::ext_standalone_specifier; 4267 4268 // Note that a linkage-specification sets a storage class, but 4269 // 'extern "C" struct foo;' is actually valid and not theoretically 4270 // useless. 4271 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4272 if (SCS == DeclSpec::SCS_mutable) 4273 // Since mutable is not a viable storage class specifier in C, there is 4274 // no reason to treat it as an extension. Instead, diagnose as an error. 4275 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4276 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4277 Diag(DS.getStorageClassSpecLoc(), DiagID) 4278 << DeclSpec::getSpecifierName(SCS); 4279 } 4280 4281 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4282 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4283 << DeclSpec::getSpecifierName(TSCS); 4284 if (DS.getTypeQualifiers()) { 4285 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4286 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4287 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4288 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4289 // Restrict is covered above. 4290 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4291 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4292 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4293 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4294 } 4295 4296 // Warn about ignored type attributes, for example: 4297 // __attribute__((aligned)) struct A; 4298 // Attributes should be placed after tag to apply to type declaration. 4299 if (!DS.getAttributes().empty()) { 4300 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4301 if (TypeSpecType == DeclSpec::TST_class || 4302 TypeSpecType == DeclSpec::TST_struct || 4303 TypeSpecType == DeclSpec::TST_interface || 4304 TypeSpecType == DeclSpec::TST_union || 4305 TypeSpecType == DeclSpec::TST_enum) { 4306 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4307 attrs = attrs->getNext()) 4308 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4309 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4310 } 4311 } 4312 4313 return TagD; 4314 } 4315 4316 /// We are trying to inject an anonymous member into the given scope; 4317 /// check if there's an existing declaration that can't be overloaded. 4318 /// 4319 /// \return true if this is a forbidden redeclaration 4320 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4321 Scope *S, 4322 DeclContext *Owner, 4323 DeclarationName Name, 4324 SourceLocation NameLoc, 4325 bool IsUnion) { 4326 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4327 Sema::ForRedeclaration); 4328 if (!SemaRef.LookupName(R, S)) return false; 4329 4330 // Pick a representative declaration. 4331 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4332 assert(PrevDecl && "Expected a non-null Decl"); 4333 4334 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4335 return false; 4336 4337 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4338 << IsUnion << Name; 4339 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4340 4341 return true; 4342 } 4343 4344 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4345 /// anonymous struct or union AnonRecord into the owning context Owner 4346 /// and scope S. This routine will be invoked just after we realize 4347 /// that an unnamed union or struct is actually an anonymous union or 4348 /// struct, e.g., 4349 /// 4350 /// @code 4351 /// union { 4352 /// int i; 4353 /// float f; 4354 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4355 /// // f into the surrounding scope.x 4356 /// @endcode 4357 /// 4358 /// This routine is recursive, injecting the names of nested anonymous 4359 /// structs/unions into the owning context and scope as well. 4360 static bool 4361 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4362 RecordDecl *AnonRecord, AccessSpecifier AS, 4363 SmallVectorImpl<NamedDecl *> &Chaining) { 4364 bool Invalid = false; 4365 4366 // Look every FieldDecl and IndirectFieldDecl with a name. 4367 for (auto *D : AnonRecord->decls()) { 4368 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4369 cast<NamedDecl>(D)->getDeclName()) { 4370 ValueDecl *VD = cast<ValueDecl>(D); 4371 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4372 VD->getLocation(), 4373 AnonRecord->isUnion())) { 4374 // C++ [class.union]p2: 4375 // The names of the members of an anonymous union shall be 4376 // distinct from the names of any other entity in the 4377 // scope in which the anonymous union is declared. 4378 Invalid = true; 4379 } else { 4380 // C++ [class.union]p2: 4381 // For the purpose of name lookup, after the anonymous union 4382 // definition, the members of the anonymous union are 4383 // considered to have been defined in the scope in which the 4384 // anonymous union is declared. 4385 unsigned OldChainingSize = Chaining.size(); 4386 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4387 Chaining.append(IF->chain_begin(), IF->chain_end()); 4388 else 4389 Chaining.push_back(VD); 4390 4391 assert(Chaining.size() >= 2); 4392 NamedDecl **NamedChain = 4393 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4394 for (unsigned i = 0; i < Chaining.size(); i++) 4395 NamedChain[i] = Chaining[i]; 4396 4397 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4398 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4399 VD->getType(), {NamedChain, Chaining.size()}); 4400 4401 for (const auto *Attr : VD->attrs()) 4402 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4403 4404 IndirectField->setAccess(AS); 4405 IndirectField->setImplicit(); 4406 SemaRef.PushOnScopeChains(IndirectField, S); 4407 4408 // That includes picking up the appropriate access specifier. 4409 if (AS != AS_none) IndirectField->setAccess(AS); 4410 4411 Chaining.resize(OldChainingSize); 4412 } 4413 } 4414 } 4415 4416 return Invalid; 4417 } 4418 4419 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4420 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4421 /// illegal input values are mapped to SC_None. 4422 static StorageClass 4423 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4424 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4425 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4426 "Parser allowed 'typedef' as storage class VarDecl."); 4427 switch (StorageClassSpec) { 4428 case DeclSpec::SCS_unspecified: return SC_None; 4429 case DeclSpec::SCS_extern: 4430 if (DS.isExternInLinkageSpec()) 4431 return SC_None; 4432 return SC_Extern; 4433 case DeclSpec::SCS_static: return SC_Static; 4434 case DeclSpec::SCS_auto: return SC_Auto; 4435 case DeclSpec::SCS_register: return SC_Register; 4436 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4437 // Illegal SCSs map to None: error reporting is up to the caller. 4438 case DeclSpec::SCS_mutable: // Fall through. 4439 case DeclSpec::SCS_typedef: return SC_None; 4440 } 4441 llvm_unreachable("unknown storage class specifier"); 4442 } 4443 4444 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4445 assert(Record->hasInClassInitializer()); 4446 4447 for (const auto *I : Record->decls()) { 4448 const auto *FD = dyn_cast<FieldDecl>(I); 4449 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4450 FD = IFD->getAnonField(); 4451 if (FD && FD->hasInClassInitializer()) 4452 return FD->getLocation(); 4453 } 4454 4455 llvm_unreachable("couldn't find in-class initializer"); 4456 } 4457 4458 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4459 SourceLocation DefaultInitLoc) { 4460 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4461 return; 4462 4463 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4464 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4465 } 4466 4467 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4468 CXXRecordDecl *AnonUnion) { 4469 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4470 return; 4471 4472 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4473 } 4474 4475 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4476 /// anonymous structure or union. Anonymous unions are a C++ feature 4477 /// (C++ [class.union]) and a C11 feature; anonymous structures 4478 /// are a C11 feature and GNU C++ extension. 4479 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4480 AccessSpecifier AS, 4481 RecordDecl *Record, 4482 const PrintingPolicy &Policy) { 4483 DeclContext *Owner = Record->getDeclContext(); 4484 4485 // Diagnose whether this anonymous struct/union is an extension. 4486 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4487 Diag(Record->getLocation(), diag::ext_anonymous_union); 4488 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4489 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4490 else if (!Record->isUnion() && !getLangOpts().C11) 4491 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4492 4493 // C and C++ require different kinds of checks for anonymous 4494 // structs/unions. 4495 bool Invalid = false; 4496 if (getLangOpts().CPlusPlus) { 4497 const char *PrevSpec = nullptr; 4498 unsigned DiagID; 4499 if (Record->isUnion()) { 4500 // C++ [class.union]p6: 4501 // Anonymous unions declared in a named namespace or in the 4502 // global namespace shall be declared static. 4503 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4504 (isa<TranslationUnitDecl>(Owner) || 4505 (isa<NamespaceDecl>(Owner) && 4506 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4507 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4508 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4509 4510 // Recover by adding 'static'. 4511 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4512 PrevSpec, DiagID, Policy); 4513 } 4514 // C++ [class.union]p6: 4515 // A storage class is not allowed in a declaration of an 4516 // anonymous union in a class scope. 4517 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4518 isa<RecordDecl>(Owner)) { 4519 Diag(DS.getStorageClassSpecLoc(), 4520 diag::err_anonymous_union_with_storage_spec) 4521 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4522 4523 // Recover by removing the storage specifier. 4524 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4525 SourceLocation(), 4526 PrevSpec, DiagID, Context.getPrintingPolicy()); 4527 } 4528 } 4529 4530 // Ignore const/volatile/restrict qualifiers. 4531 if (DS.getTypeQualifiers()) { 4532 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4533 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4534 << Record->isUnion() << "const" 4535 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4536 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4537 Diag(DS.getVolatileSpecLoc(), 4538 diag::ext_anonymous_struct_union_qualified) 4539 << Record->isUnion() << "volatile" 4540 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4541 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4542 Diag(DS.getRestrictSpecLoc(), 4543 diag::ext_anonymous_struct_union_qualified) 4544 << Record->isUnion() << "restrict" 4545 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4546 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4547 Diag(DS.getAtomicSpecLoc(), 4548 diag::ext_anonymous_struct_union_qualified) 4549 << Record->isUnion() << "_Atomic" 4550 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4551 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4552 Diag(DS.getUnalignedSpecLoc(), 4553 diag::ext_anonymous_struct_union_qualified) 4554 << Record->isUnion() << "__unaligned" 4555 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4556 4557 DS.ClearTypeQualifiers(); 4558 } 4559 4560 // C++ [class.union]p2: 4561 // The member-specification of an anonymous union shall only 4562 // define non-static data members. [Note: nested types and 4563 // functions cannot be declared within an anonymous union. ] 4564 for (auto *Mem : Record->decls()) { 4565 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4566 // C++ [class.union]p3: 4567 // An anonymous union shall not have private or protected 4568 // members (clause 11). 4569 assert(FD->getAccess() != AS_none); 4570 if (FD->getAccess() != AS_public) { 4571 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4572 << Record->isUnion() << (FD->getAccess() == AS_protected); 4573 Invalid = true; 4574 } 4575 4576 // C++ [class.union]p1 4577 // An object of a class with a non-trivial constructor, a non-trivial 4578 // copy constructor, a non-trivial destructor, or a non-trivial copy 4579 // assignment operator cannot be a member of a union, nor can an 4580 // array of such objects. 4581 if (CheckNontrivialField(FD)) 4582 Invalid = true; 4583 } else if (Mem->isImplicit()) { 4584 // Any implicit members are fine. 4585 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4586 // This is a type that showed up in an 4587 // elaborated-type-specifier inside the anonymous struct or 4588 // union, but which actually declares a type outside of the 4589 // anonymous struct or union. It's okay. 4590 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4591 if (!MemRecord->isAnonymousStructOrUnion() && 4592 MemRecord->getDeclName()) { 4593 // Visual C++ allows type definition in anonymous struct or union. 4594 if (getLangOpts().MicrosoftExt) 4595 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4596 << Record->isUnion(); 4597 else { 4598 // This is a nested type declaration. 4599 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4600 << Record->isUnion(); 4601 Invalid = true; 4602 } 4603 } else { 4604 // This is an anonymous type definition within another anonymous type. 4605 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4606 // not part of standard C++. 4607 Diag(MemRecord->getLocation(), 4608 diag::ext_anonymous_record_with_anonymous_type) 4609 << Record->isUnion(); 4610 } 4611 } else if (isa<AccessSpecDecl>(Mem)) { 4612 // Any access specifier is fine. 4613 } else if (isa<StaticAssertDecl>(Mem)) { 4614 // In C++1z, static_assert declarations are also fine. 4615 } else { 4616 // We have something that isn't a non-static data 4617 // member. Complain about it. 4618 unsigned DK = diag::err_anonymous_record_bad_member; 4619 if (isa<TypeDecl>(Mem)) 4620 DK = diag::err_anonymous_record_with_type; 4621 else if (isa<FunctionDecl>(Mem)) 4622 DK = diag::err_anonymous_record_with_function; 4623 else if (isa<VarDecl>(Mem)) 4624 DK = diag::err_anonymous_record_with_static; 4625 4626 // Visual C++ allows type definition in anonymous struct or union. 4627 if (getLangOpts().MicrosoftExt && 4628 DK == diag::err_anonymous_record_with_type) 4629 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4630 << Record->isUnion(); 4631 else { 4632 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4633 Invalid = true; 4634 } 4635 } 4636 } 4637 4638 // C++11 [class.union]p8 (DR1460): 4639 // At most one variant member of a union may have a 4640 // brace-or-equal-initializer. 4641 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4642 Owner->isRecord()) 4643 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4644 cast<CXXRecordDecl>(Record)); 4645 } 4646 4647 if (!Record->isUnion() && !Owner->isRecord()) { 4648 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4649 << getLangOpts().CPlusPlus; 4650 Invalid = true; 4651 } 4652 4653 // Mock up a declarator. 4654 Declarator Dc(DS, Declarator::MemberContext); 4655 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4656 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4657 4658 // Create a declaration for this anonymous struct/union. 4659 NamedDecl *Anon = nullptr; 4660 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4661 Anon = FieldDecl::Create(Context, OwningClass, 4662 DS.getLocStart(), 4663 Record->getLocation(), 4664 /*IdentifierInfo=*/nullptr, 4665 Context.getTypeDeclType(Record), 4666 TInfo, 4667 /*BitWidth=*/nullptr, /*Mutable=*/false, 4668 /*InitStyle=*/ICIS_NoInit); 4669 Anon->setAccess(AS); 4670 if (getLangOpts().CPlusPlus) 4671 FieldCollector->Add(cast<FieldDecl>(Anon)); 4672 } else { 4673 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4674 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4675 if (SCSpec == DeclSpec::SCS_mutable) { 4676 // mutable can only appear on non-static class members, so it's always 4677 // an error here 4678 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4679 Invalid = true; 4680 SC = SC_None; 4681 } 4682 4683 Anon = VarDecl::Create(Context, Owner, 4684 DS.getLocStart(), 4685 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4686 Context.getTypeDeclType(Record), 4687 TInfo, SC); 4688 4689 // Default-initialize the implicit variable. This initialization will be 4690 // trivial in almost all cases, except if a union member has an in-class 4691 // initializer: 4692 // union { int n = 0; }; 4693 ActOnUninitializedDecl(Anon); 4694 } 4695 Anon->setImplicit(); 4696 4697 // Mark this as an anonymous struct/union type. 4698 Record->setAnonymousStructOrUnion(true); 4699 4700 // Add the anonymous struct/union object to the current 4701 // context. We'll be referencing this object when we refer to one of 4702 // its members. 4703 Owner->addDecl(Anon); 4704 4705 // Inject the members of the anonymous struct/union into the owning 4706 // context and into the identifier resolver chain for name lookup 4707 // purposes. 4708 SmallVector<NamedDecl*, 2> Chain; 4709 Chain.push_back(Anon); 4710 4711 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4712 Invalid = true; 4713 4714 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4715 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4716 Decl *ManglingContextDecl; 4717 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4718 NewVD->getDeclContext(), ManglingContextDecl)) { 4719 Context.setManglingNumber( 4720 NewVD, MCtx->getManglingNumber( 4721 NewVD, getMSManglingNumber(getLangOpts(), S))); 4722 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4723 } 4724 } 4725 } 4726 4727 if (Invalid) 4728 Anon->setInvalidDecl(); 4729 4730 return Anon; 4731 } 4732 4733 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4734 /// Microsoft C anonymous structure. 4735 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4736 /// Example: 4737 /// 4738 /// struct A { int a; }; 4739 /// struct B { struct A; int b; }; 4740 /// 4741 /// void foo() { 4742 /// B var; 4743 /// var.a = 3; 4744 /// } 4745 /// 4746 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4747 RecordDecl *Record) { 4748 assert(Record && "expected a record!"); 4749 4750 // Mock up a declarator. 4751 Declarator Dc(DS, Declarator::TypeNameContext); 4752 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4753 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4754 4755 auto *ParentDecl = cast<RecordDecl>(CurContext); 4756 QualType RecTy = Context.getTypeDeclType(Record); 4757 4758 // Create a declaration for this anonymous struct. 4759 NamedDecl *Anon = FieldDecl::Create(Context, 4760 ParentDecl, 4761 DS.getLocStart(), 4762 DS.getLocStart(), 4763 /*IdentifierInfo=*/nullptr, 4764 RecTy, 4765 TInfo, 4766 /*BitWidth=*/nullptr, /*Mutable=*/false, 4767 /*InitStyle=*/ICIS_NoInit); 4768 Anon->setImplicit(); 4769 4770 // Add the anonymous struct object to the current context. 4771 CurContext->addDecl(Anon); 4772 4773 // Inject the members of the anonymous struct into the current 4774 // context and into the identifier resolver chain for name lookup 4775 // purposes. 4776 SmallVector<NamedDecl*, 2> Chain; 4777 Chain.push_back(Anon); 4778 4779 RecordDecl *RecordDef = Record->getDefinition(); 4780 if (RequireCompleteType(Anon->getLocation(), RecTy, 4781 diag::err_field_incomplete) || 4782 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4783 AS_none, Chain)) { 4784 Anon->setInvalidDecl(); 4785 ParentDecl->setInvalidDecl(); 4786 } 4787 4788 return Anon; 4789 } 4790 4791 /// GetNameForDeclarator - Determine the full declaration name for the 4792 /// given Declarator. 4793 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4794 return GetNameFromUnqualifiedId(D.getName()); 4795 } 4796 4797 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4798 DeclarationNameInfo 4799 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4800 DeclarationNameInfo NameInfo; 4801 NameInfo.setLoc(Name.StartLocation); 4802 4803 switch (Name.getKind()) { 4804 4805 case UnqualifiedId::IK_ImplicitSelfParam: 4806 case UnqualifiedId::IK_Identifier: 4807 NameInfo.setName(Name.Identifier); 4808 NameInfo.setLoc(Name.StartLocation); 4809 return NameInfo; 4810 4811 case UnqualifiedId::IK_DeductionGuideName: { 4812 // C++ [temp.deduct.guide]p3: 4813 // The simple-template-id shall name a class template specialization. 4814 // The template-name shall be the same identifier as the template-name 4815 // of the simple-template-id. 4816 // These together intend to imply that the template-name shall name a 4817 // class template. 4818 // FIXME: template<typename T> struct X {}; 4819 // template<typename T> using Y = X<T>; 4820 // Y(int) -> Y<int>; 4821 // satisfies these rules but does not name a class template. 4822 TemplateName TN = Name.TemplateName.get().get(); 4823 auto *Template = TN.getAsTemplateDecl(); 4824 if (!Template || !isa<ClassTemplateDecl>(Template)) { 4825 Diag(Name.StartLocation, 4826 diag::err_deduction_guide_name_not_class_template) 4827 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 4828 if (Template) 4829 Diag(Template->getLocation(), diag::note_template_decl_here); 4830 return DeclarationNameInfo(); 4831 } 4832 4833 NameInfo.setName( 4834 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 4835 NameInfo.setLoc(Name.StartLocation); 4836 return NameInfo; 4837 } 4838 4839 case UnqualifiedId::IK_OperatorFunctionId: 4840 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4841 Name.OperatorFunctionId.Operator)); 4842 NameInfo.setLoc(Name.StartLocation); 4843 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4844 = Name.OperatorFunctionId.SymbolLocations[0]; 4845 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4846 = Name.EndLocation.getRawEncoding(); 4847 return NameInfo; 4848 4849 case UnqualifiedId::IK_LiteralOperatorId: 4850 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4851 Name.Identifier)); 4852 NameInfo.setLoc(Name.StartLocation); 4853 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4854 return NameInfo; 4855 4856 case UnqualifiedId::IK_ConversionFunctionId: { 4857 TypeSourceInfo *TInfo; 4858 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4859 if (Ty.isNull()) 4860 return DeclarationNameInfo(); 4861 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4862 Context.getCanonicalType(Ty))); 4863 NameInfo.setLoc(Name.StartLocation); 4864 NameInfo.setNamedTypeInfo(TInfo); 4865 return NameInfo; 4866 } 4867 4868 case UnqualifiedId::IK_ConstructorName: { 4869 TypeSourceInfo *TInfo; 4870 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4871 if (Ty.isNull()) 4872 return DeclarationNameInfo(); 4873 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4874 Context.getCanonicalType(Ty))); 4875 NameInfo.setLoc(Name.StartLocation); 4876 NameInfo.setNamedTypeInfo(TInfo); 4877 return NameInfo; 4878 } 4879 4880 case UnqualifiedId::IK_ConstructorTemplateId: { 4881 // In well-formed code, we can only have a constructor 4882 // template-id that refers to the current context, so go there 4883 // to find the actual type being constructed. 4884 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4885 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4886 return DeclarationNameInfo(); 4887 4888 // Determine the type of the class being constructed. 4889 QualType CurClassType = Context.getTypeDeclType(CurClass); 4890 4891 // FIXME: Check two things: that the template-id names the same type as 4892 // CurClassType, and that the template-id does not occur when the name 4893 // was qualified. 4894 4895 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4896 Context.getCanonicalType(CurClassType))); 4897 NameInfo.setLoc(Name.StartLocation); 4898 // FIXME: should we retrieve TypeSourceInfo? 4899 NameInfo.setNamedTypeInfo(nullptr); 4900 return NameInfo; 4901 } 4902 4903 case UnqualifiedId::IK_DestructorName: { 4904 TypeSourceInfo *TInfo; 4905 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4906 if (Ty.isNull()) 4907 return DeclarationNameInfo(); 4908 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4909 Context.getCanonicalType(Ty))); 4910 NameInfo.setLoc(Name.StartLocation); 4911 NameInfo.setNamedTypeInfo(TInfo); 4912 return NameInfo; 4913 } 4914 4915 case UnqualifiedId::IK_TemplateId: { 4916 TemplateName TName = Name.TemplateId->Template.get(); 4917 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4918 return Context.getNameForTemplate(TName, TNameLoc); 4919 } 4920 4921 } // switch (Name.getKind()) 4922 4923 llvm_unreachable("Unknown name kind"); 4924 } 4925 4926 static QualType getCoreType(QualType Ty) { 4927 do { 4928 if (Ty->isPointerType() || Ty->isReferenceType()) 4929 Ty = Ty->getPointeeType(); 4930 else if (Ty->isArrayType()) 4931 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4932 else 4933 return Ty.withoutLocalFastQualifiers(); 4934 } while (true); 4935 } 4936 4937 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4938 /// and Definition have "nearly" matching parameters. This heuristic is 4939 /// used to improve diagnostics in the case where an out-of-line function 4940 /// definition doesn't match any declaration within the class or namespace. 4941 /// Also sets Params to the list of indices to the parameters that differ 4942 /// between the declaration and the definition. If hasSimilarParameters 4943 /// returns true and Params is empty, then all of the parameters match. 4944 static bool hasSimilarParameters(ASTContext &Context, 4945 FunctionDecl *Declaration, 4946 FunctionDecl *Definition, 4947 SmallVectorImpl<unsigned> &Params) { 4948 Params.clear(); 4949 if (Declaration->param_size() != Definition->param_size()) 4950 return false; 4951 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4952 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4953 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4954 4955 // The parameter types are identical 4956 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4957 continue; 4958 4959 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4960 QualType DefParamBaseTy = getCoreType(DefParamTy); 4961 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4962 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4963 4964 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4965 (DeclTyName && DeclTyName == DefTyName)) 4966 Params.push_back(Idx); 4967 else // The two parameters aren't even close 4968 return false; 4969 } 4970 4971 return true; 4972 } 4973 4974 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4975 /// declarator needs to be rebuilt in the current instantiation. 4976 /// Any bits of declarator which appear before the name are valid for 4977 /// consideration here. That's specifically the type in the decl spec 4978 /// and the base type in any member-pointer chunks. 4979 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4980 DeclarationName Name) { 4981 // The types we specifically need to rebuild are: 4982 // - typenames, typeofs, and decltypes 4983 // - types which will become injected class names 4984 // Of course, we also need to rebuild any type referencing such a 4985 // type. It's safest to just say "dependent", but we call out a 4986 // few cases here. 4987 4988 DeclSpec &DS = D.getMutableDeclSpec(); 4989 switch (DS.getTypeSpecType()) { 4990 case DeclSpec::TST_typename: 4991 case DeclSpec::TST_typeofType: 4992 case DeclSpec::TST_underlyingType: 4993 case DeclSpec::TST_atomic: { 4994 // Grab the type from the parser. 4995 TypeSourceInfo *TSI = nullptr; 4996 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4997 if (T.isNull() || !T->isDependentType()) break; 4998 4999 // Make sure there's a type source info. This isn't really much 5000 // of a waste; most dependent types should have type source info 5001 // attached already. 5002 if (!TSI) 5003 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5004 5005 // Rebuild the type in the current instantiation. 5006 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5007 if (!TSI) return true; 5008 5009 // Store the new type back in the decl spec. 5010 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5011 DS.UpdateTypeRep(LocType); 5012 break; 5013 } 5014 5015 case DeclSpec::TST_decltype: 5016 case DeclSpec::TST_typeofExpr: { 5017 Expr *E = DS.getRepAsExpr(); 5018 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5019 if (Result.isInvalid()) return true; 5020 DS.UpdateExprRep(Result.get()); 5021 break; 5022 } 5023 5024 default: 5025 // Nothing to do for these decl specs. 5026 break; 5027 } 5028 5029 // It doesn't matter what order we do this in. 5030 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5031 DeclaratorChunk &Chunk = D.getTypeObject(I); 5032 5033 // The only type information in the declarator which can come 5034 // before the declaration name is the base type of a member 5035 // pointer. 5036 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5037 continue; 5038 5039 // Rebuild the scope specifier in-place. 5040 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5041 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5042 return true; 5043 } 5044 5045 return false; 5046 } 5047 5048 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5049 D.setFunctionDefinitionKind(FDK_Declaration); 5050 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5051 5052 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5053 Dcl && Dcl->getDeclContext()->isFileContext()) 5054 Dcl->setTopLevelDeclInObjCContainer(); 5055 5056 if (getLangOpts().OpenCL) 5057 setCurrentOpenCLExtensionForDecl(Dcl); 5058 5059 return Dcl; 5060 } 5061 5062 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5063 /// If T is the name of a class, then each of the following shall have a 5064 /// name different from T: 5065 /// - every static data member of class T; 5066 /// - every member function of class T 5067 /// - every member of class T that is itself a type; 5068 /// \returns true if the declaration name violates these rules. 5069 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5070 DeclarationNameInfo NameInfo) { 5071 DeclarationName Name = NameInfo.getName(); 5072 5073 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5074 while (Record && Record->isAnonymousStructOrUnion()) 5075 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5076 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5077 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5078 return true; 5079 } 5080 5081 return false; 5082 } 5083 5084 /// \brief Diagnose a declaration whose declarator-id has the given 5085 /// nested-name-specifier. 5086 /// 5087 /// \param SS The nested-name-specifier of the declarator-id. 5088 /// 5089 /// \param DC The declaration context to which the nested-name-specifier 5090 /// resolves. 5091 /// 5092 /// \param Name The name of the entity being declared. 5093 /// 5094 /// \param Loc The location of the name of the entity being declared. 5095 /// 5096 /// \returns true if we cannot safely recover from this error, false otherwise. 5097 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5098 DeclarationName Name, 5099 SourceLocation Loc) { 5100 DeclContext *Cur = CurContext; 5101 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5102 Cur = Cur->getParent(); 5103 5104 // If the user provided a superfluous scope specifier that refers back to the 5105 // class in which the entity is already declared, diagnose and ignore it. 5106 // 5107 // class X { 5108 // void X::f(); 5109 // }; 5110 // 5111 // Note, it was once ill-formed to give redundant qualification in all 5112 // contexts, but that rule was removed by DR482. 5113 if (Cur->Equals(DC)) { 5114 if (Cur->isRecord()) { 5115 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5116 : diag::err_member_extra_qualification) 5117 << Name << FixItHint::CreateRemoval(SS.getRange()); 5118 SS.clear(); 5119 } else { 5120 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5121 } 5122 return false; 5123 } 5124 5125 // Check whether the qualifying scope encloses the scope of the original 5126 // declaration. 5127 if (!Cur->Encloses(DC)) { 5128 if (Cur->isRecord()) 5129 Diag(Loc, diag::err_member_qualification) 5130 << Name << SS.getRange(); 5131 else if (isa<TranslationUnitDecl>(DC)) 5132 Diag(Loc, diag::err_invalid_declarator_global_scope) 5133 << Name << SS.getRange(); 5134 else if (isa<FunctionDecl>(Cur)) 5135 Diag(Loc, diag::err_invalid_declarator_in_function) 5136 << Name << SS.getRange(); 5137 else if (isa<BlockDecl>(Cur)) 5138 Diag(Loc, diag::err_invalid_declarator_in_block) 5139 << Name << SS.getRange(); 5140 else 5141 Diag(Loc, diag::err_invalid_declarator_scope) 5142 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5143 5144 return true; 5145 } 5146 5147 if (Cur->isRecord()) { 5148 // Cannot qualify members within a class. 5149 Diag(Loc, diag::err_member_qualification) 5150 << Name << SS.getRange(); 5151 SS.clear(); 5152 5153 // C++ constructors and destructors with incorrect scopes can break 5154 // our AST invariants by having the wrong underlying types. If 5155 // that's the case, then drop this declaration entirely. 5156 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5157 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5158 !Context.hasSameType(Name.getCXXNameType(), 5159 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5160 return true; 5161 5162 return false; 5163 } 5164 5165 // C++11 [dcl.meaning]p1: 5166 // [...] "The nested-name-specifier of the qualified declarator-id shall 5167 // not begin with a decltype-specifer" 5168 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5169 while (SpecLoc.getPrefix()) 5170 SpecLoc = SpecLoc.getPrefix(); 5171 if (dyn_cast_or_null<DecltypeType>( 5172 SpecLoc.getNestedNameSpecifier()->getAsType())) 5173 Diag(Loc, diag::err_decltype_in_declarator) 5174 << SpecLoc.getTypeLoc().getSourceRange(); 5175 5176 return false; 5177 } 5178 5179 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5180 MultiTemplateParamsArg TemplateParamLists) { 5181 // TODO: consider using NameInfo for diagnostic. 5182 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5183 DeclarationName Name = NameInfo.getName(); 5184 5185 // All of these full declarators require an identifier. If it doesn't have 5186 // one, the ParsedFreeStandingDeclSpec action should be used. 5187 if (D.isDecompositionDeclarator()) { 5188 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5189 } else if (!Name) { 5190 if (!D.isInvalidType()) // Reject this if we think it is valid. 5191 Diag(D.getDeclSpec().getLocStart(), 5192 diag::err_declarator_need_ident) 5193 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5194 return nullptr; 5195 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5196 return nullptr; 5197 5198 // The scope passed in may not be a decl scope. Zip up the scope tree until 5199 // we find one that is. 5200 while ((S->getFlags() & Scope::DeclScope) == 0 || 5201 (S->getFlags() & Scope::TemplateParamScope) != 0) 5202 S = S->getParent(); 5203 5204 DeclContext *DC = CurContext; 5205 if (D.getCXXScopeSpec().isInvalid()) 5206 D.setInvalidType(); 5207 else if (D.getCXXScopeSpec().isSet()) { 5208 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5209 UPPC_DeclarationQualifier)) 5210 return nullptr; 5211 5212 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5213 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5214 if (!DC || isa<EnumDecl>(DC)) { 5215 // If we could not compute the declaration context, it's because the 5216 // declaration context is dependent but does not refer to a class, 5217 // class template, or class template partial specialization. Complain 5218 // and return early, to avoid the coming semantic disaster. 5219 Diag(D.getIdentifierLoc(), 5220 diag::err_template_qualified_declarator_no_match) 5221 << D.getCXXScopeSpec().getScopeRep() 5222 << D.getCXXScopeSpec().getRange(); 5223 return nullptr; 5224 } 5225 bool IsDependentContext = DC->isDependentContext(); 5226 5227 if (!IsDependentContext && 5228 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5229 return nullptr; 5230 5231 // If a class is incomplete, do not parse entities inside it. 5232 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5233 Diag(D.getIdentifierLoc(), 5234 diag::err_member_def_undefined_record) 5235 << Name << DC << D.getCXXScopeSpec().getRange(); 5236 return nullptr; 5237 } 5238 if (!D.getDeclSpec().isFriendSpecified()) { 5239 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 5240 Name, D.getIdentifierLoc())) { 5241 if (DC->isRecord()) 5242 return nullptr; 5243 5244 D.setInvalidType(); 5245 } 5246 } 5247 5248 // Check whether we need to rebuild the type of the given 5249 // declaration in the current instantiation. 5250 if (EnteringContext && IsDependentContext && 5251 TemplateParamLists.size() != 0) { 5252 ContextRAII SavedContext(*this, DC); 5253 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5254 D.setInvalidType(); 5255 } 5256 } 5257 5258 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5259 QualType R = TInfo->getType(); 5260 5261 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5262 // If this is a typedef, we'll end up spewing multiple diagnostics. 5263 // Just return early; it's safer. If this is a function, let the 5264 // "constructor cannot have a return type" diagnostic handle it. 5265 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5266 return nullptr; 5267 5268 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5269 UPPC_DeclarationType)) 5270 D.setInvalidType(); 5271 5272 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5273 ForRedeclaration); 5274 5275 // See if this is a redefinition of a variable in the same scope. 5276 if (!D.getCXXScopeSpec().isSet()) { 5277 bool IsLinkageLookup = false; 5278 bool CreateBuiltins = false; 5279 5280 // If the declaration we're planning to build will be a function 5281 // or object with linkage, then look for another declaration with 5282 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5283 // 5284 // If the declaration we're planning to build will be declared with 5285 // external linkage in the translation unit, create any builtin with 5286 // the same name. 5287 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5288 /* Do nothing*/; 5289 else if (CurContext->isFunctionOrMethod() && 5290 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5291 R->isFunctionType())) { 5292 IsLinkageLookup = true; 5293 CreateBuiltins = 5294 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5295 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5296 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5297 CreateBuiltins = true; 5298 5299 if (IsLinkageLookup) 5300 Previous.clear(LookupRedeclarationWithLinkage); 5301 5302 LookupName(Previous, S, CreateBuiltins); 5303 } else { // Something like "int foo::x;" 5304 LookupQualifiedName(Previous, DC); 5305 5306 // C++ [dcl.meaning]p1: 5307 // When the declarator-id is qualified, the declaration shall refer to a 5308 // previously declared member of the class or namespace to which the 5309 // qualifier refers (or, in the case of a namespace, of an element of the 5310 // inline namespace set of that namespace (7.3.1)) or to a specialization 5311 // thereof; [...] 5312 // 5313 // Note that we already checked the context above, and that we do not have 5314 // enough information to make sure that Previous contains the declaration 5315 // we want to match. For example, given: 5316 // 5317 // class X { 5318 // void f(); 5319 // void f(float); 5320 // }; 5321 // 5322 // void X::f(int) { } // ill-formed 5323 // 5324 // In this case, Previous will point to the overload set 5325 // containing the two f's declared in X, but neither of them 5326 // matches. 5327 5328 // C++ [dcl.meaning]p1: 5329 // [...] the member shall not merely have been introduced by a 5330 // using-declaration in the scope of the class or namespace nominated by 5331 // the nested-name-specifier of the declarator-id. 5332 RemoveUsingDecls(Previous); 5333 } 5334 5335 if (Previous.isSingleResult() && 5336 Previous.getFoundDecl()->isTemplateParameter()) { 5337 // Maybe we will complain about the shadowed template parameter. 5338 if (!D.isInvalidType()) 5339 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5340 Previous.getFoundDecl()); 5341 5342 // Just pretend that we didn't see the previous declaration. 5343 Previous.clear(); 5344 } 5345 5346 // In C++, the previous declaration we find might be a tag type 5347 // (class or enum). In this case, the new declaration will hide the 5348 // tag type. Note that this does does not apply if we're declaring a 5349 // typedef (C++ [dcl.typedef]p4). 5350 if (Previous.isSingleTagDecl() && 5351 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 5352 Previous.clear(); 5353 5354 // Check that there are no default arguments other than in the parameters 5355 // of a function declaration (C++ only). 5356 if (getLangOpts().CPlusPlus) 5357 CheckExtraCXXDefaultArguments(D); 5358 5359 if (D.getDeclSpec().isConceptSpecified()) { 5360 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 5361 // applied only to the definition of a function template or variable 5362 // template, declared in namespace scope 5363 if (!TemplateParamLists.size()) { 5364 Diag(D.getDeclSpec().getConceptSpecLoc(), 5365 diag:: err_concept_wrong_decl_kind); 5366 return nullptr; 5367 } 5368 5369 if (!DC->getRedeclContext()->isFileContext()) { 5370 Diag(D.getIdentifierLoc(), 5371 diag::err_concept_decls_may_only_appear_in_namespace_scope); 5372 return nullptr; 5373 } 5374 } 5375 5376 NamedDecl *New; 5377 5378 bool AddToScope = true; 5379 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5380 if (TemplateParamLists.size()) { 5381 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5382 return nullptr; 5383 } 5384 5385 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5386 } else if (R->isFunctionType()) { 5387 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5388 TemplateParamLists, 5389 AddToScope); 5390 } else { 5391 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5392 AddToScope); 5393 } 5394 5395 if (!New) 5396 return nullptr; 5397 5398 // If this has an identifier and is not a function template specialization, 5399 // add it to the scope stack. 5400 if (New->getDeclName() && AddToScope) { 5401 // Only make a locally-scoped extern declaration visible if it is the first 5402 // declaration of this entity. Qualified lookup for such an entity should 5403 // only find this declaration if there is no visible declaration of it. 5404 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5405 PushOnScopeChains(New, S, AddToContext); 5406 if (!AddToContext) 5407 CurContext->addHiddenDecl(New); 5408 } 5409 5410 if (isInOpenMPDeclareTargetContext()) 5411 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5412 5413 return New; 5414 } 5415 5416 /// Helper method to turn variable array types into constant array 5417 /// types in certain situations which would otherwise be errors (for 5418 /// GCC compatibility). 5419 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5420 ASTContext &Context, 5421 bool &SizeIsNegative, 5422 llvm::APSInt &Oversized) { 5423 // This method tries to turn a variable array into a constant 5424 // array even when the size isn't an ICE. This is necessary 5425 // for compatibility with code that depends on gcc's buggy 5426 // constant expression folding, like struct {char x[(int)(char*)2];} 5427 SizeIsNegative = false; 5428 Oversized = 0; 5429 5430 if (T->isDependentType()) 5431 return QualType(); 5432 5433 QualifierCollector Qs; 5434 const Type *Ty = Qs.strip(T); 5435 5436 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5437 QualType Pointee = PTy->getPointeeType(); 5438 QualType FixedType = 5439 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5440 Oversized); 5441 if (FixedType.isNull()) return FixedType; 5442 FixedType = Context.getPointerType(FixedType); 5443 return Qs.apply(Context, FixedType); 5444 } 5445 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5446 QualType Inner = PTy->getInnerType(); 5447 QualType FixedType = 5448 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5449 Oversized); 5450 if (FixedType.isNull()) return FixedType; 5451 FixedType = Context.getParenType(FixedType); 5452 return Qs.apply(Context, FixedType); 5453 } 5454 5455 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5456 if (!VLATy) 5457 return QualType(); 5458 // FIXME: We should probably handle this case 5459 if (VLATy->getElementType()->isVariablyModifiedType()) 5460 return QualType(); 5461 5462 llvm::APSInt Res; 5463 if (!VLATy->getSizeExpr() || 5464 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5465 return QualType(); 5466 5467 // Check whether the array size is negative. 5468 if (Res.isSigned() && Res.isNegative()) { 5469 SizeIsNegative = true; 5470 return QualType(); 5471 } 5472 5473 // Check whether the array is too large to be addressed. 5474 unsigned ActiveSizeBits 5475 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5476 Res); 5477 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5478 Oversized = Res; 5479 return QualType(); 5480 } 5481 5482 return Context.getConstantArrayType(VLATy->getElementType(), 5483 Res, ArrayType::Normal, 0); 5484 } 5485 5486 static void 5487 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5488 SrcTL = SrcTL.getUnqualifiedLoc(); 5489 DstTL = DstTL.getUnqualifiedLoc(); 5490 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5491 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5492 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5493 DstPTL.getPointeeLoc()); 5494 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5495 return; 5496 } 5497 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5498 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5499 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5500 DstPTL.getInnerLoc()); 5501 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5502 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5503 return; 5504 } 5505 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5506 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5507 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5508 TypeLoc DstElemTL = DstATL.getElementLoc(); 5509 DstElemTL.initializeFullCopy(SrcElemTL); 5510 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5511 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5512 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5513 } 5514 5515 /// Helper method to turn variable array types into constant array 5516 /// types in certain situations which would otherwise be errors (for 5517 /// GCC compatibility). 5518 static TypeSourceInfo* 5519 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5520 ASTContext &Context, 5521 bool &SizeIsNegative, 5522 llvm::APSInt &Oversized) { 5523 QualType FixedTy 5524 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5525 SizeIsNegative, Oversized); 5526 if (FixedTy.isNull()) 5527 return nullptr; 5528 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5529 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5530 FixedTInfo->getTypeLoc()); 5531 return FixedTInfo; 5532 } 5533 5534 /// \brief Register the given locally-scoped extern "C" declaration so 5535 /// that it can be found later for redeclarations. We include any extern "C" 5536 /// declaration that is not visible in the translation unit here, not just 5537 /// function-scope declarations. 5538 void 5539 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5540 if (!getLangOpts().CPlusPlus && 5541 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5542 // Don't need to track declarations in the TU in C. 5543 return; 5544 5545 // Note that we have a locally-scoped external with this name. 5546 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5547 } 5548 5549 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5550 // FIXME: We can have multiple results via __attribute__((overloadable)). 5551 auto Result = Context.getExternCContextDecl()->lookup(Name); 5552 return Result.empty() ? nullptr : *Result.begin(); 5553 } 5554 5555 /// \brief Diagnose function specifiers on a declaration of an identifier that 5556 /// does not identify a function. 5557 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5558 // FIXME: We should probably indicate the identifier in question to avoid 5559 // confusion for constructs like "virtual int a(), b;" 5560 if (DS.isVirtualSpecified()) 5561 Diag(DS.getVirtualSpecLoc(), 5562 diag::err_virtual_non_function); 5563 5564 if (DS.isExplicitSpecified()) 5565 Diag(DS.getExplicitSpecLoc(), 5566 diag::err_explicit_non_function); 5567 5568 if (DS.isNoreturnSpecified()) 5569 Diag(DS.getNoreturnSpecLoc(), 5570 diag::err_noreturn_non_function); 5571 } 5572 5573 NamedDecl* 5574 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5575 TypeSourceInfo *TInfo, LookupResult &Previous) { 5576 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5577 if (D.getCXXScopeSpec().isSet()) { 5578 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5579 << D.getCXXScopeSpec().getRange(); 5580 D.setInvalidType(); 5581 // Pretend we didn't see the scope specifier. 5582 DC = CurContext; 5583 Previous.clear(); 5584 } 5585 5586 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5587 5588 if (D.getDeclSpec().isInlineSpecified()) 5589 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5590 << getLangOpts().CPlusPlus1z; 5591 if (D.getDeclSpec().isConstexprSpecified()) 5592 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5593 << 1; 5594 if (D.getDeclSpec().isConceptSpecified()) 5595 Diag(D.getDeclSpec().getConceptSpecLoc(), 5596 diag::err_concept_wrong_decl_kind); 5597 5598 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5599 if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName) 5600 Diag(D.getName().StartLocation, 5601 diag::err_deduction_guide_invalid_specifier) 5602 << "typedef"; 5603 else 5604 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5605 << D.getName().getSourceRange(); 5606 return nullptr; 5607 } 5608 5609 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5610 if (!NewTD) return nullptr; 5611 5612 // Handle attributes prior to checking for duplicates in MergeVarDecl 5613 ProcessDeclAttributes(S, NewTD, D); 5614 5615 CheckTypedefForVariablyModifiedType(S, NewTD); 5616 5617 bool Redeclaration = D.isRedeclaration(); 5618 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5619 D.setRedeclaration(Redeclaration); 5620 return ND; 5621 } 5622 5623 void 5624 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5625 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5626 // then it shall have block scope. 5627 // Note that variably modified types must be fixed before merging the decl so 5628 // that redeclarations will match. 5629 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5630 QualType T = TInfo->getType(); 5631 if (T->isVariablyModifiedType()) { 5632 getCurFunction()->setHasBranchProtectedScope(); 5633 5634 if (S->getFnParent() == nullptr) { 5635 bool SizeIsNegative; 5636 llvm::APSInt Oversized; 5637 TypeSourceInfo *FixedTInfo = 5638 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5639 SizeIsNegative, 5640 Oversized); 5641 if (FixedTInfo) { 5642 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5643 NewTD->setTypeSourceInfo(FixedTInfo); 5644 } else { 5645 if (SizeIsNegative) 5646 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5647 else if (T->isVariableArrayType()) 5648 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5649 else if (Oversized.getBoolValue()) 5650 Diag(NewTD->getLocation(), diag::err_array_too_large) 5651 << Oversized.toString(10); 5652 else 5653 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5654 NewTD->setInvalidDecl(); 5655 } 5656 } 5657 } 5658 } 5659 5660 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5661 /// declares a typedef-name, either using the 'typedef' type specifier or via 5662 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5663 NamedDecl* 5664 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5665 LookupResult &Previous, bool &Redeclaration) { 5666 5667 // Find the shadowed declaration before filtering for scope. 5668 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5669 5670 // Merge the decl with the existing one if appropriate. If the decl is 5671 // in an outer scope, it isn't the same thing. 5672 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5673 /*AllowInlineNamespace*/false); 5674 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5675 if (!Previous.empty()) { 5676 Redeclaration = true; 5677 MergeTypedefNameDecl(S, NewTD, Previous); 5678 } 5679 5680 if (ShadowedDecl && !Redeclaration) 5681 CheckShadow(NewTD, ShadowedDecl, Previous); 5682 5683 // If this is the C FILE type, notify the AST context. 5684 if (IdentifierInfo *II = NewTD->getIdentifier()) 5685 if (!NewTD->isInvalidDecl() && 5686 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5687 if (II->isStr("FILE")) 5688 Context.setFILEDecl(NewTD); 5689 else if (II->isStr("jmp_buf")) 5690 Context.setjmp_bufDecl(NewTD); 5691 else if (II->isStr("sigjmp_buf")) 5692 Context.setsigjmp_bufDecl(NewTD); 5693 else if (II->isStr("ucontext_t")) 5694 Context.setucontext_tDecl(NewTD); 5695 } 5696 5697 return NewTD; 5698 } 5699 5700 /// \brief Determines whether the given declaration is an out-of-scope 5701 /// previous declaration. 5702 /// 5703 /// This routine should be invoked when name lookup has found a 5704 /// previous declaration (PrevDecl) that is not in the scope where a 5705 /// new declaration by the same name is being introduced. If the new 5706 /// declaration occurs in a local scope, previous declarations with 5707 /// linkage may still be considered previous declarations (C99 5708 /// 6.2.2p4-5, C++ [basic.link]p6). 5709 /// 5710 /// \param PrevDecl the previous declaration found by name 5711 /// lookup 5712 /// 5713 /// \param DC the context in which the new declaration is being 5714 /// declared. 5715 /// 5716 /// \returns true if PrevDecl is an out-of-scope previous declaration 5717 /// for a new delcaration with the same name. 5718 static bool 5719 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5720 ASTContext &Context) { 5721 if (!PrevDecl) 5722 return false; 5723 5724 if (!PrevDecl->hasLinkage()) 5725 return false; 5726 5727 if (Context.getLangOpts().CPlusPlus) { 5728 // C++ [basic.link]p6: 5729 // If there is a visible declaration of an entity with linkage 5730 // having the same name and type, ignoring entities declared 5731 // outside the innermost enclosing namespace scope, the block 5732 // scope declaration declares that same entity and receives the 5733 // linkage of the previous declaration. 5734 DeclContext *OuterContext = DC->getRedeclContext(); 5735 if (!OuterContext->isFunctionOrMethod()) 5736 // This rule only applies to block-scope declarations. 5737 return false; 5738 5739 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5740 if (PrevOuterContext->isRecord()) 5741 // We found a member function: ignore it. 5742 return false; 5743 5744 // Find the innermost enclosing namespace for the new and 5745 // previous declarations. 5746 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5747 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5748 5749 // The previous declaration is in a different namespace, so it 5750 // isn't the same function. 5751 if (!OuterContext->Equals(PrevOuterContext)) 5752 return false; 5753 } 5754 5755 return true; 5756 } 5757 5758 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5759 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5760 if (!SS.isSet()) return; 5761 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5762 } 5763 5764 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5765 QualType type = decl->getType(); 5766 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5767 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5768 // Various kinds of declaration aren't allowed to be __autoreleasing. 5769 unsigned kind = -1U; 5770 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5771 if (var->hasAttr<BlocksAttr>()) 5772 kind = 0; // __block 5773 else if (!var->hasLocalStorage()) 5774 kind = 1; // global 5775 } else if (isa<ObjCIvarDecl>(decl)) { 5776 kind = 3; // ivar 5777 } else if (isa<FieldDecl>(decl)) { 5778 kind = 2; // field 5779 } 5780 5781 if (kind != -1U) { 5782 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5783 << kind; 5784 } 5785 } else if (lifetime == Qualifiers::OCL_None) { 5786 // Try to infer lifetime. 5787 if (!type->isObjCLifetimeType()) 5788 return false; 5789 5790 lifetime = type->getObjCARCImplicitLifetime(); 5791 type = Context.getLifetimeQualifiedType(type, lifetime); 5792 decl->setType(type); 5793 } 5794 5795 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5796 // Thread-local variables cannot have lifetime. 5797 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5798 var->getTLSKind()) { 5799 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5800 << var->getType(); 5801 return true; 5802 } 5803 } 5804 5805 return false; 5806 } 5807 5808 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5809 // Ensure that an auto decl is deduced otherwise the checks below might cache 5810 // the wrong linkage. 5811 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5812 5813 // 'weak' only applies to declarations with external linkage. 5814 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5815 if (!ND.isExternallyVisible()) { 5816 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5817 ND.dropAttr<WeakAttr>(); 5818 } 5819 } 5820 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5821 if (ND.isExternallyVisible()) { 5822 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5823 ND.dropAttr<WeakRefAttr>(); 5824 ND.dropAttr<AliasAttr>(); 5825 } 5826 } 5827 5828 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5829 if (VD->hasInit()) { 5830 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5831 assert(VD->isThisDeclarationADefinition() && 5832 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5833 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5834 VD->dropAttr<AliasAttr>(); 5835 } 5836 } 5837 } 5838 5839 // 'selectany' only applies to externally visible variable declarations. 5840 // It does not apply to functions. 5841 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5842 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5843 S.Diag(Attr->getLocation(), 5844 diag::err_attribute_selectany_non_extern_data); 5845 ND.dropAttr<SelectAnyAttr>(); 5846 } 5847 } 5848 5849 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5850 // dll attributes require external linkage. Static locals may have external 5851 // linkage but still cannot be explicitly imported or exported. 5852 auto *VD = dyn_cast<VarDecl>(&ND); 5853 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5854 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5855 << &ND << Attr; 5856 ND.setInvalidDecl(); 5857 } 5858 } 5859 5860 // Virtual functions cannot be marked as 'notail'. 5861 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5862 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5863 if (MD->isVirtual()) { 5864 S.Diag(ND.getLocation(), 5865 diag::err_invalid_attribute_on_virtual_function) 5866 << Attr; 5867 ND.dropAttr<NotTailCalledAttr>(); 5868 } 5869 } 5870 5871 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5872 NamedDecl *NewDecl, 5873 bool IsSpecialization, 5874 bool IsDefinition) { 5875 if (OldDecl->isInvalidDecl()) 5876 return; 5877 5878 bool IsTemplate = false; 5879 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 5880 OldDecl = OldTD->getTemplatedDecl(); 5881 IsTemplate = true; 5882 if (!IsSpecialization) 5883 IsDefinition = false; 5884 } 5885 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 5886 NewDecl = NewTD->getTemplatedDecl(); 5887 IsTemplate = true; 5888 } 5889 5890 if (!OldDecl || !NewDecl) 5891 return; 5892 5893 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5894 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5895 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5896 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5897 5898 // dllimport and dllexport are inheritable attributes so we have to exclude 5899 // inherited attribute instances. 5900 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5901 (NewExportAttr && !NewExportAttr->isInherited()); 5902 5903 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5904 // the only exception being explicit specializations. 5905 // Implicitly generated declarations are also excluded for now because there 5906 // is no other way to switch these to use dllimport or dllexport. 5907 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5908 5909 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5910 // Allow with a warning for free functions and global variables. 5911 bool JustWarn = false; 5912 if (!OldDecl->isCXXClassMember()) { 5913 auto *VD = dyn_cast<VarDecl>(OldDecl); 5914 if (VD && !VD->getDescribedVarTemplate()) 5915 JustWarn = true; 5916 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5917 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5918 JustWarn = true; 5919 } 5920 5921 // We cannot change a declaration that's been used because IR has already 5922 // been emitted. Dllimported functions will still work though (modulo 5923 // address equality) as they can use the thunk. 5924 if (OldDecl->isUsed()) 5925 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 5926 JustWarn = false; 5927 5928 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5929 : diag::err_attribute_dll_redeclaration; 5930 S.Diag(NewDecl->getLocation(), DiagID) 5931 << NewDecl 5932 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5933 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5934 if (!JustWarn) { 5935 NewDecl->setInvalidDecl(); 5936 return; 5937 } 5938 } 5939 5940 // A redeclaration is not allowed to drop a dllimport attribute, the only 5941 // exceptions being inline function definitions (except for function 5942 // templates), local extern declarations, qualified friend declarations or 5943 // special MSVC extension: in the last case, the declaration is treated as if 5944 // it were marked dllexport. 5945 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5946 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 5947 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 5948 // Ignore static data because out-of-line definitions are diagnosed 5949 // separately. 5950 IsStaticDataMember = VD->isStaticDataMember(); 5951 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 5952 VarDecl::DeclarationOnly; 5953 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5954 IsInline = FD->isInlined(); 5955 IsQualifiedFriend = FD->getQualifier() && 5956 FD->getFriendObjectKind() == Decl::FOK_Declared; 5957 } 5958 5959 if (OldImportAttr && !HasNewAttr && 5960 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 5961 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5962 if (IsMicrosoft && IsDefinition) { 5963 S.Diag(NewDecl->getLocation(), 5964 diag::warn_redeclaration_without_import_attribute) 5965 << NewDecl; 5966 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5967 NewDecl->dropAttr<DLLImportAttr>(); 5968 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 5969 NewImportAttr->getRange(), S.Context, 5970 NewImportAttr->getSpellingListIndex())); 5971 } else { 5972 S.Diag(NewDecl->getLocation(), 5973 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5974 << NewDecl << OldImportAttr; 5975 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5976 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5977 OldDecl->dropAttr<DLLImportAttr>(); 5978 NewDecl->dropAttr<DLLImportAttr>(); 5979 } 5980 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 5981 // In MinGW, seeing a function declared inline drops the dllimport attribute. 5982 OldDecl->dropAttr<DLLImportAttr>(); 5983 NewDecl->dropAttr<DLLImportAttr>(); 5984 S.Diag(NewDecl->getLocation(), 5985 diag::warn_dllimport_dropped_from_inline_function) 5986 << NewDecl << OldImportAttr; 5987 } 5988 } 5989 5990 /// Given that we are within the definition of the given function, 5991 /// will that definition behave like C99's 'inline', where the 5992 /// definition is discarded except for optimization purposes? 5993 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5994 // Try to avoid calling GetGVALinkageForFunction. 5995 5996 // All cases of this require the 'inline' keyword. 5997 if (!FD->isInlined()) return false; 5998 5999 // This is only possible in C++ with the gnu_inline attribute. 6000 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6001 return false; 6002 6003 // Okay, go ahead and call the relatively-more-expensive function. 6004 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6005 } 6006 6007 /// Determine whether a variable is extern "C" prior to attaching 6008 /// an initializer. We can't just call isExternC() here, because that 6009 /// will also compute and cache whether the declaration is externally 6010 /// visible, which might change when we attach the initializer. 6011 /// 6012 /// This can only be used if the declaration is known to not be a 6013 /// redeclaration of an internal linkage declaration. 6014 /// 6015 /// For instance: 6016 /// 6017 /// auto x = []{}; 6018 /// 6019 /// Attaching the initializer here makes this declaration not externally 6020 /// visible, because its type has internal linkage. 6021 /// 6022 /// FIXME: This is a hack. 6023 template<typename T> 6024 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6025 if (S.getLangOpts().CPlusPlus) { 6026 // In C++, the overloadable attribute negates the effects of extern "C". 6027 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6028 return false; 6029 6030 // So do CUDA's host/device attributes. 6031 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6032 D->template hasAttr<CUDAHostAttr>())) 6033 return false; 6034 } 6035 return D->isExternC(); 6036 } 6037 6038 static bool shouldConsiderLinkage(const VarDecl *VD) { 6039 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6040 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 6041 return VD->hasExternalStorage(); 6042 if (DC->isFileContext()) 6043 return true; 6044 if (DC->isRecord()) 6045 return false; 6046 llvm_unreachable("Unexpected context"); 6047 } 6048 6049 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6050 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6051 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6052 isa<OMPDeclareReductionDecl>(DC)) 6053 return true; 6054 if (DC->isRecord()) 6055 return false; 6056 llvm_unreachable("Unexpected context"); 6057 } 6058 6059 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 6060 AttributeList::Kind Kind) { 6061 for (const AttributeList *L = AttrList; L; L = L->getNext()) 6062 if (L->getKind() == Kind) 6063 return true; 6064 return false; 6065 } 6066 6067 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6068 AttributeList::Kind Kind) { 6069 // Check decl attributes on the DeclSpec. 6070 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 6071 return true; 6072 6073 // Walk the declarator structure, checking decl attributes that were in a type 6074 // position to the decl itself. 6075 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6076 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 6077 return true; 6078 } 6079 6080 // Finally, check attributes on the decl itself. 6081 return hasParsedAttr(S, PD.getAttributes(), Kind); 6082 } 6083 6084 /// Adjust the \c DeclContext for a function or variable that might be a 6085 /// function-local external declaration. 6086 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6087 if (!DC->isFunctionOrMethod()) 6088 return false; 6089 6090 // If this is a local extern function or variable declared within a function 6091 // template, don't add it into the enclosing namespace scope until it is 6092 // instantiated; it might have a dependent type right now. 6093 if (DC->isDependentContext()) 6094 return true; 6095 6096 // C++11 [basic.link]p7: 6097 // When a block scope declaration of an entity with linkage is not found to 6098 // refer to some other declaration, then that entity is a member of the 6099 // innermost enclosing namespace. 6100 // 6101 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6102 // semantically-enclosing namespace, not a lexically-enclosing one. 6103 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6104 DC = DC->getParent(); 6105 return true; 6106 } 6107 6108 /// \brief Returns true if given declaration has external C language linkage. 6109 static bool isDeclExternC(const Decl *D) { 6110 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6111 return FD->isExternC(); 6112 if (const auto *VD = dyn_cast<VarDecl>(D)) 6113 return VD->isExternC(); 6114 6115 llvm_unreachable("Unknown type of decl!"); 6116 } 6117 6118 NamedDecl *Sema::ActOnVariableDeclarator( 6119 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6120 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6121 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6122 QualType R = TInfo->getType(); 6123 DeclarationName Name = GetNameForDeclarator(D).getName(); 6124 6125 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6126 6127 if (D.isDecompositionDeclarator()) { 6128 AddToScope = false; 6129 // Take the name of the first declarator as our name for diagnostic 6130 // purposes. 6131 auto &Decomp = D.getDecompositionDeclarator(); 6132 if (!Decomp.bindings().empty()) { 6133 II = Decomp.bindings()[0].Name; 6134 Name = II; 6135 } 6136 } else if (!II) { 6137 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6138 return nullptr; 6139 } 6140 6141 if (getLangOpts().OpenCL) { 6142 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6143 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6144 // argument. 6145 if (R->isImageType() || R->isPipeType()) { 6146 Diag(D.getIdentifierLoc(), 6147 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6148 << R; 6149 D.setInvalidType(); 6150 return nullptr; 6151 } 6152 6153 // OpenCL v1.2 s6.9.r: 6154 // The event type cannot be used to declare a program scope variable. 6155 // OpenCL v2.0 s6.9.q: 6156 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6157 if (NULL == S->getParent()) { 6158 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6159 Diag(D.getIdentifierLoc(), 6160 diag::err_invalid_type_for_program_scope_var) << R; 6161 D.setInvalidType(); 6162 return nullptr; 6163 } 6164 } 6165 6166 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6167 QualType NR = R; 6168 while (NR->isPointerType()) { 6169 if (NR->isFunctionPointerType()) { 6170 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 6171 D.setInvalidType(); 6172 break; 6173 } 6174 NR = NR->getPointeeType(); 6175 } 6176 6177 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6178 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6179 // half array type (unless the cl_khr_fp16 extension is enabled). 6180 if (Context.getBaseElementType(R)->isHalfType()) { 6181 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6182 D.setInvalidType(); 6183 } 6184 } 6185 6186 if (R->isSamplerT()) { 6187 // OpenCL v1.2 s6.9.b p4: 6188 // The sampler type cannot be used with the __local and __global address 6189 // space qualifiers. 6190 if (R.getAddressSpace() == LangAS::opencl_local || 6191 R.getAddressSpace() == LangAS::opencl_global) { 6192 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6193 } 6194 6195 // OpenCL v1.2 s6.12.14.1: 6196 // A global sampler must be declared with either the constant address 6197 // space qualifier or with the const qualifier. 6198 if (DC->isTranslationUnit() && 6199 !(R.getAddressSpace() == LangAS::opencl_constant || 6200 R.isConstQualified())) { 6201 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6202 D.setInvalidType(); 6203 } 6204 } 6205 6206 // OpenCL v1.2 s6.9.r: 6207 // The event type cannot be used with the __local, __constant and __global 6208 // address space qualifiers. 6209 if (R->isEventT()) { 6210 if (R.getAddressSpace()) { 6211 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 6212 D.setInvalidType(); 6213 } 6214 } 6215 } 6216 6217 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6218 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6219 6220 // dllimport globals without explicit storage class are treated as extern. We 6221 // have to change the storage class this early to get the right DeclContext. 6222 if (SC == SC_None && !DC->isRecord() && 6223 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 6224 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 6225 SC = SC_Extern; 6226 6227 DeclContext *OriginalDC = DC; 6228 bool IsLocalExternDecl = SC == SC_Extern && 6229 adjustContextForLocalExternDecl(DC); 6230 6231 if (SCSpec == DeclSpec::SCS_mutable) { 6232 // mutable can only appear on non-static class members, so it's always 6233 // an error here 6234 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6235 D.setInvalidType(); 6236 SC = SC_None; 6237 } 6238 6239 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6240 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6241 D.getDeclSpec().getStorageClassSpecLoc())) { 6242 // In C++11, the 'register' storage class specifier is deprecated. 6243 // Suppress the warning in system macros, it's used in macros in some 6244 // popular C system headers, such as in glibc's htonl() macro. 6245 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6246 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class 6247 : diag::warn_deprecated_register) 6248 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6249 } 6250 6251 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6252 6253 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6254 // C99 6.9p2: The storage-class specifiers auto and register shall not 6255 // appear in the declaration specifiers in an external declaration. 6256 // Global Register+Asm is a GNU extension we support. 6257 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6258 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6259 D.setInvalidType(); 6260 } 6261 } 6262 6263 bool IsMemberSpecialization = false; 6264 bool IsVariableTemplateSpecialization = false; 6265 bool IsPartialSpecialization = false; 6266 bool IsVariableTemplate = false; 6267 VarDecl *NewVD = nullptr; 6268 VarTemplateDecl *NewTemplate = nullptr; 6269 TemplateParameterList *TemplateParams = nullptr; 6270 if (!getLangOpts().CPlusPlus) { 6271 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6272 D.getIdentifierLoc(), II, 6273 R, TInfo, SC); 6274 6275 if (R->getContainedDeducedType()) 6276 ParsingInitForAutoVars.insert(NewVD); 6277 6278 if (D.isInvalidType()) 6279 NewVD->setInvalidDecl(); 6280 } else { 6281 bool Invalid = false; 6282 6283 if (DC->isRecord() && !CurContext->isRecord()) { 6284 // This is an out-of-line definition of a static data member. 6285 switch (SC) { 6286 case SC_None: 6287 break; 6288 case SC_Static: 6289 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6290 diag::err_static_out_of_line) 6291 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6292 break; 6293 case SC_Auto: 6294 case SC_Register: 6295 case SC_Extern: 6296 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6297 // to names of variables declared in a block or to function parameters. 6298 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6299 // of class members 6300 6301 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6302 diag::err_storage_class_for_static_member) 6303 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6304 break; 6305 case SC_PrivateExtern: 6306 llvm_unreachable("C storage class in c++!"); 6307 } 6308 } 6309 6310 if (SC == SC_Static && CurContext->isRecord()) { 6311 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6312 if (RD->isLocalClass()) 6313 Diag(D.getIdentifierLoc(), 6314 diag::err_static_data_member_not_allowed_in_local_class) 6315 << Name << RD->getDeclName(); 6316 6317 // C++98 [class.union]p1: If a union contains a static data member, 6318 // the program is ill-formed. C++11 drops this restriction. 6319 if (RD->isUnion()) 6320 Diag(D.getIdentifierLoc(), 6321 getLangOpts().CPlusPlus11 6322 ? diag::warn_cxx98_compat_static_data_member_in_union 6323 : diag::ext_static_data_member_in_union) << Name; 6324 // We conservatively disallow static data members in anonymous structs. 6325 else if (!RD->getDeclName()) 6326 Diag(D.getIdentifierLoc(), 6327 diag::err_static_data_member_not_allowed_in_anon_struct) 6328 << Name << RD->isUnion(); 6329 } 6330 } 6331 6332 // Match up the template parameter lists with the scope specifier, then 6333 // determine whether we have a template or a template specialization. 6334 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6335 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6336 D.getCXXScopeSpec(), 6337 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6338 ? D.getName().TemplateId 6339 : nullptr, 6340 TemplateParamLists, 6341 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6342 6343 if (TemplateParams) { 6344 if (!TemplateParams->size() && 6345 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6346 // There is an extraneous 'template<>' for this variable. Complain 6347 // about it, but allow the declaration of the variable. 6348 Diag(TemplateParams->getTemplateLoc(), 6349 diag::err_template_variable_noparams) 6350 << II 6351 << SourceRange(TemplateParams->getTemplateLoc(), 6352 TemplateParams->getRAngleLoc()); 6353 TemplateParams = nullptr; 6354 } else { 6355 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 6356 // This is an explicit specialization or a partial specialization. 6357 // FIXME: Check that we can declare a specialization here. 6358 IsVariableTemplateSpecialization = true; 6359 IsPartialSpecialization = TemplateParams->size() > 0; 6360 } else { // if (TemplateParams->size() > 0) 6361 // This is a template declaration. 6362 IsVariableTemplate = true; 6363 6364 // Check that we can declare a template here. 6365 if (CheckTemplateDeclScope(S, TemplateParams)) 6366 return nullptr; 6367 6368 // Only C++1y supports variable templates (N3651). 6369 Diag(D.getIdentifierLoc(), 6370 getLangOpts().CPlusPlus14 6371 ? diag::warn_cxx11_compat_variable_template 6372 : diag::ext_variable_template); 6373 } 6374 } 6375 } else { 6376 assert( 6377 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 6378 "should have a 'template<>' for this decl"); 6379 } 6380 6381 if (IsVariableTemplateSpecialization) { 6382 SourceLocation TemplateKWLoc = 6383 TemplateParamLists.size() > 0 6384 ? TemplateParamLists[0]->getTemplateLoc() 6385 : SourceLocation(); 6386 DeclResult Res = ActOnVarTemplateSpecialization( 6387 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6388 IsPartialSpecialization); 6389 if (Res.isInvalid()) 6390 return nullptr; 6391 NewVD = cast<VarDecl>(Res.get()); 6392 AddToScope = false; 6393 } else if (D.isDecompositionDeclarator()) { 6394 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6395 D.getIdentifierLoc(), R, TInfo, SC, 6396 Bindings); 6397 } else 6398 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6399 D.getIdentifierLoc(), II, R, TInfo, SC); 6400 6401 // If this is supposed to be a variable template, create it as such. 6402 if (IsVariableTemplate) { 6403 NewTemplate = 6404 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6405 TemplateParams, NewVD); 6406 NewVD->setDescribedVarTemplate(NewTemplate); 6407 } 6408 6409 // If this decl has an auto type in need of deduction, make a note of the 6410 // Decl so we can diagnose uses of it in its own initializer. 6411 if (R->getContainedDeducedType()) 6412 ParsingInitForAutoVars.insert(NewVD); 6413 6414 if (D.isInvalidType() || Invalid) { 6415 NewVD->setInvalidDecl(); 6416 if (NewTemplate) 6417 NewTemplate->setInvalidDecl(); 6418 } 6419 6420 SetNestedNameSpecifier(NewVD, D); 6421 6422 // If we have any template parameter lists that don't directly belong to 6423 // the variable (matching the scope specifier), store them. 6424 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6425 if (TemplateParamLists.size() > VDTemplateParamLists) 6426 NewVD->setTemplateParameterListsInfo( 6427 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6428 6429 if (D.getDeclSpec().isConstexprSpecified()) { 6430 NewVD->setConstexpr(true); 6431 // C++1z [dcl.spec.constexpr]p1: 6432 // A static data member declared with the constexpr specifier is 6433 // implicitly an inline variable. 6434 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z) 6435 NewVD->setImplicitlyInline(); 6436 } 6437 6438 if (D.getDeclSpec().isConceptSpecified()) { 6439 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate()) 6440 VTD->setConcept(); 6441 6442 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 6443 // be declared with the thread_local, inline, friend, or constexpr 6444 // specifiers, [...] 6445 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) { 6446 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6447 diag::err_concept_decl_invalid_specifiers) 6448 << 0 << 0; 6449 NewVD->setInvalidDecl(true); 6450 } 6451 6452 if (D.getDeclSpec().isConstexprSpecified()) { 6453 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6454 diag::err_concept_decl_invalid_specifiers) 6455 << 0 << 3; 6456 NewVD->setInvalidDecl(true); 6457 } 6458 6459 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 6460 // applied only to the definition of a function template or variable 6461 // template, declared in namespace scope. 6462 if (IsVariableTemplateSpecialization) { 6463 Diag(D.getDeclSpec().getConceptSpecLoc(), 6464 diag::err_concept_specified_specialization) 6465 << (IsPartialSpecialization ? 2 : 1); 6466 } 6467 6468 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the 6469 // following restrictions: 6470 // - The declared type shall have the type bool. 6471 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) && 6472 !NewVD->isInvalidDecl()) { 6473 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl); 6474 NewVD->setInvalidDecl(true); 6475 } 6476 } 6477 } 6478 6479 if (D.getDeclSpec().isInlineSpecified()) { 6480 if (!getLangOpts().CPlusPlus) { 6481 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6482 << 0; 6483 } else if (CurContext->isFunctionOrMethod()) { 6484 // 'inline' is not allowed on block scope variable declaration. 6485 Diag(D.getDeclSpec().getInlineSpecLoc(), 6486 diag::err_inline_declaration_block_scope) << Name 6487 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6488 } else { 6489 Diag(D.getDeclSpec().getInlineSpecLoc(), 6490 getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable 6491 : diag::ext_inline_variable); 6492 NewVD->setInlineSpecified(); 6493 } 6494 } 6495 6496 // Set the lexical context. If the declarator has a C++ scope specifier, the 6497 // lexical context will be different from the semantic context. 6498 NewVD->setLexicalDeclContext(CurContext); 6499 if (NewTemplate) 6500 NewTemplate->setLexicalDeclContext(CurContext); 6501 6502 if (IsLocalExternDecl) { 6503 if (D.isDecompositionDeclarator()) 6504 for (auto *B : Bindings) 6505 B->setLocalExternDecl(); 6506 else 6507 NewVD->setLocalExternDecl(); 6508 } 6509 6510 bool EmitTLSUnsupportedError = false; 6511 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6512 // C++11 [dcl.stc]p4: 6513 // When thread_local is applied to a variable of block scope the 6514 // storage-class-specifier static is implied if it does not appear 6515 // explicitly. 6516 // Core issue: 'static' is not implied if the variable is declared 6517 // 'extern'. 6518 if (NewVD->hasLocalStorage() && 6519 (SCSpec != DeclSpec::SCS_unspecified || 6520 TSCS != DeclSpec::TSCS_thread_local || 6521 !DC->isFunctionOrMethod())) 6522 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6523 diag::err_thread_non_global) 6524 << DeclSpec::getSpecifierName(TSCS); 6525 else if (!Context.getTargetInfo().isTLSSupported()) { 6526 if (getLangOpts().CUDA) { 6527 // Postpone error emission until we've collected attributes required to 6528 // figure out whether it's a host or device variable and whether the 6529 // error should be ignored. 6530 EmitTLSUnsupportedError = true; 6531 // We still need to mark the variable as TLS so it shows up in AST with 6532 // proper storage class for other tools to use even if we're not going 6533 // to emit any code for it. 6534 NewVD->setTSCSpec(TSCS); 6535 } else 6536 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6537 diag::err_thread_unsupported); 6538 } else 6539 NewVD->setTSCSpec(TSCS); 6540 } 6541 6542 // C99 6.7.4p3 6543 // An inline definition of a function with external linkage shall 6544 // not contain a definition of a modifiable object with static or 6545 // thread storage duration... 6546 // We only apply this when the function is required to be defined 6547 // elsewhere, i.e. when the function is not 'extern inline'. Note 6548 // that a local variable with thread storage duration still has to 6549 // be marked 'static'. Also note that it's possible to get these 6550 // semantics in C++ using __attribute__((gnu_inline)). 6551 if (SC == SC_Static && S->getFnParent() != nullptr && 6552 !NewVD->getType().isConstQualified()) { 6553 FunctionDecl *CurFD = getCurFunctionDecl(); 6554 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6555 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6556 diag::warn_static_local_in_extern_inline); 6557 MaybeSuggestAddingStaticToDecl(CurFD); 6558 } 6559 } 6560 6561 if (D.getDeclSpec().isModulePrivateSpecified()) { 6562 if (IsVariableTemplateSpecialization) 6563 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6564 << (IsPartialSpecialization ? 1 : 0) 6565 << FixItHint::CreateRemoval( 6566 D.getDeclSpec().getModulePrivateSpecLoc()); 6567 else if (IsMemberSpecialization) 6568 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6569 << 2 6570 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6571 else if (NewVD->hasLocalStorage()) 6572 Diag(NewVD->getLocation(), diag::err_module_private_local) 6573 << 0 << NewVD->getDeclName() 6574 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6575 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6576 else { 6577 NewVD->setModulePrivate(); 6578 if (NewTemplate) 6579 NewTemplate->setModulePrivate(); 6580 for (auto *B : Bindings) 6581 B->setModulePrivate(); 6582 } 6583 } 6584 6585 // Handle attributes prior to checking for duplicates in MergeVarDecl 6586 ProcessDeclAttributes(S, NewVD, D); 6587 6588 if (getLangOpts().CUDA) { 6589 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) 6590 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6591 diag::err_thread_unsupported); 6592 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6593 // storage [duration]." 6594 if (SC == SC_None && S->getFnParent() != nullptr && 6595 (NewVD->hasAttr<CUDASharedAttr>() || 6596 NewVD->hasAttr<CUDAConstantAttr>())) { 6597 NewVD->setStorageClass(SC_Static); 6598 } 6599 } 6600 6601 // Ensure that dllimport globals without explicit storage class are treated as 6602 // extern. The storage class is set above using parsed attributes. Now we can 6603 // check the VarDecl itself. 6604 assert(!NewVD->hasAttr<DLLImportAttr>() || 6605 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6606 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6607 6608 // In auto-retain/release, infer strong retension for variables of 6609 // retainable type. 6610 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6611 NewVD->setInvalidDecl(); 6612 6613 // Handle GNU asm-label extension (encoded as an attribute). 6614 if (Expr *E = (Expr*)D.getAsmLabel()) { 6615 // The parser guarantees this is a string. 6616 StringLiteral *SE = cast<StringLiteral>(E); 6617 StringRef Label = SE->getString(); 6618 if (S->getFnParent() != nullptr) { 6619 switch (SC) { 6620 case SC_None: 6621 case SC_Auto: 6622 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6623 break; 6624 case SC_Register: 6625 // Local Named register 6626 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6627 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6628 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6629 break; 6630 case SC_Static: 6631 case SC_Extern: 6632 case SC_PrivateExtern: 6633 break; 6634 } 6635 } else if (SC == SC_Register) { 6636 // Global Named register 6637 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6638 const auto &TI = Context.getTargetInfo(); 6639 bool HasSizeMismatch; 6640 6641 if (!TI.isValidGCCRegisterName(Label)) 6642 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6643 else if (!TI.validateGlobalRegisterVariable(Label, 6644 Context.getTypeSize(R), 6645 HasSizeMismatch)) 6646 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6647 else if (HasSizeMismatch) 6648 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6649 } 6650 6651 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6652 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6653 NewVD->setInvalidDecl(true); 6654 } 6655 } 6656 6657 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6658 Context, Label, 0)); 6659 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6660 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6661 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6662 if (I != ExtnameUndeclaredIdentifiers.end()) { 6663 if (isDeclExternC(NewVD)) { 6664 NewVD->addAttr(I->second); 6665 ExtnameUndeclaredIdentifiers.erase(I); 6666 } else 6667 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6668 << /*Variable*/1 << NewVD; 6669 } 6670 } 6671 6672 // Find the shadowed declaration before filtering for scope. 6673 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6674 ? getShadowedDeclaration(NewVD, Previous) 6675 : nullptr; 6676 6677 // Don't consider existing declarations that are in a different 6678 // scope and are out-of-semantic-context declarations (if the new 6679 // declaration has linkage). 6680 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6681 D.getCXXScopeSpec().isNotEmpty() || 6682 IsMemberSpecialization || 6683 IsVariableTemplateSpecialization); 6684 6685 // Check whether the previous declaration is in the same block scope. This 6686 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6687 if (getLangOpts().CPlusPlus && 6688 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6689 NewVD->setPreviousDeclInSameBlockScope( 6690 Previous.isSingleResult() && !Previous.isShadowed() && 6691 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6692 6693 if (!getLangOpts().CPlusPlus) { 6694 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6695 } else { 6696 // If this is an explicit specialization of a static data member, check it. 6697 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 6698 CheckMemberSpecialization(NewVD, Previous)) 6699 NewVD->setInvalidDecl(); 6700 6701 // Merge the decl with the existing one if appropriate. 6702 if (!Previous.empty()) { 6703 if (Previous.isSingleResult() && 6704 isa<FieldDecl>(Previous.getFoundDecl()) && 6705 D.getCXXScopeSpec().isSet()) { 6706 // The user tried to define a non-static data member 6707 // out-of-line (C++ [dcl.meaning]p1). 6708 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6709 << D.getCXXScopeSpec().getRange(); 6710 Previous.clear(); 6711 NewVD->setInvalidDecl(); 6712 } 6713 } else if (D.getCXXScopeSpec().isSet()) { 6714 // No previous declaration in the qualifying scope. 6715 Diag(D.getIdentifierLoc(), diag::err_no_member) 6716 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6717 << D.getCXXScopeSpec().getRange(); 6718 NewVD->setInvalidDecl(); 6719 } 6720 6721 if (!IsVariableTemplateSpecialization) 6722 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6723 6724 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...] 6725 // an explicit specialization (14.8.3) or a partial specialization of a 6726 // concept definition. 6727 if (IsVariableTemplateSpecialization && 6728 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() && 6729 Previous.isSingleResult()) { 6730 NamedDecl *PreviousDecl = Previous.getFoundDecl(); 6731 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) { 6732 if (VarTmpl->isConcept()) { 6733 Diag(NewVD->getLocation(), diag::err_concept_specialized) 6734 << 1 /*variable*/ 6735 << (IsPartialSpecialization ? 2 /*partially specialized*/ 6736 : 1 /*explicitly specialized*/); 6737 Diag(VarTmpl->getLocation(), diag::note_previous_declaration); 6738 NewVD->setInvalidDecl(); 6739 } 6740 } 6741 } 6742 6743 if (NewTemplate) { 6744 VarTemplateDecl *PrevVarTemplate = 6745 NewVD->getPreviousDecl() 6746 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6747 : nullptr; 6748 6749 // Check the template parameter list of this declaration, possibly 6750 // merging in the template parameter list from the previous variable 6751 // template declaration. 6752 if (CheckTemplateParameterList( 6753 TemplateParams, 6754 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6755 : nullptr, 6756 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6757 DC->isDependentContext()) 6758 ? TPC_ClassTemplateMember 6759 : TPC_VarTemplate)) 6760 NewVD->setInvalidDecl(); 6761 6762 // If we are providing an explicit specialization of a static variable 6763 // template, make a note of that. 6764 if (PrevVarTemplate && 6765 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6766 PrevVarTemplate->setMemberSpecialization(); 6767 } 6768 } 6769 6770 // Diagnose shadowed variables iff this isn't a redeclaration. 6771 if (ShadowedDecl && !D.isRedeclaration()) 6772 CheckShadow(NewVD, ShadowedDecl, Previous); 6773 6774 ProcessPragmaWeak(S, NewVD); 6775 6776 // If this is the first declaration of an extern C variable, update 6777 // the map of such variables. 6778 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6779 isIncompleteDeclExternC(*this, NewVD)) 6780 RegisterLocallyScopedExternCDecl(NewVD, S); 6781 6782 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6783 Decl *ManglingContextDecl; 6784 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6785 NewVD->getDeclContext(), ManglingContextDecl)) { 6786 Context.setManglingNumber( 6787 NewVD, MCtx->getManglingNumber( 6788 NewVD, getMSManglingNumber(getLangOpts(), S))); 6789 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6790 } 6791 } 6792 6793 // Special handling of variable named 'main'. 6794 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6795 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6796 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6797 6798 // C++ [basic.start.main]p3 6799 // A program that declares a variable main at global scope is ill-formed. 6800 if (getLangOpts().CPlusPlus) 6801 Diag(D.getLocStart(), diag::err_main_global_variable); 6802 6803 // In C, and external-linkage variable named main results in undefined 6804 // behavior. 6805 else if (NewVD->hasExternalFormalLinkage()) 6806 Diag(D.getLocStart(), diag::warn_main_redefined); 6807 } 6808 6809 if (D.isRedeclaration() && !Previous.empty()) { 6810 checkDLLAttributeRedeclaration( 6811 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6812 IsMemberSpecialization, D.isFunctionDefinition()); 6813 } 6814 6815 if (NewTemplate) { 6816 if (NewVD->isInvalidDecl()) 6817 NewTemplate->setInvalidDecl(); 6818 ActOnDocumentableDecl(NewTemplate); 6819 return NewTemplate; 6820 } 6821 6822 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 6823 CompleteMemberSpecialization(NewVD, Previous); 6824 6825 return NewVD; 6826 } 6827 6828 /// Enum describing the %select options in diag::warn_decl_shadow. 6829 enum ShadowedDeclKind { 6830 SDK_Local, 6831 SDK_Global, 6832 SDK_StaticMember, 6833 SDK_Field, 6834 SDK_Typedef, 6835 SDK_Using 6836 }; 6837 6838 /// Determine what kind of declaration we're shadowing. 6839 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6840 const DeclContext *OldDC) { 6841 if (isa<TypeAliasDecl>(ShadowedDecl)) 6842 return SDK_Using; 6843 else if (isa<TypedefDecl>(ShadowedDecl)) 6844 return SDK_Typedef; 6845 else if (isa<RecordDecl>(OldDC)) 6846 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6847 6848 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6849 } 6850 6851 /// Return the location of the capture if the given lambda captures the given 6852 /// variable \p VD, or an invalid source location otherwise. 6853 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 6854 const VarDecl *VD) { 6855 for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) { 6856 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 6857 return Capture.getLocation(); 6858 } 6859 return SourceLocation(); 6860 } 6861 6862 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 6863 const LookupResult &R) { 6864 // Only diagnose if we're shadowing an unambiguous field or variable. 6865 if (R.getResultKind() != LookupResult::Found) 6866 return false; 6867 6868 // Return false if warning is ignored. 6869 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 6870 } 6871 6872 /// \brief Return the declaration shadowed by the given variable \p D, or null 6873 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6874 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 6875 const LookupResult &R) { 6876 if (!shouldWarnIfShadowedDecl(Diags, R)) 6877 return nullptr; 6878 6879 // Don't diagnose declarations at file scope. 6880 if (D->hasGlobalStorage()) 6881 return nullptr; 6882 6883 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6884 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 6885 ? ShadowedDecl 6886 : nullptr; 6887 } 6888 6889 /// \brief Return the declaration shadowed by the given typedef \p D, or null 6890 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6891 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 6892 const LookupResult &R) { 6893 // Don't warn if typedef declaration is part of a class 6894 if (D->getDeclContext()->isRecord()) 6895 return nullptr; 6896 6897 if (!shouldWarnIfShadowedDecl(Diags, R)) 6898 return nullptr; 6899 6900 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6901 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 6902 } 6903 6904 /// \brief Diagnose variable or built-in function shadowing. Implements 6905 /// -Wshadow. 6906 /// 6907 /// This method is called whenever a VarDecl is added to a "useful" 6908 /// scope. 6909 /// 6910 /// \param ShadowedDecl the declaration that is shadowed by the given variable 6911 /// \param R the lookup of the name 6912 /// 6913 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 6914 const LookupResult &R) { 6915 DeclContext *NewDC = D->getDeclContext(); 6916 6917 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 6918 // Fields are not shadowed by variables in C++ static methods. 6919 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 6920 if (MD->isStatic()) 6921 return; 6922 6923 // Fields shadowed by constructor parameters are a special case. Usually 6924 // the constructor initializes the field with the parameter. 6925 if (isa<CXXConstructorDecl>(NewDC)) 6926 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 6927 // Remember that this was shadowed so we can either warn about its 6928 // modification or its existence depending on warning settings. 6929 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 6930 return; 6931 } 6932 } 6933 6934 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6935 if (shadowedVar->isExternC()) { 6936 // For shadowing external vars, make sure that we point to the global 6937 // declaration, not a locally scoped extern declaration. 6938 for (auto I : shadowedVar->redecls()) 6939 if (I->isFileVarDecl()) { 6940 ShadowedDecl = I; 6941 break; 6942 } 6943 } 6944 6945 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6946 6947 unsigned WarningDiag = diag::warn_decl_shadow; 6948 SourceLocation CaptureLoc; 6949 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 6950 isa<CXXMethodDecl>(NewDC)) { 6951 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 6952 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 6953 if (RD->getLambdaCaptureDefault() == LCD_None) { 6954 // Try to avoid warnings for lambdas with an explicit capture list. 6955 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 6956 // Warn only when the lambda captures the shadowed decl explicitly. 6957 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 6958 if (CaptureLoc.isInvalid()) 6959 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 6960 } else { 6961 // Remember that this was shadowed so we can avoid the warning if the 6962 // shadowed decl isn't captured and the warning settings allow it. 6963 cast<LambdaScopeInfo>(getCurFunction()) 6964 ->ShadowingDecls.push_back( 6965 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 6966 return; 6967 } 6968 } 6969 } 6970 } 6971 6972 // Only warn about certain kinds of shadowing for class members. 6973 if (NewDC && NewDC->isRecord()) { 6974 // In particular, don't warn about shadowing non-class members. 6975 if (!OldDC->isRecord()) 6976 return; 6977 6978 // TODO: should we warn about static data members shadowing 6979 // static data members from base classes? 6980 6981 // TODO: don't diagnose for inaccessible shadowed members. 6982 // This is hard to do perfectly because we might friend the 6983 // shadowing context, but that's just a false negative. 6984 } 6985 6986 6987 DeclarationName Name = R.getLookupName(); 6988 6989 // Emit warning and note. 6990 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 6991 return; 6992 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 6993 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 6994 if (!CaptureLoc.isInvalid()) 6995 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 6996 << Name << /*explicitly*/ 1; 6997 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6998 } 6999 7000 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7001 /// when these variables are captured by the lambda. 7002 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7003 for (const auto &Shadow : LSI->ShadowingDecls) { 7004 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7005 // Try to avoid the warning when the shadowed decl isn't captured. 7006 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7007 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7008 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7009 ? diag::warn_decl_shadow_uncaptured_local 7010 : diag::warn_decl_shadow) 7011 << Shadow.VD->getDeclName() 7012 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7013 if (!CaptureLoc.isInvalid()) 7014 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7015 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7016 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7017 } 7018 } 7019 7020 /// \brief Check -Wshadow without the advantage of a previous lookup. 7021 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7022 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7023 return; 7024 7025 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7026 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 7027 LookupName(R, S); 7028 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7029 CheckShadow(D, ShadowedDecl, R); 7030 } 7031 7032 /// Check if 'E', which is an expression that is about to be modified, refers 7033 /// to a constructor parameter that shadows a field. 7034 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7035 // Quickly ignore expressions that can't be shadowing ctor parameters. 7036 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7037 return; 7038 E = E->IgnoreParenImpCasts(); 7039 auto *DRE = dyn_cast<DeclRefExpr>(E); 7040 if (!DRE) 7041 return; 7042 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7043 auto I = ShadowingDecls.find(D); 7044 if (I == ShadowingDecls.end()) 7045 return; 7046 const NamedDecl *ShadowedDecl = I->second; 7047 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7048 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7049 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7050 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7051 7052 // Avoid issuing multiple warnings about the same decl. 7053 ShadowingDecls.erase(I); 7054 } 7055 7056 /// Check for conflict between this global or extern "C" declaration and 7057 /// previous global or extern "C" declarations. This is only used in C++. 7058 template<typename T> 7059 static bool checkGlobalOrExternCConflict( 7060 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7061 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7062 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7063 7064 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7065 // The common case: this global doesn't conflict with any extern "C" 7066 // declaration. 7067 return false; 7068 } 7069 7070 if (Prev) { 7071 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7072 // Both the old and new declarations have C language linkage. This is a 7073 // redeclaration. 7074 Previous.clear(); 7075 Previous.addDecl(Prev); 7076 return true; 7077 } 7078 7079 // This is a global, non-extern "C" declaration, and there is a previous 7080 // non-global extern "C" declaration. Diagnose if this is a variable 7081 // declaration. 7082 if (!isa<VarDecl>(ND)) 7083 return false; 7084 } else { 7085 // The declaration is extern "C". Check for any declaration in the 7086 // translation unit which might conflict. 7087 if (IsGlobal) { 7088 // We have already performed the lookup into the translation unit. 7089 IsGlobal = false; 7090 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7091 I != E; ++I) { 7092 if (isa<VarDecl>(*I)) { 7093 Prev = *I; 7094 break; 7095 } 7096 } 7097 } else { 7098 DeclContext::lookup_result R = 7099 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7100 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7101 I != E; ++I) { 7102 if (isa<VarDecl>(*I)) { 7103 Prev = *I; 7104 break; 7105 } 7106 // FIXME: If we have any other entity with this name in global scope, 7107 // the declaration is ill-formed, but that is a defect: it breaks the 7108 // 'stat' hack, for instance. Only variables can have mangled name 7109 // clashes with extern "C" declarations, so only they deserve a 7110 // diagnostic. 7111 } 7112 } 7113 7114 if (!Prev) 7115 return false; 7116 } 7117 7118 // Use the first declaration's location to ensure we point at something which 7119 // is lexically inside an extern "C" linkage-spec. 7120 assert(Prev && "should have found a previous declaration to diagnose"); 7121 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7122 Prev = FD->getFirstDecl(); 7123 else 7124 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7125 7126 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7127 << IsGlobal << ND; 7128 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7129 << IsGlobal; 7130 return false; 7131 } 7132 7133 /// Apply special rules for handling extern "C" declarations. Returns \c true 7134 /// if we have found that this is a redeclaration of some prior entity. 7135 /// 7136 /// Per C++ [dcl.link]p6: 7137 /// Two declarations [for a function or variable] with C language linkage 7138 /// with the same name that appear in different scopes refer to the same 7139 /// [entity]. An entity with C language linkage shall not be declared with 7140 /// the same name as an entity in global scope. 7141 template<typename T> 7142 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7143 LookupResult &Previous) { 7144 if (!S.getLangOpts().CPlusPlus) { 7145 // In C, when declaring a global variable, look for a corresponding 'extern' 7146 // variable declared in function scope. We don't need this in C++, because 7147 // we find local extern decls in the surrounding file-scope DeclContext. 7148 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7149 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7150 Previous.clear(); 7151 Previous.addDecl(Prev); 7152 return true; 7153 } 7154 } 7155 return false; 7156 } 7157 7158 // A declaration in the translation unit can conflict with an extern "C" 7159 // declaration. 7160 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7161 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7162 7163 // An extern "C" declaration can conflict with a declaration in the 7164 // translation unit or can be a redeclaration of an extern "C" declaration 7165 // in another scope. 7166 if (isIncompleteDeclExternC(S,ND)) 7167 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7168 7169 // Neither global nor extern "C": nothing to do. 7170 return false; 7171 } 7172 7173 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7174 // If the decl is already known invalid, don't check it. 7175 if (NewVD->isInvalidDecl()) 7176 return; 7177 7178 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 7179 QualType T = TInfo->getType(); 7180 7181 // Defer checking an 'auto' type until its initializer is attached. 7182 if (T->isUndeducedType()) 7183 return; 7184 7185 if (NewVD->hasAttrs()) 7186 CheckAlignasUnderalignment(NewVD); 7187 7188 if (T->isObjCObjectType()) { 7189 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7190 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7191 T = Context.getObjCObjectPointerType(T); 7192 NewVD->setType(T); 7193 } 7194 7195 // Emit an error if an address space was applied to decl with local storage. 7196 // This includes arrays of objects with address space qualifiers, but not 7197 // automatic variables that point to other address spaces. 7198 // ISO/IEC TR 18037 S5.1.2 7199 if (!getLangOpts().OpenCL 7200 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 7201 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 7202 NewVD->setInvalidDecl(); 7203 return; 7204 } 7205 7206 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7207 // scope. 7208 if (getLangOpts().OpenCLVersion == 120 && 7209 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7210 NewVD->isStaticLocal()) { 7211 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7212 NewVD->setInvalidDecl(); 7213 return; 7214 } 7215 7216 if (getLangOpts().OpenCL) { 7217 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7218 if (NewVD->hasAttr<BlocksAttr>()) { 7219 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7220 return; 7221 } 7222 7223 if (T->isBlockPointerType()) { 7224 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7225 // can't use 'extern' storage class. 7226 if (!T.isConstQualified()) { 7227 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7228 << 0 /*const*/; 7229 NewVD->setInvalidDecl(); 7230 return; 7231 } 7232 if (NewVD->hasExternalStorage()) { 7233 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7234 NewVD->setInvalidDecl(); 7235 return; 7236 } 7237 } 7238 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 7239 // __constant address space. 7240 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 7241 // variables inside a function can also be declared in the global 7242 // address space. 7243 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7244 NewVD->hasExternalStorage()) { 7245 if (!T->isSamplerT() && 7246 !(T.getAddressSpace() == LangAS::opencl_constant || 7247 (T.getAddressSpace() == LangAS::opencl_global && 7248 getLangOpts().OpenCLVersion == 200))) { 7249 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7250 if (getLangOpts().OpenCLVersion == 200) 7251 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7252 << Scope << "global or constant"; 7253 else 7254 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7255 << Scope << "constant"; 7256 NewVD->setInvalidDecl(); 7257 return; 7258 } 7259 } else { 7260 if (T.getAddressSpace() == LangAS::opencl_global) { 7261 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7262 << 1 /*is any function*/ << "global"; 7263 NewVD->setInvalidDecl(); 7264 return; 7265 } 7266 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables 7267 // in functions. 7268 if (T.getAddressSpace() == LangAS::opencl_constant || 7269 T.getAddressSpace() == LangAS::opencl_local) { 7270 FunctionDecl *FD = getCurFunctionDecl(); 7271 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7272 if (T.getAddressSpace() == LangAS::opencl_constant) 7273 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7274 << 0 /*non-kernel only*/ << "constant"; 7275 else 7276 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7277 << 0 /*non-kernel only*/ << "local"; 7278 NewVD->setInvalidDecl(); 7279 return; 7280 } 7281 } 7282 } 7283 } 7284 7285 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7286 && !NewVD->hasAttr<BlocksAttr>()) { 7287 if (getLangOpts().getGC() != LangOptions::NonGC) 7288 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7289 else { 7290 assert(!getLangOpts().ObjCAutoRefCount); 7291 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7292 } 7293 } 7294 7295 bool isVM = T->isVariablyModifiedType(); 7296 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7297 NewVD->hasAttr<BlocksAttr>()) 7298 getCurFunction()->setHasBranchProtectedScope(); 7299 7300 if ((isVM && NewVD->hasLinkage()) || 7301 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7302 bool SizeIsNegative; 7303 llvm::APSInt Oversized; 7304 TypeSourceInfo *FixedTInfo = 7305 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 7306 SizeIsNegative, Oversized); 7307 if (!FixedTInfo && T->isVariableArrayType()) { 7308 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7309 // FIXME: This won't give the correct result for 7310 // int a[10][n]; 7311 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7312 7313 if (NewVD->isFileVarDecl()) 7314 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7315 << SizeRange; 7316 else if (NewVD->isStaticLocal()) 7317 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7318 << SizeRange; 7319 else 7320 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7321 << SizeRange; 7322 NewVD->setInvalidDecl(); 7323 return; 7324 } 7325 7326 if (!FixedTInfo) { 7327 if (NewVD->isFileVarDecl()) 7328 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7329 else 7330 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7331 NewVD->setInvalidDecl(); 7332 return; 7333 } 7334 7335 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7336 NewVD->setType(FixedTInfo->getType()); 7337 NewVD->setTypeSourceInfo(FixedTInfo); 7338 } 7339 7340 if (T->isVoidType()) { 7341 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7342 // of objects and functions. 7343 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7344 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7345 << T; 7346 NewVD->setInvalidDecl(); 7347 return; 7348 } 7349 } 7350 7351 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7352 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7353 NewVD->setInvalidDecl(); 7354 return; 7355 } 7356 7357 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7358 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7359 NewVD->setInvalidDecl(); 7360 return; 7361 } 7362 7363 if (NewVD->isConstexpr() && !T->isDependentType() && 7364 RequireLiteralType(NewVD->getLocation(), T, 7365 diag::err_constexpr_var_non_literal)) { 7366 NewVD->setInvalidDecl(); 7367 return; 7368 } 7369 } 7370 7371 /// \brief Perform semantic checking on a newly-created variable 7372 /// declaration. 7373 /// 7374 /// This routine performs all of the type-checking required for a 7375 /// variable declaration once it has been built. It is used both to 7376 /// check variables after they have been parsed and their declarators 7377 /// have been translated into a declaration, and to check variables 7378 /// that have been instantiated from a template. 7379 /// 7380 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7381 /// 7382 /// Returns true if the variable declaration is a redeclaration. 7383 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7384 CheckVariableDeclarationType(NewVD); 7385 7386 // If the decl is already known invalid, don't check it. 7387 if (NewVD->isInvalidDecl()) 7388 return false; 7389 7390 // If we did not find anything by this name, look for a non-visible 7391 // extern "C" declaration with the same name. 7392 if (Previous.empty() && 7393 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7394 Previous.setShadowed(); 7395 7396 if (!Previous.empty()) { 7397 MergeVarDecl(NewVD, Previous); 7398 return true; 7399 } 7400 return false; 7401 } 7402 7403 namespace { 7404 struct FindOverriddenMethod { 7405 Sema *S; 7406 CXXMethodDecl *Method; 7407 7408 /// Member lookup function that determines whether a given C++ 7409 /// method overrides a method in a base class, to be used with 7410 /// CXXRecordDecl::lookupInBases(). 7411 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7412 RecordDecl *BaseRecord = 7413 Specifier->getType()->getAs<RecordType>()->getDecl(); 7414 7415 DeclarationName Name = Method->getDeclName(); 7416 7417 // FIXME: Do we care about other names here too? 7418 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7419 // We really want to find the base class destructor here. 7420 QualType T = S->Context.getTypeDeclType(BaseRecord); 7421 CanQualType CT = S->Context.getCanonicalType(T); 7422 7423 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7424 } 7425 7426 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7427 Path.Decls = Path.Decls.slice(1)) { 7428 NamedDecl *D = Path.Decls.front(); 7429 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7430 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7431 return true; 7432 } 7433 } 7434 7435 return false; 7436 } 7437 }; 7438 7439 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7440 } // end anonymous namespace 7441 7442 /// \brief Report an error regarding overriding, along with any relevant 7443 /// overriden methods. 7444 /// 7445 /// \param DiagID the primary error to report. 7446 /// \param MD the overriding method. 7447 /// \param OEK which overrides to include as notes. 7448 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7449 OverrideErrorKind OEK = OEK_All) { 7450 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7451 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7452 E = MD->end_overridden_methods(); 7453 I != E; ++I) { 7454 // This check (& the OEK parameter) could be replaced by a predicate, but 7455 // without lambdas that would be overkill. This is still nicer than writing 7456 // out the diag loop 3 times. 7457 if ((OEK == OEK_All) || 7458 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 7459 (OEK == OEK_Deleted && (*I)->isDeleted())) 7460 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 7461 } 7462 } 7463 7464 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7465 /// and if so, check that it's a valid override and remember it. 7466 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7467 // Look for methods in base classes that this method might override. 7468 CXXBasePaths Paths; 7469 FindOverriddenMethod FOM; 7470 FOM.Method = MD; 7471 FOM.S = this; 7472 bool hasDeletedOverridenMethods = false; 7473 bool hasNonDeletedOverridenMethods = false; 7474 bool AddedAny = false; 7475 if (DC->lookupInBases(FOM, Paths)) { 7476 for (auto *I : Paths.found_decls()) { 7477 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7478 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7479 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7480 !CheckOverridingFunctionAttributes(MD, OldMD) && 7481 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7482 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7483 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7484 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7485 AddedAny = true; 7486 } 7487 } 7488 } 7489 } 7490 7491 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7492 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7493 } 7494 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7495 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7496 } 7497 7498 return AddedAny; 7499 } 7500 7501 namespace { 7502 // Struct for holding all of the extra arguments needed by 7503 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7504 struct ActOnFDArgs { 7505 Scope *S; 7506 Declarator &D; 7507 MultiTemplateParamsArg TemplateParamLists; 7508 bool AddToScope; 7509 }; 7510 } // end anonymous namespace 7511 7512 namespace { 7513 7514 // Callback to only accept typo corrections that have a non-zero edit distance. 7515 // Also only accept corrections that have the same parent decl. 7516 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7517 public: 7518 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7519 CXXRecordDecl *Parent) 7520 : Context(Context), OriginalFD(TypoFD), 7521 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7522 7523 bool ValidateCandidate(const TypoCorrection &candidate) override { 7524 if (candidate.getEditDistance() == 0) 7525 return false; 7526 7527 SmallVector<unsigned, 1> MismatchedParams; 7528 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7529 CDeclEnd = candidate.end(); 7530 CDecl != CDeclEnd; ++CDecl) { 7531 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7532 7533 if (FD && !FD->hasBody() && 7534 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7535 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7536 CXXRecordDecl *Parent = MD->getParent(); 7537 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7538 return true; 7539 } else if (!ExpectedParent) { 7540 return true; 7541 } 7542 } 7543 } 7544 7545 return false; 7546 } 7547 7548 private: 7549 ASTContext &Context; 7550 FunctionDecl *OriginalFD; 7551 CXXRecordDecl *ExpectedParent; 7552 }; 7553 7554 } // end anonymous namespace 7555 7556 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7557 TypoCorrectedFunctionDefinitions.insert(F); 7558 } 7559 7560 /// \brief Generate diagnostics for an invalid function redeclaration. 7561 /// 7562 /// This routine handles generating the diagnostic messages for an invalid 7563 /// function redeclaration, including finding possible similar declarations 7564 /// or performing typo correction if there are no previous declarations with 7565 /// the same name. 7566 /// 7567 /// Returns a NamedDecl iff typo correction was performed and substituting in 7568 /// the new declaration name does not cause new errors. 7569 static NamedDecl *DiagnoseInvalidRedeclaration( 7570 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7571 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7572 DeclarationName Name = NewFD->getDeclName(); 7573 DeclContext *NewDC = NewFD->getDeclContext(); 7574 SmallVector<unsigned, 1> MismatchedParams; 7575 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7576 TypoCorrection Correction; 7577 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7578 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7579 : diag::err_member_decl_does_not_match; 7580 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7581 IsLocalFriend ? Sema::LookupLocalFriendName 7582 : Sema::LookupOrdinaryName, 7583 Sema::ForRedeclaration); 7584 7585 NewFD->setInvalidDecl(); 7586 if (IsLocalFriend) 7587 SemaRef.LookupName(Prev, S); 7588 else 7589 SemaRef.LookupQualifiedName(Prev, NewDC); 7590 assert(!Prev.isAmbiguous() && 7591 "Cannot have an ambiguity in previous-declaration lookup"); 7592 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7593 if (!Prev.empty()) { 7594 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7595 Func != FuncEnd; ++Func) { 7596 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7597 if (FD && 7598 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7599 // Add 1 to the index so that 0 can mean the mismatch didn't 7600 // involve a parameter 7601 unsigned ParamNum = 7602 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7603 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7604 } 7605 } 7606 // If the qualified name lookup yielded nothing, try typo correction 7607 } else if ((Correction = SemaRef.CorrectTypo( 7608 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7609 &ExtraArgs.D.getCXXScopeSpec(), 7610 llvm::make_unique<DifferentNameValidatorCCC>( 7611 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7612 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7613 // Set up everything for the call to ActOnFunctionDeclarator 7614 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7615 ExtraArgs.D.getIdentifierLoc()); 7616 Previous.clear(); 7617 Previous.setLookupName(Correction.getCorrection()); 7618 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7619 CDeclEnd = Correction.end(); 7620 CDecl != CDeclEnd; ++CDecl) { 7621 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7622 if (FD && !FD->hasBody() && 7623 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7624 Previous.addDecl(FD); 7625 } 7626 } 7627 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7628 7629 NamedDecl *Result; 7630 // Retry building the function declaration with the new previous 7631 // declarations, and with errors suppressed. 7632 { 7633 // Trap errors. 7634 Sema::SFINAETrap Trap(SemaRef); 7635 7636 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7637 // pieces need to verify the typo-corrected C++ declaration and hopefully 7638 // eliminate the need for the parameter pack ExtraArgs. 7639 Result = SemaRef.ActOnFunctionDeclarator( 7640 ExtraArgs.S, ExtraArgs.D, 7641 Correction.getCorrectionDecl()->getDeclContext(), 7642 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7643 ExtraArgs.AddToScope); 7644 7645 if (Trap.hasErrorOccurred()) 7646 Result = nullptr; 7647 } 7648 7649 if (Result) { 7650 // Determine which correction we picked. 7651 Decl *Canonical = Result->getCanonicalDecl(); 7652 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7653 I != E; ++I) 7654 if ((*I)->getCanonicalDecl() == Canonical) 7655 Correction.setCorrectionDecl(*I); 7656 7657 // Let Sema know about the correction. 7658 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 7659 SemaRef.diagnoseTypo( 7660 Correction, 7661 SemaRef.PDiag(IsLocalFriend 7662 ? diag::err_no_matching_local_friend_suggest 7663 : diag::err_member_decl_does_not_match_suggest) 7664 << Name << NewDC << IsDefinition); 7665 return Result; 7666 } 7667 7668 // Pretend the typo correction never occurred 7669 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7670 ExtraArgs.D.getIdentifierLoc()); 7671 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7672 Previous.clear(); 7673 Previous.setLookupName(Name); 7674 } 7675 7676 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7677 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7678 7679 bool NewFDisConst = false; 7680 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7681 NewFDisConst = NewMD->isConst(); 7682 7683 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7684 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7685 NearMatch != NearMatchEnd; ++NearMatch) { 7686 FunctionDecl *FD = NearMatch->first; 7687 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7688 bool FDisConst = MD && MD->isConst(); 7689 bool IsMember = MD || !IsLocalFriend; 7690 7691 // FIXME: These notes are poorly worded for the local friend case. 7692 if (unsigned Idx = NearMatch->second) { 7693 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7694 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7695 if (Loc.isInvalid()) Loc = FD->getLocation(); 7696 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7697 : diag::note_local_decl_close_param_match) 7698 << Idx << FDParam->getType() 7699 << NewFD->getParamDecl(Idx - 1)->getType(); 7700 } else if (FDisConst != NewFDisConst) { 7701 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7702 << NewFDisConst << FD->getSourceRange().getEnd(); 7703 } else 7704 SemaRef.Diag(FD->getLocation(), 7705 IsMember ? diag::note_member_def_close_match 7706 : diag::note_local_decl_close_match); 7707 } 7708 return nullptr; 7709 } 7710 7711 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7712 switch (D.getDeclSpec().getStorageClassSpec()) { 7713 default: llvm_unreachable("Unknown storage class!"); 7714 case DeclSpec::SCS_auto: 7715 case DeclSpec::SCS_register: 7716 case DeclSpec::SCS_mutable: 7717 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7718 diag::err_typecheck_sclass_func); 7719 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7720 D.setInvalidType(); 7721 break; 7722 case DeclSpec::SCS_unspecified: break; 7723 case DeclSpec::SCS_extern: 7724 if (D.getDeclSpec().isExternInLinkageSpec()) 7725 return SC_None; 7726 return SC_Extern; 7727 case DeclSpec::SCS_static: { 7728 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7729 // C99 6.7.1p5: 7730 // The declaration of an identifier for a function that has 7731 // block scope shall have no explicit storage-class specifier 7732 // other than extern 7733 // See also (C++ [dcl.stc]p4). 7734 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7735 diag::err_static_block_func); 7736 break; 7737 } else 7738 return SC_Static; 7739 } 7740 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7741 } 7742 7743 // No explicit storage class has already been returned 7744 return SC_None; 7745 } 7746 7747 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7748 DeclContext *DC, QualType &R, 7749 TypeSourceInfo *TInfo, 7750 StorageClass SC, 7751 bool &IsVirtualOkay) { 7752 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7753 DeclarationName Name = NameInfo.getName(); 7754 7755 FunctionDecl *NewFD = nullptr; 7756 bool isInline = D.getDeclSpec().isInlineSpecified(); 7757 7758 if (!SemaRef.getLangOpts().CPlusPlus) { 7759 // Determine whether the function was written with a 7760 // prototype. This true when: 7761 // - there is a prototype in the declarator, or 7762 // - the type R of the function is some kind of typedef or other non- 7763 // attributed reference to a type name (which eventually refers to a 7764 // function type). 7765 bool HasPrototype = 7766 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7767 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 7768 7769 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7770 D.getLocStart(), NameInfo, R, 7771 TInfo, SC, isInline, 7772 HasPrototype, false); 7773 if (D.isInvalidType()) 7774 NewFD->setInvalidDecl(); 7775 7776 return NewFD; 7777 } 7778 7779 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7780 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7781 7782 // Check that the return type is not an abstract class type. 7783 // For record types, this is done by the AbstractClassUsageDiagnoser once 7784 // the class has been completely parsed. 7785 if (!DC->isRecord() && 7786 SemaRef.RequireNonAbstractType( 7787 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7788 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7789 D.setInvalidType(); 7790 7791 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7792 // This is a C++ constructor declaration. 7793 assert(DC->isRecord() && 7794 "Constructors can only be declared in a member context"); 7795 7796 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7797 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7798 D.getLocStart(), NameInfo, 7799 R, TInfo, isExplicit, isInline, 7800 /*isImplicitlyDeclared=*/false, 7801 isConstexpr); 7802 7803 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7804 // This is a C++ destructor declaration. 7805 if (DC->isRecord()) { 7806 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7807 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7808 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7809 SemaRef.Context, Record, 7810 D.getLocStart(), 7811 NameInfo, R, TInfo, isInline, 7812 /*isImplicitlyDeclared=*/false); 7813 7814 // If the class is complete, then we now create the implicit exception 7815 // specification. If the class is incomplete or dependent, we can't do 7816 // it yet. 7817 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7818 Record->getDefinition() && !Record->isBeingDefined() && 7819 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7820 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7821 } 7822 7823 IsVirtualOkay = true; 7824 return NewDD; 7825 7826 } else { 7827 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7828 D.setInvalidType(); 7829 7830 // Create a FunctionDecl to satisfy the function definition parsing 7831 // code path. 7832 return FunctionDecl::Create(SemaRef.Context, DC, 7833 D.getLocStart(), 7834 D.getIdentifierLoc(), Name, R, TInfo, 7835 SC, isInline, 7836 /*hasPrototype=*/true, isConstexpr); 7837 } 7838 7839 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7840 if (!DC->isRecord()) { 7841 SemaRef.Diag(D.getIdentifierLoc(), 7842 diag::err_conv_function_not_member); 7843 return nullptr; 7844 } 7845 7846 SemaRef.CheckConversionDeclarator(D, R, SC); 7847 IsVirtualOkay = true; 7848 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7849 D.getLocStart(), NameInfo, 7850 R, TInfo, isInline, isExplicit, 7851 isConstexpr, SourceLocation()); 7852 7853 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 7854 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 7855 7856 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(), 7857 isExplicit, NameInfo, R, TInfo, 7858 D.getLocEnd()); 7859 } else if (DC->isRecord()) { 7860 // If the name of the function is the same as the name of the record, 7861 // then this must be an invalid constructor that has a return type. 7862 // (The parser checks for a return type and makes the declarator a 7863 // constructor if it has no return type). 7864 if (Name.getAsIdentifierInfo() && 7865 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7866 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7867 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7868 << SourceRange(D.getIdentifierLoc()); 7869 return nullptr; 7870 } 7871 7872 // This is a C++ method declaration. 7873 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7874 cast<CXXRecordDecl>(DC), 7875 D.getLocStart(), NameInfo, R, 7876 TInfo, SC, isInline, 7877 isConstexpr, SourceLocation()); 7878 IsVirtualOkay = !Ret->isStatic(); 7879 return Ret; 7880 } else { 7881 bool isFriend = 7882 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 7883 if (!isFriend && SemaRef.CurContext->isRecord()) 7884 return nullptr; 7885 7886 // Determine whether the function was written with a 7887 // prototype. This true when: 7888 // - we're in C++ (where every function has a prototype), 7889 return FunctionDecl::Create(SemaRef.Context, DC, 7890 D.getLocStart(), 7891 NameInfo, R, TInfo, SC, isInline, 7892 true/*HasPrototype*/, isConstexpr); 7893 } 7894 } 7895 7896 enum OpenCLParamType { 7897 ValidKernelParam, 7898 PtrPtrKernelParam, 7899 PtrKernelParam, 7900 InvalidAddrSpacePtrKernelParam, 7901 InvalidKernelParam, 7902 RecordKernelParam 7903 }; 7904 7905 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 7906 if (PT->isPointerType()) { 7907 QualType PointeeType = PT->getPointeeType(); 7908 if (PointeeType->isPointerType()) 7909 return PtrPtrKernelParam; 7910 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 7911 PointeeType.getAddressSpace() == 0) 7912 return InvalidAddrSpacePtrKernelParam; 7913 return PtrKernelParam; 7914 } 7915 7916 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 7917 // be used as builtin types. 7918 7919 if (PT->isImageType()) 7920 return PtrKernelParam; 7921 7922 if (PT->isBooleanType()) 7923 return InvalidKernelParam; 7924 7925 if (PT->isEventT()) 7926 return InvalidKernelParam; 7927 7928 // OpenCL extension spec v1.2 s9.5: 7929 // This extension adds support for half scalar and vector types as built-in 7930 // types that can be used for arithmetic operations, conversions etc. 7931 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 7932 return InvalidKernelParam; 7933 7934 if (PT->isRecordType()) 7935 return RecordKernelParam; 7936 7937 return ValidKernelParam; 7938 } 7939 7940 static void checkIsValidOpenCLKernelParameter( 7941 Sema &S, 7942 Declarator &D, 7943 ParmVarDecl *Param, 7944 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 7945 QualType PT = Param->getType(); 7946 7947 // Cache the valid types we encounter to avoid rechecking structs that are 7948 // used again 7949 if (ValidTypes.count(PT.getTypePtr())) 7950 return; 7951 7952 switch (getOpenCLKernelParameterType(S, PT)) { 7953 case PtrPtrKernelParam: 7954 // OpenCL v1.2 s6.9.a: 7955 // A kernel function argument cannot be declared as a 7956 // pointer to a pointer type. 7957 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 7958 D.setInvalidType(); 7959 return; 7960 7961 case InvalidAddrSpacePtrKernelParam: 7962 // OpenCL v1.0 s6.5: 7963 // __kernel function arguments declared to be a pointer of a type can point 7964 // to one of the following address spaces only : __global, __local or 7965 // __constant. 7966 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 7967 D.setInvalidType(); 7968 return; 7969 7970 // OpenCL v1.2 s6.9.k: 7971 // Arguments to kernel functions in a program cannot be declared with the 7972 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 7973 // uintptr_t or a struct and/or union that contain fields declared to be 7974 // one of these built-in scalar types. 7975 7976 case InvalidKernelParam: 7977 // OpenCL v1.2 s6.8 n: 7978 // A kernel function argument cannot be declared 7979 // of event_t type. 7980 // Do not diagnose half type since it is diagnosed as invalid argument 7981 // type for any function elsewhere. 7982 if (!PT->isHalfType()) 7983 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7984 D.setInvalidType(); 7985 return; 7986 7987 case PtrKernelParam: 7988 case ValidKernelParam: 7989 ValidTypes.insert(PT.getTypePtr()); 7990 return; 7991 7992 case RecordKernelParam: 7993 break; 7994 } 7995 7996 // Track nested structs we will inspect 7997 SmallVector<const Decl *, 4> VisitStack; 7998 7999 // Track where we are in the nested structs. Items will migrate from 8000 // VisitStack to HistoryStack as we do the DFS for bad field. 8001 SmallVector<const FieldDecl *, 4> HistoryStack; 8002 HistoryStack.push_back(nullptr); 8003 8004 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 8005 VisitStack.push_back(PD); 8006 8007 assert(VisitStack.back() && "First decl null?"); 8008 8009 do { 8010 const Decl *Next = VisitStack.pop_back_val(); 8011 if (!Next) { 8012 assert(!HistoryStack.empty()); 8013 // Found a marker, we have gone up a level 8014 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8015 ValidTypes.insert(Hist->getType().getTypePtr()); 8016 8017 continue; 8018 } 8019 8020 // Adds everything except the original parameter declaration (which is not a 8021 // field itself) to the history stack. 8022 const RecordDecl *RD; 8023 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8024 HistoryStack.push_back(Field); 8025 RD = Field->getType()->castAs<RecordType>()->getDecl(); 8026 } else { 8027 RD = cast<RecordDecl>(Next); 8028 } 8029 8030 // Add a null marker so we know when we've gone back up a level 8031 VisitStack.push_back(nullptr); 8032 8033 for (const auto *FD : RD->fields()) { 8034 QualType QT = FD->getType(); 8035 8036 if (ValidTypes.count(QT.getTypePtr())) 8037 continue; 8038 8039 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8040 if (ParamType == ValidKernelParam) 8041 continue; 8042 8043 if (ParamType == RecordKernelParam) { 8044 VisitStack.push_back(FD); 8045 continue; 8046 } 8047 8048 // OpenCL v1.2 s6.9.p: 8049 // Arguments to kernel functions that are declared to be a struct or union 8050 // do not allow OpenCL objects to be passed as elements of the struct or 8051 // union. 8052 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8053 ParamType == InvalidAddrSpacePtrKernelParam) { 8054 S.Diag(Param->getLocation(), 8055 diag::err_record_with_pointers_kernel_param) 8056 << PT->isUnionType() 8057 << PT; 8058 } else { 8059 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8060 } 8061 8062 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 8063 << PD->getDeclName(); 8064 8065 // We have an error, now let's go back up through history and show where 8066 // the offending field came from 8067 for (ArrayRef<const FieldDecl *>::const_iterator 8068 I = HistoryStack.begin() + 1, 8069 E = HistoryStack.end(); 8070 I != E; ++I) { 8071 const FieldDecl *OuterField = *I; 8072 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8073 << OuterField->getType(); 8074 } 8075 8076 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8077 << QT->isPointerType() 8078 << QT; 8079 D.setInvalidType(); 8080 return; 8081 } 8082 } while (!VisitStack.empty()); 8083 } 8084 8085 /// Find the DeclContext in which a tag is implicitly declared if we see an 8086 /// elaborated type specifier in the specified context, and lookup finds 8087 /// nothing. 8088 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8089 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8090 DC = DC->getParent(); 8091 return DC; 8092 } 8093 8094 /// Find the Scope in which a tag is implicitly declared if we see an 8095 /// elaborated type specifier in the specified context, and lookup finds 8096 /// nothing. 8097 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8098 while (S->isClassScope() || 8099 (LangOpts.CPlusPlus && 8100 S->isFunctionPrototypeScope()) || 8101 ((S->getFlags() & Scope::DeclScope) == 0) || 8102 (S->getEntity() && S->getEntity()->isTransparentContext())) 8103 S = S->getParent(); 8104 return S; 8105 } 8106 8107 NamedDecl* 8108 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8109 TypeSourceInfo *TInfo, LookupResult &Previous, 8110 MultiTemplateParamsArg TemplateParamLists, 8111 bool &AddToScope) { 8112 QualType R = TInfo->getType(); 8113 8114 assert(R.getTypePtr()->isFunctionType()); 8115 8116 // TODO: consider using NameInfo for diagnostic. 8117 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8118 DeclarationName Name = NameInfo.getName(); 8119 StorageClass SC = getFunctionStorageClass(*this, D); 8120 8121 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8122 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8123 diag::err_invalid_thread) 8124 << DeclSpec::getSpecifierName(TSCS); 8125 8126 if (D.isFirstDeclarationOfMember()) 8127 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8128 D.getIdentifierLoc()); 8129 8130 bool isFriend = false; 8131 FunctionTemplateDecl *FunctionTemplate = nullptr; 8132 bool isMemberSpecialization = false; 8133 bool isFunctionTemplateSpecialization = false; 8134 8135 bool isDependentClassScopeExplicitSpecialization = false; 8136 bool HasExplicitTemplateArgs = false; 8137 TemplateArgumentListInfo TemplateArgs; 8138 8139 bool isVirtualOkay = false; 8140 8141 DeclContext *OriginalDC = DC; 8142 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8143 8144 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8145 isVirtualOkay); 8146 if (!NewFD) return nullptr; 8147 8148 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8149 NewFD->setTopLevelDeclInObjCContainer(); 8150 8151 // Set the lexical context. If this is a function-scope declaration, or has a 8152 // C++ scope specifier, or is the object of a friend declaration, the lexical 8153 // context will be different from the semantic context. 8154 NewFD->setLexicalDeclContext(CurContext); 8155 8156 if (IsLocalExternDecl) 8157 NewFD->setLocalExternDecl(); 8158 8159 if (getLangOpts().CPlusPlus) { 8160 bool isInline = D.getDeclSpec().isInlineSpecified(); 8161 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8162 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 8163 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 8164 bool isConcept = D.getDeclSpec().isConceptSpecified(); 8165 isFriend = D.getDeclSpec().isFriendSpecified(); 8166 if (isFriend && !isInline && D.isFunctionDefinition()) { 8167 // C++ [class.friend]p5 8168 // A function can be defined in a friend declaration of a 8169 // class . . . . Such a function is implicitly inline. 8170 NewFD->setImplicitlyInline(); 8171 } 8172 8173 // If this is a method defined in an __interface, and is not a constructor 8174 // or an overloaded operator, then set the pure flag (isVirtual will already 8175 // return true). 8176 if (const CXXRecordDecl *Parent = 8177 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8178 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8179 NewFD->setPure(true); 8180 8181 // C++ [class.union]p2 8182 // A union can have member functions, but not virtual functions. 8183 if (isVirtual && Parent->isUnion()) 8184 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8185 } 8186 8187 SetNestedNameSpecifier(NewFD, D); 8188 isMemberSpecialization = false; 8189 isFunctionTemplateSpecialization = false; 8190 if (D.isInvalidType()) 8191 NewFD->setInvalidDecl(); 8192 8193 // Match up the template parameter lists with the scope specifier, then 8194 // determine whether we have a template or a template specialization. 8195 bool Invalid = false; 8196 if (TemplateParameterList *TemplateParams = 8197 MatchTemplateParametersToScopeSpecifier( 8198 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 8199 D.getCXXScopeSpec(), 8200 D.getName().getKind() == UnqualifiedId::IK_TemplateId 8201 ? D.getName().TemplateId 8202 : nullptr, 8203 TemplateParamLists, isFriend, isMemberSpecialization, 8204 Invalid)) { 8205 if (TemplateParams->size() > 0) { 8206 // This is a function template 8207 8208 // Check that we can declare a template here. 8209 if (CheckTemplateDeclScope(S, TemplateParams)) 8210 NewFD->setInvalidDecl(); 8211 8212 // A destructor cannot be a template. 8213 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8214 Diag(NewFD->getLocation(), diag::err_destructor_template); 8215 NewFD->setInvalidDecl(); 8216 } 8217 8218 // If we're adding a template to a dependent context, we may need to 8219 // rebuilding some of the types used within the template parameter list, 8220 // now that we know what the current instantiation is. 8221 if (DC->isDependentContext()) { 8222 ContextRAII SavedContext(*this, DC); 8223 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8224 Invalid = true; 8225 } 8226 8227 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8228 NewFD->getLocation(), 8229 Name, TemplateParams, 8230 NewFD); 8231 FunctionTemplate->setLexicalDeclContext(CurContext); 8232 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8233 8234 // For source fidelity, store the other template param lists. 8235 if (TemplateParamLists.size() > 1) { 8236 NewFD->setTemplateParameterListsInfo(Context, 8237 TemplateParamLists.drop_back(1)); 8238 } 8239 } else { 8240 // This is a function template specialization. 8241 isFunctionTemplateSpecialization = true; 8242 // For source fidelity, store all the template param lists. 8243 if (TemplateParamLists.size() > 0) 8244 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8245 8246 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8247 if (isFriend) { 8248 // We want to remove the "template<>", found here. 8249 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8250 8251 // If we remove the template<> and the name is not a 8252 // template-id, we're actually silently creating a problem: 8253 // the friend declaration will refer to an untemplated decl, 8254 // and clearly the user wants a template specialization. So 8255 // we need to insert '<>' after the name. 8256 SourceLocation InsertLoc; 8257 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 8258 InsertLoc = D.getName().getSourceRange().getEnd(); 8259 InsertLoc = getLocForEndOfToken(InsertLoc); 8260 } 8261 8262 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8263 << Name << RemoveRange 8264 << FixItHint::CreateRemoval(RemoveRange) 8265 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8266 } 8267 } 8268 } 8269 else { 8270 // All template param lists were matched against the scope specifier: 8271 // this is NOT (an explicit specialization of) a template. 8272 if (TemplateParamLists.size() > 0) 8273 // For source fidelity, store all the template param lists. 8274 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8275 } 8276 8277 if (Invalid) { 8278 NewFD->setInvalidDecl(); 8279 if (FunctionTemplate) 8280 FunctionTemplate->setInvalidDecl(); 8281 } 8282 8283 // C++ [dcl.fct.spec]p5: 8284 // The virtual specifier shall only be used in declarations of 8285 // nonstatic class member functions that appear within a 8286 // member-specification of a class declaration; see 10.3. 8287 // 8288 if (isVirtual && !NewFD->isInvalidDecl()) { 8289 if (!isVirtualOkay) { 8290 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8291 diag::err_virtual_non_function); 8292 } else if (!CurContext->isRecord()) { 8293 // 'virtual' was specified outside of the class. 8294 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8295 diag::err_virtual_out_of_class) 8296 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8297 } else if (NewFD->getDescribedFunctionTemplate()) { 8298 // C++ [temp.mem]p3: 8299 // A member function template shall not be virtual. 8300 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8301 diag::err_virtual_member_function_template) 8302 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8303 } else { 8304 // Okay: Add virtual to the method. 8305 NewFD->setVirtualAsWritten(true); 8306 } 8307 8308 if (getLangOpts().CPlusPlus14 && 8309 NewFD->getReturnType()->isUndeducedType()) 8310 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8311 } 8312 8313 if (getLangOpts().CPlusPlus14 && 8314 (NewFD->isDependentContext() || 8315 (isFriend && CurContext->isDependentContext())) && 8316 NewFD->getReturnType()->isUndeducedType()) { 8317 // If the function template is referenced directly (for instance, as a 8318 // member of the current instantiation), pretend it has a dependent type. 8319 // This is not really justified by the standard, but is the only sane 8320 // thing to do. 8321 // FIXME: For a friend function, we have not marked the function as being 8322 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8323 const FunctionProtoType *FPT = 8324 NewFD->getType()->castAs<FunctionProtoType>(); 8325 QualType Result = 8326 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8327 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8328 FPT->getExtProtoInfo())); 8329 } 8330 8331 // C++ [dcl.fct.spec]p3: 8332 // The inline specifier shall not appear on a block scope function 8333 // declaration. 8334 if (isInline && !NewFD->isInvalidDecl()) { 8335 if (CurContext->isFunctionOrMethod()) { 8336 // 'inline' is not allowed on block scope function declaration. 8337 Diag(D.getDeclSpec().getInlineSpecLoc(), 8338 diag::err_inline_declaration_block_scope) << Name 8339 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8340 } 8341 } 8342 8343 // C++ [dcl.fct.spec]p6: 8344 // The explicit specifier shall be used only in the declaration of a 8345 // constructor or conversion function within its class definition; 8346 // see 12.3.1 and 12.3.2. 8347 if (isExplicit && !NewFD->isInvalidDecl() && 8348 !isa<CXXDeductionGuideDecl>(NewFD)) { 8349 if (!CurContext->isRecord()) { 8350 // 'explicit' was specified outside of the class. 8351 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8352 diag::err_explicit_out_of_class) 8353 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8354 } else if (!isa<CXXConstructorDecl>(NewFD) && 8355 !isa<CXXConversionDecl>(NewFD)) { 8356 // 'explicit' was specified on a function that wasn't a constructor 8357 // or conversion function. 8358 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8359 diag::err_explicit_non_ctor_or_conv_function) 8360 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8361 } 8362 } 8363 8364 if (isConstexpr) { 8365 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8366 // are implicitly inline. 8367 NewFD->setImplicitlyInline(); 8368 8369 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8370 // be either constructors or to return a literal type. Therefore, 8371 // destructors cannot be declared constexpr. 8372 if (isa<CXXDestructorDecl>(NewFD)) 8373 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8374 } 8375 8376 if (isConcept) { 8377 // This is a function concept. 8378 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate()) 8379 FTD->setConcept(); 8380 8381 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8382 // applied only to the definition of a function template [...] 8383 if (!D.isFunctionDefinition()) { 8384 Diag(D.getDeclSpec().getConceptSpecLoc(), 8385 diag::err_function_concept_not_defined); 8386 NewFD->setInvalidDecl(); 8387 } 8388 8389 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall 8390 // have no exception-specification and is treated as if it were specified 8391 // with noexcept(true) (15.4). [...] 8392 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) { 8393 if (FPT->hasExceptionSpec()) { 8394 SourceRange Range; 8395 if (D.isFunctionDeclarator()) 8396 Range = D.getFunctionTypeInfo().getExceptionSpecRange(); 8397 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec) 8398 << FixItHint::CreateRemoval(Range); 8399 NewFD->setInvalidDecl(); 8400 } else { 8401 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept); 8402 } 8403 8404 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8405 // following restrictions: 8406 // - The declared return type shall have the type bool. 8407 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) { 8408 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret); 8409 NewFD->setInvalidDecl(); 8410 } 8411 8412 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8413 // following restrictions: 8414 // - The declaration's parameter list shall be equivalent to an empty 8415 // parameter list. 8416 if (FPT->getNumParams() > 0 || FPT->isVariadic()) 8417 Diag(NewFD->getLocation(), diag::err_function_concept_with_params); 8418 } 8419 8420 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is 8421 // implicity defined to be a constexpr declaration (implicitly inline) 8422 NewFD->setImplicitlyInline(); 8423 8424 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 8425 // be declared with the thread_local, inline, friend, or constexpr 8426 // specifiers, [...] 8427 if (isInline) { 8428 Diag(D.getDeclSpec().getInlineSpecLoc(), 8429 diag::err_concept_decl_invalid_specifiers) 8430 << 1 << 1; 8431 NewFD->setInvalidDecl(true); 8432 } 8433 8434 if (isFriend) { 8435 Diag(D.getDeclSpec().getFriendSpecLoc(), 8436 diag::err_concept_decl_invalid_specifiers) 8437 << 1 << 2; 8438 NewFD->setInvalidDecl(true); 8439 } 8440 8441 if (isConstexpr) { 8442 Diag(D.getDeclSpec().getConstexprSpecLoc(), 8443 diag::err_concept_decl_invalid_specifiers) 8444 << 1 << 3; 8445 NewFD->setInvalidDecl(true); 8446 } 8447 8448 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8449 // applied only to the definition of a function template or variable 8450 // template, declared in namespace scope. 8451 if (isFunctionTemplateSpecialization) { 8452 Diag(D.getDeclSpec().getConceptSpecLoc(), 8453 diag::err_concept_specified_specialization) << 1; 8454 NewFD->setInvalidDecl(true); 8455 return NewFD; 8456 } 8457 } 8458 8459 // If __module_private__ was specified, mark the function accordingly. 8460 if (D.getDeclSpec().isModulePrivateSpecified()) { 8461 if (isFunctionTemplateSpecialization) { 8462 SourceLocation ModulePrivateLoc 8463 = D.getDeclSpec().getModulePrivateSpecLoc(); 8464 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8465 << 0 8466 << FixItHint::CreateRemoval(ModulePrivateLoc); 8467 } else { 8468 NewFD->setModulePrivate(); 8469 if (FunctionTemplate) 8470 FunctionTemplate->setModulePrivate(); 8471 } 8472 } 8473 8474 if (isFriend) { 8475 if (FunctionTemplate) { 8476 FunctionTemplate->setObjectOfFriendDecl(); 8477 FunctionTemplate->setAccess(AS_public); 8478 } 8479 NewFD->setObjectOfFriendDecl(); 8480 NewFD->setAccess(AS_public); 8481 } 8482 8483 // If a function is defined as defaulted or deleted, mark it as such now. 8484 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8485 // definition kind to FDK_Definition. 8486 switch (D.getFunctionDefinitionKind()) { 8487 case FDK_Declaration: 8488 case FDK_Definition: 8489 break; 8490 8491 case FDK_Defaulted: 8492 NewFD->setDefaulted(); 8493 break; 8494 8495 case FDK_Deleted: 8496 NewFD->setDeletedAsWritten(); 8497 break; 8498 } 8499 8500 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8501 D.isFunctionDefinition()) { 8502 // C++ [class.mfct]p2: 8503 // A member function may be defined (8.4) in its class definition, in 8504 // which case it is an inline member function (7.1.2) 8505 NewFD->setImplicitlyInline(); 8506 } 8507 8508 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8509 !CurContext->isRecord()) { 8510 // C++ [class.static]p1: 8511 // A data or function member of a class may be declared static 8512 // in a class definition, in which case it is a static member of 8513 // the class. 8514 8515 // Complain about the 'static' specifier if it's on an out-of-line 8516 // member function definition. 8517 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8518 diag::err_static_out_of_line) 8519 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8520 } 8521 8522 // C++11 [except.spec]p15: 8523 // A deallocation function with no exception-specification is treated 8524 // as if it were specified with noexcept(true). 8525 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8526 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8527 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8528 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8529 NewFD->setType(Context.getFunctionType( 8530 FPT->getReturnType(), FPT->getParamTypes(), 8531 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8532 } 8533 8534 // Filter out previous declarations that don't match the scope. 8535 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8536 D.getCXXScopeSpec().isNotEmpty() || 8537 isMemberSpecialization || 8538 isFunctionTemplateSpecialization); 8539 8540 // Handle GNU asm-label extension (encoded as an attribute). 8541 if (Expr *E = (Expr*) D.getAsmLabel()) { 8542 // The parser guarantees this is a string. 8543 StringLiteral *SE = cast<StringLiteral>(E); 8544 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8545 SE->getString(), 0)); 8546 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8547 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8548 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8549 if (I != ExtnameUndeclaredIdentifiers.end()) { 8550 if (isDeclExternC(NewFD)) { 8551 NewFD->addAttr(I->second); 8552 ExtnameUndeclaredIdentifiers.erase(I); 8553 } else 8554 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8555 << /*Variable*/0 << NewFD; 8556 } 8557 } 8558 8559 // Copy the parameter declarations from the declarator D to the function 8560 // declaration NewFD, if they are available. First scavenge them into Params. 8561 SmallVector<ParmVarDecl*, 16> Params; 8562 unsigned FTIIdx; 8563 if (D.isFunctionDeclarator(FTIIdx)) { 8564 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8565 8566 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8567 // function that takes no arguments, not a function that takes a 8568 // single void argument. 8569 // We let through "const void" here because Sema::GetTypeForDeclarator 8570 // already checks for that case. 8571 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8572 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8573 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8574 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8575 Param->setDeclContext(NewFD); 8576 Params.push_back(Param); 8577 8578 if (Param->isInvalidDecl()) 8579 NewFD->setInvalidDecl(); 8580 } 8581 } 8582 8583 if (!getLangOpts().CPlusPlus) { 8584 // In C, find all the tag declarations from the prototype and move them 8585 // into the function DeclContext. Remove them from the surrounding tag 8586 // injection context of the function, which is typically but not always 8587 // the TU. 8588 DeclContext *PrototypeTagContext = 8589 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8590 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8591 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8592 8593 // We don't want to reparent enumerators. Look at their parent enum 8594 // instead. 8595 if (!TD) { 8596 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8597 TD = cast<EnumDecl>(ECD->getDeclContext()); 8598 } 8599 if (!TD) 8600 continue; 8601 DeclContext *TagDC = TD->getLexicalDeclContext(); 8602 if (!TagDC->containsDecl(TD)) 8603 continue; 8604 TagDC->removeDecl(TD); 8605 TD->setDeclContext(NewFD); 8606 NewFD->addDecl(TD); 8607 8608 // Preserve the lexical DeclContext if it is not the surrounding tag 8609 // injection context of the FD. In this example, the semantic context of 8610 // E will be f and the lexical context will be S, while both the 8611 // semantic and lexical contexts of S will be f: 8612 // void f(struct S { enum E { a } f; } s); 8613 if (TagDC != PrototypeTagContext) 8614 TD->setLexicalDeclContext(TagDC); 8615 } 8616 } 8617 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8618 // When we're declaring a function with a typedef, typeof, etc as in the 8619 // following example, we'll need to synthesize (unnamed) 8620 // parameters for use in the declaration. 8621 // 8622 // @code 8623 // typedef void fn(int); 8624 // fn f; 8625 // @endcode 8626 8627 // Synthesize a parameter for each argument type. 8628 for (const auto &AI : FT->param_types()) { 8629 ParmVarDecl *Param = 8630 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8631 Param->setScopeInfo(0, Params.size()); 8632 Params.push_back(Param); 8633 } 8634 } else { 8635 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8636 "Should not need args for typedef of non-prototype fn"); 8637 } 8638 8639 // Finally, we know we have the right number of parameters, install them. 8640 NewFD->setParams(Params); 8641 8642 if (D.getDeclSpec().isNoreturnSpecified()) 8643 NewFD->addAttr( 8644 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8645 Context, 0)); 8646 8647 // Functions returning a variably modified type violate C99 6.7.5.2p2 8648 // because all functions have linkage. 8649 if (!NewFD->isInvalidDecl() && 8650 NewFD->getReturnType()->isVariablyModifiedType()) { 8651 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8652 NewFD->setInvalidDecl(); 8653 } 8654 8655 // Apply an implicit SectionAttr if #pragma code_seg is active. 8656 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8657 !NewFD->hasAttr<SectionAttr>()) { 8658 NewFD->addAttr( 8659 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8660 CodeSegStack.CurrentValue->getString(), 8661 CodeSegStack.CurrentPragmaLocation)); 8662 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8663 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8664 ASTContext::PSF_Read, 8665 NewFD)) 8666 NewFD->dropAttr<SectionAttr>(); 8667 } 8668 8669 // Handle attributes. 8670 ProcessDeclAttributes(S, NewFD, D); 8671 8672 if (getLangOpts().OpenCL) { 8673 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8674 // type declaration will generate a compilation error. 8675 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 8676 if (AddressSpace == LangAS::opencl_local || 8677 AddressSpace == LangAS::opencl_global || 8678 AddressSpace == LangAS::opencl_constant) { 8679 Diag(NewFD->getLocation(), 8680 diag::err_opencl_return_value_with_address_space); 8681 NewFD->setInvalidDecl(); 8682 } 8683 } 8684 8685 if (!getLangOpts().CPlusPlus) { 8686 // Perform semantic checking on the function declaration. 8687 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8688 CheckMain(NewFD, D.getDeclSpec()); 8689 8690 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8691 CheckMSVCRTEntryPoint(NewFD); 8692 8693 if (!NewFD->isInvalidDecl()) 8694 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8695 isMemberSpecialization)); 8696 else if (!Previous.empty()) 8697 // Recover gracefully from an invalid redeclaration. 8698 D.setRedeclaration(true); 8699 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8700 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8701 "previous declaration set still overloaded"); 8702 8703 // Diagnose no-prototype function declarations with calling conventions that 8704 // don't support variadic calls. Only do this in C and do it after merging 8705 // possibly prototyped redeclarations. 8706 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8707 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8708 CallingConv CC = FT->getExtInfo().getCC(); 8709 if (!supportsVariadicCall(CC)) { 8710 // Windows system headers sometimes accidentally use stdcall without 8711 // (void) parameters, so we relax this to a warning. 8712 int DiagID = 8713 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8714 Diag(NewFD->getLocation(), DiagID) 8715 << FunctionType::getNameForCallConv(CC); 8716 } 8717 } 8718 } else { 8719 // C++11 [replacement.functions]p3: 8720 // The program's definitions shall not be specified as inline. 8721 // 8722 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8723 // 8724 // Suppress the diagnostic if the function is __attribute__((used)), since 8725 // that forces an external definition to be emitted. 8726 if (D.getDeclSpec().isInlineSpecified() && 8727 NewFD->isReplaceableGlobalAllocationFunction() && 8728 !NewFD->hasAttr<UsedAttr>()) 8729 Diag(D.getDeclSpec().getInlineSpecLoc(), 8730 diag::ext_operator_new_delete_declared_inline) 8731 << NewFD->getDeclName(); 8732 8733 // If the declarator is a template-id, translate the parser's template 8734 // argument list into our AST format. 8735 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 8736 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8737 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8738 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8739 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8740 TemplateId->NumArgs); 8741 translateTemplateArguments(TemplateArgsPtr, 8742 TemplateArgs); 8743 8744 HasExplicitTemplateArgs = true; 8745 8746 if (NewFD->isInvalidDecl()) { 8747 HasExplicitTemplateArgs = false; 8748 } else if (FunctionTemplate) { 8749 // Function template with explicit template arguments. 8750 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8751 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8752 8753 HasExplicitTemplateArgs = false; 8754 } else { 8755 assert((isFunctionTemplateSpecialization || 8756 D.getDeclSpec().isFriendSpecified()) && 8757 "should have a 'template<>' for this decl"); 8758 // "friend void foo<>(int);" is an implicit specialization decl. 8759 isFunctionTemplateSpecialization = true; 8760 } 8761 } else if (isFriend && isFunctionTemplateSpecialization) { 8762 // This combination is only possible in a recovery case; the user 8763 // wrote something like: 8764 // template <> friend void foo(int); 8765 // which we're recovering from as if the user had written: 8766 // friend void foo<>(int); 8767 // Go ahead and fake up a template id. 8768 HasExplicitTemplateArgs = true; 8769 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8770 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8771 } 8772 8773 // We do not add HD attributes to specializations here because 8774 // they may have different constexpr-ness compared to their 8775 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8776 // may end up with different effective targets. Instead, a 8777 // specialization inherits its target attributes from its template 8778 // in the CheckFunctionTemplateSpecialization() call below. 8779 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8780 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8781 8782 // If it's a friend (and only if it's a friend), it's possible 8783 // that either the specialized function type or the specialized 8784 // template is dependent, and therefore matching will fail. In 8785 // this case, don't check the specialization yet. 8786 bool InstantiationDependent = false; 8787 if (isFunctionTemplateSpecialization && isFriend && 8788 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8789 TemplateSpecializationType::anyDependentTemplateArguments( 8790 TemplateArgs, 8791 InstantiationDependent))) { 8792 assert(HasExplicitTemplateArgs && 8793 "friend function specialization without template args"); 8794 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8795 Previous)) 8796 NewFD->setInvalidDecl(); 8797 } else if (isFunctionTemplateSpecialization) { 8798 if (CurContext->isDependentContext() && CurContext->isRecord() 8799 && !isFriend) { 8800 isDependentClassScopeExplicitSpecialization = true; 8801 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 8802 diag::ext_function_specialization_in_class : 8803 diag::err_function_specialization_in_class) 8804 << NewFD->getDeclName(); 8805 } else if (CheckFunctionTemplateSpecialization(NewFD, 8806 (HasExplicitTemplateArgs ? &TemplateArgs 8807 : nullptr), 8808 Previous)) 8809 NewFD->setInvalidDecl(); 8810 8811 // C++ [dcl.stc]p1: 8812 // A storage-class-specifier shall not be specified in an explicit 8813 // specialization (14.7.3) 8814 FunctionTemplateSpecializationInfo *Info = 8815 NewFD->getTemplateSpecializationInfo(); 8816 if (Info && SC != SC_None) { 8817 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8818 Diag(NewFD->getLocation(), 8819 diag::err_explicit_specialization_inconsistent_storage_class) 8820 << SC 8821 << FixItHint::CreateRemoval( 8822 D.getDeclSpec().getStorageClassSpecLoc()); 8823 8824 else 8825 Diag(NewFD->getLocation(), 8826 diag::ext_explicit_specialization_storage_class) 8827 << FixItHint::CreateRemoval( 8828 D.getDeclSpec().getStorageClassSpecLoc()); 8829 } 8830 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 8831 if (CheckMemberSpecialization(NewFD, Previous)) 8832 NewFD->setInvalidDecl(); 8833 } 8834 8835 // Perform semantic checking on the function declaration. 8836 if (!isDependentClassScopeExplicitSpecialization) { 8837 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8838 CheckMain(NewFD, D.getDeclSpec()); 8839 8840 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8841 CheckMSVCRTEntryPoint(NewFD); 8842 8843 if (!NewFD->isInvalidDecl()) 8844 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8845 isMemberSpecialization)); 8846 else if (!Previous.empty()) 8847 // Recover gracefully from an invalid redeclaration. 8848 D.setRedeclaration(true); 8849 } 8850 8851 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8852 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8853 "previous declaration set still overloaded"); 8854 8855 NamedDecl *PrincipalDecl = (FunctionTemplate 8856 ? cast<NamedDecl>(FunctionTemplate) 8857 : NewFD); 8858 8859 if (isFriend && NewFD->getPreviousDecl()) { 8860 AccessSpecifier Access = AS_public; 8861 if (!NewFD->isInvalidDecl()) 8862 Access = NewFD->getPreviousDecl()->getAccess(); 8863 8864 NewFD->setAccess(Access); 8865 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8866 } 8867 8868 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8869 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8870 PrincipalDecl->setNonMemberOperator(); 8871 8872 // If we have a function template, check the template parameter 8873 // list. This will check and merge default template arguments. 8874 if (FunctionTemplate) { 8875 FunctionTemplateDecl *PrevTemplate = 8876 FunctionTemplate->getPreviousDecl(); 8877 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8878 PrevTemplate ? PrevTemplate->getTemplateParameters() 8879 : nullptr, 8880 D.getDeclSpec().isFriendSpecified() 8881 ? (D.isFunctionDefinition() 8882 ? TPC_FriendFunctionTemplateDefinition 8883 : TPC_FriendFunctionTemplate) 8884 : (D.getCXXScopeSpec().isSet() && 8885 DC && DC->isRecord() && 8886 DC->isDependentContext()) 8887 ? TPC_ClassTemplateMember 8888 : TPC_FunctionTemplate); 8889 } 8890 8891 if (NewFD->isInvalidDecl()) { 8892 // Ignore all the rest of this. 8893 } else if (!D.isRedeclaration()) { 8894 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8895 AddToScope }; 8896 // Fake up an access specifier if it's supposed to be a class member. 8897 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8898 NewFD->setAccess(AS_public); 8899 8900 // Qualified decls generally require a previous declaration. 8901 if (D.getCXXScopeSpec().isSet()) { 8902 // ...with the major exception of templated-scope or 8903 // dependent-scope friend declarations. 8904 8905 // TODO: we currently also suppress this check in dependent 8906 // contexts because (1) the parameter depth will be off when 8907 // matching friend templates and (2) we might actually be 8908 // selecting a friend based on a dependent factor. But there 8909 // are situations where these conditions don't apply and we 8910 // can actually do this check immediately. 8911 if (isFriend && 8912 (TemplateParamLists.size() || 8913 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8914 CurContext->isDependentContext())) { 8915 // ignore these 8916 } else { 8917 // The user tried to provide an out-of-line definition for a 8918 // function that is a member of a class or namespace, but there 8919 // was no such member function declared (C++ [class.mfct]p2, 8920 // C++ [namespace.memdef]p2). For example: 8921 // 8922 // class X { 8923 // void f() const; 8924 // }; 8925 // 8926 // void X::f() { } // ill-formed 8927 // 8928 // Complain about this problem, and attempt to suggest close 8929 // matches (e.g., those that differ only in cv-qualifiers and 8930 // whether the parameter types are references). 8931 8932 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8933 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8934 AddToScope = ExtraArgs.AddToScope; 8935 return Result; 8936 } 8937 } 8938 8939 // Unqualified local friend declarations are required to resolve 8940 // to something. 8941 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 8942 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8943 *this, Previous, NewFD, ExtraArgs, true, S)) { 8944 AddToScope = ExtraArgs.AddToScope; 8945 return Result; 8946 } 8947 } 8948 } else if (!D.isFunctionDefinition() && 8949 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 8950 !isFriend && !isFunctionTemplateSpecialization && 8951 !isMemberSpecialization) { 8952 // An out-of-line member function declaration must also be a 8953 // definition (C++ [class.mfct]p2). 8954 // Note that this is not the case for explicit specializations of 8955 // function templates or member functions of class templates, per 8956 // C++ [temp.expl.spec]p2. We also allow these declarations as an 8957 // extension for compatibility with old SWIG code which likes to 8958 // generate them. 8959 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 8960 << D.getCXXScopeSpec().getRange(); 8961 } 8962 } 8963 8964 ProcessPragmaWeak(S, NewFD); 8965 checkAttributesAfterMerging(*this, *NewFD); 8966 8967 AddKnownFunctionAttributes(NewFD); 8968 8969 if (NewFD->hasAttr<OverloadableAttr>() && 8970 !NewFD->getType()->getAs<FunctionProtoType>()) { 8971 Diag(NewFD->getLocation(), 8972 diag::err_attribute_overloadable_no_prototype) 8973 << NewFD; 8974 8975 // Turn this into a variadic function with no parameters. 8976 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 8977 FunctionProtoType::ExtProtoInfo EPI( 8978 Context.getDefaultCallingConvention(true, false)); 8979 EPI.Variadic = true; 8980 EPI.ExtInfo = FT->getExtInfo(); 8981 8982 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 8983 NewFD->setType(R); 8984 } 8985 8986 // If there's a #pragma GCC visibility in scope, and this isn't a class 8987 // member, set the visibility of this function. 8988 if (!DC->isRecord() && NewFD->isExternallyVisible()) 8989 AddPushedVisibilityAttribute(NewFD); 8990 8991 // If there's a #pragma clang arc_cf_code_audited in scope, consider 8992 // marking the function. 8993 AddCFAuditedAttribute(NewFD); 8994 8995 // If this is a function definition, check if we have to apply optnone due to 8996 // a pragma. 8997 if(D.isFunctionDefinition()) 8998 AddRangeBasedOptnone(NewFD); 8999 9000 // If this is the first declaration of an extern C variable, update 9001 // the map of such variables. 9002 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9003 isIncompleteDeclExternC(*this, NewFD)) 9004 RegisterLocallyScopedExternCDecl(NewFD, S); 9005 9006 // Set this FunctionDecl's range up to the right paren. 9007 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9008 9009 if (D.isRedeclaration() && !Previous.empty()) { 9010 checkDLLAttributeRedeclaration( 9011 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 9012 isMemberSpecialization || isFunctionTemplateSpecialization, 9013 D.isFunctionDefinition()); 9014 } 9015 9016 if (getLangOpts().CUDA) { 9017 IdentifierInfo *II = NewFD->getIdentifier(); 9018 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() && 9019 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9020 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9021 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 9022 9023 Context.setcudaConfigureCallDecl(NewFD); 9024 } 9025 9026 // Variadic functions, other than a *declaration* of printf, are not allowed 9027 // in device-side CUDA code, unless someone passed 9028 // -fcuda-allow-variadic-functions. 9029 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9030 (NewFD->hasAttr<CUDADeviceAttr>() || 9031 NewFD->hasAttr<CUDAGlobalAttr>()) && 9032 !(II && II->isStr("printf") && NewFD->isExternC() && 9033 !D.isFunctionDefinition())) { 9034 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9035 } 9036 } 9037 9038 MarkUnusedFileScopedDecl(NewFD); 9039 9040 if (getLangOpts().CPlusPlus) { 9041 if (FunctionTemplate) { 9042 if (NewFD->isInvalidDecl()) 9043 FunctionTemplate->setInvalidDecl(); 9044 return FunctionTemplate; 9045 } 9046 9047 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9048 CompleteMemberSpecialization(NewFD, Previous); 9049 } 9050 9051 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 9052 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9053 if ((getLangOpts().OpenCLVersion >= 120) 9054 && (SC == SC_Static)) { 9055 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9056 D.setInvalidType(); 9057 } 9058 9059 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9060 if (!NewFD->getReturnType()->isVoidType()) { 9061 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9062 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9063 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9064 : FixItHint()); 9065 D.setInvalidType(); 9066 } 9067 9068 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9069 for (auto Param : NewFD->parameters()) 9070 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9071 } 9072 for (const ParmVarDecl *Param : NewFD->parameters()) { 9073 QualType PT = Param->getType(); 9074 9075 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9076 // types. 9077 if (getLangOpts().OpenCLVersion >= 200) { 9078 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9079 QualType ElemTy = PipeTy->getElementType(); 9080 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9081 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9082 D.setInvalidType(); 9083 } 9084 } 9085 } 9086 } 9087 9088 // Here we have an function template explicit specialization at class scope. 9089 // The actually specialization will be postponed to template instatiation 9090 // time via the ClassScopeFunctionSpecializationDecl node. 9091 if (isDependentClassScopeExplicitSpecialization) { 9092 ClassScopeFunctionSpecializationDecl *NewSpec = 9093 ClassScopeFunctionSpecializationDecl::Create( 9094 Context, CurContext, SourceLocation(), 9095 cast<CXXMethodDecl>(NewFD), 9096 HasExplicitTemplateArgs, TemplateArgs); 9097 CurContext->addDecl(NewSpec); 9098 AddToScope = false; 9099 } 9100 9101 return NewFD; 9102 } 9103 9104 /// \brief Checks if the new declaration declared in dependent context must be 9105 /// put in the same redeclaration chain as the specified declaration. 9106 /// 9107 /// \param D Declaration that is checked. 9108 /// \param PrevDecl Previous declaration found with proper lookup method for the 9109 /// same declaration name. 9110 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9111 /// belongs to. 9112 /// 9113 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9114 // Any declarations should be put into redeclaration chains except for 9115 // friend declaration in a dependent context that names a function in 9116 // namespace scope. 9117 // 9118 // This allows to compile code like: 9119 // 9120 // void func(); 9121 // template<typename T> class C1 { friend void func() { } }; 9122 // template<typename T> class C2 { friend void func() { } }; 9123 // 9124 // This code snippet is a valid code unless both templates are instantiated. 9125 return !(D->getLexicalDeclContext()->isDependentContext() && 9126 D->getDeclContext()->isFileContext() && 9127 D->getFriendObjectKind() != Decl::FOK_None); 9128 } 9129 9130 /// \brief Perform semantic checking of a new function declaration. 9131 /// 9132 /// Performs semantic analysis of the new function declaration 9133 /// NewFD. This routine performs all semantic checking that does not 9134 /// require the actual declarator involved in the declaration, and is 9135 /// used both for the declaration of functions as they are parsed 9136 /// (called via ActOnDeclarator) and for the declaration of functions 9137 /// that have been instantiated via C++ template instantiation (called 9138 /// via InstantiateDecl). 9139 /// 9140 /// \param IsMemberSpecialization whether this new function declaration is 9141 /// a member specialization (that replaces any definition provided by the 9142 /// previous declaration). 9143 /// 9144 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9145 /// 9146 /// \returns true if the function declaration is a redeclaration. 9147 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 9148 LookupResult &Previous, 9149 bool IsMemberSpecialization) { 9150 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 9151 "Variably modified return types are not handled here"); 9152 9153 // Determine whether the type of this function should be merged with 9154 // a previous visible declaration. This never happens for functions in C++, 9155 // and always happens in C if the previous declaration was visible. 9156 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 9157 !Previous.isShadowed(); 9158 9159 bool Redeclaration = false; 9160 NamedDecl *OldDecl = nullptr; 9161 9162 // Merge or overload the declaration with an existing declaration of 9163 // the same name, if appropriate. 9164 if (!Previous.empty()) { 9165 // Determine whether NewFD is an overload of PrevDecl or 9166 // a declaration that requires merging. If it's an overload, 9167 // there's no more work to do here; we'll just add the new 9168 // function to the scope. 9169 if (!AllowOverloadingOfFunction(Previous, Context)) { 9170 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 9171 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 9172 Redeclaration = true; 9173 OldDecl = Candidate; 9174 } 9175 } else { 9176 switch (CheckOverload(S, NewFD, Previous, OldDecl, 9177 /*NewIsUsingDecl*/ false)) { 9178 case Ovl_Match: 9179 Redeclaration = true; 9180 break; 9181 9182 case Ovl_NonFunction: 9183 Redeclaration = true; 9184 break; 9185 9186 case Ovl_Overload: 9187 Redeclaration = false; 9188 break; 9189 } 9190 9191 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 9192 // If a function name is overloadable in C, then every function 9193 // with that name must be marked "overloadable". 9194 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 9195 << Redeclaration << NewFD; 9196 NamedDecl *OverloadedDecl = 9197 Redeclaration ? OldDecl : Previous.getRepresentativeDecl(); 9198 Diag(OverloadedDecl->getLocation(), 9199 diag::note_attribute_overloadable_prev_overload); 9200 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9201 } 9202 } 9203 } 9204 9205 // Check for a previous extern "C" declaration with this name. 9206 if (!Redeclaration && 9207 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 9208 if (!Previous.empty()) { 9209 // This is an extern "C" declaration with the same name as a previous 9210 // declaration, and thus redeclares that entity... 9211 Redeclaration = true; 9212 OldDecl = Previous.getFoundDecl(); 9213 MergeTypeWithPrevious = false; 9214 9215 // ... except in the presence of __attribute__((overloadable)). 9216 if (OldDecl->hasAttr<OverloadableAttr>()) { 9217 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 9218 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 9219 << Redeclaration << NewFD; 9220 Diag(Previous.getFoundDecl()->getLocation(), 9221 diag::note_attribute_overloadable_prev_overload); 9222 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9223 } 9224 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 9225 Redeclaration = false; 9226 OldDecl = nullptr; 9227 } 9228 } 9229 } 9230 } 9231 9232 // C++11 [dcl.constexpr]p8: 9233 // A constexpr specifier for a non-static member function that is not 9234 // a constructor declares that member function to be const. 9235 // 9236 // This needs to be delayed until we know whether this is an out-of-line 9237 // definition of a static member function. 9238 // 9239 // This rule is not present in C++1y, so we produce a backwards 9240 // compatibility warning whenever it happens in C++11. 9241 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9242 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 9243 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 9244 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 9245 CXXMethodDecl *OldMD = nullptr; 9246 if (OldDecl) 9247 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 9248 if (!OldMD || !OldMD->isStatic()) { 9249 const FunctionProtoType *FPT = 9250 MD->getType()->castAs<FunctionProtoType>(); 9251 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9252 EPI.TypeQuals |= Qualifiers::Const; 9253 MD->setType(Context.getFunctionType(FPT->getReturnType(), 9254 FPT->getParamTypes(), EPI)); 9255 9256 // Warn that we did this, if we're not performing template instantiation. 9257 // In that case, we'll have warned already when the template was defined. 9258 if (!inTemplateInstantiation()) { 9259 SourceLocation AddConstLoc; 9260 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 9261 .IgnoreParens().getAs<FunctionTypeLoc>()) 9262 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 9263 9264 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 9265 << FixItHint::CreateInsertion(AddConstLoc, " const"); 9266 } 9267 } 9268 } 9269 9270 if (Redeclaration) { 9271 // NewFD and OldDecl represent declarations that need to be 9272 // merged. 9273 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 9274 NewFD->setInvalidDecl(); 9275 return Redeclaration; 9276 } 9277 9278 Previous.clear(); 9279 Previous.addDecl(OldDecl); 9280 9281 if (FunctionTemplateDecl *OldTemplateDecl 9282 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 9283 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 9284 FunctionTemplateDecl *NewTemplateDecl 9285 = NewFD->getDescribedFunctionTemplate(); 9286 assert(NewTemplateDecl && "Template/non-template mismatch"); 9287 if (CXXMethodDecl *Method 9288 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 9289 Method->setAccess(OldTemplateDecl->getAccess()); 9290 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 9291 } 9292 9293 // If this is an explicit specialization of a member that is a function 9294 // template, mark it as a member specialization. 9295 if (IsMemberSpecialization && 9296 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 9297 NewTemplateDecl->setMemberSpecialization(); 9298 assert(OldTemplateDecl->isMemberSpecialization()); 9299 // Explicit specializations of a member template do not inherit deleted 9300 // status from the parent member template that they are specializing. 9301 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) { 9302 FunctionDecl *const OldTemplatedDecl = 9303 OldTemplateDecl->getTemplatedDecl(); 9304 // FIXME: This assert will not hold in the presence of modules. 9305 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl); 9306 // FIXME: We need an update record for this AST mutation. 9307 OldTemplatedDecl->setDeletedAsWritten(false); 9308 } 9309 } 9310 9311 } else { 9312 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 9313 // This needs to happen first so that 'inline' propagates. 9314 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 9315 if (isa<CXXMethodDecl>(NewFD)) 9316 NewFD->setAccess(OldDecl->getAccess()); 9317 } 9318 } 9319 } 9320 9321 // Semantic checking for this function declaration (in isolation). 9322 9323 if (getLangOpts().CPlusPlus) { 9324 // C++-specific checks. 9325 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 9326 CheckConstructor(Constructor); 9327 } else if (CXXDestructorDecl *Destructor = 9328 dyn_cast<CXXDestructorDecl>(NewFD)) { 9329 CXXRecordDecl *Record = Destructor->getParent(); 9330 QualType ClassType = Context.getTypeDeclType(Record); 9331 9332 // FIXME: Shouldn't we be able to perform this check even when the class 9333 // type is dependent? Both gcc and edg can handle that. 9334 if (!ClassType->isDependentType()) { 9335 DeclarationName Name 9336 = Context.DeclarationNames.getCXXDestructorName( 9337 Context.getCanonicalType(ClassType)); 9338 if (NewFD->getDeclName() != Name) { 9339 Diag(NewFD->getLocation(), diag::err_destructor_name); 9340 NewFD->setInvalidDecl(); 9341 return Redeclaration; 9342 } 9343 } 9344 } else if (CXXConversionDecl *Conversion 9345 = dyn_cast<CXXConversionDecl>(NewFD)) { 9346 ActOnConversionDeclarator(Conversion); 9347 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 9348 if (auto *TD = Guide->getDescribedFunctionTemplate()) 9349 CheckDeductionGuideTemplate(TD); 9350 9351 // A deduction guide is not on the list of entities that can be 9352 // explicitly specialized. 9353 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 9354 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized) 9355 << /*explicit specialization*/ 1; 9356 } 9357 9358 // Find any virtual functions that this function overrides. 9359 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 9360 if (!Method->isFunctionTemplateSpecialization() && 9361 !Method->getDescribedFunctionTemplate() && 9362 Method->isCanonicalDecl()) { 9363 if (AddOverriddenMethods(Method->getParent(), Method)) { 9364 // If the function was marked as "static", we have a problem. 9365 if (NewFD->getStorageClass() == SC_Static) { 9366 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 9367 } 9368 } 9369 } 9370 9371 if (Method->isStatic()) 9372 checkThisInStaticMemberFunctionType(Method); 9373 } 9374 9375 // Extra checking for C++ overloaded operators (C++ [over.oper]). 9376 if (NewFD->isOverloadedOperator() && 9377 CheckOverloadedOperatorDeclaration(NewFD)) { 9378 NewFD->setInvalidDecl(); 9379 return Redeclaration; 9380 } 9381 9382 // Extra checking for C++0x literal operators (C++0x [over.literal]). 9383 if (NewFD->getLiteralIdentifier() && 9384 CheckLiteralOperatorDeclaration(NewFD)) { 9385 NewFD->setInvalidDecl(); 9386 return Redeclaration; 9387 } 9388 9389 // In C++, check default arguments now that we have merged decls. Unless 9390 // the lexical context is the class, because in this case this is done 9391 // during delayed parsing anyway. 9392 if (!CurContext->isRecord()) 9393 CheckCXXDefaultArguments(NewFD); 9394 9395 // If this function declares a builtin function, check the type of this 9396 // declaration against the expected type for the builtin. 9397 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 9398 ASTContext::GetBuiltinTypeError Error; 9399 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 9400 QualType T = Context.GetBuiltinType(BuiltinID, Error); 9401 // If the type of the builtin differs only in its exception 9402 // specification, that's OK. 9403 // FIXME: If the types do differ in this way, it would be better to 9404 // retain the 'noexcept' form of the type. 9405 if (!T.isNull() && 9406 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 9407 NewFD->getType())) 9408 // The type of this function differs from the type of the builtin, 9409 // so forget about the builtin entirely. 9410 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 9411 } 9412 9413 // If this function is declared as being extern "C", then check to see if 9414 // the function returns a UDT (class, struct, or union type) that is not C 9415 // compatible, and if it does, warn the user. 9416 // But, issue any diagnostic on the first declaration only. 9417 if (Previous.empty() && NewFD->isExternC()) { 9418 QualType R = NewFD->getReturnType(); 9419 if (R->isIncompleteType() && !R->isVoidType()) 9420 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 9421 << NewFD << R; 9422 else if (!R.isPODType(Context) && !R->isVoidType() && 9423 !R->isObjCObjectPointerType()) 9424 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 9425 } 9426 9427 // C++1z [dcl.fct]p6: 9428 // [...] whether the function has a non-throwing exception-specification 9429 // [is] part of the function type 9430 // 9431 // This results in an ABI break between C++14 and C++17 for functions whose 9432 // declared type includes an exception-specification in a parameter or 9433 // return type. (Exception specifications on the function itself are OK in 9434 // most cases, and exception specifications are not permitted in most other 9435 // contexts where they could make it into a mangling.) 9436 if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) { 9437 auto HasNoexcept = [&](QualType T) -> bool { 9438 // Strip off declarator chunks that could be between us and a function 9439 // type. We don't need to look far, exception specifications are very 9440 // restricted prior to C++17. 9441 if (auto *RT = T->getAs<ReferenceType>()) 9442 T = RT->getPointeeType(); 9443 else if (T->isAnyPointerType()) 9444 T = T->getPointeeType(); 9445 else if (auto *MPT = T->getAs<MemberPointerType>()) 9446 T = MPT->getPointeeType(); 9447 if (auto *FPT = T->getAs<FunctionProtoType>()) 9448 if (FPT->isNothrow(Context)) 9449 return true; 9450 return false; 9451 }; 9452 9453 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 9454 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 9455 for (QualType T : FPT->param_types()) 9456 AnyNoexcept |= HasNoexcept(T); 9457 if (AnyNoexcept) 9458 Diag(NewFD->getLocation(), 9459 diag::warn_cxx1z_compat_exception_spec_in_signature) 9460 << NewFD; 9461 } 9462 9463 if (!Redeclaration && LangOpts.CUDA) 9464 checkCUDATargetOverload(NewFD, Previous); 9465 } 9466 return Redeclaration; 9467 } 9468 9469 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 9470 // C++11 [basic.start.main]p3: 9471 // A program that [...] declares main to be inline, static or 9472 // constexpr is ill-formed. 9473 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9474 // appear in a declaration of main. 9475 // static main is not an error under C99, but we should warn about it. 9476 // We accept _Noreturn main as an extension. 9477 if (FD->getStorageClass() == SC_Static) 9478 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9479 ? diag::err_static_main : diag::warn_static_main) 9480 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9481 if (FD->isInlineSpecified()) 9482 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9483 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9484 if (DS.isNoreturnSpecified()) { 9485 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9486 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9487 Diag(NoreturnLoc, diag::ext_noreturn_main); 9488 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9489 << FixItHint::CreateRemoval(NoreturnRange); 9490 } 9491 if (FD->isConstexpr()) { 9492 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9493 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9494 FD->setConstexpr(false); 9495 } 9496 9497 if (getLangOpts().OpenCL) { 9498 Diag(FD->getLocation(), diag::err_opencl_no_main) 9499 << FD->hasAttr<OpenCLKernelAttr>(); 9500 FD->setInvalidDecl(); 9501 return; 9502 } 9503 9504 QualType T = FD->getType(); 9505 assert(T->isFunctionType() && "function decl is not of function type"); 9506 const FunctionType* FT = T->castAs<FunctionType>(); 9507 9508 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 9509 // In C with GNU extensions we allow main() to have non-integer return 9510 // type, but we should warn about the extension, and we disable the 9511 // implicit-return-zero rule. 9512 9513 // GCC in C mode accepts qualified 'int'. 9514 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 9515 FD->setHasImplicitReturnZero(true); 9516 else { 9517 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 9518 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9519 if (RTRange.isValid()) 9520 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 9521 << FixItHint::CreateReplacement(RTRange, "int"); 9522 } 9523 } else { 9524 // In C and C++, main magically returns 0 if you fall off the end; 9525 // set the flag which tells us that. 9526 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 9527 9528 // All the standards say that main() should return 'int'. 9529 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 9530 FD->setHasImplicitReturnZero(true); 9531 else { 9532 // Otherwise, this is just a flat-out error. 9533 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9534 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 9535 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 9536 : FixItHint()); 9537 FD->setInvalidDecl(true); 9538 } 9539 } 9540 9541 // Treat protoless main() as nullary. 9542 if (isa<FunctionNoProtoType>(FT)) return; 9543 9544 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 9545 unsigned nparams = FTP->getNumParams(); 9546 assert(FD->getNumParams() == nparams); 9547 9548 bool HasExtraParameters = (nparams > 3); 9549 9550 if (FTP->isVariadic()) { 9551 Diag(FD->getLocation(), diag::ext_variadic_main); 9552 // FIXME: if we had information about the location of the ellipsis, we 9553 // could add a FixIt hint to remove it as a parameter. 9554 } 9555 9556 // Darwin passes an undocumented fourth argument of type char**. If 9557 // other platforms start sprouting these, the logic below will start 9558 // getting shifty. 9559 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 9560 HasExtraParameters = false; 9561 9562 if (HasExtraParameters) { 9563 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 9564 FD->setInvalidDecl(true); 9565 nparams = 3; 9566 } 9567 9568 // FIXME: a lot of the following diagnostics would be improved 9569 // if we had some location information about types. 9570 9571 QualType CharPP = 9572 Context.getPointerType(Context.getPointerType(Context.CharTy)); 9573 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 9574 9575 for (unsigned i = 0; i < nparams; ++i) { 9576 QualType AT = FTP->getParamType(i); 9577 9578 bool mismatch = true; 9579 9580 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 9581 mismatch = false; 9582 else if (Expected[i] == CharPP) { 9583 // As an extension, the following forms are okay: 9584 // char const ** 9585 // char const * const * 9586 // char * const * 9587 9588 QualifierCollector qs; 9589 const PointerType* PT; 9590 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 9591 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 9592 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 9593 Context.CharTy)) { 9594 qs.removeConst(); 9595 mismatch = !qs.empty(); 9596 } 9597 } 9598 9599 if (mismatch) { 9600 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 9601 // TODO: suggest replacing given type with expected type 9602 FD->setInvalidDecl(true); 9603 } 9604 } 9605 9606 if (nparams == 1 && !FD->isInvalidDecl()) { 9607 Diag(FD->getLocation(), diag::warn_main_one_arg); 9608 } 9609 9610 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9611 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9612 FD->setInvalidDecl(); 9613 } 9614 } 9615 9616 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 9617 QualType T = FD->getType(); 9618 assert(T->isFunctionType() && "function decl is not of function type"); 9619 const FunctionType *FT = T->castAs<FunctionType>(); 9620 9621 // Set an implicit return of 'zero' if the function can return some integral, 9622 // enumeration, pointer or nullptr type. 9623 if (FT->getReturnType()->isIntegralOrEnumerationType() || 9624 FT->getReturnType()->isAnyPointerType() || 9625 FT->getReturnType()->isNullPtrType()) 9626 // DllMain is exempt because a return value of zero means it failed. 9627 if (FD->getName() != "DllMain") 9628 FD->setHasImplicitReturnZero(true); 9629 9630 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9631 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9632 FD->setInvalidDecl(); 9633 } 9634 } 9635 9636 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 9637 // FIXME: Need strict checking. In C89, we need to check for 9638 // any assignment, increment, decrement, function-calls, or 9639 // commas outside of a sizeof. In C99, it's the same list, 9640 // except that the aforementioned are allowed in unevaluated 9641 // expressions. Everything else falls under the 9642 // "may accept other forms of constant expressions" exception. 9643 // (We never end up here for C++, so the constant expression 9644 // rules there don't matter.) 9645 const Expr *Culprit; 9646 if (Init->isConstantInitializer(Context, false, &Culprit)) 9647 return false; 9648 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 9649 << Culprit->getSourceRange(); 9650 return true; 9651 } 9652 9653 namespace { 9654 // Visits an initialization expression to see if OrigDecl is evaluated in 9655 // its own initialization and throws a warning if it does. 9656 class SelfReferenceChecker 9657 : public EvaluatedExprVisitor<SelfReferenceChecker> { 9658 Sema &S; 9659 Decl *OrigDecl; 9660 bool isRecordType; 9661 bool isPODType; 9662 bool isReferenceType; 9663 9664 bool isInitList; 9665 llvm::SmallVector<unsigned, 4> InitFieldIndex; 9666 9667 public: 9668 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 9669 9670 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 9671 S(S), OrigDecl(OrigDecl) { 9672 isPODType = false; 9673 isRecordType = false; 9674 isReferenceType = false; 9675 isInitList = false; 9676 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 9677 isPODType = VD->getType().isPODType(S.Context); 9678 isRecordType = VD->getType()->isRecordType(); 9679 isReferenceType = VD->getType()->isReferenceType(); 9680 } 9681 } 9682 9683 // For most expressions, just call the visitor. For initializer lists, 9684 // track the index of the field being initialized since fields are 9685 // initialized in order allowing use of previously initialized fields. 9686 void CheckExpr(Expr *E) { 9687 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 9688 if (!InitList) { 9689 Visit(E); 9690 return; 9691 } 9692 9693 // Track and increment the index here. 9694 isInitList = true; 9695 InitFieldIndex.push_back(0); 9696 for (auto Child : InitList->children()) { 9697 CheckExpr(cast<Expr>(Child)); 9698 ++InitFieldIndex.back(); 9699 } 9700 InitFieldIndex.pop_back(); 9701 } 9702 9703 // Returns true if MemberExpr is checked and no further checking is needed. 9704 // Returns false if additional checking is required. 9705 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 9706 llvm::SmallVector<FieldDecl*, 4> Fields; 9707 Expr *Base = E; 9708 bool ReferenceField = false; 9709 9710 // Get the field memebers used. 9711 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9712 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 9713 if (!FD) 9714 return false; 9715 Fields.push_back(FD); 9716 if (FD->getType()->isReferenceType()) 9717 ReferenceField = true; 9718 Base = ME->getBase()->IgnoreParenImpCasts(); 9719 } 9720 9721 // Keep checking only if the base Decl is the same. 9722 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 9723 if (!DRE || DRE->getDecl() != OrigDecl) 9724 return false; 9725 9726 // A reference field can be bound to an unininitialized field. 9727 if (CheckReference && !ReferenceField) 9728 return true; 9729 9730 // Convert FieldDecls to their index number. 9731 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 9732 for (const FieldDecl *I : llvm::reverse(Fields)) 9733 UsedFieldIndex.push_back(I->getFieldIndex()); 9734 9735 // See if a warning is needed by checking the first difference in index 9736 // numbers. If field being used has index less than the field being 9737 // initialized, then the use is safe. 9738 for (auto UsedIter = UsedFieldIndex.begin(), 9739 UsedEnd = UsedFieldIndex.end(), 9740 OrigIter = InitFieldIndex.begin(), 9741 OrigEnd = InitFieldIndex.end(); 9742 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 9743 if (*UsedIter < *OrigIter) 9744 return true; 9745 if (*UsedIter > *OrigIter) 9746 break; 9747 } 9748 9749 // TODO: Add a different warning which will print the field names. 9750 HandleDeclRefExpr(DRE); 9751 return true; 9752 } 9753 9754 // For most expressions, the cast is directly above the DeclRefExpr. 9755 // For conditional operators, the cast can be outside the conditional 9756 // operator if both expressions are DeclRefExpr's. 9757 void HandleValue(Expr *E) { 9758 E = E->IgnoreParens(); 9759 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 9760 HandleDeclRefExpr(DRE); 9761 return; 9762 } 9763 9764 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9765 Visit(CO->getCond()); 9766 HandleValue(CO->getTrueExpr()); 9767 HandleValue(CO->getFalseExpr()); 9768 return; 9769 } 9770 9771 if (BinaryConditionalOperator *BCO = 9772 dyn_cast<BinaryConditionalOperator>(E)) { 9773 Visit(BCO->getCond()); 9774 HandleValue(BCO->getFalseExpr()); 9775 return; 9776 } 9777 9778 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 9779 HandleValue(OVE->getSourceExpr()); 9780 return; 9781 } 9782 9783 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9784 if (BO->getOpcode() == BO_Comma) { 9785 Visit(BO->getLHS()); 9786 HandleValue(BO->getRHS()); 9787 return; 9788 } 9789 } 9790 9791 if (isa<MemberExpr>(E)) { 9792 if (isInitList) { 9793 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 9794 false /*CheckReference*/)) 9795 return; 9796 } 9797 9798 Expr *Base = E->IgnoreParenImpCasts(); 9799 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9800 // Check for static member variables and don't warn on them. 9801 if (!isa<FieldDecl>(ME->getMemberDecl())) 9802 return; 9803 Base = ME->getBase()->IgnoreParenImpCasts(); 9804 } 9805 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 9806 HandleDeclRefExpr(DRE); 9807 return; 9808 } 9809 9810 Visit(E); 9811 } 9812 9813 // Reference types not handled in HandleValue are handled here since all 9814 // uses of references are bad, not just r-value uses. 9815 void VisitDeclRefExpr(DeclRefExpr *E) { 9816 if (isReferenceType) 9817 HandleDeclRefExpr(E); 9818 } 9819 9820 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 9821 if (E->getCastKind() == CK_LValueToRValue) { 9822 HandleValue(E->getSubExpr()); 9823 return; 9824 } 9825 9826 Inherited::VisitImplicitCastExpr(E); 9827 } 9828 9829 void VisitMemberExpr(MemberExpr *E) { 9830 if (isInitList) { 9831 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 9832 return; 9833 } 9834 9835 // Don't warn on arrays since they can be treated as pointers. 9836 if (E->getType()->canDecayToPointerType()) return; 9837 9838 // Warn when a non-static method call is followed by non-static member 9839 // field accesses, which is followed by a DeclRefExpr. 9840 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 9841 bool Warn = (MD && !MD->isStatic()); 9842 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 9843 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9844 if (!isa<FieldDecl>(ME->getMemberDecl())) 9845 Warn = false; 9846 Base = ME->getBase()->IgnoreParenImpCasts(); 9847 } 9848 9849 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 9850 if (Warn) 9851 HandleDeclRefExpr(DRE); 9852 return; 9853 } 9854 9855 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 9856 // Visit that expression. 9857 Visit(Base); 9858 } 9859 9860 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 9861 Expr *Callee = E->getCallee(); 9862 9863 if (isa<UnresolvedLookupExpr>(Callee)) 9864 return Inherited::VisitCXXOperatorCallExpr(E); 9865 9866 Visit(Callee); 9867 for (auto Arg: E->arguments()) 9868 HandleValue(Arg->IgnoreParenImpCasts()); 9869 } 9870 9871 void VisitUnaryOperator(UnaryOperator *E) { 9872 // For POD record types, addresses of its own members are well-defined. 9873 if (E->getOpcode() == UO_AddrOf && isRecordType && 9874 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 9875 if (!isPODType) 9876 HandleValue(E->getSubExpr()); 9877 return; 9878 } 9879 9880 if (E->isIncrementDecrementOp()) { 9881 HandleValue(E->getSubExpr()); 9882 return; 9883 } 9884 9885 Inherited::VisitUnaryOperator(E); 9886 } 9887 9888 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 9889 9890 void VisitCXXConstructExpr(CXXConstructExpr *E) { 9891 if (E->getConstructor()->isCopyConstructor()) { 9892 Expr *ArgExpr = E->getArg(0); 9893 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 9894 if (ILE->getNumInits() == 1) 9895 ArgExpr = ILE->getInit(0); 9896 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 9897 if (ICE->getCastKind() == CK_NoOp) 9898 ArgExpr = ICE->getSubExpr(); 9899 HandleValue(ArgExpr); 9900 return; 9901 } 9902 Inherited::VisitCXXConstructExpr(E); 9903 } 9904 9905 void VisitCallExpr(CallExpr *E) { 9906 // Treat std::move as a use. 9907 if (E->getNumArgs() == 1) { 9908 if (FunctionDecl *FD = E->getDirectCallee()) { 9909 if (FD->isInStdNamespace() && FD->getIdentifier() && 9910 FD->getIdentifier()->isStr("move")) { 9911 HandleValue(E->getArg(0)); 9912 return; 9913 } 9914 } 9915 } 9916 9917 Inherited::VisitCallExpr(E); 9918 } 9919 9920 void VisitBinaryOperator(BinaryOperator *E) { 9921 if (E->isCompoundAssignmentOp()) { 9922 HandleValue(E->getLHS()); 9923 Visit(E->getRHS()); 9924 return; 9925 } 9926 9927 Inherited::VisitBinaryOperator(E); 9928 } 9929 9930 // A custom visitor for BinaryConditionalOperator is needed because the 9931 // regular visitor would check the condition and true expression separately 9932 // but both point to the same place giving duplicate diagnostics. 9933 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 9934 Visit(E->getCond()); 9935 Visit(E->getFalseExpr()); 9936 } 9937 9938 void HandleDeclRefExpr(DeclRefExpr *DRE) { 9939 Decl* ReferenceDecl = DRE->getDecl(); 9940 if (OrigDecl != ReferenceDecl) return; 9941 unsigned diag; 9942 if (isReferenceType) { 9943 diag = diag::warn_uninit_self_reference_in_reference_init; 9944 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 9945 diag = diag::warn_static_self_reference_in_init; 9946 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 9947 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 9948 DRE->getDecl()->getType()->isRecordType()) { 9949 diag = diag::warn_uninit_self_reference_in_init; 9950 } else { 9951 // Local variables will be handled by the CFG analysis. 9952 return; 9953 } 9954 9955 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 9956 S.PDiag(diag) 9957 << DRE->getNameInfo().getName() 9958 << OrigDecl->getLocation() 9959 << DRE->getSourceRange()); 9960 } 9961 }; 9962 9963 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 9964 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 9965 bool DirectInit) { 9966 // Parameters arguments are occassionially constructed with itself, 9967 // for instance, in recursive functions. Skip them. 9968 if (isa<ParmVarDecl>(OrigDecl)) 9969 return; 9970 9971 E = E->IgnoreParens(); 9972 9973 // Skip checking T a = a where T is not a record or reference type. 9974 // Doing so is a way to silence uninitialized warnings. 9975 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 9976 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 9977 if (ICE->getCastKind() == CK_LValueToRValue) 9978 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 9979 if (DRE->getDecl() == OrigDecl) 9980 return; 9981 9982 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 9983 } 9984 } // end anonymous namespace 9985 9986 namespace { 9987 // Simple wrapper to add the name of a variable or (if no variable is 9988 // available) a DeclarationName into a diagnostic. 9989 struct VarDeclOrName { 9990 VarDecl *VDecl; 9991 DeclarationName Name; 9992 9993 friend const Sema::SemaDiagnosticBuilder & 9994 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 9995 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 9996 } 9997 }; 9998 } // end anonymous namespace 9999 10000 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 10001 DeclarationName Name, QualType Type, 10002 TypeSourceInfo *TSI, 10003 SourceRange Range, bool DirectInit, 10004 Expr *Init) { 10005 bool IsInitCapture = !VDecl; 10006 assert((!VDecl || !VDecl->isInitCapture()) && 10007 "init captures are expected to be deduced prior to initialization"); 10008 10009 VarDeclOrName VN{VDecl, Name}; 10010 10011 DeducedType *Deduced = Type->getContainedDeducedType(); 10012 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 10013 10014 // C++11 [dcl.spec.auto]p3 10015 if (!Init) { 10016 assert(VDecl && "no init for init capture deduction?"); 10017 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 10018 << VDecl->getDeclName() << Type; 10019 return QualType(); 10020 } 10021 10022 ArrayRef<Expr*> DeduceInits = Init; 10023 if (DirectInit) { 10024 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 10025 DeduceInits = PL->exprs(); 10026 } 10027 10028 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 10029 assert(VDecl && "non-auto type for init capture deduction?"); 10030 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10031 InitializationKind Kind = InitializationKind::CreateForInit( 10032 VDecl->getLocation(), DirectInit, Init); 10033 // FIXME: Initialization should not be taking a mutable list of inits. 10034 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 10035 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 10036 InitsCopy); 10037 } 10038 10039 if (DirectInit) { 10040 if (auto *IL = dyn_cast<InitListExpr>(Init)) 10041 DeduceInits = IL->inits(); 10042 } 10043 10044 // Deduction only works if we have exactly one source expression. 10045 if (DeduceInits.empty()) { 10046 // It isn't possible to write this directly, but it is possible to 10047 // end up in this situation with "auto x(some_pack...);" 10048 Diag(Init->getLocStart(), IsInitCapture 10049 ? diag::err_init_capture_no_expression 10050 : diag::err_auto_var_init_no_expression) 10051 << VN << Type << Range; 10052 return QualType(); 10053 } 10054 10055 if (DeduceInits.size() > 1) { 10056 Diag(DeduceInits[1]->getLocStart(), 10057 IsInitCapture ? diag::err_init_capture_multiple_expressions 10058 : diag::err_auto_var_init_multiple_expressions) 10059 << VN << Type << Range; 10060 return QualType(); 10061 } 10062 10063 Expr *DeduceInit = DeduceInits[0]; 10064 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 10065 Diag(Init->getLocStart(), IsInitCapture 10066 ? diag::err_init_capture_paren_braces 10067 : diag::err_auto_var_init_paren_braces) 10068 << isa<InitListExpr>(Init) << VN << Type << Range; 10069 return QualType(); 10070 } 10071 10072 // Expressions default to 'id' when we're in a debugger. 10073 bool DefaultedAnyToId = false; 10074 if (getLangOpts().DebuggerCastResultToId && 10075 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 10076 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10077 if (Result.isInvalid()) { 10078 return QualType(); 10079 } 10080 Init = Result.get(); 10081 DefaultedAnyToId = true; 10082 } 10083 10084 // C++ [dcl.decomp]p1: 10085 // If the assignment-expression [...] has array type A and no ref-qualifier 10086 // is present, e has type cv A 10087 if (VDecl && isa<DecompositionDecl>(VDecl) && 10088 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 10089 DeduceInit->getType()->isConstantArrayType()) 10090 return Context.getQualifiedType(DeduceInit->getType(), 10091 Type.getQualifiers()); 10092 10093 QualType DeducedType; 10094 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 10095 if (!IsInitCapture) 10096 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 10097 else if (isa<InitListExpr>(Init)) 10098 Diag(Range.getBegin(), 10099 diag::err_init_capture_deduction_failure_from_init_list) 10100 << VN 10101 << (DeduceInit->getType().isNull() ? TSI->getType() 10102 : DeduceInit->getType()) 10103 << DeduceInit->getSourceRange(); 10104 else 10105 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 10106 << VN << TSI->getType() 10107 << (DeduceInit->getType().isNull() ? TSI->getType() 10108 : DeduceInit->getType()) 10109 << DeduceInit->getSourceRange(); 10110 } 10111 10112 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 10113 // 'id' instead of a specific object type prevents most of our usual 10114 // checks. 10115 // We only want to warn outside of template instantiations, though: 10116 // inside a template, the 'id' could have come from a parameter. 10117 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 10118 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 10119 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 10120 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 10121 } 10122 10123 return DeducedType; 10124 } 10125 10126 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 10127 Expr *Init) { 10128 QualType DeducedType = deduceVarTypeFromInitializer( 10129 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 10130 VDecl->getSourceRange(), DirectInit, Init); 10131 if (DeducedType.isNull()) { 10132 VDecl->setInvalidDecl(); 10133 return true; 10134 } 10135 10136 VDecl->setType(DeducedType); 10137 assert(VDecl->isLinkageValid()); 10138 10139 // In ARC, infer lifetime. 10140 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 10141 VDecl->setInvalidDecl(); 10142 10143 // If this is a redeclaration, check that the type we just deduced matches 10144 // the previously declared type. 10145 if (VarDecl *Old = VDecl->getPreviousDecl()) { 10146 // We never need to merge the type, because we cannot form an incomplete 10147 // array of auto, nor deduce such a type. 10148 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 10149 } 10150 10151 // Check the deduced type is valid for a variable declaration. 10152 CheckVariableDeclarationType(VDecl); 10153 return VDecl->isInvalidDecl(); 10154 } 10155 10156 /// AddInitializerToDecl - Adds the initializer Init to the 10157 /// declaration dcl. If DirectInit is true, this is C++ direct 10158 /// initialization rather than copy initialization. 10159 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 10160 // If there is no declaration, there was an error parsing it. Just ignore 10161 // the initializer. 10162 if (!RealDecl || RealDecl->isInvalidDecl()) { 10163 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 10164 return; 10165 } 10166 10167 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 10168 // Pure-specifiers are handled in ActOnPureSpecifier. 10169 Diag(Method->getLocation(), diag::err_member_function_initialization) 10170 << Method->getDeclName() << Init->getSourceRange(); 10171 Method->setInvalidDecl(); 10172 return; 10173 } 10174 10175 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 10176 if (!VDecl) { 10177 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 10178 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 10179 RealDecl->setInvalidDecl(); 10180 return; 10181 } 10182 10183 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 10184 if (VDecl->getType()->isUndeducedType()) { 10185 // Attempt typo correction early so that the type of the init expression can 10186 // be deduced based on the chosen correction if the original init contains a 10187 // TypoExpr. 10188 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 10189 if (!Res.isUsable()) { 10190 RealDecl->setInvalidDecl(); 10191 return; 10192 } 10193 Init = Res.get(); 10194 10195 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 10196 return; 10197 } 10198 10199 // dllimport cannot be used on variable definitions. 10200 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 10201 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 10202 VDecl->setInvalidDecl(); 10203 return; 10204 } 10205 10206 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 10207 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 10208 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 10209 VDecl->setInvalidDecl(); 10210 return; 10211 } 10212 10213 if (!VDecl->getType()->isDependentType()) { 10214 // A definition must end up with a complete type, which means it must be 10215 // complete with the restriction that an array type might be completed by 10216 // the initializer; note that later code assumes this restriction. 10217 QualType BaseDeclType = VDecl->getType(); 10218 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 10219 BaseDeclType = Array->getElementType(); 10220 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 10221 diag::err_typecheck_decl_incomplete_type)) { 10222 RealDecl->setInvalidDecl(); 10223 return; 10224 } 10225 10226 // The variable can not have an abstract class type. 10227 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 10228 diag::err_abstract_type_in_decl, 10229 AbstractVariableType)) 10230 VDecl->setInvalidDecl(); 10231 } 10232 10233 // If adding the initializer will turn this declaration into a definition, 10234 // and we already have a definition for this variable, diagnose or otherwise 10235 // handle the situation. 10236 VarDecl *Def; 10237 if ((Def = VDecl->getDefinition()) && Def != VDecl && 10238 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 10239 !VDecl->isThisDeclarationADemotedDefinition() && 10240 checkVarDeclRedefinition(Def, VDecl)) 10241 return; 10242 10243 if (getLangOpts().CPlusPlus) { 10244 // C++ [class.static.data]p4 10245 // If a static data member is of const integral or const 10246 // enumeration type, its declaration in the class definition can 10247 // specify a constant-initializer which shall be an integral 10248 // constant expression (5.19). In that case, the member can appear 10249 // in integral constant expressions. The member shall still be 10250 // defined in a namespace scope if it is used in the program and the 10251 // namespace scope definition shall not contain an initializer. 10252 // 10253 // We already performed a redefinition check above, but for static 10254 // data members we also need to check whether there was an in-class 10255 // declaration with an initializer. 10256 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 10257 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 10258 << VDecl->getDeclName(); 10259 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 10260 diag::note_previous_initializer) 10261 << 0; 10262 return; 10263 } 10264 10265 if (VDecl->hasLocalStorage()) 10266 getCurFunction()->setHasBranchProtectedScope(); 10267 10268 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 10269 VDecl->setInvalidDecl(); 10270 return; 10271 } 10272 } 10273 10274 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 10275 // a kernel function cannot be initialized." 10276 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 10277 Diag(VDecl->getLocation(), diag::err_local_cant_init); 10278 VDecl->setInvalidDecl(); 10279 return; 10280 } 10281 10282 // Get the decls type and save a reference for later, since 10283 // CheckInitializerTypes may change it. 10284 QualType DclT = VDecl->getType(), SavT = DclT; 10285 10286 // Expressions default to 'id' when we're in a debugger 10287 // and we are assigning it to a variable of Objective-C pointer type. 10288 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 10289 Init->getType() == Context.UnknownAnyTy) { 10290 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10291 if (Result.isInvalid()) { 10292 VDecl->setInvalidDecl(); 10293 return; 10294 } 10295 Init = Result.get(); 10296 } 10297 10298 // Perform the initialization. 10299 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 10300 if (!VDecl->isInvalidDecl()) { 10301 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10302 InitializationKind Kind = InitializationKind::CreateForInit( 10303 VDecl->getLocation(), DirectInit, Init); 10304 10305 MultiExprArg Args = Init; 10306 if (CXXDirectInit) 10307 Args = MultiExprArg(CXXDirectInit->getExprs(), 10308 CXXDirectInit->getNumExprs()); 10309 10310 // Try to correct any TypoExprs in the initialization arguments. 10311 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 10312 ExprResult Res = CorrectDelayedTyposInExpr( 10313 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 10314 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 10315 return Init.Failed() ? ExprError() : E; 10316 }); 10317 if (Res.isInvalid()) { 10318 VDecl->setInvalidDecl(); 10319 } else if (Res.get() != Args[Idx]) { 10320 Args[Idx] = Res.get(); 10321 } 10322 } 10323 if (VDecl->isInvalidDecl()) 10324 return; 10325 10326 InitializationSequence InitSeq(*this, Entity, Kind, Args, 10327 /*TopLevelOfInitList=*/false, 10328 /*TreatUnavailableAsInvalid=*/false); 10329 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 10330 if (Result.isInvalid()) { 10331 VDecl->setInvalidDecl(); 10332 return; 10333 } 10334 10335 Init = Result.getAs<Expr>(); 10336 } 10337 10338 // Check for self-references within variable initializers. 10339 // Variables declared within a function/method body (except for references) 10340 // are handled by a dataflow analysis. 10341 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 10342 VDecl->getType()->isReferenceType()) { 10343 CheckSelfReference(*this, RealDecl, Init, DirectInit); 10344 } 10345 10346 // If the type changed, it means we had an incomplete type that was 10347 // completed by the initializer. For example: 10348 // int ary[] = { 1, 3, 5 }; 10349 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 10350 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 10351 VDecl->setType(DclT); 10352 10353 if (!VDecl->isInvalidDecl()) { 10354 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 10355 10356 if (VDecl->hasAttr<BlocksAttr>()) 10357 checkRetainCycles(VDecl, Init); 10358 10359 // It is safe to assign a weak reference into a strong variable. 10360 // Although this code can still have problems: 10361 // id x = self.weakProp; 10362 // id y = self.weakProp; 10363 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10364 // paths through the function. This should be revisited if 10365 // -Wrepeated-use-of-weak is made flow-sensitive. 10366 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 10367 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 10368 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10369 Init->getLocStart())) 10370 getCurFunction()->markSafeWeakUse(Init); 10371 } 10372 10373 // The initialization is usually a full-expression. 10374 // 10375 // FIXME: If this is a braced initialization of an aggregate, it is not 10376 // an expression, and each individual field initializer is a separate 10377 // full-expression. For instance, in: 10378 // 10379 // struct Temp { ~Temp(); }; 10380 // struct S { S(Temp); }; 10381 // struct T { S a, b; } t = { Temp(), Temp() } 10382 // 10383 // we should destroy the first Temp before constructing the second. 10384 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 10385 false, 10386 VDecl->isConstexpr()); 10387 if (Result.isInvalid()) { 10388 VDecl->setInvalidDecl(); 10389 return; 10390 } 10391 Init = Result.get(); 10392 10393 // Attach the initializer to the decl. 10394 VDecl->setInit(Init); 10395 10396 if (VDecl->isLocalVarDecl()) { 10397 // Don't check the initializer if the declaration is malformed. 10398 if (VDecl->isInvalidDecl()) { 10399 // do nothing 10400 10401 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 10402 // This is true even in OpenCL C++. 10403 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 10404 CheckForConstantInitializer(Init, DclT); 10405 10406 // Otherwise, C++ does not restrict the initializer. 10407 } else if (getLangOpts().CPlusPlus) { 10408 // do nothing 10409 10410 // C99 6.7.8p4: All the expressions in an initializer for an object that has 10411 // static storage duration shall be constant expressions or string literals. 10412 } else if (VDecl->getStorageClass() == SC_Static) { 10413 CheckForConstantInitializer(Init, DclT); 10414 10415 // C89 is stricter than C99 for aggregate initializers. 10416 // C89 6.5.7p3: All the expressions [...] in an initializer list 10417 // for an object that has aggregate or union type shall be 10418 // constant expressions. 10419 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 10420 isa<InitListExpr>(Init)) { 10421 const Expr *Culprit; 10422 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 10423 Diag(Culprit->getExprLoc(), 10424 diag::ext_aggregate_init_not_constant) 10425 << Culprit->getSourceRange(); 10426 } 10427 } 10428 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 10429 VDecl->getLexicalDeclContext()->isRecord()) { 10430 // This is an in-class initialization for a static data member, e.g., 10431 // 10432 // struct S { 10433 // static const int value = 17; 10434 // }; 10435 10436 // C++ [class.mem]p4: 10437 // A member-declarator can contain a constant-initializer only 10438 // if it declares a static member (9.4) of const integral or 10439 // const enumeration type, see 9.4.2. 10440 // 10441 // C++11 [class.static.data]p3: 10442 // If a non-volatile non-inline const static data member is of integral 10443 // or enumeration type, its declaration in the class definition can 10444 // specify a brace-or-equal-initializer in which every initializer-clause 10445 // that is an assignment-expression is a constant expression. A static 10446 // data member of literal type can be declared in the class definition 10447 // with the constexpr specifier; if so, its declaration shall specify a 10448 // brace-or-equal-initializer in which every initializer-clause that is 10449 // an assignment-expression is a constant expression. 10450 10451 // Do nothing on dependent types. 10452 if (DclT->isDependentType()) { 10453 10454 // Allow any 'static constexpr' members, whether or not they are of literal 10455 // type. We separately check that every constexpr variable is of literal 10456 // type. 10457 } else if (VDecl->isConstexpr()) { 10458 10459 // Require constness. 10460 } else if (!DclT.isConstQualified()) { 10461 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 10462 << Init->getSourceRange(); 10463 VDecl->setInvalidDecl(); 10464 10465 // We allow integer constant expressions in all cases. 10466 } else if (DclT->isIntegralOrEnumerationType()) { 10467 // Check whether the expression is a constant expression. 10468 SourceLocation Loc; 10469 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 10470 // In C++11, a non-constexpr const static data member with an 10471 // in-class initializer cannot be volatile. 10472 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 10473 else if (Init->isValueDependent()) 10474 ; // Nothing to check. 10475 else if (Init->isIntegerConstantExpr(Context, &Loc)) 10476 ; // Ok, it's an ICE! 10477 else if (Init->isEvaluatable(Context)) { 10478 // If we can constant fold the initializer through heroics, accept it, 10479 // but report this as a use of an extension for -pedantic. 10480 Diag(Loc, diag::ext_in_class_initializer_non_constant) 10481 << Init->getSourceRange(); 10482 } else { 10483 // Otherwise, this is some crazy unknown case. Report the issue at the 10484 // location provided by the isIntegerConstantExpr failed check. 10485 Diag(Loc, diag::err_in_class_initializer_non_constant) 10486 << Init->getSourceRange(); 10487 VDecl->setInvalidDecl(); 10488 } 10489 10490 // We allow foldable floating-point constants as an extension. 10491 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 10492 // In C++98, this is a GNU extension. In C++11, it is not, but we support 10493 // it anyway and provide a fixit to add the 'constexpr'. 10494 if (getLangOpts().CPlusPlus11) { 10495 Diag(VDecl->getLocation(), 10496 diag::ext_in_class_initializer_float_type_cxx11) 10497 << DclT << Init->getSourceRange(); 10498 Diag(VDecl->getLocStart(), 10499 diag::note_in_class_initializer_float_type_cxx11) 10500 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10501 } else { 10502 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 10503 << DclT << Init->getSourceRange(); 10504 10505 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 10506 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 10507 << Init->getSourceRange(); 10508 VDecl->setInvalidDecl(); 10509 } 10510 } 10511 10512 // Suggest adding 'constexpr' in C++11 for literal types. 10513 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 10514 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 10515 << DclT << Init->getSourceRange() 10516 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10517 VDecl->setConstexpr(true); 10518 10519 } else { 10520 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 10521 << DclT << Init->getSourceRange(); 10522 VDecl->setInvalidDecl(); 10523 } 10524 } else if (VDecl->isFileVarDecl()) { 10525 // In C, extern is typically used to avoid tentative definitions when 10526 // declaring variables in headers, but adding an intializer makes it a 10527 // defintion. This is somewhat confusing, so GCC and Clang both warn on it. 10528 // In C++, extern is often used to give implictly static const variables 10529 // external linkage, so don't warn in that case. If selectany is present, 10530 // this might be header code intended for C and C++ inclusion, so apply the 10531 // C++ rules. 10532 if (VDecl->getStorageClass() == SC_Extern && 10533 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 10534 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 10535 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 10536 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 10537 Diag(VDecl->getLocation(), diag::warn_extern_init); 10538 10539 // C99 6.7.8p4. All file scoped initializers need to be constant. 10540 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 10541 CheckForConstantInitializer(Init, DclT); 10542 } 10543 10544 // We will represent direct-initialization similarly to copy-initialization: 10545 // int x(1); -as-> int x = 1; 10546 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 10547 // 10548 // Clients that want to distinguish between the two forms, can check for 10549 // direct initializer using VarDecl::getInitStyle(). 10550 // A major benefit is that clients that don't particularly care about which 10551 // exactly form was it (like the CodeGen) can handle both cases without 10552 // special case code. 10553 10554 // C++ 8.5p11: 10555 // The form of initialization (using parentheses or '=') is generally 10556 // insignificant, but does matter when the entity being initialized has a 10557 // class type. 10558 if (CXXDirectInit) { 10559 assert(DirectInit && "Call-style initializer must be direct init."); 10560 VDecl->setInitStyle(VarDecl::CallInit); 10561 } else if (DirectInit) { 10562 // This must be list-initialization. No other way is direct-initialization. 10563 VDecl->setInitStyle(VarDecl::ListInit); 10564 } 10565 10566 CheckCompleteVariableDeclaration(VDecl); 10567 } 10568 10569 /// ActOnInitializerError - Given that there was an error parsing an 10570 /// initializer for the given declaration, try to return to some form 10571 /// of sanity. 10572 void Sema::ActOnInitializerError(Decl *D) { 10573 // Our main concern here is re-establishing invariants like "a 10574 // variable's type is either dependent or complete". 10575 if (!D || D->isInvalidDecl()) return; 10576 10577 VarDecl *VD = dyn_cast<VarDecl>(D); 10578 if (!VD) return; 10579 10580 // Bindings are not usable if we can't make sense of the initializer. 10581 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 10582 for (auto *BD : DD->bindings()) 10583 BD->setInvalidDecl(); 10584 10585 // Auto types are meaningless if we can't make sense of the initializer. 10586 if (ParsingInitForAutoVars.count(D)) { 10587 D->setInvalidDecl(); 10588 return; 10589 } 10590 10591 QualType Ty = VD->getType(); 10592 if (Ty->isDependentType()) return; 10593 10594 // Require a complete type. 10595 if (RequireCompleteType(VD->getLocation(), 10596 Context.getBaseElementType(Ty), 10597 diag::err_typecheck_decl_incomplete_type)) { 10598 VD->setInvalidDecl(); 10599 return; 10600 } 10601 10602 // Require a non-abstract type. 10603 if (RequireNonAbstractType(VD->getLocation(), Ty, 10604 diag::err_abstract_type_in_decl, 10605 AbstractVariableType)) { 10606 VD->setInvalidDecl(); 10607 return; 10608 } 10609 10610 // Don't bother complaining about constructors or destructors, 10611 // though. 10612 } 10613 10614 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 10615 // If there is no declaration, there was an error parsing it. Just ignore it. 10616 if (!RealDecl) 10617 return; 10618 10619 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 10620 QualType Type = Var->getType(); 10621 10622 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 10623 if (isa<DecompositionDecl>(RealDecl)) { 10624 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 10625 Var->setInvalidDecl(); 10626 return; 10627 } 10628 10629 if (Type->isUndeducedType() && 10630 DeduceVariableDeclarationType(Var, false, nullptr)) 10631 return; 10632 10633 // C++11 [class.static.data]p3: A static data member can be declared with 10634 // the constexpr specifier; if so, its declaration shall specify 10635 // a brace-or-equal-initializer. 10636 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 10637 // the definition of a variable [...] or the declaration of a static data 10638 // member. 10639 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 10640 !Var->isThisDeclarationADemotedDefinition()) { 10641 if (Var->isStaticDataMember()) { 10642 // C++1z removes the relevant rule; the in-class declaration is always 10643 // a definition there. 10644 if (!getLangOpts().CPlusPlus1z) { 10645 Diag(Var->getLocation(), 10646 diag::err_constexpr_static_mem_var_requires_init) 10647 << Var->getDeclName(); 10648 Var->setInvalidDecl(); 10649 return; 10650 } 10651 } else { 10652 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 10653 Var->setInvalidDecl(); 10654 return; 10655 } 10656 } 10657 10658 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template 10659 // definition having the concept specifier is called a variable concept. A 10660 // concept definition refers to [...] a variable concept and its initializer. 10661 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) { 10662 if (VTD->isConcept()) { 10663 Diag(Var->getLocation(), diag::err_var_concept_not_initialized); 10664 Var->setInvalidDecl(); 10665 return; 10666 } 10667 } 10668 10669 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 10670 // be initialized. 10671 if (!Var->isInvalidDecl() && 10672 Var->getType().getAddressSpace() == LangAS::opencl_constant && 10673 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 10674 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 10675 Var->setInvalidDecl(); 10676 return; 10677 } 10678 10679 switch (Var->isThisDeclarationADefinition()) { 10680 case VarDecl::Definition: 10681 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 10682 break; 10683 10684 // We have an out-of-line definition of a static data member 10685 // that has an in-class initializer, so we type-check this like 10686 // a declaration. 10687 // 10688 // Fall through 10689 10690 case VarDecl::DeclarationOnly: 10691 // It's only a declaration. 10692 10693 // Block scope. C99 6.7p7: If an identifier for an object is 10694 // declared with no linkage (C99 6.2.2p6), the type for the 10695 // object shall be complete. 10696 if (!Type->isDependentType() && Var->isLocalVarDecl() && 10697 !Var->hasLinkage() && !Var->isInvalidDecl() && 10698 RequireCompleteType(Var->getLocation(), Type, 10699 diag::err_typecheck_decl_incomplete_type)) 10700 Var->setInvalidDecl(); 10701 10702 // Make sure that the type is not abstract. 10703 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10704 RequireNonAbstractType(Var->getLocation(), Type, 10705 diag::err_abstract_type_in_decl, 10706 AbstractVariableType)) 10707 Var->setInvalidDecl(); 10708 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10709 Var->getStorageClass() == SC_PrivateExtern) { 10710 Diag(Var->getLocation(), diag::warn_private_extern); 10711 Diag(Var->getLocation(), diag::note_private_extern); 10712 } 10713 10714 return; 10715 10716 case VarDecl::TentativeDefinition: 10717 // File scope. C99 6.9.2p2: A declaration of an identifier for an 10718 // object that has file scope without an initializer, and without a 10719 // storage-class specifier or with the storage-class specifier "static", 10720 // constitutes a tentative definition. Note: A tentative definition with 10721 // external linkage is valid (C99 6.2.2p5). 10722 if (!Var->isInvalidDecl()) { 10723 if (const IncompleteArrayType *ArrayT 10724 = Context.getAsIncompleteArrayType(Type)) { 10725 if (RequireCompleteType(Var->getLocation(), 10726 ArrayT->getElementType(), 10727 diag::err_illegal_decl_array_incomplete_type)) 10728 Var->setInvalidDecl(); 10729 } else if (Var->getStorageClass() == SC_Static) { 10730 // C99 6.9.2p3: If the declaration of an identifier for an object is 10731 // a tentative definition and has internal linkage (C99 6.2.2p3), the 10732 // declared type shall not be an incomplete type. 10733 // NOTE: code such as the following 10734 // static struct s; 10735 // struct s { int a; }; 10736 // is accepted by gcc. Hence here we issue a warning instead of 10737 // an error and we do not invalidate the static declaration. 10738 // NOTE: to avoid multiple warnings, only check the first declaration. 10739 if (Var->isFirstDecl()) 10740 RequireCompleteType(Var->getLocation(), Type, 10741 diag::ext_typecheck_decl_incomplete_type); 10742 } 10743 } 10744 10745 // Record the tentative definition; we're done. 10746 if (!Var->isInvalidDecl()) 10747 TentativeDefinitions.push_back(Var); 10748 return; 10749 } 10750 10751 // Provide a specific diagnostic for uninitialized variable 10752 // definitions with incomplete array type. 10753 if (Type->isIncompleteArrayType()) { 10754 Diag(Var->getLocation(), 10755 diag::err_typecheck_incomplete_array_needs_initializer); 10756 Var->setInvalidDecl(); 10757 return; 10758 } 10759 10760 // Provide a specific diagnostic for uninitialized variable 10761 // definitions with reference type. 10762 if (Type->isReferenceType()) { 10763 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 10764 << Var->getDeclName() 10765 << SourceRange(Var->getLocation(), Var->getLocation()); 10766 Var->setInvalidDecl(); 10767 return; 10768 } 10769 10770 // Do not attempt to type-check the default initializer for a 10771 // variable with dependent type. 10772 if (Type->isDependentType()) 10773 return; 10774 10775 if (Var->isInvalidDecl()) 10776 return; 10777 10778 if (!Var->hasAttr<AliasAttr>()) { 10779 if (RequireCompleteType(Var->getLocation(), 10780 Context.getBaseElementType(Type), 10781 diag::err_typecheck_decl_incomplete_type)) { 10782 Var->setInvalidDecl(); 10783 return; 10784 } 10785 } else { 10786 return; 10787 } 10788 10789 // The variable can not have an abstract class type. 10790 if (RequireNonAbstractType(Var->getLocation(), Type, 10791 diag::err_abstract_type_in_decl, 10792 AbstractVariableType)) { 10793 Var->setInvalidDecl(); 10794 return; 10795 } 10796 10797 // Check for jumps past the implicit initializer. C++0x 10798 // clarifies that this applies to a "variable with automatic 10799 // storage duration", not a "local variable". 10800 // C++11 [stmt.dcl]p3 10801 // A program that jumps from a point where a variable with automatic 10802 // storage duration is not in scope to a point where it is in scope is 10803 // ill-formed unless the variable has scalar type, class type with a 10804 // trivial default constructor and a trivial destructor, a cv-qualified 10805 // version of one of these types, or an array of one of the preceding 10806 // types and is declared without an initializer. 10807 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 10808 if (const RecordType *Record 10809 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 10810 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 10811 // Mark the function for further checking even if the looser rules of 10812 // C++11 do not require such checks, so that we can diagnose 10813 // incompatibilities with C++98. 10814 if (!CXXRecord->isPOD()) 10815 getCurFunction()->setHasBranchProtectedScope(); 10816 } 10817 } 10818 10819 // C++03 [dcl.init]p9: 10820 // If no initializer is specified for an object, and the 10821 // object is of (possibly cv-qualified) non-POD class type (or 10822 // array thereof), the object shall be default-initialized; if 10823 // the object is of const-qualified type, the underlying class 10824 // type shall have a user-declared default 10825 // constructor. Otherwise, if no initializer is specified for 10826 // a non- static object, the object and its subobjects, if 10827 // any, have an indeterminate initial value); if the object 10828 // or any of its subobjects are of const-qualified type, the 10829 // program is ill-formed. 10830 // C++0x [dcl.init]p11: 10831 // If no initializer is specified for an object, the object is 10832 // default-initialized; [...]. 10833 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 10834 InitializationKind Kind 10835 = InitializationKind::CreateDefault(Var->getLocation()); 10836 10837 InitializationSequence InitSeq(*this, Entity, Kind, None); 10838 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 10839 if (Init.isInvalid()) 10840 Var->setInvalidDecl(); 10841 else if (Init.get()) { 10842 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 10843 // This is important for template substitution. 10844 Var->setInitStyle(VarDecl::CallInit); 10845 } 10846 10847 CheckCompleteVariableDeclaration(Var); 10848 } 10849 } 10850 10851 void Sema::ActOnCXXForRangeDecl(Decl *D) { 10852 // If there is no declaration, there was an error parsing it. Ignore it. 10853 if (!D) 10854 return; 10855 10856 VarDecl *VD = dyn_cast<VarDecl>(D); 10857 if (!VD) { 10858 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 10859 D->setInvalidDecl(); 10860 return; 10861 } 10862 10863 VD->setCXXForRangeDecl(true); 10864 10865 // for-range-declaration cannot be given a storage class specifier. 10866 int Error = -1; 10867 switch (VD->getStorageClass()) { 10868 case SC_None: 10869 break; 10870 case SC_Extern: 10871 Error = 0; 10872 break; 10873 case SC_Static: 10874 Error = 1; 10875 break; 10876 case SC_PrivateExtern: 10877 Error = 2; 10878 break; 10879 case SC_Auto: 10880 Error = 3; 10881 break; 10882 case SC_Register: 10883 Error = 4; 10884 break; 10885 } 10886 if (Error != -1) { 10887 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 10888 << VD->getDeclName() << Error; 10889 D->setInvalidDecl(); 10890 } 10891 } 10892 10893 StmtResult 10894 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 10895 IdentifierInfo *Ident, 10896 ParsedAttributes &Attrs, 10897 SourceLocation AttrEnd) { 10898 // C++1y [stmt.iter]p1: 10899 // A range-based for statement of the form 10900 // for ( for-range-identifier : for-range-initializer ) statement 10901 // is equivalent to 10902 // for ( auto&& for-range-identifier : for-range-initializer ) statement 10903 DeclSpec DS(Attrs.getPool().getFactory()); 10904 10905 const char *PrevSpec; 10906 unsigned DiagID; 10907 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 10908 getPrintingPolicy()); 10909 10910 Declarator D(DS, Declarator::ForContext); 10911 D.SetIdentifier(Ident, IdentLoc); 10912 D.takeAttributes(Attrs, AttrEnd); 10913 10914 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 10915 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 10916 EmptyAttrs, IdentLoc); 10917 Decl *Var = ActOnDeclarator(S, D); 10918 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 10919 FinalizeDeclaration(Var); 10920 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 10921 AttrEnd.isValid() ? AttrEnd : IdentLoc); 10922 } 10923 10924 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 10925 if (var->isInvalidDecl()) return; 10926 10927 if (getLangOpts().OpenCL) { 10928 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 10929 // initialiser 10930 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 10931 !var->hasInit()) { 10932 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 10933 << 1 /*Init*/; 10934 var->setInvalidDecl(); 10935 return; 10936 } 10937 } 10938 10939 // In Objective-C, don't allow jumps past the implicit initialization of a 10940 // local retaining variable. 10941 if (getLangOpts().ObjC1 && 10942 var->hasLocalStorage()) { 10943 switch (var->getType().getObjCLifetime()) { 10944 case Qualifiers::OCL_None: 10945 case Qualifiers::OCL_ExplicitNone: 10946 case Qualifiers::OCL_Autoreleasing: 10947 break; 10948 10949 case Qualifiers::OCL_Weak: 10950 case Qualifiers::OCL_Strong: 10951 getCurFunction()->setHasBranchProtectedScope(); 10952 break; 10953 } 10954 } 10955 10956 // Warn about externally-visible variables being defined without a 10957 // prior declaration. We only want to do this for global 10958 // declarations, but we also specifically need to avoid doing it for 10959 // class members because the linkage of an anonymous class can 10960 // change if it's later given a typedef name. 10961 if (var->isThisDeclarationADefinition() && 10962 var->getDeclContext()->getRedeclContext()->isFileContext() && 10963 var->isExternallyVisible() && var->hasLinkage() && 10964 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 10965 var->getLocation())) { 10966 // Find a previous declaration that's not a definition. 10967 VarDecl *prev = var->getPreviousDecl(); 10968 while (prev && prev->isThisDeclarationADefinition()) 10969 prev = prev->getPreviousDecl(); 10970 10971 if (!prev) 10972 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 10973 } 10974 10975 // Cache the result of checking for constant initialization. 10976 Optional<bool> CacheHasConstInit; 10977 const Expr *CacheCulprit; 10978 auto checkConstInit = [&]() mutable { 10979 if (!CacheHasConstInit) 10980 CacheHasConstInit = var->getInit()->isConstantInitializer( 10981 Context, var->getType()->isReferenceType(), &CacheCulprit); 10982 return *CacheHasConstInit; 10983 }; 10984 10985 if (var->getTLSKind() == VarDecl::TLS_Static) { 10986 if (var->getType().isDestructedType()) { 10987 // GNU C++98 edits for __thread, [basic.start.term]p3: 10988 // The type of an object with thread storage duration shall not 10989 // have a non-trivial destructor. 10990 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 10991 if (getLangOpts().CPlusPlus11) 10992 Diag(var->getLocation(), diag::note_use_thread_local); 10993 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 10994 if (!checkConstInit()) { 10995 // GNU C++98 edits for __thread, [basic.start.init]p4: 10996 // An object of thread storage duration shall not require dynamic 10997 // initialization. 10998 // FIXME: Need strict checking here. 10999 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 11000 << CacheCulprit->getSourceRange(); 11001 if (getLangOpts().CPlusPlus11) 11002 Diag(var->getLocation(), diag::note_use_thread_local); 11003 } 11004 } 11005 } 11006 11007 // Apply section attributes and pragmas to global variables. 11008 bool GlobalStorage = var->hasGlobalStorage(); 11009 if (GlobalStorage && var->isThisDeclarationADefinition() && 11010 !inTemplateInstantiation()) { 11011 PragmaStack<StringLiteral *> *Stack = nullptr; 11012 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 11013 if (var->getType().isConstQualified()) 11014 Stack = &ConstSegStack; 11015 else if (!var->getInit()) { 11016 Stack = &BSSSegStack; 11017 SectionFlags |= ASTContext::PSF_Write; 11018 } else { 11019 Stack = &DataSegStack; 11020 SectionFlags |= ASTContext::PSF_Write; 11021 } 11022 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 11023 var->addAttr(SectionAttr::CreateImplicit( 11024 Context, SectionAttr::Declspec_allocate, 11025 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 11026 } 11027 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 11028 if (UnifySection(SA->getName(), SectionFlags, var)) 11029 var->dropAttr<SectionAttr>(); 11030 11031 // Apply the init_seg attribute if this has an initializer. If the 11032 // initializer turns out to not be dynamic, we'll end up ignoring this 11033 // attribute. 11034 if (CurInitSeg && var->getInit()) 11035 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 11036 CurInitSegLoc)); 11037 } 11038 11039 // All the following checks are C++ only. 11040 if (!getLangOpts().CPlusPlus) { 11041 // If this variable must be emitted, add it as an initializer for the 11042 // current module. 11043 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11044 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11045 return; 11046 } 11047 11048 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 11049 CheckCompleteDecompositionDeclaration(DD); 11050 11051 QualType type = var->getType(); 11052 if (type->isDependentType()) return; 11053 11054 // __block variables might require us to capture a copy-initializer. 11055 if (var->hasAttr<BlocksAttr>()) { 11056 // It's currently invalid to ever have a __block variable with an 11057 // array type; should we diagnose that here? 11058 11059 // Regardless, we don't want to ignore array nesting when 11060 // constructing this copy. 11061 if (type->isStructureOrClassType()) { 11062 EnterExpressionEvaluationContext scope( 11063 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 11064 SourceLocation poi = var->getLocation(); 11065 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 11066 ExprResult result 11067 = PerformMoveOrCopyInitialization( 11068 InitializedEntity::InitializeBlock(poi, type, false), 11069 var, var->getType(), varRef, /*AllowNRVO=*/true); 11070 if (!result.isInvalid()) { 11071 result = MaybeCreateExprWithCleanups(result); 11072 Expr *init = result.getAs<Expr>(); 11073 Context.setBlockVarCopyInits(var, init); 11074 } 11075 } 11076 } 11077 11078 Expr *Init = var->getInit(); 11079 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 11080 QualType baseType = Context.getBaseElementType(type); 11081 11082 if (!var->getDeclContext()->isDependentContext() && 11083 Init && !Init->isValueDependent()) { 11084 11085 if (var->isConstexpr()) { 11086 SmallVector<PartialDiagnosticAt, 8> Notes; 11087 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 11088 SourceLocation DiagLoc = var->getLocation(); 11089 // If the note doesn't add any useful information other than a source 11090 // location, fold it into the primary diagnostic. 11091 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11092 diag::note_invalid_subexpr_in_const_expr) { 11093 DiagLoc = Notes[0].first; 11094 Notes.clear(); 11095 } 11096 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 11097 << var << Init->getSourceRange(); 11098 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11099 Diag(Notes[I].first, Notes[I].second); 11100 } 11101 } else if (var->isUsableInConstantExpressions(Context)) { 11102 // Check whether the initializer of a const variable of integral or 11103 // enumeration type is an ICE now, since we can't tell whether it was 11104 // initialized by a constant expression if we check later. 11105 var->checkInitIsICE(); 11106 } 11107 11108 // Don't emit further diagnostics about constexpr globals since they 11109 // were just diagnosed. 11110 if (!var->isConstexpr() && GlobalStorage && 11111 var->hasAttr<RequireConstantInitAttr>()) { 11112 // FIXME: Need strict checking in C++03 here. 11113 bool DiagErr = getLangOpts().CPlusPlus11 11114 ? !var->checkInitIsICE() : !checkConstInit(); 11115 if (DiagErr) { 11116 auto attr = var->getAttr<RequireConstantInitAttr>(); 11117 Diag(var->getLocation(), diag::err_require_constant_init_failed) 11118 << Init->getSourceRange(); 11119 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 11120 << attr->getRange(); 11121 } 11122 } 11123 else if (!var->isConstexpr() && IsGlobal && 11124 !getDiagnostics().isIgnored(diag::warn_global_constructor, 11125 var->getLocation())) { 11126 // Warn about globals which don't have a constant initializer. Don't 11127 // warn about globals with a non-trivial destructor because we already 11128 // warned about them. 11129 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 11130 if (!(RD && !RD->hasTrivialDestructor())) { 11131 if (!checkConstInit()) 11132 Diag(var->getLocation(), diag::warn_global_constructor) 11133 << Init->getSourceRange(); 11134 } 11135 } 11136 } 11137 11138 // Require the destructor. 11139 if (const RecordType *recordType = baseType->getAs<RecordType>()) 11140 FinalizeVarWithDestructor(var, recordType); 11141 11142 // If this variable must be emitted, add it as an initializer for the current 11143 // module. 11144 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11145 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11146 } 11147 11148 /// \brief Determines if a variable's alignment is dependent. 11149 static bool hasDependentAlignment(VarDecl *VD) { 11150 if (VD->getType()->isDependentType()) 11151 return true; 11152 for (auto *I : VD->specific_attrs<AlignedAttr>()) 11153 if (I->isAlignmentDependent()) 11154 return true; 11155 return false; 11156 } 11157 11158 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 11159 /// any semantic actions necessary after any initializer has been attached. 11160 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 11161 // Note that we are no longer parsing the initializer for this declaration. 11162 ParsingInitForAutoVars.erase(ThisDecl); 11163 11164 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 11165 if (!VD) 11166 return; 11167 11168 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 11169 for (auto *BD : DD->bindings()) { 11170 FinalizeDeclaration(BD); 11171 } 11172 } 11173 11174 checkAttributesAfterMerging(*this, *VD); 11175 11176 // Perform TLS alignment check here after attributes attached to the variable 11177 // which may affect the alignment have been processed. Only perform the check 11178 // if the target has a maximum TLS alignment (zero means no constraints). 11179 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 11180 // Protect the check so that it's not performed on dependent types and 11181 // dependent alignments (we can't determine the alignment in that case). 11182 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 11183 !VD->isInvalidDecl()) { 11184 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 11185 if (Context.getDeclAlign(VD) > MaxAlignChars) { 11186 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 11187 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 11188 << (unsigned)MaxAlignChars.getQuantity(); 11189 } 11190 } 11191 } 11192 11193 if (VD->isStaticLocal()) { 11194 if (FunctionDecl *FD = 11195 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 11196 // Static locals inherit dll attributes from their function. 11197 if (Attr *A = getDLLAttr(FD)) { 11198 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 11199 NewAttr->setInherited(true); 11200 VD->addAttr(NewAttr); 11201 } 11202 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 11203 // function, only __shared__ variables may be declared with 11204 // static storage class. 11205 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 11206 CUDADiagIfDeviceCode(VD->getLocation(), 11207 diag::err_device_static_local_var) 11208 << CurrentCUDATarget()) 11209 VD->setInvalidDecl(); 11210 } 11211 } 11212 11213 // Perform check for initializers of device-side global variables. 11214 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 11215 // 7.5). We must also apply the same checks to all __shared__ 11216 // variables whether they are local or not. CUDA also allows 11217 // constant initializers for __constant__ and __device__ variables. 11218 if (getLangOpts().CUDA) { 11219 const Expr *Init = VD->getInit(); 11220 if (Init && VD->hasGlobalStorage()) { 11221 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 11222 VD->hasAttr<CUDASharedAttr>()) { 11223 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()); 11224 bool AllowedInit = false; 11225 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 11226 AllowedInit = 11227 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 11228 // We'll allow constant initializers even if it's a non-empty 11229 // constructor according to CUDA rules. This deviates from NVCC, 11230 // but allows us to handle things like constexpr constructors. 11231 if (!AllowedInit && 11232 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 11233 AllowedInit = VD->getInit()->isConstantInitializer( 11234 Context, VD->getType()->isReferenceType()); 11235 11236 // Also make sure that destructor, if there is one, is empty. 11237 if (AllowedInit) 11238 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 11239 AllowedInit = 11240 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 11241 11242 if (!AllowedInit) { 11243 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 11244 ? diag::err_shared_var_init 11245 : diag::err_dynamic_var_init) 11246 << Init->getSourceRange(); 11247 VD->setInvalidDecl(); 11248 } 11249 } else { 11250 // This is a host-side global variable. Check that the initializer is 11251 // callable from the host side. 11252 const FunctionDecl *InitFn = nullptr; 11253 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 11254 InitFn = CE->getConstructor(); 11255 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 11256 InitFn = CE->getDirectCallee(); 11257 } 11258 if (InitFn) { 11259 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 11260 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 11261 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 11262 << InitFnTarget << InitFn; 11263 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 11264 VD->setInvalidDecl(); 11265 } 11266 } 11267 } 11268 } 11269 } 11270 11271 // Grab the dllimport or dllexport attribute off of the VarDecl. 11272 const InheritableAttr *DLLAttr = getDLLAttr(VD); 11273 11274 // Imported static data members cannot be defined out-of-line. 11275 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 11276 if (VD->isStaticDataMember() && VD->isOutOfLine() && 11277 VD->isThisDeclarationADefinition()) { 11278 // We allow definitions of dllimport class template static data members 11279 // with a warning. 11280 CXXRecordDecl *Context = 11281 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 11282 bool IsClassTemplateMember = 11283 isa<ClassTemplatePartialSpecializationDecl>(Context) || 11284 Context->getDescribedClassTemplate(); 11285 11286 Diag(VD->getLocation(), 11287 IsClassTemplateMember 11288 ? diag::warn_attribute_dllimport_static_field_definition 11289 : diag::err_attribute_dllimport_static_field_definition); 11290 Diag(IA->getLocation(), diag::note_attribute); 11291 if (!IsClassTemplateMember) 11292 VD->setInvalidDecl(); 11293 } 11294 } 11295 11296 // dllimport/dllexport variables cannot be thread local, their TLS index 11297 // isn't exported with the variable. 11298 if (DLLAttr && VD->getTLSKind()) { 11299 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 11300 if (F && getDLLAttr(F)) { 11301 assert(VD->isStaticLocal()); 11302 // But if this is a static local in a dlimport/dllexport function, the 11303 // function will never be inlined, which means the var would never be 11304 // imported, so having it marked import/export is safe. 11305 } else { 11306 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 11307 << DLLAttr; 11308 VD->setInvalidDecl(); 11309 } 11310 } 11311 11312 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 11313 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 11314 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 11315 VD->dropAttr<UsedAttr>(); 11316 } 11317 } 11318 11319 const DeclContext *DC = VD->getDeclContext(); 11320 // If there's a #pragma GCC visibility in scope, and this isn't a class 11321 // member, set the visibility of this variable. 11322 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 11323 AddPushedVisibilityAttribute(VD); 11324 11325 // FIXME: Warn on unused var template partial specializations. 11326 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 11327 MarkUnusedFileScopedDecl(VD); 11328 11329 // Now we have parsed the initializer and can update the table of magic 11330 // tag values. 11331 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 11332 !VD->getType()->isIntegralOrEnumerationType()) 11333 return; 11334 11335 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 11336 const Expr *MagicValueExpr = VD->getInit(); 11337 if (!MagicValueExpr) { 11338 continue; 11339 } 11340 llvm::APSInt MagicValueInt; 11341 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 11342 Diag(I->getRange().getBegin(), 11343 diag::err_type_tag_for_datatype_not_ice) 11344 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11345 continue; 11346 } 11347 if (MagicValueInt.getActiveBits() > 64) { 11348 Diag(I->getRange().getBegin(), 11349 diag::err_type_tag_for_datatype_too_large) 11350 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11351 continue; 11352 } 11353 uint64_t MagicValue = MagicValueInt.getZExtValue(); 11354 RegisterTypeTagForDatatype(I->getArgumentKind(), 11355 MagicValue, 11356 I->getMatchingCType(), 11357 I->getLayoutCompatible(), 11358 I->getMustBeNull()); 11359 } 11360 } 11361 11362 static bool hasDeducedAuto(DeclaratorDecl *DD) { 11363 auto *VD = dyn_cast<VarDecl>(DD); 11364 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 11365 } 11366 11367 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 11368 ArrayRef<Decl *> Group) { 11369 SmallVector<Decl*, 8> Decls; 11370 11371 if (DS.isTypeSpecOwned()) 11372 Decls.push_back(DS.getRepAsDecl()); 11373 11374 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 11375 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 11376 bool DiagnosedMultipleDecomps = false; 11377 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 11378 bool DiagnosedNonDeducedAuto = false; 11379 11380 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11381 if (Decl *D = Group[i]) { 11382 // For declarators, there are some additional syntactic-ish checks we need 11383 // to perform. 11384 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 11385 if (!FirstDeclaratorInGroup) 11386 FirstDeclaratorInGroup = DD; 11387 if (!FirstDecompDeclaratorInGroup) 11388 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 11389 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 11390 !hasDeducedAuto(DD)) 11391 FirstNonDeducedAutoInGroup = DD; 11392 11393 if (FirstDeclaratorInGroup != DD) { 11394 // A decomposition declaration cannot be combined with any other 11395 // declaration in the same group. 11396 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 11397 Diag(FirstDecompDeclaratorInGroup->getLocation(), 11398 diag::err_decomp_decl_not_alone) 11399 << FirstDeclaratorInGroup->getSourceRange() 11400 << DD->getSourceRange(); 11401 DiagnosedMultipleDecomps = true; 11402 } 11403 11404 // A declarator that uses 'auto' in any way other than to declare a 11405 // variable with a deduced type cannot be combined with any other 11406 // declarator in the same group. 11407 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 11408 Diag(FirstNonDeducedAutoInGroup->getLocation(), 11409 diag::err_auto_non_deduced_not_alone) 11410 << FirstNonDeducedAutoInGroup->getType() 11411 ->hasAutoForTrailingReturnType() 11412 << FirstDeclaratorInGroup->getSourceRange() 11413 << DD->getSourceRange(); 11414 DiagnosedNonDeducedAuto = true; 11415 } 11416 } 11417 } 11418 11419 Decls.push_back(D); 11420 } 11421 } 11422 11423 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 11424 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 11425 handleTagNumbering(Tag, S); 11426 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 11427 getLangOpts().CPlusPlus) 11428 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 11429 } 11430 } 11431 11432 return BuildDeclaratorGroup(Decls); 11433 } 11434 11435 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 11436 /// group, performing any necessary semantic checking. 11437 Sema::DeclGroupPtrTy 11438 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 11439 // C++14 [dcl.spec.auto]p7: (DR1347) 11440 // If the type that replaces the placeholder type is not the same in each 11441 // deduction, the program is ill-formed. 11442 if (Group.size() > 1) { 11443 QualType Deduced; 11444 VarDecl *DeducedDecl = nullptr; 11445 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11446 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 11447 if (!D || D->isInvalidDecl()) 11448 break; 11449 DeducedType *DT = D->getType()->getContainedDeducedType(); 11450 if (!DT || DT->getDeducedType().isNull()) 11451 continue; 11452 if (Deduced.isNull()) { 11453 Deduced = DT->getDeducedType(); 11454 DeducedDecl = D; 11455 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 11456 auto *AT = dyn_cast<AutoType>(DT); 11457 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 11458 diag::err_auto_different_deductions) 11459 << (AT ? (unsigned)AT->getKeyword() : 3) 11460 << Deduced << DeducedDecl->getDeclName() 11461 << DT->getDeducedType() << D->getDeclName() 11462 << DeducedDecl->getInit()->getSourceRange() 11463 << D->getInit()->getSourceRange(); 11464 D->setInvalidDecl(); 11465 break; 11466 } 11467 } 11468 } 11469 11470 ActOnDocumentableDecls(Group); 11471 11472 return DeclGroupPtrTy::make( 11473 DeclGroupRef::Create(Context, Group.data(), Group.size())); 11474 } 11475 11476 void Sema::ActOnDocumentableDecl(Decl *D) { 11477 ActOnDocumentableDecls(D); 11478 } 11479 11480 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 11481 // Don't parse the comment if Doxygen diagnostics are ignored. 11482 if (Group.empty() || !Group[0]) 11483 return; 11484 11485 if (Diags.isIgnored(diag::warn_doc_param_not_found, 11486 Group[0]->getLocation()) && 11487 Diags.isIgnored(diag::warn_unknown_comment_command_name, 11488 Group[0]->getLocation())) 11489 return; 11490 11491 if (Group.size() >= 2) { 11492 // This is a decl group. Normally it will contain only declarations 11493 // produced from declarator list. But in case we have any definitions or 11494 // additional declaration references: 11495 // 'typedef struct S {} S;' 11496 // 'typedef struct S *S;' 11497 // 'struct S *pS;' 11498 // FinalizeDeclaratorGroup adds these as separate declarations. 11499 Decl *MaybeTagDecl = Group[0]; 11500 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 11501 Group = Group.slice(1); 11502 } 11503 } 11504 11505 // See if there are any new comments that are not attached to a decl. 11506 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 11507 if (!Comments.empty() && 11508 !Comments.back()->isAttached()) { 11509 // There is at least one comment that not attached to a decl. 11510 // Maybe it should be attached to one of these decls? 11511 // 11512 // Note that this way we pick up not only comments that precede the 11513 // declaration, but also comments that *follow* the declaration -- thanks to 11514 // the lookahead in the lexer: we've consumed the semicolon and looked 11515 // ahead through comments. 11516 for (unsigned i = 0, e = Group.size(); i != e; ++i) 11517 Context.getCommentForDecl(Group[i], &PP); 11518 } 11519 } 11520 11521 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 11522 /// to introduce parameters into function prototype scope. 11523 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 11524 const DeclSpec &DS = D.getDeclSpec(); 11525 11526 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 11527 11528 // C++03 [dcl.stc]p2 also permits 'auto'. 11529 StorageClass SC = SC_None; 11530 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 11531 SC = SC_Register; 11532 } else if (getLangOpts().CPlusPlus && 11533 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 11534 SC = SC_Auto; 11535 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 11536 Diag(DS.getStorageClassSpecLoc(), 11537 diag::err_invalid_storage_class_in_func_decl); 11538 D.getMutableDeclSpec().ClearStorageClassSpecs(); 11539 } 11540 11541 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 11542 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 11543 << DeclSpec::getSpecifierName(TSCS); 11544 if (DS.isInlineSpecified()) 11545 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 11546 << getLangOpts().CPlusPlus1z; 11547 if (DS.isConstexprSpecified()) 11548 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 11549 << 0; 11550 if (DS.isConceptSpecified()) 11551 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 11552 11553 DiagnoseFunctionSpecifiers(DS); 11554 11555 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11556 QualType parmDeclType = TInfo->getType(); 11557 11558 if (getLangOpts().CPlusPlus) { 11559 // Check that there are no default arguments inside the type of this 11560 // parameter. 11561 CheckExtraCXXDefaultArguments(D); 11562 11563 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 11564 if (D.getCXXScopeSpec().isSet()) { 11565 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 11566 << D.getCXXScopeSpec().getRange(); 11567 D.getCXXScopeSpec().clear(); 11568 } 11569 } 11570 11571 // Ensure we have a valid name 11572 IdentifierInfo *II = nullptr; 11573 if (D.hasName()) { 11574 II = D.getIdentifier(); 11575 if (!II) { 11576 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 11577 << GetNameForDeclarator(D).getName(); 11578 D.setInvalidType(true); 11579 } 11580 } 11581 11582 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 11583 if (II) { 11584 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 11585 ForRedeclaration); 11586 LookupName(R, S); 11587 if (R.isSingleResult()) { 11588 NamedDecl *PrevDecl = R.getFoundDecl(); 11589 if (PrevDecl->isTemplateParameter()) { 11590 // Maybe we will complain about the shadowed template parameter. 11591 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11592 // Just pretend that we didn't see the previous declaration. 11593 PrevDecl = nullptr; 11594 } else if (S->isDeclScope(PrevDecl)) { 11595 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 11596 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11597 11598 // Recover by removing the name 11599 II = nullptr; 11600 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 11601 D.setInvalidType(true); 11602 } 11603 } 11604 } 11605 11606 // Temporarily put parameter variables in the translation unit, not 11607 // the enclosing context. This prevents them from accidentally 11608 // looking like class members in C++. 11609 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 11610 D.getLocStart(), 11611 D.getIdentifierLoc(), II, 11612 parmDeclType, TInfo, 11613 SC); 11614 11615 if (D.isInvalidType()) 11616 New->setInvalidDecl(); 11617 11618 assert(S->isFunctionPrototypeScope()); 11619 assert(S->getFunctionPrototypeDepth() >= 1); 11620 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 11621 S->getNextFunctionPrototypeIndex()); 11622 11623 // Add the parameter declaration into this scope. 11624 S->AddDecl(New); 11625 if (II) 11626 IdResolver.AddDecl(New); 11627 11628 ProcessDeclAttributes(S, New, D); 11629 11630 if (D.getDeclSpec().isModulePrivateSpecified()) 11631 Diag(New->getLocation(), diag::err_module_private_local) 11632 << 1 << New->getDeclName() 11633 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11634 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11635 11636 if (New->hasAttr<BlocksAttr>()) { 11637 Diag(New->getLocation(), diag::err_block_on_nonlocal); 11638 } 11639 return New; 11640 } 11641 11642 /// \brief Synthesizes a variable for a parameter arising from a 11643 /// typedef. 11644 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 11645 SourceLocation Loc, 11646 QualType T) { 11647 /* FIXME: setting StartLoc == Loc. 11648 Would it be worth to modify callers so as to provide proper source 11649 location for the unnamed parameters, embedding the parameter's type? */ 11650 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 11651 T, Context.getTrivialTypeSourceInfo(T, Loc), 11652 SC_None, nullptr); 11653 Param->setImplicit(); 11654 return Param; 11655 } 11656 11657 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 11658 // Don't diagnose unused-parameter errors in template instantiations; we 11659 // will already have done so in the template itself. 11660 if (inTemplateInstantiation()) 11661 return; 11662 11663 for (const ParmVarDecl *Parameter : Parameters) { 11664 if (!Parameter->isReferenced() && Parameter->getDeclName() && 11665 !Parameter->hasAttr<UnusedAttr>()) { 11666 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 11667 << Parameter->getDeclName(); 11668 } 11669 } 11670 } 11671 11672 void Sema::DiagnoseSizeOfParametersAndReturnValue( 11673 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 11674 if (LangOpts.NumLargeByValueCopy == 0) // No check. 11675 return; 11676 11677 // Warn if the return value is pass-by-value and larger than the specified 11678 // threshold. 11679 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 11680 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 11681 if (Size > LangOpts.NumLargeByValueCopy) 11682 Diag(D->getLocation(), diag::warn_return_value_size) 11683 << D->getDeclName() << Size; 11684 } 11685 11686 // Warn if any parameter is pass-by-value and larger than the specified 11687 // threshold. 11688 for (const ParmVarDecl *Parameter : Parameters) { 11689 QualType T = Parameter->getType(); 11690 if (T->isDependentType() || !T.isPODType(Context)) 11691 continue; 11692 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 11693 if (Size > LangOpts.NumLargeByValueCopy) 11694 Diag(Parameter->getLocation(), diag::warn_parameter_size) 11695 << Parameter->getDeclName() << Size; 11696 } 11697 } 11698 11699 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 11700 SourceLocation NameLoc, IdentifierInfo *Name, 11701 QualType T, TypeSourceInfo *TSInfo, 11702 StorageClass SC) { 11703 // In ARC, infer a lifetime qualifier for appropriate parameter types. 11704 if (getLangOpts().ObjCAutoRefCount && 11705 T.getObjCLifetime() == Qualifiers::OCL_None && 11706 T->isObjCLifetimeType()) { 11707 11708 Qualifiers::ObjCLifetime lifetime; 11709 11710 // Special cases for arrays: 11711 // - if it's const, use __unsafe_unretained 11712 // - otherwise, it's an error 11713 if (T->isArrayType()) { 11714 if (!T.isConstQualified()) { 11715 DelayedDiagnostics.add( 11716 sema::DelayedDiagnostic::makeForbiddenType( 11717 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 11718 } 11719 lifetime = Qualifiers::OCL_ExplicitNone; 11720 } else { 11721 lifetime = T->getObjCARCImplicitLifetime(); 11722 } 11723 T = Context.getLifetimeQualifiedType(T, lifetime); 11724 } 11725 11726 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 11727 Context.getAdjustedParameterType(T), 11728 TSInfo, SC, nullptr); 11729 11730 // Parameters can not be abstract class types. 11731 // For record types, this is done by the AbstractClassUsageDiagnoser once 11732 // the class has been completely parsed. 11733 if (!CurContext->isRecord() && 11734 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 11735 AbstractParamType)) 11736 New->setInvalidDecl(); 11737 11738 // Parameter declarators cannot be interface types. All ObjC objects are 11739 // passed by reference. 11740 if (T->isObjCObjectType()) { 11741 SourceLocation TypeEndLoc = 11742 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 11743 Diag(NameLoc, 11744 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 11745 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 11746 T = Context.getObjCObjectPointerType(T); 11747 New->setType(T); 11748 } 11749 11750 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 11751 // duration shall not be qualified by an address-space qualifier." 11752 // Since all parameters have automatic store duration, they can not have 11753 // an address space. 11754 if (T.getAddressSpace() != 0) { 11755 // OpenCL allows function arguments declared to be an array of a type 11756 // to be qualified with an address space. 11757 if (!(getLangOpts().OpenCL && T->isArrayType())) { 11758 Diag(NameLoc, diag::err_arg_with_address_space); 11759 New->setInvalidDecl(); 11760 } 11761 } 11762 11763 return New; 11764 } 11765 11766 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 11767 SourceLocation LocAfterDecls) { 11768 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 11769 11770 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 11771 // for a K&R function. 11772 if (!FTI.hasPrototype) { 11773 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 11774 --i; 11775 if (FTI.Params[i].Param == nullptr) { 11776 SmallString<256> Code; 11777 llvm::raw_svector_ostream(Code) 11778 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 11779 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 11780 << FTI.Params[i].Ident 11781 << FixItHint::CreateInsertion(LocAfterDecls, Code); 11782 11783 // Implicitly declare the argument as type 'int' for lack of a better 11784 // type. 11785 AttributeFactory attrs; 11786 DeclSpec DS(attrs); 11787 const char* PrevSpec; // unused 11788 unsigned DiagID; // unused 11789 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 11790 DiagID, Context.getPrintingPolicy()); 11791 // Use the identifier location for the type source range. 11792 DS.SetRangeStart(FTI.Params[i].IdentLoc); 11793 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 11794 Declarator ParamD(DS, Declarator::KNRTypeListContext); 11795 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 11796 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 11797 } 11798 } 11799 } 11800 } 11801 11802 Decl * 11803 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 11804 MultiTemplateParamsArg TemplateParameterLists, 11805 SkipBodyInfo *SkipBody) { 11806 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 11807 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 11808 Scope *ParentScope = FnBodyScope->getParent(); 11809 11810 D.setFunctionDefinitionKind(FDK_Definition); 11811 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 11812 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 11813 } 11814 11815 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 11816 Consumer.HandleInlineFunctionDefinition(D); 11817 } 11818 11819 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 11820 const FunctionDecl*& PossibleZeroParamPrototype) { 11821 // Don't warn about invalid declarations. 11822 if (FD->isInvalidDecl()) 11823 return false; 11824 11825 // Or declarations that aren't global. 11826 if (!FD->isGlobal()) 11827 return false; 11828 11829 // Don't warn about C++ member functions. 11830 if (isa<CXXMethodDecl>(FD)) 11831 return false; 11832 11833 // Don't warn about 'main'. 11834 if (FD->isMain()) 11835 return false; 11836 11837 // Don't warn about inline functions. 11838 if (FD->isInlined()) 11839 return false; 11840 11841 // Don't warn about function templates. 11842 if (FD->getDescribedFunctionTemplate()) 11843 return false; 11844 11845 // Don't warn about function template specializations. 11846 if (FD->isFunctionTemplateSpecialization()) 11847 return false; 11848 11849 // Don't warn for OpenCL kernels. 11850 if (FD->hasAttr<OpenCLKernelAttr>()) 11851 return false; 11852 11853 // Don't warn on explicitly deleted functions. 11854 if (FD->isDeleted()) 11855 return false; 11856 11857 bool MissingPrototype = true; 11858 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 11859 Prev; Prev = Prev->getPreviousDecl()) { 11860 // Ignore any declarations that occur in function or method 11861 // scope, because they aren't visible from the header. 11862 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 11863 continue; 11864 11865 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 11866 if (FD->getNumParams() == 0) 11867 PossibleZeroParamPrototype = Prev; 11868 break; 11869 } 11870 11871 return MissingPrototype; 11872 } 11873 11874 void 11875 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 11876 const FunctionDecl *EffectiveDefinition, 11877 SkipBodyInfo *SkipBody) { 11878 const FunctionDecl *Definition = EffectiveDefinition; 11879 if (!Definition) 11880 if (!FD->isDefined(Definition)) 11881 return; 11882 11883 if (canRedefineFunction(Definition, getLangOpts())) 11884 return; 11885 11886 // Don't emit an error when this is redifinition of a typo-corrected 11887 // definition. 11888 if (TypoCorrectedFunctionDefinitions.count(Definition)) 11889 return; 11890 11891 // If we don't have a visible definition of the function, and it's inline or 11892 // a template, skip the new definition. 11893 if (SkipBody && !hasVisibleDefinition(Definition) && 11894 (Definition->getFormalLinkage() == InternalLinkage || 11895 Definition->isInlined() || 11896 Definition->getDescribedFunctionTemplate() || 11897 Definition->getNumTemplateParameterLists())) { 11898 SkipBody->ShouldSkip = true; 11899 if (auto *TD = Definition->getDescribedFunctionTemplate()) 11900 makeMergedDefinitionVisible(TD); 11901 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 11902 return; 11903 } 11904 11905 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 11906 Definition->getStorageClass() == SC_Extern) 11907 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 11908 << FD->getDeclName() << getLangOpts().CPlusPlus; 11909 else 11910 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 11911 11912 Diag(Definition->getLocation(), diag::note_previous_definition); 11913 FD->setInvalidDecl(); 11914 } 11915 11916 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 11917 Sema &S) { 11918 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 11919 11920 LambdaScopeInfo *LSI = S.PushLambdaScope(); 11921 LSI->CallOperator = CallOperator; 11922 LSI->Lambda = LambdaClass; 11923 LSI->ReturnType = CallOperator->getReturnType(); 11924 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 11925 11926 if (LCD == LCD_None) 11927 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 11928 else if (LCD == LCD_ByCopy) 11929 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 11930 else if (LCD == LCD_ByRef) 11931 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 11932 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 11933 11934 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 11935 LSI->Mutable = !CallOperator->isConst(); 11936 11937 // Add the captures to the LSI so they can be noted as already 11938 // captured within tryCaptureVar. 11939 auto I = LambdaClass->field_begin(); 11940 for (const auto &C : LambdaClass->captures()) { 11941 if (C.capturesVariable()) { 11942 VarDecl *VD = C.getCapturedVar(); 11943 if (VD->isInitCapture()) 11944 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 11945 QualType CaptureType = VD->getType(); 11946 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 11947 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 11948 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 11949 /*EllipsisLoc*/C.isPackExpansion() 11950 ? C.getEllipsisLoc() : SourceLocation(), 11951 CaptureType, /*Expr*/ nullptr); 11952 11953 } else if (C.capturesThis()) { 11954 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 11955 /*Expr*/ nullptr, 11956 C.getCaptureKind() == LCK_StarThis); 11957 } else { 11958 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 11959 } 11960 ++I; 11961 } 11962 } 11963 11964 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 11965 SkipBodyInfo *SkipBody) { 11966 if (!D) 11967 return D; 11968 FunctionDecl *FD = nullptr; 11969 11970 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 11971 FD = FunTmpl->getTemplatedDecl(); 11972 else 11973 FD = cast<FunctionDecl>(D); 11974 11975 // Check for defining attributes before the check for redefinition. 11976 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 11977 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 11978 FD->dropAttr<AliasAttr>(); 11979 FD->setInvalidDecl(); 11980 } 11981 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 11982 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 11983 FD->dropAttr<IFuncAttr>(); 11984 FD->setInvalidDecl(); 11985 } 11986 11987 // See if this is a redefinition. 11988 if (!FD->isLateTemplateParsed()) { 11989 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 11990 11991 // If we're skipping the body, we're done. Don't enter the scope. 11992 if (SkipBody && SkipBody->ShouldSkip) 11993 return D; 11994 } 11995 11996 // Mark this function as "will have a body eventually". This lets users to 11997 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 11998 // this function. 11999 FD->setWillHaveBody(); 12000 12001 // If we are instantiating a generic lambda call operator, push 12002 // a LambdaScopeInfo onto the function stack. But use the information 12003 // that's already been calculated (ActOnLambdaExpr) to prime the current 12004 // LambdaScopeInfo. 12005 // When the template operator is being specialized, the LambdaScopeInfo, 12006 // has to be properly restored so that tryCaptureVariable doesn't try 12007 // and capture any new variables. In addition when calculating potential 12008 // captures during transformation of nested lambdas, it is necessary to 12009 // have the LSI properly restored. 12010 if (isGenericLambdaCallOperatorSpecialization(FD)) { 12011 assert(inTemplateInstantiation() && 12012 "There should be an active template instantiation on the stack " 12013 "when instantiating a generic lambda!"); 12014 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 12015 } else { 12016 // Enter a new function scope 12017 PushFunctionScope(); 12018 } 12019 12020 // Builtin functions cannot be defined. 12021 if (unsigned BuiltinID = FD->getBuiltinID()) { 12022 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 12023 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 12024 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 12025 FD->setInvalidDecl(); 12026 } 12027 } 12028 12029 // The return type of a function definition must be complete 12030 // (C99 6.9.1p3, C++ [dcl.fct]p6). 12031 QualType ResultType = FD->getReturnType(); 12032 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 12033 !FD->isInvalidDecl() && 12034 RequireCompleteType(FD->getLocation(), ResultType, 12035 diag::err_func_def_incomplete_result)) 12036 FD->setInvalidDecl(); 12037 12038 if (FnBodyScope) 12039 PushDeclContext(FnBodyScope, FD); 12040 12041 // Check the validity of our function parameters 12042 CheckParmsForFunctionDef(FD->parameters(), 12043 /*CheckParameterNames=*/true); 12044 12045 // Add non-parameter declarations already in the function to the current 12046 // scope. 12047 if (FnBodyScope) { 12048 for (Decl *NPD : FD->decls()) { 12049 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 12050 if (!NonParmDecl) 12051 continue; 12052 assert(!isa<ParmVarDecl>(NonParmDecl) && 12053 "parameters should not be in newly created FD yet"); 12054 12055 // If the decl has a name, make it accessible in the current scope. 12056 if (NonParmDecl->getDeclName()) 12057 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 12058 12059 // Similarly, dive into enums and fish their constants out, making them 12060 // accessible in this scope. 12061 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 12062 for (auto *EI : ED->enumerators()) 12063 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 12064 } 12065 } 12066 } 12067 12068 // Introduce our parameters into the function scope 12069 for (auto Param : FD->parameters()) { 12070 Param->setOwningFunction(FD); 12071 12072 // If this has an identifier, add it to the scope stack. 12073 if (Param->getIdentifier() && FnBodyScope) { 12074 CheckShadow(FnBodyScope, Param); 12075 12076 PushOnScopeChains(Param, FnBodyScope); 12077 } 12078 } 12079 12080 // Ensure that the function's exception specification is instantiated. 12081 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 12082 ResolveExceptionSpec(D->getLocation(), FPT); 12083 12084 // dllimport cannot be applied to non-inline function definitions. 12085 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 12086 !FD->isTemplateInstantiation()) { 12087 assert(!FD->hasAttr<DLLExportAttr>()); 12088 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 12089 FD->setInvalidDecl(); 12090 return D; 12091 } 12092 // We want to attach documentation to original Decl (which might be 12093 // a function template). 12094 ActOnDocumentableDecl(D); 12095 if (getCurLexicalContext()->isObjCContainer() && 12096 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 12097 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 12098 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 12099 12100 return D; 12101 } 12102 12103 /// \brief Given the set of return statements within a function body, 12104 /// compute the variables that are subject to the named return value 12105 /// optimization. 12106 /// 12107 /// Each of the variables that is subject to the named return value 12108 /// optimization will be marked as NRVO variables in the AST, and any 12109 /// return statement that has a marked NRVO variable as its NRVO candidate can 12110 /// use the named return value optimization. 12111 /// 12112 /// This function applies a very simplistic algorithm for NRVO: if every return 12113 /// statement in the scope of a variable has the same NRVO candidate, that 12114 /// candidate is an NRVO variable. 12115 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 12116 ReturnStmt **Returns = Scope->Returns.data(); 12117 12118 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 12119 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 12120 if (!NRVOCandidate->isNRVOVariable()) 12121 Returns[I]->setNRVOCandidate(nullptr); 12122 } 12123 } 12124 } 12125 12126 bool Sema::canDelayFunctionBody(const Declarator &D) { 12127 // We can't delay parsing the body of a constexpr function template (yet). 12128 if (D.getDeclSpec().isConstexprSpecified()) 12129 return false; 12130 12131 // We can't delay parsing the body of a function template with a deduced 12132 // return type (yet). 12133 if (D.getDeclSpec().hasAutoTypeSpec()) { 12134 // If the placeholder introduces a non-deduced trailing return type, 12135 // we can still delay parsing it. 12136 if (D.getNumTypeObjects()) { 12137 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 12138 if (Outer.Kind == DeclaratorChunk::Function && 12139 Outer.Fun.hasTrailingReturnType()) { 12140 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 12141 return Ty.isNull() || !Ty->isUndeducedType(); 12142 } 12143 } 12144 return false; 12145 } 12146 12147 return true; 12148 } 12149 12150 bool Sema::canSkipFunctionBody(Decl *D) { 12151 // We cannot skip the body of a function (or function template) which is 12152 // constexpr, since we may need to evaluate its body in order to parse the 12153 // rest of the file. 12154 // We cannot skip the body of a function with an undeduced return type, 12155 // because any callers of that function need to know the type. 12156 if (const FunctionDecl *FD = D->getAsFunction()) 12157 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 12158 return false; 12159 return Consumer.shouldSkipFunctionBody(D); 12160 } 12161 12162 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 12163 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 12164 FD->setHasSkippedBody(); 12165 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 12166 MD->setHasSkippedBody(); 12167 return Decl; 12168 } 12169 12170 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 12171 return ActOnFinishFunctionBody(D, BodyArg, false); 12172 } 12173 12174 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 12175 bool IsInstantiation) { 12176 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 12177 12178 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12179 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 12180 12181 if (getLangOpts().CoroutinesTS && getCurFunction()->CoroutinePromise) 12182 CheckCompletedCoroutineBody(FD, Body); 12183 12184 if (FD) { 12185 FD->setBody(Body); 12186 12187 if (getLangOpts().CPlusPlus14) { 12188 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 12189 FD->getReturnType()->isUndeducedType()) { 12190 // If the function has a deduced result type but contains no 'return' 12191 // statements, the result type as written must be exactly 'auto', and 12192 // the deduced result type is 'void'. 12193 if (!FD->getReturnType()->getAs<AutoType>()) { 12194 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 12195 << FD->getReturnType(); 12196 FD->setInvalidDecl(); 12197 } else { 12198 // Substitute 'void' for the 'auto' in the type. 12199 TypeLoc ResultType = getReturnTypeLoc(FD); 12200 Context.adjustDeducedFunctionResultType( 12201 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 12202 } 12203 } 12204 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 12205 // In C++11, we don't use 'auto' deduction rules for lambda call 12206 // operators because we don't support return type deduction. 12207 auto *LSI = getCurLambda(); 12208 if (LSI->HasImplicitReturnType) { 12209 deduceClosureReturnType(*LSI); 12210 12211 // C++11 [expr.prim.lambda]p4: 12212 // [...] if there are no return statements in the compound-statement 12213 // [the deduced type is] the type void 12214 QualType RetType = 12215 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 12216 12217 // Update the return type to the deduced type. 12218 const FunctionProtoType *Proto = 12219 FD->getType()->getAs<FunctionProtoType>(); 12220 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 12221 Proto->getExtProtoInfo())); 12222 } 12223 } 12224 12225 // The only way to be included in UndefinedButUsed is if there is an 12226 // ODR use before the definition. Avoid the expensive map lookup if this 12227 // is the first declaration. 12228 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 12229 if (!FD->isExternallyVisible()) 12230 UndefinedButUsed.erase(FD); 12231 else if (FD->isInlined() && 12232 !LangOpts.GNUInline && 12233 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 12234 UndefinedButUsed.erase(FD); 12235 } 12236 12237 // If the function implicitly returns zero (like 'main') or is naked, 12238 // don't complain about missing return statements. 12239 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 12240 WP.disableCheckFallThrough(); 12241 12242 // MSVC permits the use of pure specifier (=0) on function definition, 12243 // defined at class scope, warn about this non-standard construct. 12244 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 12245 Diag(FD->getLocation(), diag::ext_pure_function_definition); 12246 12247 if (!FD->isInvalidDecl()) { 12248 // Don't diagnose unused parameters of defaulted or deleted functions. 12249 if (!FD->isDeleted() && !FD->isDefaulted()) 12250 DiagnoseUnusedParameters(FD->parameters()); 12251 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 12252 FD->getReturnType(), FD); 12253 12254 // If this is a structor, we need a vtable. 12255 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 12256 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 12257 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 12258 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 12259 12260 // Try to apply the named return value optimization. We have to check 12261 // if we can do this here because lambdas keep return statements around 12262 // to deduce an implicit return type. 12263 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 12264 !FD->isDependentContext()) 12265 computeNRVO(Body, getCurFunction()); 12266 } 12267 12268 // GNU warning -Wmissing-prototypes: 12269 // Warn if a global function is defined without a previous 12270 // prototype declaration. This warning is issued even if the 12271 // definition itself provides a prototype. The aim is to detect 12272 // global functions that fail to be declared in header files. 12273 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 12274 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 12275 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 12276 12277 if (PossibleZeroParamPrototype) { 12278 // We found a declaration that is not a prototype, 12279 // but that could be a zero-parameter prototype 12280 if (TypeSourceInfo *TI = 12281 PossibleZeroParamPrototype->getTypeSourceInfo()) { 12282 TypeLoc TL = TI->getTypeLoc(); 12283 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 12284 Diag(PossibleZeroParamPrototype->getLocation(), 12285 diag::note_declaration_not_a_prototype) 12286 << PossibleZeroParamPrototype 12287 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 12288 } 12289 } 12290 12291 // GNU warning -Wstrict-prototypes 12292 // Warn if K&R function is defined without a previous declaration. 12293 // This warning is issued only if the definition itself does not provide 12294 // a prototype. Only K&R definitions do not provide a prototype. 12295 // An empty list in a function declarator that is part of a definition 12296 // of that function specifies that the function has no parameters 12297 // (C99 6.7.5.3p14) 12298 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 12299 !LangOpts.CPlusPlus) { 12300 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 12301 TypeLoc TL = TI->getTypeLoc(); 12302 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 12303 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1; 12304 } 12305 } 12306 12307 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 12308 const CXXMethodDecl *KeyFunction; 12309 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 12310 MD->isVirtual() && 12311 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 12312 MD == KeyFunction->getCanonicalDecl()) { 12313 // Update the key-function state if necessary for this ABI. 12314 if (FD->isInlined() && 12315 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 12316 Context.setNonKeyFunction(MD); 12317 12318 // If the newly-chosen key function is already defined, then we 12319 // need to mark the vtable as used retroactively. 12320 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 12321 const FunctionDecl *Definition; 12322 if (KeyFunction && KeyFunction->isDefined(Definition)) 12323 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 12324 } else { 12325 // We just defined they key function; mark the vtable as used. 12326 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 12327 } 12328 } 12329 } 12330 12331 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 12332 "Function parsing confused"); 12333 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 12334 assert(MD == getCurMethodDecl() && "Method parsing confused"); 12335 MD->setBody(Body); 12336 if (!MD->isInvalidDecl()) { 12337 DiagnoseUnusedParameters(MD->parameters()); 12338 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 12339 MD->getReturnType(), MD); 12340 12341 if (Body) 12342 computeNRVO(Body, getCurFunction()); 12343 } 12344 if (getCurFunction()->ObjCShouldCallSuper) { 12345 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 12346 << MD->getSelector().getAsString(); 12347 getCurFunction()->ObjCShouldCallSuper = false; 12348 } 12349 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 12350 const ObjCMethodDecl *InitMethod = nullptr; 12351 bool isDesignated = 12352 MD->isDesignatedInitializerForTheInterface(&InitMethod); 12353 assert(isDesignated && InitMethod); 12354 (void)isDesignated; 12355 12356 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 12357 auto IFace = MD->getClassInterface(); 12358 if (!IFace) 12359 return false; 12360 auto SuperD = IFace->getSuperClass(); 12361 if (!SuperD) 12362 return false; 12363 return SuperD->getIdentifier() == 12364 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 12365 }; 12366 // Don't issue this warning for unavailable inits or direct subclasses 12367 // of NSObject. 12368 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 12369 Diag(MD->getLocation(), 12370 diag::warn_objc_designated_init_missing_super_call); 12371 Diag(InitMethod->getLocation(), 12372 diag::note_objc_designated_init_marked_here); 12373 } 12374 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 12375 } 12376 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 12377 // Don't issue this warning for unavaialable inits. 12378 if (!MD->isUnavailable()) 12379 Diag(MD->getLocation(), 12380 diag::warn_objc_secondary_init_missing_init_call); 12381 getCurFunction()->ObjCWarnForNoInitDelegation = false; 12382 } 12383 } else { 12384 return nullptr; 12385 } 12386 12387 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12388 DiagnoseUnguardedAvailabilityViolations(dcl); 12389 12390 assert(!getCurFunction()->ObjCShouldCallSuper && 12391 "This should only be set for ObjC methods, which should have been " 12392 "handled in the block above."); 12393 12394 // Verify and clean out per-function state. 12395 if (Body && (!FD || !FD->isDefaulted())) { 12396 // C++ constructors that have function-try-blocks can't have return 12397 // statements in the handlers of that block. (C++ [except.handle]p14) 12398 // Verify this. 12399 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 12400 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 12401 12402 // Verify that gotos and switch cases don't jump into scopes illegally. 12403 if (getCurFunction()->NeedsScopeChecking() && 12404 !PP.isCodeCompletionEnabled()) 12405 DiagnoseInvalidJumps(Body); 12406 12407 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 12408 if (!Destructor->getParent()->isDependentType()) 12409 CheckDestructor(Destructor); 12410 12411 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12412 Destructor->getParent()); 12413 } 12414 12415 // If any errors have occurred, clear out any temporaries that may have 12416 // been leftover. This ensures that these temporaries won't be picked up for 12417 // deletion in some later function. 12418 if (getDiagnostics().hasErrorOccurred() || 12419 getDiagnostics().getSuppressAllDiagnostics()) { 12420 DiscardCleanupsInEvaluationContext(); 12421 } 12422 if (!getDiagnostics().hasUncompilableErrorOccurred() && 12423 !isa<FunctionTemplateDecl>(dcl)) { 12424 // Since the body is valid, issue any analysis-based warnings that are 12425 // enabled. 12426 ActivePolicy = &WP; 12427 } 12428 12429 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 12430 (!CheckConstexprFunctionDecl(FD) || 12431 !CheckConstexprFunctionBody(FD, Body))) 12432 FD->setInvalidDecl(); 12433 12434 if (FD && FD->hasAttr<NakedAttr>()) { 12435 for (const Stmt *S : Body->children()) { 12436 // Allow local register variables without initializer as they don't 12437 // require prologue. 12438 bool RegisterVariables = false; 12439 if (auto *DS = dyn_cast<DeclStmt>(S)) { 12440 for (const auto *Decl : DS->decls()) { 12441 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 12442 RegisterVariables = 12443 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 12444 if (!RegisterVariables) 12445 break; 12446 } 12447 } 12448 } 12449 if (RegisterVariables) 12450 continue; 12451 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 12452 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 12453 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 12454 FD->setInvalidDecl(); 12455 break; 12456 } 12457 } 12458 } 12459 12460 assert(ExprCleanupObjects.size() == 12461 ExprEvalContexts.back().NumCleanupObjects && 12462 "Leftover temporaries in function"); 12463 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 12464 assert(MaybeODRUseExprs.empty() && 12465 "Leftover expressions for odr-use checking"); 12466 } 12467 12468 if (!IsInstantiation) 12469 PopDeclContext(); 12470 12471 PopFunctionScopeInfo(ActivePolicy, dcl); 12472 // If any errors have occurred, clear out any temporaries that may have 12473 // been leftover. This ensures that these temporaries won't be picked up for 12474 // deletion in some later function. 12475 if (getDiagnostics().hasErrorOccurred()) { 12476 DiscardCleanupsInEvaluationContext(); 12477 } 12478 12479 return dcl; 12480 } 12481 12482 /// When we finish delayed parsing of an attribute, we must attach it to the 12483 /// relevant Decl. 12484 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 12485 ParsedAttributes &Attrs) { 12486 // Always attach attributes to the underlying decl. 12487 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 12488 D = TD->getTemplatedDecl(); 12489 ProcessDeclAttributeList(S, D, Attrs.getList()); 12490 12491 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 12492 if (Method->isStatic()) 12493 checkThisInStaticMemberFunctionAttributes(Method); 12494 } 12495 12496 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 12497 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 12498 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 12499 IdentifierInfo &II, Scope *S) { 12500 // Before we produce a declaration for an implicitly defined 12501 // function, see whether there was a locally-scoped declaration of 12502 // this name as a function or variable. If so, use that 12503 // (non-visible) declaration, and complain about it. 12504 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 12505 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 12506 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 12507 return ExternCPrev; 12508 } 12509 12510 // Extension in C99. Legal in C90, but warn about it. 12511 unsigned diag_id; 12512 if (II.getName().startswith("__builtin_")) 12513 diag_id = diag::warn_builtin_unknown; 12514 else if (getLangOpts().C99) 12515 diag_id = diag::ext_implicit_function_decl; 12516 else 12517 diag_id = diag::warn_implicit_function_decl; 12518 Diag(Loc, diag_id) << &II; 12519 12520 // Because typo correction is expensive, only do it if the implicit 12521 // function declaration is going to be treated as an error. 12522 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 12523 TypoCorrection Corrected; 12524 if (S && 12525 (Corrected = CorrectTypo( 12526 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 12527 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 12528 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 12529 /*ErrorRecovery*/false); 12530 } 12531 12532 // Set a Declarator for the implicit definition: int foo(); 12533 const char *Dummy; 12534 AttributeFactory attrFactory; 12535 DeclSpec DS(attrFactory); 12536 unsigned DiagID; 12537 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 12538 Context.getPrintingPolicy()); 12539 (void)Error; // Silence warning. 12540 assert(!Error && "Error setting up implicit decl!"); 12541 SourceLocation NoLoc; 12542 Declarator D(DS, Declarator::BlockContext); 12543 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 12544 /*IsAmbiguous=*/false, 12545 /*LParenLoc=*/NoLoc, 12546 /*Params=*/nullptr, 12547 /*NumParams=*/0, 12548 /*EllipsisLoc=*/NoLoc, 12549 /*RParenLoc=*/NoLoc, 12550 /*TypeQuals=*/0, 12551 /*RefQualifierIsLvalueRef=*/true, 12552 /*RefQualifierLoc=*/NoLoc, 12553 /*ConstQualifierLoc=*/NoLoc, 12554 /*VolatileQualifierLoc=*/NoLoc, 12555 /*RestrictQualifierLoc=*/NoLoc, 12556 /*MutableLoc=*/NoLoc, 12557 EST_None, 12558 /*ESpecRange=*/SourceRange(), 12559 /*Exceptions=*/nullptr, 12560 /*ExceptionRanges=*/nullptr, 12561 /*NumExceptions=*/0, 12562 /*NoexceptExpr=*/nullptr, 12563 /*ExceptionSpecTokens=*/nullptr, 12564 /*DeclsInPrototype=*/None, 12565 Loc, Loc, D), 12566 DS.getAttributes(), 12567 SourceLocation()); 12568 D.SetIdentifier(&II, Loc); 12569 12570 // Insert this function into translation-unit scope. 12571 12572 DeclContext *PrevDC = CurContext; 12573 CurContext = Context.getTranslationUnitDecl(); 12574 12575 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 12576 FD->setImplicit(); 12577 12578 CurContext = PrevDC; 12579 12580 AddKnownFunctionAttributes(FD); 12581 12582 return FD; 12583 } 12584 12585 /// \brief Adds any function attributes that we know a priori based on 12586 /// the declaration of this function. 12587 /// 12588 /// These attributes can apply both to implicitly-declared builtins 12589 /// (like __builtin___printf_chk) or to library-declared functions 12590 /// like NSLog or printf. 12591 /// 12592 /// We need to check for duplicate attributes both here and where user-written 12593 /// attributes are applied to declarations. 12594 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 12595 if (FD->isInvalidDecl()) 12596 return; 12597 12598 // If this is a built-in function, map its builtin attributes to 12599 // actual attributes. 12600 if (unsigned BuiltinID = FD->getBuiltinID()) { 12601 // Handle printf-formatting attributes. 12602 unsigned FormatIdx; 12603 bool HasVAListArg; 12604 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 12605 if (!FD->hasAttr<FormatAttr>()) { 12606 const char *fmt = "printf"; 12607 unsigned int NumParams = FD->getNumParams(); 12608 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 12609 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 12610 fmt = "NSString"; 12611 FD->addAttr(FormatAttr::CreateImplicit(Context, 12612 &Context.Idents.get(fmt), 12613 FormatIdx+1, 12614 HasVAListArg ? 0 : FormatIdx+2, 12615 FD->getLocation())); 12616 } 12617 } 12618 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 12619 HasVAListArg)) { 12620 if (!FD->hasAttr<FormatAttr>()) 12621 FD->addAttr(FormatAttr::CreateImplicit(Context, 12622 &Context.Idents.get("scanf"), 12623 FormatIdx+1, 12624 HasVAListArg ? 0 : FormatIdx+2, 12625 FD->getLocation())); 12626 } 12627 12628 // Mark const if we don't care about errno and that is the only 12629 // thing preventing the function from being const. This allows 12630 // IRgen to use LLVM intrinsics for such functions. 12631 if (!getLangOpts().MathErrno && 12632 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 12633 if (!FD->hasAttr<ConstAttr>()) 12634 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12635 } 12636 12637 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 12638 !FD->hasAttr<ReturnsTwiceAttr>()) 12639 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 12640 FD->getLocation())); 12641 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 12642 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12643 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 12644 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 12645 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 12646 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12647 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 12648 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 12649 // Add the appropriate attribute, depending on the CUDA compilation mode 12650 // and which target the builtin belongs to. For example, during host 12651 // compilation, aux builtins are __device__, while the rest are __host__. 12652 if (getLangOpts().CUDAIsDevice != 12653 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 12654 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 12655 else 12656 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 12657 } 12658 } 12659 12660 // If C++ exceptions are enabled but we are told extern "C" functions cannot 12661 // throw, add an implicit nothrow attribute to any extern "C" function we come 12662 // across. 12663 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 12664 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 12665 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 12666 if (!FPT || FPT->getExceptionSpecType() == EST_None) 12667 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12668 } 12669 12670 IdentifierInfo *Name = FD->getIdentifier(); 12671 if (!Name) 12672 return; 12673 if ((!getLangOpts().CPlusPlus && 12674 FD->getDeclContext()->isTranslationUnit()) || 12675 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 12676 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 12677 LinkageSpecDecl::lang_c)) { 12678 // Okay: this could be a libc/libm/Objective-C function we know 12679 // about. 12680 } else 12681 return; 12682 12683 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 12684 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 12685 // target-specific builtins, perhaps? 12686 if (!FD->hasAttr<FormatAttr>()) 12687 FD->addAttr(FormatAttr::CreateImplicit(Context, 12688 &Context.Idents.get("printf"), 2, 12689 Name->isStr("vasprintf") ? 0 : 3, 12690 FD->getLocation())); 12691 } 12692 12693 if (Name->isStr("__CFStringMakeConstantString")) { 12694 // We already have a __builtin___CFStringMakeConstantString, 12695 // but builds that use -fno-constant-cfstrings don't go through that. 12696 if (!FD->hasAttr<FormatArgAttr>()) 12697 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 12698 FD->getLocation())); 12699 } 12700 } 12701 12702 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 12703 TypeSourceInfo *TInfo) { 12704 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 12705 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 12706 12707 if (!TInfo) { 12708 assert(D.isInvalidType() && "no declarator info for valid type"); 12709 TInfo = Context.getTrivialTypeSourceInfo(T); 12710 } 12711 12712 // Scope manipulation handled by caller. 12713 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 12714 D.getLocStart(), 12715 D.getIdentifierLoc(), 12716 D.getIdentifier(), 12717 TInfo); 12718 12719 // Bail out immediately if we have an invalid declaration. 12720 if (D.isInvalidType()) { 12721 NewTD->setInvalidDecl(); 12722 return NewTD; 12723 } 12724 12725 if (D.getDeclSpec().isModulePrivateSpecified()) { 12726 if (CurContext->isFunctionOrMethod()) 12727 Diag(NewTD->getLocation(), diag::err_module_private_local) 12728 << 2 << NewTD->getDeclName() 12729 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12730 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12731 else 12732 NewTD->setModulePrivate(); 12733 } 12734 12735 // C++ [dcl.typedef]p8: 12736 // If the typedef declaration defines an unnamed class (or 12737 // enum), the first typedef-name declared by the declaration 12738 // to be that class type (or enum type) is used to denote the 12739 // class type (or enum type) for linkage purposes only. 12740 // We need to check whether the type was declared in the declaration. 12741 switch (D.getDeclSpec().getTypeSpecType()) { 12742 case TST_enum: 12743 case TST_struct: 12744 case TST_interface: 12745 case TST_union: 12746 case TST_class: { 12747 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 12748 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 12749 break; 12750 } 12751 12752 default: 12753 break; 12754 } 12755 12756 return NewTD; 12757 } 12758 12759 /// \brief Check that this is a valid underlying type for an enum declaration. 12760 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 12761 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 12762 QualType T = TI->getType(); 12763 12764 if (T->isDependentType()) 12765 return false; 12766 12767 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 12768 if (BT->isInteger()) 12769 return false; 12770 12771 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 12772 return true; 12773 } 12774 12775 /// Check whether this is a valid redeclaration of a previous enumeration. 12776 /// \return true if the redeclaration was invalid. 12777 bool Sema::CheckEnumRedeclaration( 12778 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, 12779 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) { 12780 bool IsFixed = !EnumUnderlyingTy.isNull(); 12781 12782 if (IsScoped != Prev->isScoped()) { 12783 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 12784 << Prev->isScoped(); 12785 Diag(Prev->getLocation(), diag::note_previous_declaration); 12786 return true; 12787 } 12788 12789 if (IsFixed && Prev->isFixed()) { 12790 if (!EnumUnderlyingTy->isDependentType() && 12791 !Prev->getIntegerType()->isDependentType() && 12792 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 12793 Prev->getIntegerType())) { 12794 // TODO: Highlight the underlying type of the redeclaration. 12795 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 12796 << EnumUnderlyingTy << Prev->getIntegerType(); 12797 Diag(Prev->getLocation(), diag::note_previous_declaration) 12798 << Prev->getIntegerTypeRange(); 12799 return true; 12800 } 12801 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) { 12802 ; 12803 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) { 12804 ; 12805 } else if (IsFixed != Prev->isFixed()) { 12806 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 12807 << Prev->isFixed(); 12808 Diag(Prev->getLocation(), diag::note_previous_declaration); 12809 return true; 12810 } 12811 12812 return false; 12813 } 12814 12815 /// \brief Get diagnostic %select index for tag kind for 12816 /// redeclaration diagnostic message. 12817 /// WARNING: Indexes apply to particular diagnostics only! 12818 /// 12819 /// \returns diagnostic %select index. 12820 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 12821 switch (Tag) { 12822 case TTK_Struct: return 0; 12823 case TTK_Interface: return 1; 12824 case TTK_Class: return 2; 12825 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 12826 } 12827 } 12828 12829 /// \brief Determine if tag kind is a class-key compatible with 12830 /// class for redeclaration (class, struct, or __interface). 12831 /// 12832 /// \returns true iff the tag kind is compatible. 12833 static bool isClassCompatTagKind(TagTypeKind Tag) 12834 { 12835 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 12836 } 12837 12838 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 12839 TagTypeKind TTK) { 12840 if (isa<TypedefDecl>(PrevDecl)) 12841 return NTK_Typedef; 12842 else if (isa<TypeAliasDecl>(PrevDecl)) 12843 return NTK_TypeAlias; 12844 else if (isa<ClassTemplateDecl>(PrevDecl)) 12845 return NTK_Template; 12846 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 12847 return NTK_TypeAliasTemplate; 12848 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 12849 return NTK_TemplateTemplateArgument; 12850 switch (TTK) { 12851 case TTK_Struct: 12852 case TTK_Interface: 12853 case TTK_Class: 12854 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 12855 case TTK_Union: 12856 return NTK_NonUnion; 12857 case TTK_Enum: 12858 return NTK_NonEnum; 12859 } 12860 llvm_unreachable("invalid TTK"); 12861 } 12862 12863 /// \brief Determine whether a tag with a given kind is acceptable 12864 /// as a redeclaration of the given tag declaration. 12865 /// 12866 /// \returns true if the new tag kind is acceptable, false otherwise. 12867 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 12868 TagTypeKind NewTag, bool isDefinition, 12869 SourceLocation NewTagLoc, 12870 const IdentifierInfo *Name) { 12871 // C++ [dcl.type.elab]p3: 12872 // The class-key or enum keyword present in the 12873 // elaborated-type-specifier shall agree in kind with the 12874 // declaration to which the name in the elaborated-type-specifier 12875 // refers. This rule also applies to the form of 12876 // elaborated-type-specifier that declares a class-name or 12877 // friend class since it can be construed as referring to the 12878 // definition of the class. Thus, in any 12879 // elaborated-type-specifier, the enum keyword shall be used to 12880 // refer to an enumeration (7.2), the union class-key shall be 12881 // used to refer to a union (clause 9), and either the class or 12882 // struct class-key shall be used to refer to a class (clause 9) 12883 // declared using the class or struct class-key. 12884 TagTypeKind OldTag = Previous->getTagKind(); 12885 if (!isDefinition || !isClassCompatTagKind(NewTag)) 12886 if (OldTag == NewTag) 12887 return true; 12888 12889 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 12890 // Warn about the struct/class tag mismatch. 12891 bool isTemplate = false; 12892 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 12893 isTemplate = Record->getDescribedClassTemplate(); 12894 12895 if (inTemplateInstantiation()) { 12896 // In a template instantiation, do not offer fix-its for tag mismatches 12897 // since they usually mess up the template instead of fixing the problem. 12898 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12899 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12900 << getRedeclDiagFromTagKind(OldTag); 12901 return true; 12902 } 12903 12904 if (isDefinition) { 12905 // On definitions, check previous tags and issue a fix-it for each 12906 // one that doesn't match the current tag. 12907 if (Previous->getDefinition()) { 12908 // Don't suggest fix-its for redefinitions. 12909 return true; 12910 } 12911 12912 bool previousMismatch = false; 12913 for (auto I : Previous->redecls()) { 12914 if (I->getTagKind() != NewTag) { 12915 if (!previousMismatch) { 12916 previousMismatch = true; 12917 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 12918 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12919 << getRedeclDiagFromTagKind(I->getTagKind()); 12920 } 12921 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 12922 << getRedeclDiagFromTagKind(NewTag) 12923 << FixItHint::CreateReplacement(I->getInnerLocStart(), 12924 TypeWithKeyword::getTagTypeKindName(NewTag)); 12925 } 12926 } 12927 return true; 12928 } 12929 12930 // Check for a previous definition. If current tag and definition 12931 // are same type, do nothing. If no definition, but disagree with 12932 // with previous tag type, give a warning, but no fix-it. 12933 const TagDecl *Redecl = Previous->getDefinition() ? 12934 Previous->getDefinition() : Previous; 12935 if (Redecl->getTagKind() == NewTag) { 12936 return true; 12937 } 12938 12939 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12940 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12941 << getRedeclDiagFromTagKind(OldTag); 12942 Diag(Redecl->getLocation(), diag::note_previous_use); 12943 12944 // If there is a previous definition, suggest a fix-it. 12945 if (Previous->getDefinition()) { 12946 Diag(NewTagLoc, diag::note_struct_class_suggestion) 12947 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 12948 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 12949 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 12950 } 12951 12952 return true; 12953 } 12954 return false; 12955 } 12956 12957 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 12958 /// from an outer enclosing namespace or file scope inside a friend declaration. 12959 /// This should provide the commented out code in the following snippet: 12960 /// namespace N { 12961 /// struct X; 12962 /// namespace M { 12963 /// struct Y { friend struct /*N::*/ X; }; 12964 /// } 12965 /// } 12966 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 12967 SourceLocation NameLoc) { 12968 // While the decl is in a namespace, do repeated lookup of that name and see 12969 // if we get the same namespace back. If we do not, continue until 12970 // translation unit scope, at which point we have a fully qualified NNS. 12971 SmallVector<IdentifierInfo *, 4> Namespaces; 12972 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12973 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 12974 // This tag should be declared in a namespace, which can only be enclosed by 12975 // other namespaces. Bail if there's an anonymous namespace in the chain. 12976 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 12977 if (!Namespace || Namespace->isAnonymousNamespace()) 12978 return FixItHint(); 12979 IdentifierInfo *II = Namespace->getIdentifier(); 12980 Namespaces.push_back(II); 12981 NamedDecl *Lookup = SemaRef.LookupSingleName( 12982 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 12983 if (Lookup == Namespace) 12984 break; 12985 } 12986 12987 // Once we have all the namespaces, reverse them to go outermost first, and 12988 // build an NNS. 12989 SmallString<64> Insertion; 12990 llvm::raw_svector_ostream OS(Insertion); 12991 if (DC->isTranslationUnit()) 12992 OS << "::"; 12993 std::reverse(Namespaces.begin(), Namespaces.end()); 12994 for (auto *II : Namespaces) 12995 OS << II->getName() << "::"; 12996 return FixItHint::CreateInsertion(NameLoc, Insertion); 12997 } 12998 12999 /// \brief Determine whether a tag originally declared in context \p OldDC can 13000 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup 13001 /// found a declaration in \p OldDC as a previous decl, perhaps through a 13002 /// using-declaration). 13003 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 13004 DeclContext *NewDC) { 13005 OldDC = OldDC->getRedeclContext(); 13006 NewDC = NewDC->getRedeclContext(); 13007 13008 if (OldDC->Equals(NewDC)) 13009 return true; 13010 13011 // In MSVC mode, we allow a redeclaration if the contexts are related (either 13012 // encloses the other). 13013 if (S.getLangOpts().MSVCCompat && 13014 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 13015 return true; 13016 13017 return false; 13018 } 13019 13020 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 13021 /// former case, Name will be non-null. In the later case, Name will be null. 13022 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 13023 /// reference/declaration/definition of a tag. 13024 /// 13025 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 13026 /// trailing-type-specifier) other than one in an alias-declaration. 13027 /// 13028 /// \param SkipBody If non-null, will be set to indicate if the caller should 13029 /// skip the definition of this tag and treat it as if it were a declaration. 13030 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 13031 SourceLocation KWLoc, CXXScopeSpec &SS, 13032 IdentifierInfo *Name, SourceLocation NameLoc, 13033 AttributeList *Attr, AccessSpecifier AS, 13034 SourceLocation ModulePrivateLoc, 13035 MultiTemplateParamsArg TemplateParameterLists, 13036 bool &OwnedDecl, bool &IsDependent, 13037 SourceLocation ScopedEnumKWLoc, 13038 bool ScopedEnumUsesClassTag, 13039 TypeResult UnderlyingType, 13040 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) { 13041 // If this is not a definition, it must have a name. 13042 IdentifierInfo *OrigName = Name; 13043 assert((Name != nullptr || TUK == TUK_Definition) && 13044 "Nameless record must be a definition!"); 13045 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 13046 13047 OwnedDecl = false; 13048 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13049 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 13050 13051 // FIXME: Check member specializations more carefully. 13052 bool isMemberSpecialization = false; 13053 bool Invalid = false; 13054 13055 // We only need to do this matching if we have template parameters 13056 // or a scope specifier, which also conveniently avoids this work 13057 // for non-C++ cases. 13058 if (TemplateParameterLists.size() > 0 || 13059 (SS.isNotEmpty() && TUK != TUK_Reference)) { 13060 if (TemplateParameterList *TemplateParams = 13061 MatchTemplateParametersToScopeSpecifier( 13062 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 13063 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 13064 if (Kind == TTK_Enum) { 13065 Diag(KWLoc, diag::err_enum_template); 13066 return nullptr; 13067 } 13068 13069 if (TemplateParams->size() > 0) { 13070 // This is a declaration or definition of a class template (which may 13071 // be a member of another template). 13072 13073 if (Invalid) 13074 return nullptr; 13075 13076 OwnedDecl = false; 13077 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 13078 SS, Name, NameLoc, Attr, 13079 TemplateParams, AS, 13080 ModulePrivateLoc, 13081 /*FriendLoc*/SourceLocation(), 13082 TemplateParameterLists.size()-1, 13083 TemplateParameterLists.data(), 13084 SkipBody); 13085 return Result.get(); 13086 } else { 13087 // The "template<>" header is extraneous. 13088 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13089 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13090 isMemberSpecialization = true; 13091 } 13092 } 13093 } 13094 13095 // Figure out the underlying type if this a enum declaration. We need to do 13096 // this early, because it's needed to detect if this is an incompatible 13097 // redeclaration. 13098 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 13099 bool EnumUnderlyingIsImplicit = false; 13100 13101 if (Kind == TTK_Enum) { 13102 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 13103 // No underlying type explicitly specified, or we failed to parse the 13104 // type, default to int. 13105 EnumUnderlying = Context.IntTy.getTypePtr(); 13106 else if (UnderlyingType.get()) { 13107 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 13108 // integral type; any cv-qualification is ignored. 13109 TypeSourceInfo *TI = nullptr; 13110 GetTypeFromParser(UnderlyingType.get(), &TI); 13111 EnumUnderlying = TI; 13112 13113 if (CheckEnumUnderlyingType(TI)) 13114 // Recover by falling back to int. 13115 EnumUnderlying = Context.IntTy.getTypePtr(); 13116 13117 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 13118 UPPC_FixedUnderlyingType)) 13119 EnumUnderlying = Context.IntTy.getTypePtr(); 13120 13121 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13122 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) { 13123 // Microsoft enums are always of int type. 13124 EnumUnderlying = Context.IntTy.getTypePtr(); 13125 EnumUnderlyingIsImplicit = true; 13126 } 13127 } 13128 } 13129 13130 DeclContext *SearchDC = CurContext; 13131 DeclContext *DC = CurContext; 13132 bool isStdBadAlloc = false; 13133 bool isStdAlignValT = false; 13134 13135 RedeclarationKind Redecl = ForRedeclaration; 13136 if (TUK == TUK_Friend || TUK == TUK_Reference) 13137 Redecl = NotForRedeclaration; 13138 13139 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 13140 if (Name && SS.isNotEmpty()) { 13141 // We have a nested-name tag ('struct foo::bar'). 13142 13143 // Check for invalid 'foo::'. 13144 if (SS.isInvalid()) { 13145 Name = nullptr; 13146 goto CreateNewDecl; 13147 } 13148 13149 // If this is a friend or a reference to a class in a dependent 13150 // context, don't try to make a decl for it. 13151 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13152 DC = computeDeclContext(SS, false); 13153 if (!DC) { 13154 IsDependent = true; 13155 return nullptr; 13156 } 13157 } else { 13158 DC = computeDeclContext(SS, true); 13159 if (!DC) { 13160 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 13161 << SS.getRange(); 13162 return nullptr; 13163 } 13164 } 13165 13166 if (RequireCompleteDeclContext(SS, DC)) 13167 return nullptr; 13168 13169 SearchDC = DC; 13170 // Look-up name inside 'foo::'. 13171 LookupQualifiedName(Previous, DC); 13172 13173 if (Previous.isAmbiguous()) 13174 return nullptr; 13175 13176 if (Previous.empty()) { 13177 // Name lookup did not find anything. However, if the 13178 // nested-name-specifier refers to the current instantiation, 13179 // and that current instantiation has any dependent base 13180 // classes, we might find something at instantiation time: treat 13181 // this as a dependent elaborated-type-specifier. 13182 // But this only makes any sense for reference-like lookups. 13183 if (Previous.wasNotFoundInCurrentInstantiation() && 13184 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13185 IsDependent = true; 13186 return nullptr; 13187 } 13188 13189 // A tag 'foo::bar' must already exist. 13190 Diag(NameLoc, diag::err_not_tag_in_scope) 13191 << Kind << Name << DC << SS.getRange(); 13192 Name = nullptr; 13193 Invalid = true; 13194 goto CreateNewDecl; 13195 } 13196 } else if (Name) { 13197 // C++14 [class.mem]p14: 13198 // If T is the name of a class, then each of the following shall have a 13199 // name different from T: 13200 // -- every member of class T that is itself a type 13201 if (TUK != TUK_Reference && TUK != TUK_Friend && 13202 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 13203 return nullptr; 13204 13205 // If this is a named struct, check to see if there was a previous forward 13206 // declaration or definition. 13207 // FIXME: We're looking into outer scopes here, even when we 13208 // shouldn't be. Doing so can result in ambiguities that we 13209 // shouldn't be diagnosing. 13210 LookupName(Previous, S); 13211 13212 // When declaring or defining a tag, ignore ambiguities introduced 13213 // by types using'ed into this scope. 13214 if (Previous.isAmbiguous() && 13215 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 13216 LookupResult::Filter F = Previous.makeFilter(); 13217 while (F.hasNext()) { 13218 NamedDecl *ND = F.next(); 13219 if (!ND->getDeclContext()->getRedeclContext()->Equals( 13220 SearchDC->getRedeclContext())) 13221 F.erase(); 13222 } 13223 F.done(); 13224 } 13225 13226 // C++11 [namespace.memdef]p3: 13227 // If the name in a friend declaration is neither qualified nor 13228 // a template-id and the declaration is a function or an 13229 // elaborated-type-specifier, the lookup to determine whether 13230 // the entity has been previously declared shall not consider 13231 // any scopes outside the innermost enclosing namespace. 13232 // 13233 // MSVC doesn't implement the above rule for types, so a friend tag 13234 // declaration may be a redeclaration of a type declared in an enclosing 13235 // scope. They do implement this rule for friend functions. 13236 // 13237 // Does it matter that this should be by scope instead of by 13238 // semantic context? 13239 if (!Previous.empty() && TUK == TUK_Friend) { 13240 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 13241 LookupResult::Filter F = Previous.makeFilter(); 13242 bool FriendSawTagOutsideEnclosingNamespace = false; 13243 while (F.hasNext()) { 13244 NamedDecl *ND = F.next(); 13245 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13246 if (DC->isFileContext() && 13247 !EnclosingNS->Encloses(ND->getDeclContext())) { 13248 if (getLangOpts().MSVCCompat) 13249 FriendSawTagOutsideEnclosingNamespace = true; 13250 else 13251 F.erase(); 13252 } 13253 } 13254 F.done(); 13255 13256 // Diagnose this MSVC extension in the easy case where lookup would have 13257 // unambiguously found something outside the enclosing namespace. 13258 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 13259 NamedDecl *ND = Previous.getFoundDecl(); 13260 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 13261 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 13262 } 13263 } 13264 13265 // Note: there used to be some attempt at recovery here. 13266 if (Previous.isAmbiguous()) 13267 return nullptr; 13268 13269 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 13270 // FIXME: This makes sure that we ignore the contexts associated 13271 // with C structs, unions, and enums when looking for a matching 13272 // tag declaration or definition. See the similar lookup tweak 13273 // in Sema::LookupName; is there a better way to deal with this? 13274 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 13275 SearchDC = SearchDC->getParent(); 13276 } 13277 } 13278 13279 if (Previous.isSingleResult() && 13280 Previous.getFoundDecl()->isTemplateParameter()) { 13281 // Maybe we will complain about the shadowed template parameter. 13282 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 13283 // Just pretend that we didn't see the previous declaration. 13284 Previous.clear(); 13285 } 13286 13287 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 13288 DC->Equals(getStdNamespace())) { 13289 if (Name->isStr("bad_alloc")) { 13290 // This is a declaration of or a reference to "std::bad_alloc". 13291 isStdBadAlloc = true; 13292 13293 // If std::bad_alloc has been implicitly declared (but made invisible to 13294 // name lookup), fill in this implicit declaration as the previous 13295 // declaration, so that the declarations get chained appropriately. 13296 if (Previous.empty() && StdBadAlloc) 13297 Previous.addDecl(getStdBadAlloc()); 13298 } else if (Name->isStr("align_val_t")) { 13299 isStdAlignValT = true; 13300 if (Previous.empty() && StdAlignValT) 13301 Previous.addDecl(getStdAlignValT()); 13302 } 13303 } 13304 13305 // If we didn't find a previous declaration, and this is a reference 13306 // (or friend reference), move to the correct scope. In C++, we 13307 // also need to do a redeclaration lookup there, just in case 13308 // there's a shadow friend decl. 13309 if (Name && Previous.empty() && 13310 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13311 if (Invalid) goto CreateNewDecl; 13312 assert(SS.isEmpty()); 13313 13314 if (TUK == TUK_Reference) { 13315 // C++ [basic.scope.pdecl]p5: 13316 // -- for an elaborated-type-specifier of the form 13317 // 13318 // class-key identifier 13319 // 13320 // if the elaborated-type-specifier is used in the 13321 // decl-specifier-seq or parameter-declaration-clause of a 13322 // function defined in namespace scope, the identifier is 13323 // declared as a class-name in the namespace that contains 13324 // the declaration; otherwise, except as a friend 13325 // declaration, the identifier is declared in the smallest 13326 // non-class, non-function-prototype scope that contains the 13327 // declaration. 13328 // 13329 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 13330 // C structs and unions. 13331 // 13332 // It is an error in C++ to declare (rather than define) an enum 13333 // type, including via an elaborated type specifier. We'll 13334 // diagnose that later; for now, declare the enum in the same 13335 // scope as we would have picked for any other tag type. 13336 // 13337 // GNU C also supports this behavior as part of its incomplete 13338 // enum types extension, while GNU C++ does not. 13339 // 13340 // Find the context where we'll be declaring the tag. 13341 // FIXME: We would like to maintain the current DeclContext as the 13342 // lexical context, 13343 SearchDC = getTagInjectionContext(SearchDC); 13344 13345 // Find the scope where we'll be declaring the tag. 13346 S = getTagInjectionScope(S, getLangOpts()); 13347 } else { 13348 assert(TUK == TUK_Friend); 13349 // C++ [namespace.memdef]p3: 13350 // If a friend declaration in a non-local class first declares a 13351 // class or function, the friend class or function is a member of 13352 // the innermost enclosing namespace. 13353 SearchDC = SearchDC->getEnclosingNamespaceContext(); 13354 } 13355 13356 // In C++, we need to do a redeclaration lookup to properly 13357 // diagnose some problems. 13358 // FIXME: redeclaration lookup is also used (with and without C++) to find a 13359 // hidden declaration so that we don't get ambiguity errors when using a 13360 // type declared by an elaborated-type-specifier. In C that is not correct 13361 // and we should instead merge compatible types found by lookup. 13362 if (getLangOpts().CPlusPlus) { 13363 Previous.setRedeclarationKind(ForRedeclaration); 13364 LookupQualifiedName(Previous, SearchDC); 13365 } else { 13366 Previous.setRedeclarationKind(ForRedeclaration); 13367 LookupName(Previous, S); 13368 } 13369 } 13370 13371 // If we have a known previous declaration to use, then use it. 13372 if (Previous.empty() && SkipBody && SkipBody->Previous) 13373 Previous.addDecl(SkipBody->Previous); 13374 13375 if (!Previous.empty()) { 13376 NamedDecl *PrevDecl = Previous.getFoundDecl(); 13377 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 13378 13379 // It's okay to have a tag decl in the same scope as a typedef 13380 // which hides a tag decl in the same scope. Finding this 13381 // insanity with a redeclaration lookup can only actually happen 13382 // in C++. 13383 // 13384 // This is also okay for elaborated-type-specifiers, which is 13385 // technically forbidden by the current standard but which is 13386 // okay according to the likely resolution of an open issue; 13387 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 13388 if (getLangOpts().CPlusPlus) { 13389 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13390 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 13391 TagDecl *Tag = TT->getDecl(); 13392 if (Tag->getDeclName() == Name && 13393 Tag->getDeclContext()->getRedeclContext() 13394 ->Equals(TD->getDeclContext()->getRedeclContext())) { 13395 PrevDecl = Tag; 13396 Previous.clear(); 13397 Previous.addDecl(Tag); 13398 Previous.resolveKind(); 13399 } 13400 } 13401 } 13402 } 13403 13404 // If this is a redeclaration of a using shadow declaration, it must 13405 // declare a tag in the same context. In MSVC mode, we allow a 13406 // redefinition if either context is within the other. 13407 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 13408 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 13409 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 13410 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 13411 !(OldTag && isAcceptableTagRedeclContext( 13412 *this, OldTag->getDeclContext(), SearchDC))) { 13413 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 13414 Diag(Shadow->getTargetDecl()->getLocation(), 13415 diag::note_using_decl_target); 13416 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 13417 << 0; 13418 // Recover by ignoring the old declaration. 13419 Previous.clear(); 13420 goto CreateNewDecl; 13421 } 13422 } 13423 13424 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 13425 // If this is a use of a previous tag, or if the tag is already declared 13426 // in the same scope (so that the definition/declaration completes or 13427 // rementions the tag), reuse the decl. 13428 if (TUK == TUK_Reference || TUK == TUK_Friend || 13429 isDeclInScope(DirectPrevDecl, SearchDC, S, 13430 SS.isNotEmpty() || isMemberSpecialization)) { 13431 // Make sure that this wasn't declared as an enum and now used as a 13432 // struct or something similar. 13433 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 13434 TUK == TUK_Definition, KWLoc, 13435 Name)) { 13436 bool SafeToContinue 13437 = (PrevTagDecl->getTagKind() != TTK_Enum && 13438 Kind != TTK_Enum); 13439 if (SafeToContinue) 13440 Diag(KWLoc, diag::err_use_with_wrong_tag) 13441 << Name 13442 << FixItHint::CreateReplacement(SourceRange(KWLoc), 13443 PrevTagDecl->getKindName()); 13444 else 13445 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 13446 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 13447 13448 if (SafeToContinue) 13449 Kind = PrevTagDecl->getTagKind(); 13450 else { 13451 // Recover by making this an anonymous redefinition. 13452 Name = nullptr; 13453 Previous.clear(); 13454 Invalid = true; 13455 } 13456 } 13457 13458 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 13459 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 13460 13461 // If this is an elaborated-type-specifier for a scoped enumeration, 13462 // the 'class' keyword is not necessary and not permitted. 13463 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13464 if (ScopedEnum) 13465 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 13466 << PrevEnum->isScoped() 13467 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 13468 return PrevTagDecl; 13469 } 13470 13471 QualType EnumUnderlyingTy; 13472 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13473 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 13474 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 13475 EnumUnderlyingTy = QualType(T, 0); 13476 13477 // All conflicts with previous declarations are recovered by 13478 // returning the previous declaration, unless this is a definition, 13479 // in which case we want the caller to bail out. 13480 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 13481 ScopedEnum, EnumUnderlyingTy, 13482 EnumUnderlyingIsImplicit, PrevEnum)) 13483 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 13484 } 13485 13486 // C++11 [class.mem]p1: 13487 // A member shall not be declared twice in the member-specification, 13488 // except that a nested class or member class template can be declared 13489 // and then later defined. 13490 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 13491 S->isDeclScope(PrevDecl)) { 13492 Diag(NameLoc, diag::ext_member_redeclared); 13493 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 13494 } 13495 13496 if (!Invalid) { 13497 // If this is a use, just return the declaration we found, unless 13498 // we have attributes. 13499 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13500 if (Attr) { 13501 // FIXME: Diagnose these attributes. For now, we create a new 13502 // declaration to hold them. 13503 } else if (TUK == TUK_Reference && 13504 (PrevTagDecl->getFriendObjectKind() == 13505 Decl::FOK_Undeclared || 13506 PP.getModuleContainingLocation( 13507 PrevDecl->getLocation()) != 13508 PP.getModuleContainingLocation(KWLoc)) && 13509 SS.isEmpty()) { 13510 // This declaration is a reference to an existing entity, but 13511 // has different visibility from that entity: it either makes 13512 // a friend visible or it makes a type visible in a new module. 13513 // In either case, create a new declaration. We only do this if 13514 // the declaration would have meant the same thing if no prior 13515 // declaration were found, that is, if it was found in the same 13516 // scope where we would have injected a declaration. 13517 if (!getTagInjectionContext(CurContext)->getRedeclContext() 13518 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 13519 return PrevTagDecl; 13520 // This is in the injected scope, create a new declaration in 13521 // that scope. 13522 S = getTagInjectionScope(S, getLangOpts()); 13523 } else { 13524 return PrevTagDecl; 13525 } 13526 } 13527 13528 // Diagnose attempts to redefine a tag. 13529 if (TUK == TUK_Definition) { 13530 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 13531 // If we're defining a specialization and the previous definition 13532 // is from an implicit instantiation, don't emit an error 13533 // here; we'll catch this in the general case below. 13534 bool IsExplicitSpecializationAfterInstantiation = false; 13535 if (isMemberSpecialization) { 13536 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 13537 IsExplicitSpecializationAfterInstantiation = 13538 RD->getTemplateSpecializationKind() != 13539 TSK_ExplicitSpecialization; 13540 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 13541 IsExplicitSpecializationAfterInstantiation = 13542 ED->getTemplateSpecializationKind() != 13543 TSK_ExplicitSpecialization; 13544 } 13545 13546 NamedDecl *Hidden = nullptr; 13547 if (SkipBody && getLangOpts().CPlusPlus && 13548 !hasVisibleDefinition(Def, &Hidden)) { 13549 // There is a definition of this tag, but it is not visible. We 13550 // explicitly make use of C++'s one definition rule here, and 13551 // assume that this definition is identical to the hidden one 13552 // we already have. Make the existing definition visible and 13553 // use it in place of this one. 13554 SkipBody->ShouldSkip = true; 13555 makeMergedDefinitionVisible(Hidden); 13556 return Def; 13557 } else if (!IsExplicitSpecializationAfterInstantiation) { 13558 // A redeclaration in function prototype scope in C isn't 13559 // visible elsewhere, so merely issue a warning. 13560 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 13561 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 13562 else 13563 Diag(NameLoc, diag::err_redefinition) << Name; 13564 notePreviousDefinition(Def->getLocation(), 13565 NameLoc.isValid() ? NameLoc : KWLoc); 13566 // If this is a redefinition, recover by making this 13567 // struct be anonymous, which will make any later 13568 // references get the previous definition. 13569 Name = nullptr; 13570 Previous.clear(); 13571 Invalid = true; 13572 } 13573 } else { 13574 // If the type is currently being defined, complain 13575 // about a nested redefinition. 13576 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 13577 if (TD->isBeingDefined()) { 13578 Diag(NameLoc, diag::err_nested_redefinition) << Name; 13579 Diag(PrevTagDecl->getLocation(), 13580 diag::note_previous_definition); 13581 Name = nullptr; 13582 Previous.clear(); 13583 Invalid = true; 13584 } 13585 } 13586 13587 // Okay, this is definition of a previously declared or referenced 13588 // tag. We're going to create a new Decl for it. 13589 } 13590 13591 // Okay, we're going to make a redeclaration. If this is some kind 13592 // of reference, make sure we build the redeclaration in the same DC 13593 // as the original, and ignore the current access specifier. 13594 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13595 SearchDC = PrevTagDecl->getDeclContext(); 13596 AS = AS_none; 13597 } 13598 } 13599 // If we get here we have (another) forward declaration or we 13600 // have a definition. Just create a new decl. 13601 13602 } else { 13603 // If we get here, this is a definition of a new tag type in a nested 13604 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 13605 // new decl/type. We set PrevDecl to NULL so that the entities 13606 // have distinct types. 13607 Previous.clear(); 13608 } 13609 // If we get here, we're going to create a new Decl. If PrevDecl 13610 // is non-NULL, it's a definition of the tag declared by 13611 // PrevDecl. If it's NULL, we have a new definition. 13612 13613 // Otherwise, PrevDecl is not a tag, but was found with tag 13614 // lookup. This is only actually possible in C++, where a few 13615 // things like templates still live in the tag namespace. 13616 } else { 13617 // Use a better diagnostic if an elaborated-type-specifier 13618 // found the wrong kind of type on the first 13619 // (non-redeclaration) lookup. 13620 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 13621 !Previous.isForRedeclaration()) { 13622 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13623 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 13624 << Kind; 13625 Diag(PrevDecl->getLocation(), diag::note_declared_at); 13626 Invalid = true; 13627 13628 // Otherwise, only diagnose if the declaration is in scope. 13629 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 13630 SS.isNotEmpty() || isMemberSpecialization)) { 13631 // do nothing 13632 13633 // Diagnose implicit declarations introduced by elaborated types. 13634 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 13635 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13636 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 13637 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13638 Invalid = true; 13639 13640 // Otherwise it's a declaration. Call out a particularly common 13641 // case here. 13642 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13643 unsigned Kind = 0; 13644 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 13645 Diag(NameLoc, diag::err_tag_definition_of_typedef) 13646 << Name << Kind << TND->getUnderlyingType(); 13647 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13648 Invalid = true; 13649 13650 // Otherwise, diagnose. 13651 } else { 13652 // The tag name clashes with something else in the target scope, 13653 // issue an error and recover by making this tag be anonymous. 13654 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 13655 notePreviousDefinition(PrevDecl->getLocation(), NameLoc); 13656 Name = nullptr; 13657 Invalid = true; 13658 } 13659 13660 // The existing declaration isn't relevant to us; we're in a 13661 // new scope, so clear out the previous declaration. 13662 Previous.clear(); 13663 } 13664 } 13665 13666 CreateNewDecl: 13667 13668 TagDecl *PrevDecl = nullptr; 13669 if (Previous.isSingleResult()) 13670 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 13671 13672 // If there is an identifier, use the location of the identifier as the 13673 // location of the decl, otherwise use the location of the struct/union 13674 // keyword. 13675 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13676 13677 // Otherwise, create a new declaration. If there is a previous 13678 // declaration of the same entity, the two will be linked via 13679 // PrevDecl. 13680 TagDecl *New; 13681 13682 bool IsForwardReference = false; 13683 if (Kind == TTK_Enum) { 13684 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13685 // enum X { A, B, C } D; D should chain to X. 13686 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 13687 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 13688 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 13689 13690 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 13691 StdAlignValT = cast<EnumDecl>(New); 13692 13693 // If this is an undefined enum, warn. 13694 if (TUK != TUK_Definition && !Invalid) { 13695 TagDecl *Def; 13696 if (!EnumUnderlyingIsImplicit && 13697 (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 13698 cast<EnumDecl>(New)->isFixed()) { 13699 // C++0x: 7.2p2: opaque-enum-declaration. 13700 // Conflicts are diagnosed above. Do nothing. 13701 } 13702 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 13703 Diag(Loc, diag::ext_forward_ref_enum_def) 13704 << New; 13705 Diag(Def->getLocation(), diag::note_previous_definition); 13706 } else { 13707 unsigned DiagID = diag::ext_forward_ref_enum; 13708 if (getLangOpts().MSVCCompat) 13709 DiagID = diag::ext_ms_forward_ref_enum; 13710 else if (getLangOpts().CPlusPlus) 13711 DiagID = diag::err_forward_ref_enum; 13712 Diag(Loc, DiagID); 13713 13714 // If this is a forward-declared reference to an enumeration, make a 13715 // note of it; we won't actually be introducing the declaration into 13716 // the declaration context. 13717 if (TUK == TUK_Reference) 13718 IsForwardReference = true; 13719 } 13720 } 13721 13722 if (EnumUnderlying) { 13723 EnumDecl *ED = cast<EnumDecl>(New); 13724 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13725 ED->setIntegerTypeSourceInfo(TI); 13726 else 13727 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 13728 ED->setPromotionType(ED->getIntegerType()); 13729 } 13730 } else { 13731 // struct/union/class 13732 13733 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13734 // struct X { int A; } D; D should chain to X. 13735 if (getLangOpts().CPlusPlus) { 13736 // FIXME: Look for a way to use RecordDecl for simple structs. 13737 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13738 cast_or_null<CXXRecordDecl>(PrevDecl)); 13739 13740 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 13741 StdBadAlloc = cast<CXXRecordDecl>(New); 13742 } else 13743 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13744 cast_or_null<RecordDecl>(PrevDecl)); 13745 } 13746 13747 // C++11 [dcl.type]p3: 13748 // A type-specifier-seq shall not define a class or enumeration [...]. 13749 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 13750 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 13751 << Context.getTagDeclType(New); 13752 Invalid = true; 13753 } 13754 13755 // Maybe add qualifier info. 13756 if (SS.isNotEmpty()) { 13757 if (SS.isSet()) { 13758 // If this is either a declaration or a definition, check the 13759 // nested-name-specifier against the current context. We don't do this 13760 // for explicit specializations, because they have similar checking 13761 // (with more specific diagnostics) in the call to 13762 // CheckMemberSpecialization, below. 13763 if (!isMemberSpecialization && 13764 (TUK == TUK_Definition || TUK == TUK_Declaration) && 13765 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 13766 Invalid = true; 13767 13768 New->setQualifierInfo(SS.getWithLocInContext(Context)); 13769 if (TemplateParameterLists.size() > 0) { 13770 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 13771 } 13772 } 13773 else 13774 Invalid = true; 13775 } 13776 13777 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13778 // Add alignment attributes if necessary; these attributes are checked when 13779 // the ASTContext lays out the structure. 13780 // 13781 // It is important for implementing the correct semantics that this 13782 // happen here (in act on tag decl). The #pragma pack stack is 13783 // maintained as a result of parser callbacks which can occur at 13784 // many points during the parsing of a struct declaration (because 13785 // the #pragma tokens are effectively skipped over during the 13786 // parsing of the struct). 13787 if (TUK == TUK_Definition) { 13788 AddAlignmentAttributesForRecord(RD); 13789 AddMsStructLayoutForRecord(RD); 13790 } 13791 } 13792 13793 if (ModulePrivateLoc.isValid()) { 13794 if (isMemberSpecialization) 13795 Diag(New->getLocation(), diag::err_module_private_specialization) 13796 << 2 13797 << FixItHint::CreateRemoval(ModulePrivateLoc); 13798 // __module_private__ does not apply to local classes. However, we only 13799 // diagnose this as an error when the declaration specifiers are 13800 // freestanding. Here, we just ignore the __module_private__. 13801 else if (!SearchDC->isFunctionOrMethod()) 13802 New->setModulePrivate(); 13803 } 13804 13805 // If this is a specialization of a member class (of a class template), 13806 // check the specialization. 13807 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 13808 Invalid = true; 13809 13810 // If we're declaring or defining a tag in function prototype scope in C, 13811 // note that this type can only be used within the function and add it to 13812 // the list of decls to inject into the function definition scope. 13813 if ((Name || Kind == TTK_Enum) && 13814 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 13815 if (getLangOpts().CPlusPlus) { 13816 // C++ [dcl.fct]p6: 13817 // Types shall not be defined in return or parameter types. 13818 if (TUK == TUK_Definition && !IsTypeSpecifier) { 13819 Diag(Loc, diag::err_type_defined_in_param_type) 13820 << Name; 13821 Invalid = true; 13822 } 13823 } else if (!PrevDecl) { 13824 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 13825 } 13826 } 13827 13828 if (Invalid) 13829 New->setInvalidDecl(); 13830 13831 // Set the lexical context. If the tag has a C++ scope specifier, the 13832 // lexical context will be different from the semantic context. 13833 New->setLexicalDeclContext(CurContext); 13834 13835 // Mark this as a friend decl if applicable. 13836 // In Microsoft mode, a friend declaration also acts as a forward 13837 // declaration so we always pass true to setObjectOfFriendDecl to make 13838 // the tag name visible. 13839 if (TUK == TUK_Friend) 13840 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 13841 13842 // Set the access specifier. 13843 if (!Invalid && SearchDC->isRecord()) 13844 SetMemberAccessSpecifier(New, PrevDecl, AS); 13845 13846 if (TUK == TUK_Definition) 13847 New->startDefinition(); 13848 13849 if (Attr) 13850 ProcessDeclAttributeList(S, New, Attr); 13851 AddPragmaAttributes(S, New); 13852 13853 // If this has an identifier, add it to the scope stack. 13854 if (TUK == TUK_Friend) { 13855 // We might be replacing an existing declaration in the lookup tables; 13856 // if so, borrow its access specifier. 13857 if (PrevDecl) 13858 New->setAccess(PrevDecl->getAccess()); 13859 13860 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 13861 DC->makeDeclVisibleInContext(New); 13862 if (Name) // can be null along some error paths 13863 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13864 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 13865 } else if (Name) { 13866 S = getNonFieldDeclScope(S); 13867 PushOnScopeChains(New, S, !IsForwardReference); 13868 if (IsForwardReference) 13869 SearchDC->makeDeclVisibleInContext(New); 13870 } else { 13871 CurContext->addDecl(New); 13872 } 13873 13874 // If this is the C FILE type, notify the AST context. 13875 if (IdentifierInfo *II = New->getIdentifier()) 13876 if (!New->isInvalidDecl() && 13877 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 13878 II->isStr("FILE")) 13879 Context.setFILEDecl(New); 13880 13881 if (PrevDecl) 13882 mergeDeclAttributes(New, PrevDecl); 13883 13884 // If there's a #pragma GCC visibility in scope, set the visibility of this 13885 // record. 13886 AddPushedVisibilityAttribute(New); 13887 13888 if (isMemberSpecialization && !New->isInvalidDecl()) 13889 CompleteMemberSpecialization(New, Previous); 13890 13891 OwnedDecl = true; 13892 // In C++, don't return an invalid declaration. We can't recover well from 13893 // the cases where we make the type anonymous. 13894 if (Invalid && getLangOpts().CPlusPlus) { 13895 if (New->isBeingDefined()) 13896 if (auto RD = dyn_cast<RecordDecl>(New)) 13897 RD->completeDefinition(); 13898 return nullptr; 13899 } else { 13900 return New; 13901 } 13902 } 13903 13904 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 13905 AdjustDeclIfTemplate(TagD); 13906 TagDecl *Tag = cast<TagDecl>(TagD); 13907 13908 // Enter the tag context. 13909 PushDeclContext(S, Tag); 13910 13911 ActOnDocumentableDecl(TagD); 13912 13913 // If there's a #pragma GCC visibility in scope, set the visibility of this 13914 // record. 13915 AddPushedVisibilityAttribute(Tag); 13916 } 13917 13918 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 13919 assert(isa<ObjCContainerDecl>(IDecl) && 13920 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 13921 DeclContext *OCD = cast<DeclContext>(IDecl); 13922 assert(getContainingDC(OCD) == CurContext && 13923 "The next DeclContext should be lexically contained in the current one."); 13924 CurContext = OCD; 13925 return IDecl; 13926 } 13927 13928 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 13929 SourceLocation FinalLoc, 13930 bool IsFinalSpelledSealed, 13931 SourceLocation LBraceLoc) { 13932 AdjustDeclIfTemplate(TagD); 13933 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 13934 13935 FieldCollector->StartClass(); 13936 13937 if (!Record->getIdentifier()) 13938 return; 13939 13940 if (FinalLoc.isValid()) 13941 Record->addAttr(new (Context) 13942 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 13943 13944 // C++ [class]p2: 13945 // [...] The class-name is also inserted into the scope of the 13946 // class itself; this is known as the injected-class-name. For 13947 // purposes of access checking, the injected-class-name is treated 13948 // as if it were a public member name. 13949 CXXRecordDecl *InjectedClassName 13950 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 13951 Record->getLocStart(), Record->getLocation(), 13952 Record->getIdentifier(), 13953 /*PrevDecl=*/nullptr, 13954 /*DelayTypeCreation=*/true); 13955 Context.getTypeDeclType(InjectedClassName, Record); 13956 InjectedClassName->setImplicit(); 13957 InjectedClassName->setAccess(AS_public); 13958 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 13959 InjectedClassName->setDescribedClassTemplate(Template); 13960 PushOnScopeChains(InjectedClassName, S); 13961 assert(InjectedClassName->isInjectedClassName() && 13962 "Broken injected-class-name"); 13963 } 13964 13965 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 13966 SourceRange BraceRange) { 13967 AdjustDeclIfTemplate(TagD); 13968 TagDecl *Tag = cast<TagDecl>(TagD); 13969 Tag->setBraceRange(BraceRange); 13970 13971 // Make sure we "complete" the definition even it is invalid. 13972 if (Tag->isBeingDefined()) { 13973 assert(Tag->isInvalidDecl() && "We should already have completed it"); 13974 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13975 RD->completeDefinition(); 13976 } 13977 13978 if (isa<CXXRecordDecl>(Tag)) { 13979 FieldCollector->FinishClass(); 13980 } 13981 13982 // Exit this scope of this tag's definition. 13983 PopDeclContext(); 13984 13985 if (getCurLexicalContext()->isObjCContainer() && 13986 Tag->getDeclContext()->isFileContext()) 13987 Tag->setTopLevelDeclInObjCContainer(); 13988 13989 // Notify the consumer that we've defined a tag. 13990 if (!Tag->isInvalidDecl()) 13991 Consumer.HandleTagDeclDefinition(Tag); 13992 } 13993 13994 void Sema::ActOnObjCContainerFinishDefinition() { 13995 // Exit this scope of this interface definition. 13996 PopDeclContext(); 13997 } 13998 13999 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 14000 assert(DC == CurContext && "Mismatch of container contexts"); 14001 OriginalLexicalContext = DC; 14002 ActOnObjCContainerFinishDefinition(); 14003 } 14004 14005 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 14006 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 14007 OriginalLexicalContext = nullptr; 14008 } 14009 14010 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 14011 AdjustDeclIfTemplate(TagD); 14012 TagDecl *Tag = cast<TagDecl>(TagD); 14013 Tag->setInvalidDecl(); 14014 14015 // Make sure we "complete" the definition even it is invalid. 14016 if (Tag->isBeingDefined()) { 14017 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14018 RD->completeDefinition(); 14019 } 14020 14021 // We're undoing ActOnTagStartDefinition here, not 14022 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 14023 // the FieldCollector. 14024 14025 PopDeclContext(); 14026 } 14027 14028 // Note that FieldName may be null for anonymous bitfields. 14029 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 14030 IdentifierInfo *FieldName, 14031 QualType FieldTy, bool IsMsStruct, 14032 Expr *BitWidth, bool *ZeroWidth) { 14033 // Default to true; that shouldn't confuse checks for emptiness 14034 if (ZeroWidth) 14035 *ZeroWidth = true; 14036 14037 // C99 6.7.2.1p4 - verify the field type. 14038 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 14039 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 14040 // Handle incomplete types with specific error. 14041 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 14042 return ExprError(); 14043 if (FieldName) 14044 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 14045 << FieldName << FieldTy << BitWidth->getSourceRange(); 14046 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 14047 << FieldTy << BitWidth->getSourceRange(); 14048 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 14049 UPPC_BitFieldWidth)) 14050 return ExprError(); 14051 14052 // If the bit-width is type- or value-dependent, don't try to check 14053 // it now. 14054 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 14055 return BitWidth; 14056 14057 llvm::APSInt Value; 14058 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 14059 if (ICE.isInvalid()) 14060 return ICE; 14061 BitWidth = ICE.get(); 14062 14063 if (Value != 0 && ZeroWidth) 14064 *ZeroWidth = false; 14065 14066 // Zero-width bitfield is ok for anonymous field. 14067 if (Value == 0 && FieldName) 14068 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 14069 14070 if (Value.isSigned() && Value.isNegative()) { 14071 if (FieldName) 14072 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 14073 << FieldName << Value.toString(10); 14074 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 14075 << Value.toString(10); 14076 } 14077 14078 if (!FieldTy->isDependentType()) { 14079 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 14080 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 14081 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 14082 14083 // Over-wide bitfields are an error in C or when using the MSVC bitfield 14084 // ABI. 14085 bool CStdConstraintViolation = 14086 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 14087 bool MSBitfieldViolation = 14088 Value.ugt(TypeStorageSize) && 14089 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 14090 if (CStdConstraintViolation || MSBitfieldViolation) { 14091 unsigned DiagWidth = 14092 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 14093 if (FieldName) 14094 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 14095 << FieldName << (unsigned)Value.getZExtValue() 14096 << !CStdConstraintViolation << DiagWidth; 14097 14098 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 14099 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 14100 << DiagWidth; 14101 } 14102 14103 // Warn on types where the user might conceivably expect to get all 14104 // specified bits as value bits: that's all integral types other than 14105 // 'bool'. 14106 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 14107 if (FieldName) 14108 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 14109 << FieldName << (unsigned)Value.getZExtValue() 14110 << (unsigned)TypeWidth; 14111 else 14112 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 14113 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 14114 } 14115 } 14116 14117 return BitWidth; 14118 } 14119 14120 /// ActOnField - Each field of a C struct/union is passed into this in order 14121 /// to create a FieldDecl object for it. 14122 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 14123 Declarator &D, Expr *BitfieldWidth) { 14124 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 14125 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 14126 /*InitStyle=*/ICIS_NoInit, AS_public); 14127 return Res; 14128 } 14129 14130 /// HandleField - Analyze a field of a C struct or a C++ data member. 14131 /// 14132 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 14133 SourceLocation DeclStart, 14134 Declarator &D, Expr *BitWidth, 14135 InClassInitStyle InitStyle, 14136 AccessSpecifier AS) { 14137 if (D.isDecompositionDeclarator()) { 14138 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 14139 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 14140 << Decomp.getSourceRange(); 14141 return nullptr; 14142 } 14143 14144 IdentifierInfo *II = D.getIdentifier(); 14145 SourceLocation Loc = DeclStart; 14146 if (II) Loc = D.getIdentifierLoc(); 14147 14148 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14149 QualType T = TInfo->getType(); 14150 if (getLangOpts().CPlusPlus) { 14151 CheckExtraCXXDefaultArguments(D); 14152 14153 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14154 UPPC_DataMemberType)) { 14155 D.setInvalidType(); 14156 T = Context.IntTy; 14157 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14158 } 14159 } 14160 14161 // TR 18037 does not allow fields to be declared with address spaces. 14162 if (T.getQualifiers().hasAddressSpace()) { 14163 Diag(Loc, diag::err_field_with_address_space); 14164 D.setInvalidType(); 14165 } 14166 14167 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 14168 // used as structure or union field: image, sampler, event or block types. 14169 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 14170 T->isSamplerT() || T->isBlockPointerType())) { 14171 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 14172 D.setInvalidType(); 14173 } 14174 14175 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14176 14177 if (D.getDeclSpec().isInlineSpecified()) 14178 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14179 << getLangOpts().CPlusPlus1z; 14180 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14181 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14182 diag::err_invalid_thread) 14183 << DeclSpec::getSpecifierName(TSCS); 14184 14185 // Check to see if this name was declared as a member previously 14186 NamedDecl *PrevDecl = nullptr; 14187 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 14188 LookupName(Previous, S); 14189 switch (Previous.getResultKind()) { 14190 case LookupResult::Found: 14191 case LookupResult::FoundUnresolvedValue: 14192 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14193 break; 14194 14195 case LookupResult::FoundOverloaded: 14196 PrevDecl = Previous.getRepresentativeDecl(); 14197 break; 14198 14199 case LookupResult::NotFound: 14200 case LookupResult::NotFoundInCurrentInstantiation: 14201 case LookupResult::Ambiguous: 14202 break; 14203 } 14204 Previous.suppressDiagnostics(); 14205 14206 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14207 // Maybe we will complain about the shadowed template parameter. 14208 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14209 // Just pretend that we didn't see the previous declaration. 14210 PrevDecl = nullptr; 14211 } 14212 14213 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14214 PrevDecl = nullptr; 14215 14216 bool Mutable 14217 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 14218 SourceLocation TSSL = D.getLocStart(); 14219 FieldDecl *NewFD 14220 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 14221 TSSL, AS, PrevDecl, &D); 14222 14223 if (NewFD->isInvalidDecl()) 14224 Record->setInvalidDecl(); 14225 14226 if (D.getDeclSpec().isModulePrivateSpecified()) 14227 NewFD->setModulePrivate(); 14228 14229 if (NewFD->isInvalidDecl() && PrevDecl) { 14230 // Don't introduce NewFD into scope; there's already something 14231 // with the same name in the same scope. 14232 } else if (II) { 14233 PushOnScopeChains(NewFD, S); 14234 } else 14235 Record->addDecl(NewFD); 14236 14237 return NewFD; 14238 } 14239 14240 /// \brief Build a new FieldDecl and check its well-formedness. 14241 /// 14242 /// This routine builds a new FieldDecl given the fields name, type, 14243 /// record, etc. \p PrevDecl should refer to any previous declaration 14244 /// with the same name and in the same scope as the field to be 14245 /// created. 14246 /// 14247 /// \returns a new FieldDecl. 14248 /// 14249 /// \todo The Declarator argument is a hack. It will be removed once 14250 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 14251 TypeSourceInfo *TInfo, 14252 RecordDecl *Record, SourceLocation Loc, 14253 bool Mutable, Expr *BitWidth, 14254 InClassInitStyle InitStyle, 14255 SourceLocation TSSL, 14256 AccessSpecifier AS, NamedDecl *PrevDecl, 14257 Declarator *D) { 14258 IdentifierInfo *II = Name.getAsIdentifierInfo(); 14259 bool InvalidDecl = false; 14260 if (D) InvalidDecl = D->isInvalidType(); 14261 14262 // If we receive a broken type, recover by assuming 'int' and 14263 // marking this declaration as invalid. 14264 if (T.isNull()) { 14265 InvalidDecl = true; 14266 T = Context.IntTy; 14267 } 14268 14269 QualType EltTy = Context.getBaseElementType(T); 14270 if (!EltTy->isDependentType()) { 14271 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 14272 // Fields of incomplete type force their record to be invalid. 14273 Record->setInvalidDecl(); 14274 InvalidDecl = true; 14275 } else { 14276 NamedDecl *Def; 14277 EltTy->isIncompleteType(&Def); 14278 if (Def && Def->isInvalidDecl()) { 14279 Record->setInvalidDecl(); 14280 InvalidDecl = true; 14281 } 14282 } 14283 } 14284 14285 // OpenCL v1.2 s6.9.c: bitfields are not supported. 14286 if (BitWidth && getLangOpts().OpenCL) { 14287 Diag(Loc, diag::err_opencl_bitfields); 14288 InvalidDecl = true; 14289 } 14290 14291 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14292 // than a variably modified type. 14293 if (!InvalidDecl && T->isVariablyModifiedType()) { 14294 bool SizeIsNegative; 14295 llvm::APSInt Oversized; 14296 14297 TypeSourceInfo *FixedTInfo = 14298 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 14299 SizeIsNegative, 14300 Oversized); 14301 if (FixedTInfo) { 14302 Diag(Loc, diag::warn_illegal_constant_array_size); 14303 TInfo = FixedTInfo; 14304 T = FixedTInfo->getType(); 14305 } else { 14306 if (SizeIsNegative) 14307 Diag(Loc, diag::err_typecheck_negative_array_size); 14308 else if (Oversized.getBoolValue()) 14309 Diag(Loc, diag::err_array_too_large) 14310 << Oversized.toString(10); 14311 else 14312 Diag(Loc, diag::err_typecheck_field_variable_size); 14313 InvalidDecl = true; 14314 } 14315 } 14316 14317 // Fields can not have abstract class types 14318 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 14319 diag::err_abstract_type_in_decl, 14320 AbstractFieldType)) 14321 InvalidDecl = true; 14322 14323 bool ZeroWidth = false; 14324 if (InvalidDecl) 14325 BitWidth = nullptr; 14326 // If this is declared as a bit-field, check the bit-field. 14327 if (BitWidth) { 14328 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 14329 &ZeroWidth).get(); 14330 if (!BitWidth) { 14331 InvalidDecl = true; 14332 BitWidth = nullptr; 14333 ZeroWidth = false; 14334 } 14335 } 14336 14337 // Check that 'mutable' is consistent with the type of the declaration. 14338 if (!InvalidDecl && Mutable) { 14339 unsigned DiagID = 0; 14340 if (T->isReferenceType()) 14341 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 14342 : diag::err_mutable_reference; 14343 else if (T.isConstQualified()) 14344 DiagID = diag::err_mutable_const; 14345 14346 if (DiagID) { 14347 SourceLocation ErrLoc = Loc; 14348 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 14349 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 14350 Diag(ErrLoc, DiagID); 14351 if (DiagID != diag::ext_mutable_reference) { 14352 Mutable = false; 14353 InvalidDecl = true; 14354 } 14355 } 14356 } 14357 14358 // C++11 [class.union]p8 (DR1460): 14359 // At most one variant member of a union may have a 14360 // brace-or-equal-initializer. 14361 if (InitStyle != ICIS_NoInit) 14362 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 14363 14364 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 14365 BitWidth, Mutable, InitStyle); 14366 if (InvalidDecl) 14367 NewFD->setInvalidDecl(); 14368 14369 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 14370 Diag(Loc, diag::err_duplicate_member) << II; 14371 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14372 NewFD->setInvalidDecl(); 14373 } 14374 14375 if (!InvalidDecl && getLangOpts().CPlusPlus) { 14376 if (Record->isUnion()) { 14377 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14378 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14379 if (RDecl->getDefinition()) { 14380 // C++ [class.union]p1: An object of a class with a non-trivial 14381 // constructor, a non-trivial copy constructor, a non-trivial 14382 // destructor, or a non-trivial copy assignment operator 14383 // cannot be a member of a union, nor can an array of such 14384 // objects. 14385 if (CheckNontrivialField(NewFD)) 14386 NewFD->setInvalidDecl(); 14387 } 14388 } 14389 14390 // C++ [class.union]p1: If a union contains a member of reference type, 14391 // the program is ill-formed, except when compiling with MSVC extensions 14392 // enabled. 14393 if (EltTy->isReferenceType()) { 14394 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 14395 diag::ext_union_member_of_reference_type : 14396 diag::err_union_member_of_reference_type) 14397 << NewFD->getDeclName() << EltTy; 14398 if (!getLangOpts().MicrosoftExt) 14399 NewFD->setInvalidDecl(); 14400 } 14401 } 14402 } 14403 14404 // FIXME: We need to pass in the attributes given an AST 14405 // representation, not a parser representation. 14406 if (D) { 14407 // FIXME: The current scope is almost... but not entirely... correct here. 14408 ProcessDeclAttributes(getCurScope(), NewFD, *D); 14409 14410 if (NewFD->hasAttrs()) 14411 CheckAlignasUnderalignment(NewFD); 14412 } 14413 14414 // In auto-retain/release, infer strong retension for fields of 14415 // retainable type. 14416 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 14417 NewFD->setInvalidDecl(); 14418 14419 if (T.isObjCGCWeak()) 14420 Diag(Loc, diag::warn_attribute_weak_on_field); 14421 14422 NewFD->setAccess(AS); 14423 return NewFD; 14424 } 14425 14426 bool Sema::CheckNontrivialField(FieldDecl *FD) { 14427 assert(FD); 14428 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 14429 14430 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 14431 return false; 14432 14433 QualType EltTy = Context.getBaseElementType(FD->getType()); 14434 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14435 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14436 if (RDecl->getDefinition()) { 14437 // We check for copy constructors before constructors 14438 // because otherwise we'll never get complaints about 14439 // copy constructors. 14440 14441 CXXSpecialMember member = CXXInvalid; 14442 // We're required to check for any non-trivial constructors. Since the 14443 // implicit default constructor is suppressed if there are any 14444 // user-declared constructors, we just need to check that there is a 14445 // trivial default constructor and a trivial copy constructor. (We don't 14446 // worry about move constructors here, since this is a C++98 check.) 14447 if (RDecl->hasNonTrivialCopyConstructor()) 14448 member = CXXCopyConstructor; 14449 else if (!RDecl->hasTrivialDefaultConstructor()) 14450 member = CXXDefaultConstructor; 14451 else if (RDecl->hasNonTrivialCopyAssignment()) 14452 member = CXXCopyAssignment; 14453 else if (RDecl->hasNonTrivialDestructor()) 14454 member = CXXDestructor; 14455 14456 if (member != CXXInvalid) { 14457 if (!getLangOpts().CPlusPlus11 && 14458 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 14459 // Objective-C++ ARC: it is an error to have a non-trivial field of 14460 // a union. However, system headers in Objective-C programs 14461 // occasionally have Objective-C lifetime objects within unions, 14462 // and rather than cause the program to fail, we make those 14463 // members unavailable. 14464 SourceLocation Loc = FD->getLocation(); 14465 if (getSourceManager().isInSystemHeader(Loc)) { 14466 if (!FD->hasAttr<UnavailableAttr>()) 14467 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14468 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 14469 return false; 14470 } 14471 } 14472 14473 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 14474 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 14475 diag::err_illegal_union_or_anon_struct_member) 14476 << FD->getParent()->isUnion() << FD->getDeclName() << member; 14477 DiagnoseNontrivial(RDecl, member); 14478 return !getLangOpts().CPlusPlus11; 14479 } 14480 } 14481 } 14482 14483 return false; 14484 } 14485 14486 /// TranslateIvarVisibility - Translate visibility from a token ID to an 14487 /// AST enum value. 14488 static ObjCIvarDecl::AccessControl 14489 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 14490 switch (ivarVisibility) { 14491 default: llvm_unreachable("Unknown visitibility kind"); 14492 case tok::objc_private: return ObjCIvarDecl::Private; 14493 case tok::objc_public: return ObjCIvarDecl::Public; 14494 case tok::objc_protected: return ObjCIvarDecl::Protected; 14495 case tok::objc_package: return ObjCIvarDecl::Package; 14496 } 14497 } 14498 14499 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 14500 /// in order to create an IvarDecl object for it. 14501 Decl *Sema::ActOnIvar(Scope *S, 14502 SourceLocation DeclStart, 14503 Declarator &D, Expr *BitfieldWidth, 14504 tok::ObjCKeywordKind Visibility) { 14505 14506 IdentifierInfo *II = D.getIdentifier(); 14507 Expr *BitWidth = (Expr*)BitfieldWidth; 14508 SourceLocation Loc = DeclStart; 14509 if (II) Loc = D.getIdentifierLoc(); 14510 14511 // FIXME: Unnamed fields can be handled in various different ways, for 14512 // example, unnamed unions inject all members into the struct namespace! 14513 14514 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14515 QualType T = TInfo->getType(); 14516 14517 if (BitWidth) { 14518 // 6.7.2.1p3, 6.7.2.1p4 14519 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 14520 if (!BitWidth) 14521 D.setInvalidType(); 14522 } else { 14523 // Not a bitfield. 14524 14525 // validate II. 14526 14527 } 14528 if (T->isReferenceType()) { 14529 Diag(Loc, diag::err_ivar_reference_type); 14530 D.setInvalidType(); 14531 } 14532 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14533 // than a variably modified type. 14534 else if (T->isVariablyModifiedType()) { 14535 Diag(Loc, diag::err_typecheck_ivar_variable_size); 14536 D.setInvalidType(); 14537 } 14538 14539 // Get the visibility (access control) for this ivar. 14540 ObjCIvarDecl::AccessControl ac = 14541 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 14542 : ObjCIvarDecl::None; 14543 // Must set ivar's DeclContext to its enclosing interface. 14544 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 14545 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 14546 return nullptr; 14547 ObjCContainerDecl *EnclosingContext; 14548 if (ObjCImplementationDecl *IMPDecl = 14549 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14550 if (LangOpts.ObjCRuntime.isFragile()) { 14551 // Case of ivar declared in an implementation. Context is that of its class. 14552 EnclosingContext = IMPDecl->getClassInterface(); 14553 assert(EnclosingContext && "Implementation has no class interface!"); 14554 } 14555 else 14556 EnclosingContext = EnclosingDecl; 14557 } else { 14558 if (ObjCCategoryDecl *CDecl = 14559 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14560 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 14561 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 14562 return nullptr; 14563 } 14564 } 14565 EnclosingContext = EnclosingDecl; 14566 } 14567 14568 // Construct the decl. 14569 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 14570 DeclStart, Loc, II, T, 14571 TInfo, ac, (Expr *)BitfieldWidth); 14572 14573 if (II) { 14574 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 14575 ForRedeclaration); 14576 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 14577 && !isa<TagDecl>(PrevDecl)) { 14578 Diag(Loc, diag::err_duplicate_member) << II; 14579 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14580 NewID->setInvalidDecl(); 14581 } 14582 } 14583 14584 // Process attributes attached to the ivar. 14585 ProcessDeclAttributes(S, NewID, D); 14586 14587 if (D.isInvalidType()) 14588 NewID->setInvalidDecl(); 14589 14590 // In ARC, infer 'retaining' for ivars of retainable type. 14591 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 14592 NewID->setInvalidDecl(); 14593 14594 if (D.getDeclSpec().isModulePrivateSpecified()) 14595 NewID->setModulePrivate(); 14596 14597 if (II) { 14598 // FIXME: When interfaces are DeclContexts, we'll need to add 14599 // these to the interface. 14600 S->AddDecl(NewID); 14601 IdResolver.AddDecl(NewID); 14602 } 14603 14604 if (LangOpts.ObjCRuntime.isNonFragile() && 14605 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 14606 Diag(Loc, diag::warn_ivars_in_interface); 14607 14608 return NewID; 14609 } 14610 14611 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 14612 /// class and class extensions. For every class \@interface and class 14613 /// extension \@interface, if the last ivar is a bitfield of any type, 14614 /// then add an implicit `char :0` ivar to the end of that interface. 14615 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 14616 SmallVectorImpl<Decl *> &AllIvarDecls) { 14617 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 14618 return; 14619 14620 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 14621 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 14622 14623 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 14624 return; 14625 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 14626 if (!ID) { 14627 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 14628 if (!CD->IsClassExtension()) 14629 return; 14630 } 14631 // No need to add this to end of @implementation. 14632 else 14633 return; 14634 } 14635 // All conditions are met. Add a new bitfield to the tail end of ivars. 14636 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 14637 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 14638 14639 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 14640 DeclLoc, DeclLoc, nullptr, 14641 Context.CharTy, 14642 Context.getTrivialTypeSourceInfo(Context.CharTy, 14643 DeclLoc), 14644 ObjCIvarDecl::Private, BW, 14645 true); 14646 AllIvarDecls.push_back(Ivar); 14647 } 14648 14649 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 14650 ArrayRef<Decl *> Fields, SourceLocation LBrac, 14651 SourceLocation RBrac, AttributeList *Attr) { 14652 assert(EnclosingDecl && "missing record or interface decl"); 14653 14654 // If this is an Objective-C @implementation or category and we have 14655 // new fields here we should reset the layout of the interface since 14656 // it will now change. 14657 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 14658 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 14659 switch (DC->getKind()) { 14660 default: break; 14661 case Decl::ObjCCategory: 14662 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 14663 break; 14664 case Decl::ObjCImplementation: 14665 Context. 14666 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 14667 break; 14668 } 14669 } 14670 14671 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 14672 14673 // Start counting up the number of named members; make sure to include 14674 // members of anonymous structs and unions in the total. 14675 unsigned NumNamedMembers = 0; 14676 if (Record) { 14677 for (const auto *I : Record->decls()) { 14678 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 14679 if (IFD->getDeclName()) 14680 ++NumNamedMembers; 14681 } 14682 } 14683 14684 // Verify that all the fields are okay. 14685 SmallVector<FieldDecl*, 32> RecFields; 14686 14687 bool ObjCFieldLifetimeErrReported = false; 14688 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 14689 i != end; ++i) { 14690 FieldDecl *FD = cast<FieldDecl>(*i); 14691 14692 // Get the type for the field. 14693 const Type *FDTy = FD->getType().getTypePtr(); 14694 14695 if (!FD->isAnonymousStructOrUnion()) { 14696 // Remember all fields written by the user. 14697 RecFields.push_back(FD); 14698 } 14699 14700 // If the field is already invalid for some reason, don't emit more 14701 // diagnostics about it. 14702 if (FD->isInvalidDecl()) { 14703 EnclosingDecl->setInvalidDecl(); 14704 continue; 14705 } 14706 14707 // C99 6.7.2.1p2: 14708 // A structure or union shall not contain a member with 14709 // incomplete or function type (hence, a structure shall not 14710 // contain an instance of itself, but may contain a pointer to 14711 // an instance of itself), except that the last member of a 14712 // structure with more than one named member may have incomplete 14713 // array type; such a structure (and any union containing, 14714 // possibly recursively, a member that is such a structure) 14715 // shall not be a member of a structure or an element of an 14716 // array. 14717 if (FDTy->isFunctionType()) { 14718 // Field declared as a function. 14719 Diag(FD->getLocation(), diag::err_field_declared_as_function) 14720 << FD->getDeclName(); 14721 FD->setInvalidDecl(); 14722 EnclosingDecl->setInvalidDecl(); 14723 continue; 14724 } else if (FDTy->isIncompleteArrayType() && Record && 14725 ((i + 1 == Fields.end() && !Record->isUnion()) || 14726 ((getLangOpts().MicrosoftExt || 14727 getLangOpts().CPlusPlus) && 14728 (i + 1 == Fields.end() || Record->isUnion())))) { 14729 // Flexible array member. 14730 // Microsoft and g++ is more permissive regarding flexible array. 14731 // It will accept flexible array in union and also 14732 // as the sole element of a struct/class. 14733 unsigned DiagID = 0; 14734 if (Record->isUnion()) 14735 DiagID = getLangOpts().MicrosoftExt 14736 ? diag::ext_flexible_array_union_ms 14737 : getLangOpts().CPlusPlus 14738 ? diag::ext_flexible_array_union_gnu 14739 : diag::err_flexible_array_union; 14740 else if (NumNamedMembers < 1) 14741 DiagID = getLangOpts().MicrosoftExt 14742 ? diag::ext_flexible_array_empty_aggregate_ms 14743 : getLangOpts().CPlusPlus 14744 ? diag::ext_flexible_array_empty_aggregate_gnu 14745 : diag::err_flexible_array_empty_aggregate; 14746 14747 if (DiagID) 14748 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 14749 << Record->getTagKind(); 14750 // While the layout of types that contain virtual bases is not specified 14751 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 14752 // virtual bases after the derived members. This would make a flexible 14753 // array member declared at the end of an object not adjacent to the end 14754 // of the type. 14755 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 14756 if (RD->getNumVBases() != 0) 14757 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 14758 << FD->getDeclName() << Record->getTagKind(); 14759 if (!getLangOpts().C99) 14760 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 14761 << FD->getDeclName() << Record->getTagKind(); 14762 14763 // If the element type has a non-trivial destructor, we would not 14764 // implicitly destroy the elements, so disallow it for now. 14765 // 14766 // FIXME: GCC allows this. We should probably either implicitly delete 14767 // the destructor of the containing class, or just allow this. 14768 QualType BaseElem = Context.getBaseElementType(FD->getType()); 14769 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 14770 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 14771 << FD->getDeclName() << FD->getType(); 14772 FD->setInvalidDecl(); 14773 EnclosingDecl->setInvalidDecl(); 14774 continue; 14775 } 14776 // Okay, we have a legal flexible array member at the end of the struct. 14777 Record->setHasFlexibleArrayMember(true); 14778 } else if (!FDTy->isDependentType() && 14779 RequireCompleteType(FD->getLocation(), FD->getType(), 14780 diag::err_field_incomplete)) { 14781 // Incomplete type 14782 FD->setInvalidDecl(); 14783 EnclosingDecl->setInvalidDecl(); 14784 continue; 14785 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 14786 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 14787 // A type which contains a flexible array member is considered to be a 14788 // flexible array member. 14789 Record->setHasFlexibleArrayMember(true); 14790 if (!Record->isUnion()) { 14791 // If this is a struct/class and this is not the last element, reject 14792 // it. Note that GCC supports variable sized arrays in the middle of 14793 // structures. 14794 if (i + 1 != Fields.end()) 14795 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 14796 << FD->getDeclName() << FD->getType(); 14797 else { 14798 // We support flexible arrays at the end of structs in 14799 // other structs as an extension. 14800 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 14801 << FD->getDeclName(); 14802 } 14803 } 14804 } 14805 if (isa<ObjCContainerDecl>(EnclosingDecl) && 14806 RequireNonAbstractType(FD->getLocation(), FD->getType(), 14807 diag::err_abstract_type_in_decl, 14808 AbstractIvarType)) { 14809 // Ivars can not have abstract class types 14810 FD->setInvalidDecl(); 14811 } 14812 if (Record && FDTTy->getDecl()->hasObjectMember()) 14813 Record->setHasObjectMember(true); 14814 if (Record && FDTTy->getDecl()->hasVolatileMember()) 14815 Record->setHasVolatileMember(true); 14816 } else if (FDTy->isObjCObjectType()) { 14817 /// A field cannot be an Objective-c object 14818 Diag(FD->getLocation(), diag::err_statically_allocated_object) 14819 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 14820 QualType T = Context.getObjCObjectPointerType(FD->getType()); 14821 FD->setType(T); 14822 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 14823 Record && !ObjCFieldLifetimeErrReported && 14824 (!getLangOpts().CPlusPlus || Record->isUnion())) { 14825 // It's an error in ARC or Weak if a field has lifetime. 14826 // We don't want to report this in a system header, though, 14827 // so we just make the field unavailable. 14828 // FIXME: that's really not sufficient; we need to make the type 14829 // itself invalid to, say, initialize or copy. 14830 QualType T = FD->getType(); 14831 if (T.hasNonTrivialObjCLifetime()) { 14832 SourceLocation loc = FD->getLocation(); 14833 if (getSourceManager().isInSystemHeader(loc)) { 14834 if (!FD->hasAttr<UnavailableAttr>()) { 14835 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14836 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 14837 } 14838 } else { 14839 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 14840 << T->isBlockPointerType() << Record->getTagKind(); 14841 } 14842 ObjCFieldLifetimeErrReported = true; 14843 } 14844 } else if (getLangOpts().ObjC1 && 14845 getLangOpts().getGC() != LangOptions::NonGC && 14846 Record && !Record->hasObjectMember()) { 14847 if (FD->getType()->isObjCObjectPointerType() || 14848 FD->getType().isObjCGCStrong()) 14849 Record->setHasObjectMember(true); 14850 else if (Context.getAsArrayType(FD->getType())) { 14851 QualType BaseType = Context.getBaseElementType(FD->getType()); 14852 if (BaseType->isRecordType() && 14853 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 14854 Record->setHasObjectMember(true); 14855 else if (BaseType->isObjCObjectPointerType() || 14856 BaseType.isObjCGCStrong()) 14857 Record->setHasObjectMember(true); 14858 } 14859 } 14860 if (Record && FD->getType().isVolatileQualified()) 14861 Record->setHasVolatileMember(true); 14862 // Keep track of the number of named members. 14863 if (FD->getIdentifier()) 14864 ++NumNamedMembers; 14865 } 14866 14867 // Okay, we successfully defined 'Record'. 14868 if (Record) { 14869 bool Completed = false; 14870 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14871 if (!CXXRecord->isInvalidDecl()) { 14872 // Set access bits correctly on the directly-declared conversions. 14873 for (CXXRecordDecl::conversion_iterator 14874 I = CXXRecord->conversion_begin(), 14875 E = CXXRecord->conversion_end(); I != E; ++I) 14876 I.setAccess((*I)->getAccess()); 14877 } 14878 14879 if (!CXXRecord->isDependentType()) { 14880 if (CXXRecord->hasUserDeclaredDestructor()) { 14881 // Adjust user-defined destructor exception spec. 14882 if (getLangOpts().CPlusPlus11) 14883 AdjustDestructorExceptionSpec(CXXRecord, 14884 CXXRecord->getDestructor()); 14885 } 14886 14887 if (!CXXRecord->isInvalidDecl()) { 14888 // Add any implicitly-declared members to this class. 14889 AddImplicitlyDeclaredMembersToClass(CXXRecord); 14890 14891 // If we have virtual base classes, we may end up finding multiple 14892 // final overriders for a given virtual function. Check for this 14893 // problem now. 14894 if (CXXRecord->getNumVBases()) { 14895 CXXFinalOverriderMap FinalOverriders; 14896 CXXRecord->getFinalOverriders(FinalOverriders); 14897 14898 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 14899 MEnd = FinalOverriders.end(); 14900 M != MEnd; ++M) { 14901 for (OverridingMethods::iterator SO = M->second.begin(), 14902 SOEnd = M->second.end(); 14903 SO != SOEnd; ++SO) { 14904 assert(SO->second.size() > 0 && 14905 "Virtual function without overridding functions?"); 14906 if (SO->second.size() == 1) 14907 continue; 14908 14909 // C++ [class.virtual]p2: 14910 // In a derived class, if a virtual member function of a base 14911 // class subobject has more than one final overrider the 14912 // program is ill-formed. 14913 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 14914 << (const NamedDecl *)M->first << Record; 14915 Diag(M->first->getLocation(), 14916 diag::note_overridden_virtual_function); 14917 for (OverridingMethods::overriding_iterator 14918 OM = SO->second.begin(), 14919 OMEnd = SO->second.end(); 14920 OM != OMEnd; ++OM) 14921 Diag(OM->Method->getLocation(), diag::note_final_overrider) 14922 << (const NamedDecl *)M->first << OM->Method->getParent(); 14923 14924 Record->setInvalidDecl(); 14925 } 14926 } 14927 CXXRecord->completeDefinition(&FinalOverriders); 14928 Completed = true; 14929 } 14930 } 14931 } 14932 } 14933 14934 if (!Completed) 14935 Record->completeDefinition(); 14936 14937 // We may have deferred checking for a deleted destructor. Check now. 14938 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14939 auto *Dtor = CXXRecord->getDestructor(); 14940 if (Dtor && Dtor->isImplicit() && 14941 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) 14942 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 14943 } 14944 14945 if (Record->hasAttrs()) { 14946 CheckAlignasUnderalignment(Record); 14947 14948 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 14949 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 14950 IA->getRange(), IA->getBestCase(), 14951 IA->getSemanticSpelling()); 14952 } 14953 14954 // Check if the structure/union declaration is a type that can have zero 14955 // size in C. For C this is a language extension, for C++ it may cause 14956 // compatibility problems. 14957 bool CheckForZeroSize; 14958 if (!getLangOpts().CPlusPlus) { 14959 CheckForZeroSize = true; 14960 } else { 14961 // For C++ filter out types that cannot be referenced in C code. 14962 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 14963 CheckForZeroSize = 14964 CXXRecord->getLexicalDeclContext()->isExternCContext() && 14965 !CXXRecord->isDependentType() && 14966 CXXRecord->isCLike(); 14967 } 14968 if (CheckForZeroSize) { 14969 bool ZeroSize = true; 14970 bool IsEmpty = true; 14971 unsigned NonBitFields = 0; 14972 for (RecordDecl::field_iterator I = Record->field_begin(), 14973 E = Record->field_end(); 14974 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 14975 IsEmpty = false; 14976 if (I->isUnnamedBitfield()) { 14977 if (I->getBitWidthValue(Context) > 0) 14978 ZeroSize = false; 14979 } else { 14980 ++NonBitFields; 14981 QualType FieldType = I->getType(); 14982 if (FieldType->isIncompleteType() || 14983 !Context.getTypeSizeInChars(FieldType).isZero()) 14984 ZeroSize = false; 14985 } 14986 } 14987 14988 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 14989 // allowed in C++, but warn if its declaration is inside 14990 // extern "C" block. 14991 if (ZeroSize) { 14992 Diag(RecLoc, getLangOpts().CPlusPlus ? 14993 diag::warn_zero_size_struct_union_in_extern_c : 14994 diag::warn_zero_size_struct_union_compat) 14995 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 14996 } 14997 14998 // Structs without named members are extension in C (C99 6.7.2.1p7), 14999 // but are accepted by GCC. 15000 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 15001 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 15002 diag::ext_no_named_members_in_struct_union) 15003 << Record->isUnion(); 15004 } 15005 } 15006 } else { 15007 ObjCIvarDecl **ClsFields = 15008 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 15009 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 15010 ID->setEndOfDefinitionLoc(RBrac); 15011 // Add ivar's to class's DeclContext. 15012 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15013 ClsFields[i]->setLexicalDeclContext(ID); 15014 ID->addDecl(ClsFields[i]); 15015 } 15016 // Must enforce the rule that ivars in the base classes may not be 15017 // duplicates. 15018 if (ID->getSuperClass()) 15019 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 15020 } else if (ObjCImplementationDecl *IMPDecl = 15021 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15022 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 15023 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 15024 // Ivar declared in @implementation never belongs to the implementation. 15025 // Only it is in implementation's lexical context. 15026 ClsFields[I]->setLexicalDeclContext(IMPDecl); 15027 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 15028 IMPDecl->setIvarLBraceLoc(LBrac); 15029 IMPDecl->setIvarRBraceLoc(RBrac); 15030 } else if (ObjCCategoryDecl *CDecl = 15031 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15032 // case of ivars in class extension; all other cases have been 15033 // reported as errors elsewhere. 15034 // FIXME. Class extension does not have a LocEnd field. 15035 // CDecl->setLocEnd(RBrac); 15036 // Add ivar's to class extension's DeclContext. 15037 // Diagnose redeclaration of private ivars. 15038 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 15039 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15040 if (IDecl) { 15041 if (const ObjCIvarDecl *ClsIvar = 15042 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 15043 Diag(ClsFields[i]->getLocation(), 15044 diag::err_duplicate_ivar_declaration); 15045 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 15046 continue; 15047 } 15048 for (const auto *Ext : IDecl->known_extensions()) { 15049 if (const ObjCIvarDecl *ClsExtIvar 15050 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 15051 Diag(ClsFields[i]->getLocation(), 15052 diag::err_duplicate_ivar_declaration); 15053 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 15054 continue; 15055 } 15056 } 15057 } 15058 ClsFields[i]->setLexicalDeclContext(CDecl); 15059 CDecl->addDecl(ClsFields[i]); 15060 } 15061 CDecl->setIvarLBraceLoc(LBrac); 15062 CDecl->setIvarRBraceLoc(RBrac); 15063 } 15064 } 15065 15066 if (Attr) 15067 ProcessDeclAttributeList(S, Record, Attr); 15068 } 15069 15070 /// \brief Determine whether the given integral value is representable within 15071 /// the given type T. 15072 static bool isRepresentableIntegerValue(ASTContext &Context, 15073 llvm::APSInt &Value, 15074 QualType T) { 15075 assert(T->isIntegralType(Context) && "Integral type required!"); 15076 unsigned BitWidth = Context.getIntWidth(T); 15077 15078 if (Value.isUnsigned() || Value.isNonNegative()) { 15079 if (T->isSignedIntegerOrEnumerationType()) 15080 --BitWidth; 15081 return Value.getActiveBits() <= BitWidth; 15082 } 15083 return Value.getMinSignedBits() <= BitWidth; 15084 } 15085 15086 // \brief Given an integral type, return the next larger integral type 15087 // (or a NULL type of no such type exists). 15088 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 15089 // FIXME: Int128/UInt128 support, which also needs to be introduced into 15090 // enum checking below. 15091 assert(T->isIntegralType(Context) && "Integral type required!"); 15092 const unsigned NumTypes = 4; 15093 QualType SignedIntegralTypes[NumTypes] = { 15094 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 15095 }; 15096 QualType UnsignedIntegralTypes[NumTypes] = { 15097 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 15098 Context.UnsignedLongLongTy 15099 }; 15100 15101 unsigned BitWidth = Context.getTypeSize(T); 15102 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 15103 : UnsignedIntegralTypes; 15104 for (unsigned I = 0; I != NumTypes; ++I) 15105 if (Context.getTypeSize(Types[I]) > BitWidth) 15106 return Types[I]; 15107 15108 return QualType(); 15109 } 15110 15111 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 15112 EnumConstantDecl *LastEnumConst, 15113 SourceLocation IdLoc, 15114 IdentifierInfo *Id, 15115 Expr *Val) { 15116 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15117 llvm::APSInt EnumVal(IntWidth); 15118 QualType EltTy; 15119 15120 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 15121 Val = nullptr; 15122 15123 if (Val) 15124 Val = DefaultLvalueConversion(Val).get(); 15125 15126 if (Val) { 15127 if (Enum->isDependentType() || Val->isTypeDependent()) 15128 EltTy = Context.DependentTy; 15129 else { 15130 SourceLocation ExpLoc; 15131 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 15132 !getLangOpts().MSVCCompat) { 15133 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 15134 // constant-expression in the enumerator-definition shall be a converted 15135 // constant expression of the underlying type. 15136 EltTy = Enum->getIntegerType(); 15137 ExprResult Converted = 15138 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 15139 CCEK_Enumerator); 15140 if (Converted.isInvalid()) 15141 Val = nullptr; 15142 else 15143 Val = Converted.get(); 15144 } else if (!Val->isValueDependent() && 15145 !(Val = VerifyIntegerConstantExpression(Val, 15146 &EnumVal).get())) { 15147 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 15148 } else { 15149 if (Enum->isFixed()) { 15150 EltTy = Enum->getIntegerType(); 15151 15152 // In Obj-C and Microsoft mode, require the enumeration value to be 15153 // representable in the underlying type of the enumeration. In C++11, 15154 // we perform a non-narrowing conversion as part of converted constant 15155 // expression checking. 15156 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15157 if (getLangOpts().MSVCCompat) { 15158 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 15159 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 15160 } else 15161 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 15162 } else 15163 Val = ImpCastExprToType(Val, EltTy, 15164 EltTy->isBooleanType() ? 15165 CK_IntegralToBoolean : CK_IntegralCast) 15166 .get(); 15167 } else if (getLangOpts().CPlusPlus) { 15168 // C++11 [dcl.enum]p5: 15169 // If the underlying type is not fixed, the type of each enumerator 15170 // is the type of its initializing value: 15171 // - If an initializer is specified for an enumerator, the 15172 // initializing value has the same type as the expression. 15173 EltTy = Val->getType(); 15174 } else { 15175 // C99 6.7.2.2p2: 15176 // The expression that defines the value of an enumeration constant 15177 // shall be an integer constant expression that has a value 15178 // representable as an int. 15179 15180 // Complain if the value is not representable in an int. 15181 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 15182 Diag(IdLoc, diag::ext_enum_value_not_int) 15183 << EnumVal.toString(10) << Val->getSourceRange() 15184 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 15185 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 15186 // Force the type of the expression to 'int'. 15187 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 15188 } 15189 EltTy = Val->getType(); 15190 } 15191 } 15192 } 15193 } 15194 15195 if (!Val) { 15196 if (Enum->isDependentType()) 15197 EltTy = Context.DependentTy; 15198 else if (!LastEnumConst) { 15199 // C++0x [dcl.enum]p5: 15200 // If the underlying type is not fixed, the type of each enumerator 15201 // is the type of its initializing value: 15202 // - If no initializer is specified for the first enumerator, the 15203 // initializing value has an unspecified integral type. 15204 // 15205 // GCC uses 'int' for its unspecified integral type, as does 15206 // C99 6.7.2.2p3. 15207 if (Enum->isFixed()) { 15208 EltTy = Enum->getIntegerType(); 15209 } 15210 else { 15211 EltTy = Context.IntTy; 15212 } 15213 } else { 15214 // Assign the last value + 1. 15215 EnumVal = LastEnumConst->getInitVal(); 15216 ++EnumVal; 15217 EltTy = LastEnumConst->getType(); 15218 15219 // Check for overflow on increment. 15220 if (EnumVal < LastEnumConst->getInitVal()) { 15221 // C++0x [dcl.enum]p5: 15222 // If the underlying type is not fixed, the type of each enumerator 15223 // is the type of its initializing value: 15224 // 15225 // - Otherwise the type of the initializing value is the same as 15226 // the type of the initializing value of the preceding enumerator 15227 // unless the incremented value is not representable in that type, 15228 // in which case the type is an unspecified integral type 15229 // sufficient to contain the incremented value. If no such type 15230 // exists, the program is ill-formed. 15231 QualType T = getNextLargerIntegralType(Context, EltTy); 15232 if (T.isNull() || Enum->isFixed()) { 15233 // There is no integral type larger enough to represent this 15234 // value. Complain, then allow the value to wrap around. 15235 EnumVal = LastEnumConst->getInitVal(); 15236 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 15237 ++EnumVal; 15238 if (Enum->isFixed()) 15239 // When the underlying type is fixed, this is ill-formed. 15240 Diag(IdLoc, diag::err_enumerator_wrapped) 15241 << EnumVal.toString(10) 15242 << EltTy; 15243 else 15244 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 15245 << EnumVal.toString(10); 15246 } else { 15247 EltTy = T; 15248 } 15249 15250 // Retrieve the last enumerator's value, extent that type to the 15251 // type that is supposed to be large enough to represent the incremented 15252 // value, then increment. 15253 EnumVal = LastEnumConst->getInitVal(); 15254 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15255 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 15256 ++EnumVal; 15257 15258 // If we're not in C++, diagnose the overflow of enumerator values, 15259 // which in C99 means that the enumerator value is not representable in 15260 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 15261 // permits enumerator values that are representable in some larger 15262 // integral type. 15263 if (!getLangOpts().CPlusPlus && !T.isNull()) 15264 Diag(IdLoc, diag::warn_enum_value_overflow); 15265 } else if (!getLangOpts().CPlusPlus && 15266 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15267 // Enforce C99 6.7.2.2p2 even when we compute the next value. 15268 Diag(IdLoc, diag::ext_enum_value_not_int) 15269 << EnumVal.toString(10) << 1; 15270 } 15271 } 15272 } 15273 15274 if (!EltTy->isDependentType()) { 15275 // Make the enumerator value match the signedness and size of the 15276 // enumerator's type. 15277 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 15278 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15279 } 15280 15281 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 15282 Val, EnumVal); 15283 } 15284 15285 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 15286 SourceLocation IILoc) { 15287 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 15288 !getLangOpts().CPlusPlus) 15289 return SkipBodyInfo(); 15290 15291 // We have an anonymous enum definition. Look up the first enumerator to 15292 // determine if we should merge the definition with an existing one and 15293 // skip the body. 15294 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 15295 ForRedeclaration); 15296 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 15297 if (!PrevECD) 15298 return SkipBodyInfo(); 15299 15300 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 15301 NamedDecl *Hidden; 15302 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 15303 SkipBodyInfo Skip; 15304 Skip.Previous = Hidden; 15305 return Skip; 15306 } 15307 15308 return SkipBodyInfo(); 15309 } 15310 15311 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 15312 SourceLocation IdLoc, IdentifierInfo *Id, 15313 AttributeList *Attr, 15314 SourceLocation EqualLoc, Expr *Val) { 15315 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 15316 EnumConstantDecl *LastEnumConst = 15317 cast_or_null<EnumConstantDecl>(lastEnumConst); 15318 15319 // The scope passed in may not be a decl scope. Zip up the scope tree until 15320 // we find one that is. 15321 S = getNonFieldDeclScope(S); 15322 15323 // Verify that there isn't already something declared with this name in this 15324 // scope. 15325 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 15326 ForRedeclaration); 15327 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15328 // Maybe we will complain about the shadowed template parameter. 15329 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 15330 // Just pretend that we didn't see the previous declaration. 15331 PrevDecl = nullptr; 15332 } 15333 15334 // C++ [class.mem]p15: 15335 // If T is the name of a class, then each of the following shall have a name 15336 // different from T: 15337 // - every enumerator of every member of class T that is an unscoped 15338 // enumerated type 15339 if (!TheEnumDecl->isScoped()) 15340 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 15341 DeclarationNameInfo(Id, IdLoc)); 15342 15343 EnumConstantDecl *New = 15344 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 15345 if (!New) 15346 return nullptr; 15347 15348 if (PrevDecl) { 15349 // When in C++, we may get a TagDecl with the same name; in this case the 15350 // enum constant will 'hide' the tag. 15351 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 15352 "Received TagDecl when not in C++!"); 15353 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) && 15354 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) { 15355 if (isa<EnumConstantDecl>(PrevDecl)) 15356 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 15357 else 15358 Diag(IdLoc, diag::err_redefinition) << Id; 15359 notePreviousDefinition(PrevDecl->getLocation(), IdLoc); 15360 return nullptr; 15361 } 15362 } 15363 15364 // Process attributes. 15365 if (Attr) ProcessDeclAttributeList(S, New, Attr); 15366 AddPragmaAttributes(S, New); 15367 15368 // Register this decl in the current scope stack. 15369 New->setAccess(TheEnumDecl->getAccess()); 15370 PushOnScopeChains(New, S); 15371 15372 ActOnDocumentableDecl(New); 15373 15374 return New; 15375 } 15376 15377 // Returns true when the enum initial expression does not trigger the 15378 // duplicate enum warning. A few common cases are exempted as follows: 15379 // Element2 = Element1 15380 // Element2 = Element1 + 1 15381 // Element2 = Element1 - 1 15382 // Where Element2 and Element1 are from the same enum. 15383 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 15384 Expr *InitExpr = ECD->getInitExpr(); 15385 if (!InitExpr) 15386 return true; 15387 InitExpr = InitExpr->IgnoreImpCasts(); 15388 15389 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 15390 if (!BO->isAdditiveOp()) 15391 return true; 15392 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 15393 if (!IL) 15394 return true; 15395 if (IL->getValue() != 1) 15396 return true; 15397 15398 InitExpr = BO->getLHS(); 15399 } 15400 15401 // This checks if the elements are from the same enum. 15402 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 15403 if (!DRE) 15404 return true; 15405 15406 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 15407 if (!EnumConstant) 15408 return true; 15409 15410 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 15411 Enum) 15412 return true; 15413 15414 return false; 15415 } 15416 15417 namespace { 15418 struct DupKey { 15419 int64_t val; 15420 bool isTombstoneOrEmptyKey; 15421 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 15422 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 15423 }; 15424 15425 static DupKey GetDupKey(const llvm::APSInt& Val) { 15426 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 15427 false); 15428 } 15429 15430 struct DenseMapInfoDupKey { 15431 static DupKey getEmptyKey() { return DupKey(0, true); } 15432 static DupKey getTombstoneKey() { return DupKey(1, true); } 15433 static unsigned getHashValue(const DupKey Key) { 15434 return (unsigned)(Key.val * 37); 15435 } 15436 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 15437 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 15438 LHS.val == RHS.val; 15439 } 15440 }; 15441 } // end anonymous namespace 15442 15443 // Emits a warning when an element is implicitly set a value that 15444 // a previous element has already been set to. 15445 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 15446 EnumDecl *Enum, 15447 QualType EnumType) { 15448 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 15449 return; 15450 // Avoid anonymous enums 15451 if (!Enum->getIdentifier()) 15452 return; 15453 15454 // Only check for small enums. 15455 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 15456 return; 15457 15458 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 15459 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 15460 15461 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 15462 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 15463 ValueToVectorMap; 15464 15465 DuplicatesVector DupVector; 15466 ValueToVectorMap EnumMap; 15467 15468 // Populate the EnumMap with all values represented by enum constants without 15469 // an initialier. 15470 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15471 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 15472 15473 // Null EnumConstantDecl means a previous diagnostic has been emitted for 15474 // this constant. Skip this enum since it may be ill-formed. 15475 if (!ECD) { 15476 return; 15477 } 15478 15479 if (ECD->getInitExpr()) 15480 continue; 15481 15482 DupKey Key = GetDupKey(ECD->getInitVal()); 15483 DeclOrVector &Entry = EnumMap[Key]; 15484 15485 // First time encountering this value. 15486 if (Entry.isNull()) 15487 Entry = ECD; 15488 } 15489 15490 // Create vectors for any values that has duplicates. 15491 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15492 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 15493 if (!ValidDuplicateEnum(ECD, Enum)) 15494 continue; 15495 15496 DupKey Key = GetDupKey(ECD->getInitVal()); 15497 15498 DeclOrVector& Entry = EnumMap[Key]; 15499 if (Entry.isNull()) 15500 continue; 15501 15502 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 15503 // Ensure constants are different. 15504 if (D == ECD) 15505 continue; 15506 15507 // Create new vector and push values onto it. 15508 ECDVector *Vec = new ECDVector(); 15509 Vec->push_back(D); 15510 Vec->push_back(ECD); 15511 15512 // Update entry to point to the duplicates vector. 15513 Entry = Vec; 15514 15515 // Store the vector somewhere we can consult later for quick emission of 15516 // diagnostics. 15517 DupVector.push_back(Vec); 15518 continue; 15519 } 15520 15521 ECDVector *Vec = Entry.get<ECDVector*>(); 15522 // Make sure constants are not added more than once. 15523 if (*Vec->begin() == ECD) 15524 continue; 15525 15526 Vec->push_back(ECD); 15527 } 15528 15529 // Emit diagnostics. 15530 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 15531 DupVectorEnd = DupVector.end(); 15532 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 15533 ECDVector *Vec = *DupVectorIter; 15534 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 15535 15536 // Emit warning for one enum constant. 15537 ECDVector::iterator I = Vec->begin(); 15538 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 15539 << (*I)->getName() << (*I)->getInitVal().toString(10) 15540 << (*I)->getSourceRange(); 15541 ++I; 15542 15543 // Emit one note for each of the remaining enum constants with 15544 // the same value. 15545 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 15546 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 15547 << (*I)->getName() << (*I)->getInitVal().toString(10) 15548 << (*I)->getSourceRange(); 15549 delete Vec; 15550 } 15551 } 15552 15553 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 15554 bool AllowMask) const { 15555 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 15556 assert(ED->isCompleteDefinition() && "expected enum definition"); 15557 15558 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 15559 llvm::APInt &FlagBits = R.first->second; 15560 15561 if (R.second) { 15562 for (auto *E : ED->enumerators()) { 15563 const auto &EVal = E->getInitVal(); 15564 // Only single-bit enumerators introduce new flag values. 15565 if (EVal.isPowerOf2()) 15566 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 15567 } 15568 } 15569 15570 // A value is in a flag enum if either its bits are a subset of the enum's 15571 // flag bits (the first condition) or we are allowing masks and the same is 15572 // true of its complement (the second condition). When masks are allowed, we 15573 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 15574 // 15575 // While it's true that any value could be used as a mask, the assumption is 15576 // that a mask will have all of the insignificant bits set. Anything else is 15577 // likely a logic error. 15578 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 15579 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 15580 } 15581 15582 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 15583 Decl *EnumDeclX, 15584 ArrayRef<Decl *> Elements, 15585 Scope *S, AttributeList *Attr) { 15586 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 15587 QualType EnumType = Context.getTypeDeclType(Enum); 15588 15589 if (Attr) 15590 ProcessDeclAttributeList(S, Enum, Attr); 15591 15592 if (Enum->isDependentType()) { 15593 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15594 EnumConstantDecl *ECD = 15595 cast_or_null<EnumConstantDecl>(Elements[i]); 15596 if (!ECD) continue; 15597 15598 ECD->setType(EnumType); 15599 } 15600 15601 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 15602 return; 15603 } 15604 15605 // TODO: If the result value doesn't fit in an int, it must be a long or long 15606 // long value. ISO C does not support this, but GCC does as an extension, 15607 // emit a warning. 15608 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15609 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 15610 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 15611 15612 // Verify that all the values are okay, compute the size of the values, and 15613 // reverse the list. 15614 unsigned NumNegativeBits = 0; 15615 unsigned NumPositiveBits = 0; 15616 15617 // Keep track of whether all elements have type int. 15618 bool AllElementsInt = true; 15619 15620 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15621 EnumConstantDecl *ECD = 15622 cast_or_null<EnumConstantDecl>(Elements[i]); 15623 if (!ECD) continue; // Already issued a diagnostic. 15624 15625 const llvm::APSInt &InitVal = ECD->getInitVal(); 15626 15627 // Keep track of the size of positive and negative values. 15628 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 15629 NumPositiveBits = std::max(NumPositiveBits, 15630 (unsigned)InitVal.getActiveBits()); 15631 else 15632 NumNegativeBits = std::max(NumNegativeBits, 15633 (unsigned)InitVal.getMinSignedBits()); 15634 15635 // Keep track of whether every enum element has type int (very commmon). 15636 if (AllElementsInt) 15637 AllElementsInt = ECD->getType() == Context.IntTy; 15638 } 15639 15640 // Figure out the type that should be used for this enum. 15641 QualType BestType; 15642 unsigned BestWidth; 15643 15644 // C++0x N3000 [conv.prom]p3: 15645 // An rvalue of an unscoped enumeration type whose underlying 15646 // type is not fixed can be converted to an rvalue of the first 15647 // of the following types that can represent all the values of 15648 // the enumeration: int, unsigned int, long int, unsigned long 15649 // int, long long int, or unsigned long long int. 15650 // C99 6.4.4.3p2: 15651 // An identifier declared as an enumeration constant has type int. 15652 // The C99 rule is modified by a gcc extension 15653 QualType BestPromotionType; 15654 15655 bool Packed = Enum->hasAttr<PackedAttr>(); 15656 // -fshort-enums is the equivalent to specifying the packed attribute on all 15657 // enum definitions. 15658 if (LangOpts.ShortEnums) 15659 Packed = true; 15660 15661 if (Enum->isFixed()) { 15662 BestType = Enum->getIntegerType(); 15663 if (BestType->isPromotableIntegerType()) 15664 BestPromotionType = Context.getPromotedIntegerType(BestType); 15665 else 15666 BestPromotionType = BestType; 15667 15668 BestWidth = Context.getIntWidth(BestType); 15669 } 15670 else if (NumNegativeBits) { 15671 // If there is a negative value, figure out the smallest integer type (of 15672 // int/long/longlong) that fits. 15673 // If it's packed, check also if it fits a char or a short. 15674 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 15675 BestType = Context.SignedCharTy; 15676 BestWidth = CharWidth; 15677 } else if (Packed && NumNegativeBits <= ShortWidth && 15678 NumPositiveBits < ShortWidth) { 15679 BestType = Context.ShortTy; 15680 BestWidth = ShortWidth; 15681 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 15682 BestType = Context.IntTy; 15683 BestWidth = IntWidth; 15684 } else { 15685 BestWidth = Context.getTargetInfo().getLongWidth(); 15686 15687 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 15688 BestType = Context.LongTy; 15689 } else { 15690 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15691 15692 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 15693 Diag(Enum->getLocation(), diag::ext_enum_too_large); 15694 BestType = Context.LongLongTy; 15695 } 15696 } 15697 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 15698 } else { 15699 // If there is no negative value, figure out the smallest type that fits 15700 // all of the enumerator values. 15701 // If it's packed, check also if it fits a char or a short. 15702 if (Packed && NumPositiveBits <= CharWidth) { 15703 BestType = Context.UnsignedCharTy; 15704 BestPromotionType = Context.IntTy; 15705 BestWidth = CharWidth; 15706 } else if (Packed && NumPositiveBits <= ShortWidth) { 15707 BestType = Context.UnsignedShortTy; 15708 BestPromotionType = Context.IntTy; 15709 BestWidth = ShortWidth; 15710 } else if (NumPositiveBits <= IntWidth) { 15711 BestType = Context.UnsignedIntTy; 15712 BestWidth = IntWidth; 15713 BestPromotionType 15714 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15715 ? Context.UnsignedIntTy : Context.IntTy; 15716 } else if (NumPositiveBits <= 15717 (BestWidth = Context.getTargetInfo().getLongWidth())) { 15718 BestType = Context.UnsignedLongTy; 15719 BestPromotionType 15720 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15721 ? Context.UnsignedLongTy : Context.LongTy; 15722 } else { 15723 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15724 assert(NumPositiveBits <= BestWidth && 15725 "How could an initializer get larger than ULL?"); 15726 BestType = Context.UnsignedLongLongTy; 15727 BestPromotionType 15728 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15729 ? Context.UnsignedLongLongTy : Context.LongLongTy; 15730 } 15731 } 15732 15733 // Loop over all of the enumerator constants, changing their types to match 15734 // the type of the enum if needed. 15735 for (auto *D : Elements) { 15736 auto *ECD = cast_or_null<EnumConstantDecl>(D); 15737 if (!ECD) continue; // Already issued a diagnostic. 15738 15739 // Standard C says the enumerators have int type, but we allow, as an 15740 // extension, the enumerators to be larger than int size. If each 15741 // enumerator value fits in an int, type it as an int, otherwise type it the 15742 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 15743 // that X has type 'int', not 'unsigned'. 15744 15745 // Determine whether the value fits into an int. 15746 llvm::APSInt InitVal = ECD->getInitVal(); 15747 15748 // If it fits into an integer type, force it. Otherwise force it to match 15749 // the enum decl type. 15750 QualType NewTy; 15751 unsigned NewWidth; 15752 bool NewSign; 15753 if (!getLangOpts().CPlusPlus && 15754 !Enum->isFixed() && 15755 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 15756 NewTy = Context.IntTy; 15757 NewWidth = IntWidth; 15758 NewSign = true; 15759 } else if (ECD->getType() == BestType) { 15760 // Already the right type! 15761 if (getLangOpts().CPlusPlus) 15762 // C++ [dcl.enum]p4: Following the closing brace of an 15763 // enum-specifier, each enumerator has the type of its 15764 // enumeration. 15765 ECD->setType(EnumType); 15766 continue; 15767 } else { 15768 NewTy = BestType; 15769 NewWidth = BestWidth; 15770 NewSign = BestType->isSignedIntegerOrEnumerationType(); 15771 } 15772 15773 // Adjust the APSInt value. 15774 InitVal = InitVal.extOrTrunc(NewWidth); 15775 InitVal.setIsSigned(NewSign); 15776 ECD->setInitVal(InitVal); 15777 15778 // Adjust the Expr initializer and type. 15779 if (ECD->getInitExpr() && 15780 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 15781 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 15782 CK_IntegralCast, 15783 ECD->getInitExpr(), 15784 /*base paths*/ nullptr, 15785 VK_RValue)); 15786 if (getLangOpts().CPlusPlus) 15787 // C++ [dcl.enum]p4: Following the closing brace of an 15788 // enum-specifier, each enumerator has the type of its 15789 // enumeration. 15790 ECD->setType(EnumType); 15791 else 15792 ECD->setType(NewTy); 15793 } 15794 15795 Enum->completeDefinition(BestType, BestPromotionType, 15796 NumPositiveBits, NumNegativeBits); 15797 15798 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 15799 15800 if (Enum->isClosedFlag()) { 15801 for (Decl *D : Elements) { 15802 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 15803 if (!ECD) continue; // Already issued a diagnostic. 15804 15805 llvm::APSInt InitVal = ECD->getInitVal(); 15806 if (InitVal != 0 && !InitVal.isPowerOf2() && 15807 !IsValueInFlagEnum(Enum, InitVal, true)) 15808 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 15809 << ECD << Enum; 15810 } 15811 } 15812 15813 // Now that the enum type is defined, ensure it's not been underaligned. 15814 if (Enum->hasAttrs()) 15815 CheckAlignasUnderalignment(Enum); 15816 } 15817 15818 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 15819 SourceLocation StartLoc, 15820 SourceLocation EndLoc) { 15821 StringLiteral *AsmString = cast<StringLiteral>(expr); 15822 15823 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 15824 AsmString, StartLoc, 15825 EndLoc); 15826 CurContext->addDecl(New); 15827 return New; 15828 } 15829 15830 static void checkModuleImportContext(Sema &S, Module *M, 15831 SourceLocation ImportLoc, DeclContext *DC, 15832 bool FromInclude = false) { 15833 SourceLocation ExternCLoc; 15834 15835 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 15836 switch (LSD->getLanguage()) { 15837 case LinkageSpecDecl::lang_c: 15838 if (ExternCLoc.isInvalid()) 15839 ExternCLoc = LSD->getLocStart(); 15840 break; 15841 case LinkageSpecDecl::lang_cxx: 15842 break; 15843 } 15844 DC = LSD->getParent(); 15845 } 15846 15847 while (isa<LinkageSpecDecl>(DC)) 15848 DC = DC->getParent(); 15849 15850 if (!isa<TranslationUnitDecl>(DC)) { 15851 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 15852 ? diag::ext_module_import_not_at_top_level_noop 15853 : diag::err_module_import_not_at_top_level_fatal) 15854 << M->getFullModuleName() << DC; 15855 S.Diag(cast<Decl>(DC)->getLocStart(), 15856 diag::note_module_import_not_at_top_level) << DC; 15857 } else if (!M->IsExternC && ExternCLoc.isValid()) { 15858 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 15859 << M->getFullModuleName(); 15860 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 15861 } 15862 } 15863 15864 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc, 15865 SourceLocation ModuleLoc, 15866 ModuleDeclKind MDK, 15867 ModuleIdPath Path) { 15868 // A module implementation unit requires that we are not compiling a module 15869 // of any kind. A module interface unit requires that we are not compiling a 15870 // module map. 15871 switch (getLangOpts().getCompilingModule()) { 15872 case LangOptions::CMK_None: 15873 // It's OK to compile a module interface as a normal translation unit. 15874 break; 15875 15876 case LangOptions::CMK_ModuleInterface: 15877 if (MDK != ModuleDeclKind::Implementation) 15878 break; 15879 15880 // We were asked to compile a module interface unit but this is a module 15881 // implementation unit. That indicates the 'export' is missing. 15882 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 15883 << FixItHint::CreateInsertion(ModuleLoc, "export "); 15884 break; 15885 15886 case LangOptions::CMK_ModuleMap: 15887 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); 15888 return nullptr; 15889 } 15890 15891 // FIXME: Create a ModuleDecl and return it. 15892 15893 // FIXME: Most of this work should be done by the preprocessor rather than 15894 // here, in order to support macro import. 15895 15896 // Flatten the dots in a module name. Unlike Clang's hierarchical module map 15897 // modules, the dots here are just another character that can appear in a 15898 // module name. 15899 std::string ModuleName; 15900 for (auto &Piece : Path) { 15901 if (!ModuleName.empty()) 15902 ModuleName += "."; 15903 ModuleName += Piece.first->getName(); 15904 } 15905 15906 // If a module name was explicitly specified on the command line, it must be 15907 // correct. 15908 if (!getLangOpts().CurrentModule.empty() && 15909 getLangOpts().CurrentModule != ModuleName) { 15910 Diag(Path.front().second, diag::err_current_module_name_mismatch) 15911 << SourceRange(Path.front().second, Path.back().second) 15912 << getLangOpts().CurrentModule; 15913 return nullptr; 15914 } 15915 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 15916 15917 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 15918 15919 switch (MDK) { 15920 case ModuleDeclKind::Module: { 15921 // FIXME: Check we're not in a submodule. 15922 15923 // We can't have parsed or imported a definition of this module or parsed a 15924 // module map defining it already. 15925 if (auto *M = Map.findModule(ModuleName)) { 15926 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 15927 if (M->DefinitionLoc.isValid()) 15928 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 15929 else if (const auto *FE = M->getASTFile()) 15930 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 15931 << FE->getName(); 15932 return nullptr; 15933 } 15934 15935 // Create a Module for the module that we're defining. 15936 Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName); 15937 assert(Mod && "module creation should not fail"); 15938 15939 // Enter the semantic scope of the module. 15940 ActOnModuleBegin(ModuleLoc, Mod); 15941 return nullptr; 15942 } 15943 15944 case ModuleDeclKind::Partition: 15945 // FIXME: Check we are in a submodule of the named module. 15946 return nullptr; 15947 15948 case ModuleDeclKind::Implementation: 15949 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 15950 PP.getIdentifierInfo(ModuleName), Path[0].second); 15951 15952 DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc); 15953 if (Import.isInvalid()) 15954 return nullptr; 15955 return ConvertDeclToDeclGroup(Import.get()); 15956 } 15957 15958 llvm_unreachable("unexpected module decl kind"); 15959 } 15960 15961 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 15962 SourceLocation ImportLoc, 15963 ModuleIdPath Path) { 15964 Module *Mod = 15965 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 15966 /*IsIncludeDirective=*/false); 15967 if (!Mod) 15968 return true; 15969 15970 VisibleModules.setVisible(Mod, ImportLoc); 15971 15972 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 15973 15974 // FIXME: we should support importing a submodule within a different submodule 15975 // of the same top-level module. Until we do, make it an error rather than 15976 // silently ignoring the import. 15977 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 15978 // warn on a redundant import of the current module? 15979 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 15980 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 15981 Diag(ImportLoc, getLangOpts().isCompilingModule() 15982 ? diag::err_module_self_import 15983 : diag::err_module_import_in_implementation) 15984 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 15985 15986 SmallVector<SourceLocation, 2> IdentifierLocs; 15987 Module *ModCheck = Mod; 15988 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 15989 // If we've run out of module parents, just drop the remaining identifiers. 15990 // We need the length to be consistent. 15991 if (!ModCheck) 15992 break; 15993 ModCheck = ModCheck->Parent; 15994 15995 IdentifierLocs.push_back(Path[I].second); 15996 } 15997 15998 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15999 ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc, 16000 Mod, IdentifierLocs); 16001 if (!ModuleScopes.empty()) 16002 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 16003 TU->addDecl(Import); 16004 return Import; 16005 } 16006 16007 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16008 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16009 BuildModuleInclude(DirectiveLoc, Mod); 16010 } 16011 16012 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16013 // Determine whether we're in the #include buffer for a module. The #includes 16014 // in that buffer do not qualify as module imports; they're just an 16015 // implementation detail of us building the module. 16016 // 16017 // FIXME: Should we even get ActOnModuleInclude calls for those? 16018 bool IsInModuleIncludes = 16019 TUKind == TU_Module && 16020 getSourceManager().isWrittenInMainFile(DirectiveLoc); 16021 16022 bool ShouldAddImport = !IsInModuleIncludes; 16023 16024 // If this module import was due to an inclusion directive, create an 16025 // implicit import declaration to capture it in the AST. 16026 if (ShouldAddImport) { 16027 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16028 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16029 DirectiveLoc, Mod, 16030 DirectiveLoc); 16031 if (!ModuleScopes.empty()) 16032 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 16033 TU->addDecl(ImportD); 16034 Consumer.HandleImplicitImportDecl(ImportD); 16035 } 16036 16037 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 16038 VisibleModules.setVisible(Mod, DirectiveLoc); 16039 } 16040 16041 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 16042 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16043 16044 ModuleScopes.push_back({}); 16045 ModuleScopes.back().Module = Mod; 16046 if (getLangOpts().ModulesLocalVisibility) 16047 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 16048 16049 VisibleModules.setVisible(Mod, DirectiveLoc); 16050 16051 // The enclosing context is now part of this module. 16052 // FIXME: Consider creating a child DeclContext to hold the entities 16053 // lexically within the module. 16054 if (getLangOpts().trackLocalOwningModule()) { 16055 cast<Decl>(CurContext)->setHidden(true); 16056 cast<Decl>(CurContext)->setLocalOwningModule(Mod); 16057 } 16058 } 16059 16060 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { 16061 if (getLangOpts().ModulesLocalVisibility) { 16062 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 16063 // Leaving a module hides namespace names, so our visible namespace cache 16064 // is now out of date. 16065 VisibleNamespaceCache.clear(); 16066 } 16067 16068 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 16069 "left the wrong module scope"); 16070 ModuleScopes.pop_back(); 16071 16072 // We got to the end of processing a local module. Create an 16073 // ImportDecl as we would for an imported module. 16074 FileID File = getSourceManager().getFileID(EomLoc); 16075 SourceLocation DirectiveLoc; 16076 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { 16077 // We reached the end of a #included module header. Use the #include loc. 16078 assert(File != getSourceManager().getMainFileID() && 16079 "end of submodule in main source file"); 16080 DirectiveLoc = getSourceManager().getIncludeLoc(File); 16081 } else { 16082 // We reached an EOM pragma. Use the pragma location. 16083 DirectiveLoc = EomLoc; 16084 } 16085 BuildModuleInclude(DirectiveLoc, Mod); 16086 16087 // Any further declarations are in whatever module we returned to. 16088 if (getLangOpts().trackLocalOwningModule()) { 16089 cast<Decl>(CurContext)->setLocalOwningModule(getCurrentModule()); 16090 if (!getCurrentModule()) 16091 cast<Decl>(CurContext)->setHidden(false); 16092 } 16093 } 16094 16095 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 16096 Module *Mod) { 16097 // Bail if we're not allowed to implicitly import a module here. 16098 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 16099 return; 16100 16101 // Create the implicit import declaration. 16102 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16103 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16104 Loc, Mod, Loc); 16105 TU->addDecl(ImportD); 16106 Consumer.HandleImplicitImportDecl(ImportD); 16107 16108 // Make the module visible. 16109 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 16110 VisibleModules.setVisible(Mod, Loc); 16111 } 16112 16113 /// We have parsed the start of an export declaration, including the '{' 16114 /// (if present). 16115 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 16116 SourceLocation LBraceLoc) { 16117 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 16118 16119 // C++ Modules TS draft: 16120 // An export-declaration shall appear in the purview of a module other than 16121 // the global module. 16122 if (ModuleScopes.empty() || !ModuleScopes.back().Module || 16123 ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit) 16124 Diag(ExportLoc, diag::err_export_not_in_module_interface); 16125 16126 // An export-declaration [...] shall not contain more than one 16127 // export keyword. 16128 // 16129 // The intent here is that an export-declaration cannot appear within another 16130 // export-declaration. 16131 if (D->isExported()) 16132 Diag(ExportLoc, diag::err_export_within_export); 16133 16134 CurContext->addDecl(D); 16135 PushDeclContext(S, D); 16136 return D; 16137 } 16138 16139 /// Complete the definition of an export declaration. 16140 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 16141 auto *ED = cast<ExportDecl>(D); 16142 if (RBraceLoc.isValid()) 16143 ED->setRBraceLoc(RBraceLoc); 16144 16145 // FIXME: Diagnose export of internal-linkage declaration (including 16146 // anonymous namespace). 16147 16148 PopDeclContext(); 16149 return D; 16150 } 16151 16152 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 16153 IdentifierInfo* AliasName, 16154 SourceLocation PragmaLoc, 16155 SourceLocation NameLoc, 16156 SourceLocation AliasNameLoc) { 16157 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 16158 LookupOrdinaryName); 16159 AsmLabelAttr *Attr = 16160 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 16161 16162 // If a declaration that: 16163 // 1) declares a function or a variable 16164 // 2) has external linkage 16165 // already exists, add a label attribute to it. 16166 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16167 if (isDeclExternC(PrevDecl)) 16168 PrevDecl->addAttr(Attr); 16169 else 16170 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 16171 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 16172 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 16173 } else 16174 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 16175 } 16176 16177 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 16178 SourceLocation PragmaLoc, 16179 SourceLocation NameLoc) { 16180 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 16181 16182 if (PrevDecl) { 16183 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 16184 } else { 16185 (void)WeakUndeclaredIdentifiers.insert( 16186 std::pair<IdentifierInfo*,WeakInfo> 16187 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 16188 } 16189 } 16190 16191 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 16192 IdentifierInfo* AliasName, 16193 SourceLocation PragmaLoc, 16194 SourceLocation NameLoc, 16195 SourceLocation AliasNameLoc) { 16196 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 16197 LookupOrdinaryName); 16198 WeakInfo W = WeakInfo(Name, NameLoc); 16199 16200 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16201 if (!PrevDecl->hasAttr<AliasAttr>()) 16202 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 16203 DeclApplyPragmaWeak(TUScope, ND, W); 16204 } else { 16205 (void)WeakUndeclaredIdentifiers.insert( 16206 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 16207 } 16208 } 16209 16210 Decl *Sema::getObjCDeclContext() const { 16211 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 16212 } 16213